From ca773ac0d4fbab41f378332263b3dd25c43db9f6 Mon Sep 17 00:00:00 2001 From: Siddhesh Sonar Date: Tue, 3 Nov 2026 21:59:05 +0530 Subject: [PATCH 01/26] feat(harness): hybrid router with a local lane for subagents --- pls/README.md | 76 ++ pls/model_server.py | 414 +++++++++++ pls/pls.py | 1290 ++++++++++++++++++++++++++++++++++ pls/requirements.in | 4 + pls/requirements.lock | 249 +++++++ pls/test_pls.py | 500 +++++++++++++ src/app.rs | 40 +- src/commands/cmd_harness.rs | 29 +- src/commands/cmd_pls.rs | 48 ++ src/commands/mod.rs | 2 + src/harness/agents.rs | 252 +++++++ src/harness/mod.rs | 1 + src/harness/pls.rs | 425 +++++++++++ src/progress/progress_bar.rs | 80 +++ 14 files changed, 3403 insertions(+), 7 deletions(-) create mode 100644 pls/README.md create mode 100644 pls/model_server.py create mode 100644 pls/pls.py create mode 100644 pls/requirements.in create mode 100644 pls/requirements.lock create mode 100644 pls/test_pls.py create mode 100644 src/commands/cmd_pls.rs create mode 100644 src/harness/pls.rs diff --git a/pls/README.md b/pls/README.md new file mode 100644 index 00000000..8275f4b2 --- /dev/null +++ b/pls/README.md @@ -0,0 +1,76 @@ +# PLS — hybrid router + +A loopback router that exposes one model id and two lanes: + +| Path | Lane | +|---|---| +| `/v1/...` | cloud | +| `/local/v1/...` | local MLX model, result summarised | +| `/local-only/v1/...` | local MLX model, result withheld | + +`wally` starts it, points the harness at it, and stops it on exit. The local +model server is spawned by the router and killed with it. + +## Running + +``` +wally deepseek --hybrid -m --cloud-model [prompt] +``` + +`wally pls -m ` runs the router alone, for development. + +## Subscription gate + +The router asks wally for the account's entitlement over a unix socket at +`~/.config/wally/pls/entitlement.sock` (mode `0600`). Without a subscription +every request goes to the cloud and the local model is never loaded. The +answer is cached five seconds; an unreachable socket keeps the last answer, so +a lost wally fails closed to the cloud. + +Premium accounts get the mode file and the two lanes. + +## Debug console (temporary) + +Set `PLS_DEBUG=1` and run `wally pls`. Open `/debug` and watch every +request, its lane, its reason and every file's PII counts live. `/debug/state` +holds the backlog, `/debug/events` is the stream. Remove once the MVP ships. + +## PII + +Every request is scanned for emails, phone numbers, API keys, IPv4 addresses and +IBANs. Counts are attributed to the file path the text mentions and travel to +the cloud in `x-pls-pii`, plus `/stats`. Only counts leave the machine, never +the values. + +## Mode + +`~/.config/wally/pls/config.json` is re-read on every request: + +```json +{ "mode": "hybrid", "max_turns": 20 } +``` + +- `cloud` — everything goes to the cloud, the local model is never loaded. +- `hybrid` — the parent goes to the cloud, subagents go local. +- `local` — everything goes local. + +Missing or unparseable falls back to `hybrid` and 20 turns. + +## Files + +``` +~/.config/wally/pls/pls.py override, wins over the copy beside the binary +~/.config/wally/pls/config.json mode and turn cap +~/.config/wally/pls/venv/ built once from requirements.lock +~/.config/wally/pls/pls.pid swept on the next start +``` + +## Requirements + +`uv` on `PATH` or beside the binary. The first launch builds the venv +(`mlx-vlm`, `fastapi`, `uvicorn`, `httpx`) — about 1–2 GB. + +## Limits + +Text only, one concurrent local request (queue depth 8, then overflow to the +cloud), no auth on the port, one global mode. diff --git a/pls/model_server.py b/pls/model_server.py new file mode 100644 index 00000000..9d577088 --- /dev/null +++ b/pls/model_server.py @@ -0,0 +1,414 @@ +"""OpenAI-compatible server over mlx-vlm, spawned and owned by pls.py. + +Text only. Tool calls are parsed from the Qwen XML form the chat template +emits. The context cap is enforced by trimming the prompt cache, because +`max_kv_size` is a no-op on models whose `make_cache()` takes no size. + +Binds port 0 and prints `{"port": N}` on stdout once listening, so the router +never has to guess a port. +""" + +import asyncio +import json +import os +import re +import socket +import sys +import time +import uuid +from collections import OrderedDict +from concurrent.futures import ThreadPoolExecutor +from typing import Any + +import mlx.core as mx +import mlx_vlm +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, StreamingResponse +import uvicorn + +MODEL_PATH = os.environ["PLS_MODEL"] +MODEL_ID = os.environ.get("PLS_MODEL_ID", "Hybird-Wally-0.1") +MAX_KV = int(os.environ.get("PLS_MAX_KV", "57344")) +MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192")) +PROMPT_CACHE_MAX = int(os.environ.get("PLS_PROMPT_CACHE_MAX", "8")) + +app = FastAPI() +model = None +processor = None + +# MLX streams are thread-local: load and generate on one dedicated thread, which +# also serialises requests. +POOL = ThreadPoolExecutor(max_workers=1) + +STATS: dict[str, Any] = { + "requests": 0, + "errors": 0, + "in_flight": 0, + "prompt_tokens": 0, + "completion_tokens": 0, + "peak_context": 0, + "max_kv": MAX_KV, + "trims": 0, + "last": None, +} + +PROMPT_CACHES: "OrderedDict[str, list]" = OrderedDict() + +TOOL_RE = re.compile(r"\s*\n]+)>(.*?)\s*", re.S) +PARAM_RE = re.compile(r"\n]+)>\n?(.*?)\n?", re.S) + + +def log(event: dict) -> None: + print(json.dumps(event), file=sys.stderr, flush=True) + + +def cache_key(request: Request) -> str: + for name in ("x-session-affinity", "x-session-id", "x-opencode-session-id"): + value = request.headers.get(name) + if value: + return value + return "default" + + +def trim_cache(cache) -> None: + """Keep the live KV under the cap by dropping the oldest half.""" + try: + used = max((c.size() for c in cache if hasattr(c, "size")), default=0) + except Exception: + return + if used <= MAX_KV: + return + keep = MAX_KV // 2 + for c in cache: + trimmable = getattr(c, "is_trimmable", None) + if not hasattr(c, "trim") or (trimmable is not None and not trimmable()): + continue + try: + c.trim(c.size() - keep) + except Exception: + pass + STATS["trims"] += 1 + + +def take_cache(key: str): + cache = PROMPT_CACHES.get(key) + if cache is not None: + PROMPT_CACHES.move_to_end(key) + return cache + + +def put_cache(key: str, cache) -> None: + PROMPT_CACHES[key] = cache + PROMPT_CACHES.move_to_end(key) + while len(PROMPT_CACHES) > PROMPT_CACHE_MAX: + PROMPT_CACHES.popitem(last=False) + + +def parse_tool_calls(text: str): + calls = [] + for name, body in TOOL_RE.findall(text): + args = {k: v for k, v in PARAM_RE.findall(body)} + calls.append( + { + "id": "call_" + uuid.uuid4().hex[:24], + "type": "function", + "function": {"name": name.strip(), "arguments": json.dumps(args)}, + } + ) + return calls + + +def strip_tool_calls(text: str) -> str: + return TOOL_RE.sub("", text).strip() + + +def build_prompt(messages, tools): + return mlx_vlm.apply_chat_template( + processor, + model.config, + messages, + tools=tools or None, + add_generation_prompt=True, + ) + + +def usage_of(result, prompt_tokens: int, completion_tokens: int) -> dict: + pt = getattr(result, "prompt_tokens", 0) or prompt_tokens + ct = getattr(result, "generation_tokens", 0) or completion_tokens + return { + "prompt_tokens": pt, + "completion_tokens": ct, + "total_tokens": pt + ct, + "context_used": pt + ct, + "context_max": MAX_KV, + "cached_tokens": getattr(result, "cached_tokens", 0) or 0, + "prompt_tps": round(getattr(result, "prompt_tps", 0.0) or 0.0, 2), + "generation_tps": round(getattr(result, "generation_tps", 0.0) or 0.0, 2), + "peak_memory_mb": round((getattr(result, "peak_memory", 0) or 0) / 1e6, 1), + } + + +def record(req_id: str, usage: dict, ttft_ms: float, total_ms: float, finish: str) -> None: + STATS["requests"] += 1 + STATS["prompt_tokens"] += usage["prompt_tokens"] + STATS["completion_tokens"] += usage["completion_tokens"] + STATS["peak_context"] = max(STATS["peak_context"], usage["context_used"]) + entry = { + "event": "request", + "id": req_id, + "ttft_ms": round(ttft_ms, 1), + "total_ms": round(total_ms, 1), + "finish": finish, + **usage, + } + STATS["last"] = entry + log(entry) + + +@app.get("/v1/models") +def models(): + return {"object": "list", "data": [{"id": MODEL_ID, "object": "model", "owned_by": "local"}]} + + +@app.get("/health") +def health(): + return {"ok": model is not None} + + +@app.get("/stats") +def stats(): + s = dict(STATS) + s["context_headroom"] = MAX_KV - s["peak_context"] + s["prompt_caches"] = len(PROMPT_CACHES) + return s + + +@app.post("/v1/chat/completions") +async def chat(request: Request): + body: dict[str, Any] = await request.json() + messages = body.get("messages") or [] + tools = body.get("tools") + stream = bool(body.get("stream")) + want_usage = bool((body.get("stream_options") or {}).get("include_usage")) + max_tokens = min(int(body.get("max_tokens") or MAX_OUT), MAX_OUT) + temperature = float(body.get("temperature", 0.7)) + + prompt = build_prompt(messages, tools) + kwargs = dict( + max_tokens=max_tokens, + temperature=temperature, + verbose=False, + ) + + key = cache_key(request) + cache = take_cache(key) + if cache is None: + try: + cache = model.language_model.make_cache() + except AttributeError: + from mlx_vlm.models.cache import make_prompt_cache + + cache = make_prompt_cache(model.language_model) + put_cache(key, cache) + trim_cache(cache) + kwargs["prompt_cache"] = cache + + loop = asyncio.get_running_loop() + cid = "chatcmpl-" + uuid.uuid4().hex[:24] + created = int(time.time()) + started = time.monotonic() + STATS["in_flight"] += 1 + + try: + if not stream: + out = await loop.run_in_executor( + POOL, lambda: mlx_vlm.generate(model, processor, prompt, **kwargs) + ) + elapsed = (time.monotonic() - started) * 1000 + text = out.text if hasattr(out, "text") else str(out) + calls = parse_tool_calls(text) + usage = usage_of(out, 0, 0) + record(cid, usage, elapsed, elapsed, "tool_calls" if calls else "stop") + msg: dict[str, Any] = { + "role": "assistant", + "content": strip_tool_calls(text) or None, + } + if calls: + msg["tool_calls"] = calls + return JSONResponse( + { + "id": cid, + "object": "chat.completion", + "created": created, + "model": MODEL_ID, + "choices": [ + { + "index": 0, + "message": msg, + "finish_reason": "tool_calls" if calls else "stop", + } + ], + "usage": usage, + } + ) + + async def sse(): + acc = "" + held = "" + in_call = False + call_index = 0 + pt = ct = 0 + ttft = 0.0 + last = None + + def content_delta(text): + return { + "id": cid, + "object": "chat.completion.chunk", + "created": created, + "model": MODEL_ID, + "choices": [ + {"index": 0, "delta": {"content": text}, "finish_reason": None} + ], + } + + def call_delta(calls): + nonlocal call_index + payload = { + "id": cid, + "object": "chat.completion.chunk", + "created": created, + "model": MODEL_ID, + "choices": [ + { + "index": 0, + "delta": { + "tool_calls": [ + {"index": call_index + i, **c} + for i, c in enumerate(calls) + ] + }, + "finish_reason": None, + } + ], + } + call_index += len(calls) + return payload + + def flush_held(): + nonlocal held + while "" in held: + end = held.index("") + len("") + block, held = held[:end], held[end:] + calls = parse_tool_calls(block) + if calls: + yield call_delta(calls) + else: + yield content_delta(block) + + first = { + "id": cid, + "object": "chat.completion.chunk", + "created": created, + "model": MODEL_ID, + "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}], + } + yield f"data: {json.dumps(first)}\n\n" + + it = await loop.run_in_executor( + POOL, lambda: mlx_vlm.stream_generate(model, processor, prompt, **kwargs) + ) + for chunk in it: + last = chunk + piece = chunk.text if hasattr(chunk, "text") else str(chunk) + pt = getattr(chunk, "prompt_tokens", pt) or pt + ct = getattr(chunk, "generation_tokens", ct) or ct + if not piece: + continue + if not ttft: + ttft = (time.monotonic() - started) * 1000 + acc += piece + + if in_call: + held += piece + for out in flush_held(): + yield f"data: {json.dumps(out)}\n\n" + if "" in held or not held.lstrip().startswith(""): + in_call = held.lstrip().startswith("") + continue + + if "" in piece: + head, _, tail = piece.partition("") + if head: + yield f"data: {json.dumps(content_delta(head))}\n\n" + in_call = True + held = "" + tail + for out in flush_held(): + yield f"data: {json.dumps(out)}\n\n" + if "" in held: + in_call = False + continue + + yield f"data: {json.dumps(content_delta(piece))}\n\n" + + if held: + for out in flush_held(): + yield f"data: {json.dumps(out)}\n\n" + if held: + yield f"data: {json.dumps(content_delta(held))}\n\n" + + calls = parse_tool_calls(acc) + usage = usage_of(last, pt, ct) + record(cid, usage, ttft, (time.monotonic() - started) * 1000, + "tool_calls" if calls else "stop") + final = { + "id": cid, + "object": "chat.completion.chunk", + "created": created, + "model": MODEL_ID, + "choices": [ + {"index": 0, "delta": {}, "finish_reason": "tool_calls" if calls else "stop"} + ], + } + yield f"data: {json.dumps(final)}\n\n" + if want_usage: + yield f"data: {json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'model': MODEL_ID, 'choices': [], 'usage': usage})}\n\n" + yield "data: [DONE]\n\n" + + return StreamingResponse(sse(), media_type="text/event-stream") + + except Exception as error: + STATS["errors"] += 1 + log({"event": "error", "id": cid, "error": f"{type(error).__name__}: {error}"}) + raise + finally: + STATS["in_flight"] -= 1 + + +@app.on_event("startup") +async def load(): + global model, processor + loop = asyncio.get_running_loop() + + def _load(): + mx.set_cache_limit(0) + return mlx_vlm.load(MODEL_PATH) + + model, processor = await loop.run_in_executor(POOL, _load) + log({"event": "loaded", "model": MODEL_ID, "max_kv": MAX_KV, "max_out": MAX_OUT}) + + +def main() -> None: + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", 0)) + sock.listen(128) + port = sock.getsockname()[1] + print(json.dumps({"port": port}), flush=True) + uvicorn.Server( + uvicorn.Config(app, log_level="warning", lifespan="on") + ).run(sockets=[sock]) + + +if __name__ == "__main__": + main() diff --git a/pls/pls.py b/pls/pls.py new file mode 100644 index 00000000..3209c42b --- /dev/null +++ b/pls/pls.py @@ -0,0 +1,1290 @@ +"""PLS — Proxy LocalHost:Server. + +A loopback router that exposes one model id and two lanes: + + /v1/... cloud + /local/v1/... local MLX model, result summarised + /local-only/v1/... local MLX model, result withheld + +The harness is pointed at this process by wally. Mode comes from a JSON file +re-read on every request. The local model server is spawned lazily and killed +on exit, including on SIGTERM and when the parent disappears. + +Binds port 0 and prints `{"port": N}` on stdout once listening. +""" + +import asyncio +import atexit +import collections +import hashlib +import json +import os +import re +import signal +import socket +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +import httpx +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, Response, StreamingResponse +import uvicorn + +MODEL_ID = "Hybird-Wally-0.1" +DEFAULT_MODE = "hybrid" +DEFAULT_MAX_TURNS = 20 +QUEUE_MAX = 8 +SUMMARY_MAX_TOKENS = 512 + +WITHHELD = ( + "[content withheld: this subagent ran under local-only disclosure — its " + "result was kept on your device]" +) +WRAP_UP = ( + "You have reached the turn limit. Wrap up now: synthesize the best result " + "available and answer in text only." +) +DELEGATION = ( + "\n\nYou are the cloud half of a hybrid pair. File exploration — reading, " + "grepping, listing, summarising files — belongs to the `subagent` tool: it " + "runs on a local model and its result comes back filtered. Do it yourself " + "only for small things, or when the subagent fails." + "\n\nBegin every `subagent` prompt with a disclosure marker on its own line:" + "\n disclosure: local_only — nothing but a placeholder comes back; use when the file must not reach the cloud at all." + "\n disclosure: title — a one-line title comes back; use for a file inventory." + "\n disclosure: summary — a short summary comes back; the default for reading content." + "\n disclosure: none — the full result comes back; use when you need exact text." +) + +# File tools the parent loses in hybrid, so exploration has to go through the +# subagent instead of relying on the model's judgement. +PARENT_DENIED = {"read", "grep", "glob"} +# The gateway drops tool arguments when `tool_choice` is pinned, so a forced +# call arrives as `subagent {}` and dsh rejects it. Off until it is fixed. +FORCE_DELEGATION = False + +# The guard is router-owned, not model-owned: the router says what to call and +# checks the answer. A reply that reaches for a file tool is dropped and asked +# again; after GUARD_RETRIES the router emits the call itself. PII turns also +# get a spoken instruction and a forced mode; a plain work turn keeps the mode +# the model named. +PII_MODE = "local_only" +WORK_MODE = "summary" +GUARD_RETRIES = 2 +PII_TOOL = "subagent" +NUDGE_PREFIX = "Wrong: you answered with" +INSTRUCTION_PREFIX = "Route this turn locally:" + +WORK_RE = re.compile( + r"(\b(read|list|find|search|grep|open|summar|review|explain|audit|inspect)\b" + r"|/[\w.-]+|\bsrc/|\bdocs/)", + re.I, +) + +# The cloud names the disclosure mode on the child prompt, the way PPLX's +# `disclosureMode` field does. First token wins; the marker is stripped. +DISCLOSURE_RE = re.compile(r"^\s*disclosure:\s*(local_only|summary|title|none)\b[ \t]*\n?", re.I) + +# Told to the local child. The ceiling is enforced by the router; this keeps +# the model from pasting rows the filter then has to strip. +CHILD_RULES = { + "title": " Answer with one line, no content.", + "summary": " Answer in at most 120 words. Keep counts, column names and shapes; " + "do not paste rows or raw values.", + "none": " Answer normally; the full result is returned.", +} + +SUMMARY_PROMPT = ( + "Summarise the following result in at most 120 words. Keep file paths, " + "names and numbers. Answer with the summary only.\n\n" +) + +ENTITLEMENT_SOCKET = os.environ.get("PLS_ENTITLEMENT_SOCKET", "") +# Debug console: remove once the MVP ships. +DEBUG = os.environ.get("PLS_DEBUG") == "1" +EVENTS: "collections.deque[dict]" = collections.deque(maxlen=1000) +SUBSCRIBERS: "set[asyncio.Queue]" = set() +premium_cache = {"value": False, "at": 0.0} + +PROFILE_DIR = Path( + os.environ.get("WALLY_PROFILE_DIR") + or os.environ.get("RCLI_PROFILE_DIR") + or Path.home() / ".config" / "wally" +) +CONFIG_DIR = PROFILE_DIR / "pls" +CONFIG_PATH = CONFIG_DIR / "config.json" +CREDENTIALS_PATH = PROFILE_DIR / "credentials.json" +PID_PATH = CONFIG_DIR / "pls.pid" +SERVER_SCRIPT = Path(__file__).with_name("model_server.py") + +app = FastAPI() +http = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=10.0)) + +local_sem = asyncio.Semaphore(1) +waiting = 0 +turns: dict[str, int] = {} +local_sessions: "set[str]" = set() +model_proc: subprocess.Popen | None = None +model_port: int | None = None +model_lock = asyncio.Lock() +explicit_parent = int(os.environ.get("PLS_PARENT_PID") or 0) +parent_pid = explicit_parent or os.getppid() +shutting_down = False + +STATS: dict[str, Any] = { + "requests": 0, + "errors": 0, + "queued": 0, + "overflow": 0, + "local_turns": 0, + "cloud_tokens": 0, + "local_tokens": 0, + "cap_hits": 0, + "disclosure": {"summary": 0, "local_only": 0, "title": 0}, + "pii_files": 0, + "pii_hits": 0, + "premium_blocked": 0, + "hints": 0, + "guard_retries": 0, + "guard_synth": 0, + "mode": DEFAULT_MODE, + "last": None, +} + + +PII_PATTERNS = { + "email": re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b"), + "phone": re.compile(r"\+?\d[\d ().-]{7,}\d"), + "key": re.compile(r"\b(?:sk-[A-Za-z0-9_-]{16,}|AKIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9]{20,})\b"), + "ipv4": re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), + "iban": re.compile(r"\b[A-Z]{2}\d{2}[A-Z0-9]{12,30}\b"), +} +PATH_RE = re.compile(r"(? str: + home = str(Path.home()) + return text.replace(home, "~") if home else text + + +def inject_child_rules(body: dict, disclosure: str) -> None: + rule = CHILD_RULES.get(disclosure) + if not rule: + return + messages = body.get("messages") + if not isinstance(messages, list): + return + for message in messages: + if message.get("role") != "system": + continue + if isinstance(message.get("content"), str): + message["content"] += rule + return + + +def redact(text: str) -> str: + """Replace PII values with typed placeholders. The shape survives, the value does not.""" + for name, pattern in PII_PATTERNS.items(): + text = pattern.sub(f"[{name}]", text) + return text + + +def take_disclosure(messages: list, fallback: str) -> tuple[str, list]: + """Pull a `disclosure:` marker off the child prompt and strip it.""" + for index in range(len(messages) - 1, -1, -1): + message = messages[index] + if message.get("role") != "user": + continue + content = message.get("content") + if not isinstance(content, str): + return fallback, messages + found = DISCLOSURE_RE.match(content) + if not found: + return fallback, messages + updated = list(messages) + updated[index] = {**message, "content": content[found.end():]} + return found.group(1).lower(), updated + return fallback, messages + + +def last_is_work(body: dict) -> bool: + messages = [m for m in body.get("messages") or [] if m.get("role") != "system"] + last = messages[-1] if messages else None + return bool(last and last.get("role") == "user" and WORK_RE.search(str(last.get("content") or ""))) + + +def shape_hybrid(body: dict, pii: dict | None = None) -> tuple[int, list, bool, bool]: + """Remove the parent's file tools and force delegation on a first work turn. + + Returns the tools left on the request and whether `tool_choice` was pinned. + """ + tools = body.get("tools") + if not isinstance(tools, list): + return 0, [], False, False + names = [t.get("function", {}).get("name") for t in tools] + kept = [t for t, name in zip(tools, names) if name not in PARENT_DENIED] + removed = sorted(PARENT_DENIED.intersection(names)) + body["tools"] = kept + + force = False + by_pii = bool(pii and pii.get("total")) + trigger = "pii" if by_pii else ("work" if last_is_work(body) else "") + pinned = isinstance(body.get("tool_choice"), dict) + if FORCE_DELEGATION and "subagent" in names and not pinned: + # Every turn where the user just spoke, not only the first: a long + # session would otherwise never be pinned again. + messages = [m for m in body.get("messages") or [] if m.get("role") != "system"] + last = messages[-1] if messages else None + if ( + last is not None + and last.get("role") == "user" + and (by_pii or WORK_RE.search(str(last.get("content") or ""))) + ): + body["tool_choice"] = {"type": "function", "function": {"name": "subagent"}} + force = True + return len(kept), removed, force, trigger + + +def inject_delegation(body: dict, pii: dict | None = None) -> bool: + """Append the hybrid instruction to the system message, once.""" + messages = body.get("messages") + if not isinstance(messages, list): + return False + extra = DELEGATION + for message in messages: + if message.get("role") != "system": + continue + content = message.get("content") + if isinstance(content, list): + text = " ".join(p.get("text", "") for p in content if isinstance(p, dict)) + if DELEGATION.strip() in text: + return False + content.append({"type": "text", "text": extra}) + return True + content = content or "" + if DELEGATION.strip() in content: + return False + message["content"] = content + extra + return True + return False + + +def pii_instruction(pii: dict, mode: str) -> str: + """The turn instruction that makes the cloud delegate a PII file. + + Names the file, what was found in it, and the mode the child must answer + in, so neither the lane nor the disclosure is left to the model. + """ + files = list(pii["files"])[:8] + named = ", ".join(files) + kinds = sorted({kind for counts in pii["files"].values() for kind in counts}) + plural = "files" if len(files) > 1 else "file" + verb = "carry" if len(files) > 1 else "carries" + return ( + f"Route this turn locally: {named} {verb} PII ({', '.join(kinds)}) and " + f"must be processed locally. Call the `{PII_TOOL}` tool now for this " + f"{plural}, and begin its prompt with this line:\n disclosure: {mode}\n" + f"Then state the task. Answer with the tool call only — a `read`, `grep` " + f"or `glob` call here puts the file on the cloud." + ) + + +def parse_calls(buffered: bytes) -> dict[int, dict]: + """Tool calls in a held SSE body, by index, with their arguments joined. + + Reads deltas, because a name and its arguments can arrive in separate + chunks and the finish reason only says that *some* call happened. + """ + calls: dict[int, dict] = {} + for line in buffered.split(b"data: ")[1:]: + raw = line.split(b"\n", 1)[0] + if raw in (b"", b"[DONE]"): + continue + try: + event = json.loads(raw) + except Exception: + continue + for choice in event.get("choices") or []: + for call in (choice.get("delta") or {}).get("tool_calls") or []: + slot = calls.setdefault( + int(call.get("index") or 0), {"name": "", "arguments": ""} + ) + function = call.get("function") or {} + if function.get("name"): + slot["name"] = function["name"] + if function.get("arguments"): + slot["arguments"] += function["arguments"] + return calls + + +def child_prompt(body: dict, pii: dict, mode: str) -> str: + """The prompt for a call the router had to emit itself.""" + files = list(pii["files"])[:8] + task = "" + for message in reversed(body.get("messages") or []): + if message.get("role") != "user" or not isinstance(message.get("content"), str): + continue + text = message["content"].strip() + if text.startswith(NUDGE_PREFIX) or text.startswith(INSTRUCTION_PREFIX): + continue + task = text + break + if not files: + return f"disclosure: {mode}\n\n{task}" + return ( + f"disclosure: {mode}\n\n" + f"Read {', '.join(files)}. It carries PII, so work from the file itself.\n\n" + f"Task: {task}" + ) + + +def patch_call_args(calls: dict[int, dict], body: dict, pii: dict, mode: str) -> bool: + """Fill a subagent call the model left empty or without the mode marker. + + A pinned `tool_choice` makes the gateway strip arguments, so a call can + arrive as `subagent {}`; dsh rejects that. + """ + changed = False + for call in calls.values(): + if call.get("name") != PII_TOOL: + continue + try: + arguments = json.loads(call.get("arguments") or "{}") + except Exception: + arguments = {} + if not isinstance(arguments, dict): + arguments = {} + prompt = str(arguments.get("prompt") or "") + if not prompt: + arguments["prompt"] = child_prompt(body, pii, mode) + changed = True + elif not DISCLOSURE_RE.match(prompt): + arguments["prompt"] = f"disclosure: {mode}\n\n{prompt}" + changed = True + if not arguments.get("description"): + arguments["description"] = "Read PII file locally" + changed = True + call["arguments"] = json.dumps(arguments) + return changed + + +def calls_stream(calls: dict[int, dict]) -> Response: + """Re-emit held calls as one SSE body, after a rewrite.""" + created = int(time.time()) + cid = "chatcmpl-pls-patch" + + async def stream(): + yield sse(chunk(cid, created, {"role": "assistant"})) + for index, call in calls.items(): + yield sse(chunk(cid, created, {"tool_calls": [{ + "index": index, + "id": f"call_pls_{index}", + "type": "function", + "function": {"name": call["name"], "arguments": call["arguments"]}, + }]})) + yield sse(chunk(cid, created, {}, "tool_calls")) + yield "data: [DONE]\n\n" + + return StreamingResponse(stream(), media_type="text/event-stream") + + +def synthetic_call(body: dict, pii: dict, mode: str) -> Response: + """Emit the subagent call ourselves when the model will not. + + dsh executes whatever tool call the stream carries, so this is the only + hard guarantee that a PII file never lands on the cloud. + """ + calls = {0: {"name": PII_TOOL, "arguments": ""}} + patch_call_args(calls, body, pii, mode) + return calls_stream(calls) + + +def scan_pii(messages: list) -> dict: + """Count PII per file mentioned in the request. + + The file is whatever path the message carries; a message with no path is + counted under ``. Only counts travel, never the values. + """ + files: dict[str, dict[str, int]] = {} + + def add(path: str, segment: str) -> None: + for name, pattern in PII_PATTERNS.items(): + found = len(pattern.findall(segment)) + if found: + counts = files.setdefault(path, {}) + counts[name] = counts.get(name, 0) + found + + for message in messages: + content = message.get("content") + if isinstance(content, list): + text = " ".join( + part.get("text", "") for part in content if isinstance(part, dict) + ) + else: + text = content or "" + if not text: + continue + # A message names the files it covers; each path owns the text up to + # the next one, so a key in one file is not blamed on its neighbour. + spans = list(PATH_RE.finditer(text)) + if not spans: + add("", text) + continue + if spans[0].start() > 0: + add("", text[: spans[0].start()]) + for index, span in enumerate(spans): + end = spans[index + 1].start() if index + 1 < len(spans) else len(text) + add(span.group(1), text[span.end():end]) + + return {"files": files, "total": sum(sum(c.values()) for c in files.values())} + + +async def premium() -> bool: + """Ask wally whether this account may run work locally. + + No socket means a hand-run router, which is not gated. + """ + if not ENTITLEMENT_SOCKET: + return True + now = time.monotonic() + if now - premium_cache["at"] < 5: + return premium_cache["value"] + value = premium_cache["value"] + try: + reader, writer = await asyncio.open_unix_connection(ENTITLEMENT_SOCKET) + writer.write(b"GET /entitlement HTTP/1.1\r\nHost: local\r\n\r\n") + await writer.drain() + raw = await asyncio.wait_for(reader.read(512), 2) + writer.close() + body = raw.split(b"\r\n\r\n", 1)[-1] + value = bool(json.loads(body).get("sub")) + except Exception: + pass + premium_cache.update(value=value, at=now) + return value + + +def log(event: dict) -> None: + print(json.dumps(event), file=sys.stderr, flush=True) + if DEBUG: + event = {"ts": round(time.time(), 3), **event} + EVENTS.append(event) + for queue in list(SUBSCRIBERS): + try: + queue.put_nowait(event) + except Exception: + pass + + +# -------------------------------------------------------------------------- +# config and credentials +# -------------------------------------------------------------------------- + + +def read_config() -> dict: + try: + data = json.loads(CONFIG_PATH.read_text()) + except Exception: + data = {} + mode = data.get("mode") + if mode not in ("cloud", "hybrid", "local"): + mode = DEFAULT_MODE + pii_mode = data.get("pii_mode") + if pii_mode not in CHILD_RULES: + pii_mode = PII_MODE + try: + max_turns = int(data.get("max_turns", DEFAULT_MAX_TURNS)) + except Exception: + max_turns = DEFAULT_MAX_TURNS + return { + "mode": mode, + "pii_mode": pii_mode, + "max_turns": max(1, max_turns), + "model_path": data.get("model_path") or os.environ.get("PLS_MODEL", ""), + "cloud_model": data.get("cloud_model") or os.environ.get("PLS_CLOUD_MODEL", ""), + } + + +def read_credentials() -> dict: + try: + return json.loads(CREDENTIALS_PATH.read_text()) + except Exception: + return {} + + +def write_credentials(creds: dict) -> None: + CONFIG_DIR.mkdir(parents=True, exist_ok=True) + tmp = CREDENTIALS_PATH.with_suffix(".json.tmp") + tmp.write_text(json.dumps(creds)) + os.chmod(tmp, 0o600) + tmp.replace(CREDENTIALS_PATH) + + +async def refresh_credentials(creds: dict) -> dict: + refresh_token = creds.get("refresh_token", "") + console = creds.get("console_url", "") + if not refresh_token or not console: + return creds + try: + response = await http.post( + f"{console.rstrip('/')}/auth/cli/refresh", + json={"refresh_token": refresh_token}, + ) + if response.status_code != 200: + log({"event": "refresh_failed", "status": response.status_code}) + return creds + grant = response.json() + except Exception: + return creds + if not grant.get("access_token"): + return creds + creds = dict(creds) + creds["access_token"] = grant["access_token"] + if grant.get("refresh_token"): + creds["refresh_token"] = grant["refresh_token"] + if grant.get("expires_in"): + creds["expires_at"] = int(time.time()) + int(grant["expires_in"]) + try: + write_credentials(creds) + except Exception: + pass + log({"event": "refreshed"}) + return creds + + +async def cloud_credentials() -> dict: + creds = read_credentials() + expires_at = int(creds.get("expires_at") or 0) + if expires_at and expires_at <= time.time() + 60: + creds = await refresh_credentials(creds) + return creds + + +# -------------------------------------------------------------------------- +# model server +# -------------------------------------------------------------------------- + + +def kill_model_server() -> None: + global model_proc + proc = model_proc + model_proc = None + if proc is None or proc.poll() is not None: + return + try: + proc.terminate() + proc.wait(timeout=10) + except Exception: + try: + proc.kill() + except Exception: + pass + + +async def ensure_model_server() -> int: + global model_proc, model_port + async with model_lock: + if model_proc is not None and model_proc.poll() is None and model_port: + return model_port + config = read_config() + model_path = config["model_path"] + if not model_path: + raise RuntimeError("no model path: set model_path in config.json or PLS_MODEL") + env = dict(os.environ) + env["PLS_MODEL"] = model_path + env["PLS_MODEL_ID"] = MODEL_ID + proc = subprocess.Popen( + [sys.executable, str(SERVER_SCRIPT)], + stdout=subprocess.PIPE, + stderr=None, + env=env, + text=True, + ) + line = await asyncio.get_running_loop().run_in_executor(None, proc.stdout.readline) + if not line: + proc.kill() + raise RuntimeError("model server exited before the handshake") + port = int(json.loads(line)["port"]) + model_proc = proc + model_port = port + log({"event": "model_server", "port": port}) + return port + + +# -------------------------------------------------------------------------- +# helpers +# -------------------------------------------------------------------------- + + +def session_key(request: Request, body: dict) -> str: + for name in ("x-session-affinity", "x-session-id", "x-opencode-session-id"): + value = request.headers.get(name) + if value: + return value + messages = body.get("messages") or [] + first = json.dumps(messages[:1], sort_keys=True) if messages else "" + return hashlib.sha1(first.encode()).hexdigest()[:16] + + +def sse(payload: dict) -> str: + return f"data: {json.dumps(payload)}\n\n" + + +def chunk(cid: str, created: int, delta: dict, finish: str | None = None) -> dict: + return { + "id": cid, + "object": "chat.completion.chunk", + "created": created, + "model": MODEL_ID, + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], + } + + +def as_stream(result: dict, want_usage: bool = False) -> StreamingResponse: + cid = result.get("id", "chatcmpl-pls") + created = result.get("created", int(time.time())) + choice = (result.get("choices") or [{}])[0] + message = choice.get("message") or {} + finish = choice.get("finish_reason") or "stop" + + async def body(): + yield sse(chunk(cid, created, {"role": "assistant"})) + if message.get("content"): + yield sse(chunk(cid, created, {"content": message["content"]})) + for index, call in enumerate(message.get("tool_calls") or []): + yield sse(chunk(cid, created, {"tool_calls": [{"index": index, **call}]})) + yield sse(chunk(cid, created, {}, finish)) + if want_usage and result.get("usage"): + yield sse( + { + "id": cid, + "object": "chat.completion.chunk", + "model": MODEL_ID, + "choices": [], + "usage": result["usage"], + } + ) + yield "data: [DONE]\n\n" + + return StreamingResponse(body(), media_type="text/event-stream") + + +async def summarise(text: str) -> str: + port = await ensure_model_server() + try: + response = await http.post( + f"http://127.0.0.1:{port}/v1/chat/completions", + json={ + "model": MODEL_ID, + "messages": [{"role": "user", "content": SUMMARY_PROMPT + text}], + "max_tokens": SUMMARY_MAX_TOKENS, + "temperature": 0.2, + }, + headers={"x-session-affinity": "pls-summary"}, + ) + result = response.json() + return ((result.get("choices") or [{}])[0].get("message") or {}).get("content") or "" + except Exception as error: + log({"event": "summary_failed", "error": str(error)}) + return text + + +# -------------------------------------------------------------------------- +# routes +# -------------------------------------------------------------------------- + + +@app.get("/health") +def health(): + return {"ok": True, "mode": read_config()["mode"]} + + +@app.get("/stats") +def stats(): + data = dict(STATS) + data["mode"] = read_config()["mode"] + data["waiting"] = waiting + data["model_port"] = model_port + return data + + +@app.post("/stats/reset") +def stats_reset(): + for key in ("requests", "errors", "queued", "overflow", "local_turns", + "cloud_tokens", "local_tokens", "cap_hits", "guard_retries", + "guard_synth"): + STATS[key] = 0 + STATS["disclosure"] = {"summary": 0, "local_only": 0, "title": 0} + STATS["last"] = None + return {"ok": True} + + +DEBUG_PAGE = """ +PLS debug + +
+

PLS router

+mode ? +sub ? +local 0 +cloud 0 +pii files 0 + + +
+
timeeventlanepath / filedetail
+""" + + +@app.get("/favicon.ico") +def favicon(): + return Response(b"", media_type="image/x-icon", status_code=204) + + +@app.get("/debug") +def debug_page(): + if not DEBUG: + return JSONResponse({"error": {"message": "debug console off (start with PLS_DEBUG=1)"}}, status_code=404) + return Response(DEBUG_PAGE, media_type="text/html") + + +@app.get("/debug/state") +def debug_state(): + return {"mode": read_config()["mode"], "sub": premium_cache["value"], + "events": list(EVENTS)} + + +@app.get("/debug/export") +def debug_export(): + body = "\n".join(json.dumps(event) for event in EVENTS) + return Response( + body + "\n", + media_type="application/x-ndjson", + headers={"content-disposition": 'attachment; filename="pls-events.ndjson"'}, + ) + + +@app.get("/debug/events") +async def debug_events(): + queue: asyncio.Queue = asyncio.Queue() + SUBSCRIBERS.add(queue) + + async def stream(): + try: + while True: + yield "data: " + json.dumps(await queue.get()) + "\n\n" + finally: + SUBSCRIBERS.discard(queue) + + return StreamingResponse(stream(), media_type="text/event-stream") + + +@app.api_route("/{path:path}", methods=["GET", "POST"]) +async def route(path: str, request: Request): + global waiting, model_port + + if path in ("v1/models", "local/v1/models", "local-only/v1/models"): + return {"object": "list", "data": [{"id": MODEL_ID, "object": "model", "owned_by": "wally"}]} + + body: dict = {} + if request.method == "POST": + try: + body = await request.json() + except Exception: + body = {} + + config = read_config() + STATS["mode"] = config["mode"] + + disclosure = "summary" + lane = "cloud" + if path.startswith("local-only/"): + lane, disclosure = "local", "local_only" + elif path.startswith("local/"): + lane = "local" + + if config["mode"] == "cloud": + lane = "cloud" + elif config["mode"] == "local": + lane, disclosure = "local", "summary" + + upstream_path = path + for prefix in ("local-only/", "local/"): + if upstream_path.startswith(prefix): + upstream_path = upstream_path[len(prefix):] + break + + sub = await premium() + reason = "path" + if not sub: + lane = "cloud" + reason = "no-subscription" + STATS["premium_blocked"] += 1 + elif config["mode"] == "cloud": + reason = "mode" + elif config["mode"] == "local": + reason = "mode" + + messages = body.get("messages") or [] + pii = scan_pii(messages) if messages else {"files": {}, "total": 0} + if pii["total"]: + STATS["pii_files"] += len(pii["files"]) + STATS["pii_hits"] += pii["total"] + + tools = [t.get("function", {}).get("name") for t in (body.get("tools") or [])] + log({"event": "route", "path": path, "lane": lane, "mode": config["mode"], + "disclosure": disclosure, "reason": reason, "sub": sub, + "pii": pii["total"], "pii_files": len(pii["files"]), "tools": tools, + "messages": len(messages)}) + if lane == "cloud" and sub and config["mode"] == "hybrid" and len(messages) >= 4: + if session_key(request, body) not in local_sessions: + log({"event": "hint", + "message": "parent working alone: no subagent call yet, so nothing is local. " + "Ask it to use the subagent tool, or set mode local."}) + STATS["hints"] += 1 + + work = last_is_work(body) + work = last_is_work(body) + guard = ( + sub + and config["mode"] == "hybrid" + and PII_TOOL in tools + and (bool(pii["total"]) or work) + ) + for file_path, counts in pii["files"].items(): + action = "summarise" if lane == "local" else ("delegated" if guard else "sent to cloud") + log({"event": "pii_file", "file": file_path, "counts": counts, + "lane": lane, "action": action}) + + if lane == "cloud" and sub and config["mode"] == "hybrid": + if inject_delegation(body, pii): + log({"event": "injected", "what": "delegation prompt"}) + remaining, removed, forced, trigger = shape_hybrid(body, pii) + log({"event": "shaped", "tools": remaining, "removed": removed, + "forced_subagent": forced, "trigger": trigger}) + + if guard and lane == "cloud": + # PII: a turn of its own, so the file and the mode are stated rather + # than inferred, and the reply is checked against them. + if pii["total"]: + body["messages"] = [*messages, { + "role": "user", + "content": pii_instruction(pii, config["pii_mode"]), + }] + log({"event": "instructed", "files": list(pii["files"])[:8], + "mode": config["pii_mode"]}) + + if lane == "cloud": + mode = config["pii_mode"] if pii["total"] else WORK_MODE + return await cloud(upstream_path, body, request, pii, sub, + guard=guard, mode=mode) + return await local(upstream_path, body, request, config, disclosure) + + +def _with_model(payload: bytes) -> bytes: + """Rewrite the upstream model id to the one model id the router exposes.""" + try: + parsed = json.loads(payload) + except Exception: + return payload + parsed["model"] = MODEL_ID + return json.dumps(parsed).encode() + + +def _unauthorized(payload: bytes) -> bytes: + """Add the one thing the gateway's 401 does not say: how to fix it.""" + try: + parsed = json.loads(payload) + except Exception: + parsed = {"error": {"message": payload.decode(errors="replace")}} + message = (parsed.get("error") or {}).get("message") or "unauthorized" + parsed["error"] = { + "message": f"{message} — run `wally account login` to sign in again", + } + return json.dumps(parsed).encode() + + +async def cloud(path: str, body: dict, request: Request, + pii: dict | None = None, sub: bool = True, + guard: bool = False, mode: str = PII_MODE, attempt: int = 0): + config_cloud_model = read_config()["cloud_model"] + creds = await cloud_credentials() + console = creds.get("console_url", "") + if not console or not creds.get("access_token"): + STATS["errors"] += 1 + return JSONResponse( + {"error": {"message": "not signed in: no cloud credentials in the wally profile"}}, + status_code=503, + ) + if config_cloud_model: + body = {**body, "model": config_cloud_model} + url = f"{console.rstrip('/')}/{path}" + headers = { + "authorization": f"Bearer {creds['access_token']}", + "content-type": "application/json", + } + if pii and pii.get("total"): + headers["x-pls-pii"] = json.dumps(pii["files"], separators=(",", ":"))[:4000] + stream = bool(body.get("stream")) + + async def send(token: str): + return await http.send( + http.build_request( + "POST", url, json=body, + headers={**headers, "authorization": f"Bearer {token}"}, + ), + stream=stream, + ) + + try: + response = await send(creds["access_token"]) + if response.status_code == 401: + await response.aclose() + creds = await refresh_credentials(creds) + response = await send(creds["access_token"]) + except Exception as error: + STATS["errors"] += 1 + message = str(error) or type(error).__name__ + log({"event": "cloud_error", "error": message}) + return JSONResponse({"error": {"message": message}}, status_code=502) + + STATS["requests"] += 1 + STATS["last"] = {"lane": "cloud", "path": path, "status": response.status_code} + log({"event": "cloud", "path": path, "status": response.status_code, + "stream": stream, "content_type": response.headers.get("content-type"), + "keys": sorted(body)}) + + # An error, or a gateway that answered with JSON despite `stream`, is not + # an event stream. Relaying it as one makes dsh report a transport error + # ("Stream ended without finish_reason") instead of the real status. + content_type = response.headers.get("content-type", "") + if response.status_code >= 400 or "text/event-stream" not in content_type: + payload = await response.aread() + await response.aclose() + if response.status_code == 401: + payload = _unauthorized(payload) + elif response.status_code < 400: + payload = _with_model(payload) + return Response(payload, status_code=response.status_code, + media_type="application/json") + + if not stream: + payload = await response.aread() + await response.aclose() + try: + parsed = json.loads(payload) + usage = parsed.get("usage") or {} + STATS["cloud_tokens"] += int(usage.get("total_tokens") or 0) + payload = _with_model(payload) + except Exception: + pass + return Response( + payload, status_code=response.status_code, + media_type=response.headers.get("content-type", "application/json"), + ) + + # Loop ownership: file work must happen on the local lane. dsh keeps + # dispatching `read` from its own registry whatever tools we send, so the + # reply is held and checked: a file tool, a text answer, or an empty call is + # dropped and asked again. After GUARD_RETRIES the router emits the call. + if guard and stream: + buffered = b"" + async for piece in response.aiter_bytes(): + buffered += piece + await response.aclose() + if config_cloud_model: + buffered = buffered.replace( + f'"model":"{config_cloud_model}"'.encode(), f'"model":"{MODEL_ID}"'.encode() + ) + calls = parse_calls(buffered) + names = {call["name"] for call in calls.values()} + # A PII turn accepts the subagent call alone. A work turn also accepts + # bash/edit/write, but never a file tool: dsh would run it up here. + if pii and pii.get("total"): + clean = names == {PII_TOOL} + else: + clean = bool(names) and not (names & PARENT_DENIED) + if clean: + if patch_call_args(calls, body, pii or {"files": {}}, mode): + log({"event": "guard", "outcome": "patched", "attempt": attempt}) + return calls_stream(calls) + log({"event": "guard", "outcome": "delegated", "attempt": attempt}) + return Response(buffered, media_type="text/event-stream") + + STATS["guard_retries"] += 1 + log({"event": "guard", "outcome": "rejected", "attempt": attempt, + "saw": sorted(names)}) + if attempt >= GUARD_RETRIES: + STATS["guard_synth"] += 1 + log({"event": "guard", "outcome": "synthesised", "saw": sorted(names)}) + return synthetic_call(body, pii or {"files": {}}, mode) + + saw = ", ".join(sorted(names)) or "no tool call" + if pii and pii.get("total"): + wrong = (f"Wrong: you answered with {saw}. Call the `{PII_TOOL}` tool " + f"now, nothing else, and begin its prompt with " + f"`disclosure: {mode}`.") + else: + wrong = (f"Wrong: you answered with {saw}. The file work belongs to " + f"the `{PII_TOOL}` tool — call it now and begin its prompt " + f"with `disclosure: {mode}`.") + nudged = {**body, "messages": [*body.get("messages", []), { + "role": "user", "content": wrong, + }]} + return await cloud(path, nudged, request, pii, sub, + guard=True, mode=mode, attempt=attempt + 1) + + async def relay(): + # Raw bytes, not lines: a provider may split one `data:` event across + # several lines, and re-framing per line would cut it in half and lose + # the finish chunk. + seen_finish = False + try: + # aiter_bytes, not aiter_raw: raw yields still-compressed bytes when + # the gateway gzips, and we do not forward its content-encoding. + async for piece in response.aiter_bytes(): + if b"finish_reason" in piece and b"finish_reason\":null" not in piece: + seen_finish = True + if config_cloud_model: + piece = piece.replace( + f'"model":"{config_cloud_model}"'.encode(), + f'"model":"{MODEL_ID}"'.encode(), + ) + yield piece + if not seen_finish: + log({"event": "cloud_no_finish", "path": path}) + finally: + await response.aclose() + + return StreamingResponse(relay(), media_type="text/event-stream") + + +async def local(path: str, body: dict, request: Request, config: dict, disclosure: str): + global waiting + + overflow = False + if local_sem.locked(): + if waiting >= QUEUE_MAX: + overflow = True + else: + waiting += 1 + STATS["queued"] += 1 + if overflow: + STATS["overflow"] += 1 + response = await cloud(path, body, request) + response.headers["x-pls-overflow"] = "1" + return response + + try: + async with local_sem: + waiting = max(0, waiting - 1) + return await local_inner(path, body, request, config, disclosure) + finally: + pass + + +async def local_inner(path: str, body: dict, request: Request, config: dict, disclosure: str): + key = session_key(request, body) + local_sessions.add(key) + count = turns.get(key, 0) + 1 + turns[key] = count + STATS["local_turns"] += 1 + + messages = list(body.get("messages") or []) + disclosure, messages = take_disclosure(messages, disclosure) + body = {**body, "messages": messages} + inject_child_rules(body, disclosure) + client_stream = bool(body.get("stream")) + body = {**body, "stream": False} + capped = count >= config["max_turns"] + if capped: + STATS["cap_hits"] += 1 + messages.append({"role": "user", "content": WRAP_UP}) + body = {**body, "messages": messages, "tool_choice": "none"} + + try: + port = await ensure_model_server() + response = await http.post( + f"http://127.0.0.1:{port}/{path.lstrip('/')}", + json=body, + headers={"x-session-affinity": key}, + ) + except Exception as error: + STATS["errors"] += 1 + log({"event": "local_error", "error": str(error)}) + return JSONResponse({"error": {"message": str(error)}}, status_code=502) + + if response.status_code != 200: + STATS["errors"] += 1 + return Response(response.content, status_code=response.status_code, + media_type="application/json") + + try: + result = response.json() + except Exception: + STATS["errors"] += 1 + log({"event": "local_bad_body", "status": response.status_code, + "body": response.text[:400]}) + return Response(response.content, status_code=502, + media_type="application/json") + choice = (result.get("choices") or [{}])[0] + message = choice.get("message") or {} + calls = message.get("tool_calls") or [] + usage = result.get("usage") or {} + STATS["local_tokens"] += int(usage.get("total_tokens") or 0) + + # Disclosure only applies to a final answer; a tool call must pass through + # intact or the child cannot continue. + if not calls and message.get("content"): + if disclosure == "local_only": + message["content"] = WITHHELD + STATS["disclosure"]["local_only"] += 1 + elif disclosure == "title": + first = message["content"].strip().splitlines()[0] + message["content"] = short_paths(redact(" ".join(first.split()[:12]))) + STATS["disclosure"]["title"] += 1 + elif disclosure == "summary": + # A short answer summarises into something vaguer than itself. + if len(message["content"]) > 400: + message["content"] = await summarise(message["content"]) + message["content"] = short_paths(redact(message["content"])) + STATS["disclosure"]["summary"] += 1 + choice["message"] = message + + log({"event": "local_done", "turns": count, "capped": capped, + "disclosure": disclosure, "prompt_tokens": usage.get("prompt_tokens"), + "completion_tokens": usage.get("completion_tokens"), + "calls": len(calls)}) + STATS["requests"] += 1 + STATS["last"] = { + "lane": "local", "path": path, "disclosure": disclosure, + "turns": count, "capped": capped, + "prompt_tokens": usage.get("prompt_tokens"), + "completion_tokens": usage.get("completion_tokens"), + } + log({"event": "local", **STATS["last"]}) + + if client_stream: + want_usage = bool((body.get("stream_options") or {}).get("include_usage")) + return as_stream(result, want_usage) + return JSONResponse(result) + + +# -------------------------------------------------------------------------- +# lifecycle +# -------------------------------------------------------------------------- + + +def cleanup() -> None: + global shutting_down + if shutting_down: + return + shutting_down = True + kill_model_server() + try: + PID_PATH.unlink() + except Exception: + pass + + +async def watch_parent() -> None: + while True: + await asyncio.sleep(2) + alive = True + if explicit_parent: + try: + os.kill(explicit_parent, 0) + except ProcessLookupError: + alive = False + except PermissionError: + pass + elif parent_pid != 1: + alive = os.getppid() == parent_pid + if not alive: + log({"event": "parent_gone"}) + cleanup() + os._exit(0) + + +def on_signal(signum, _frame): + cleanup() + os._exit(0) + + +def main() -> None: + CONFIG_DIR.mkdir(parents=True, exist_ok=True) + if not CONFIG_PATH.exists(): + CONFIG_PATH.write_text(json.dumps({"mode": DEFAULT_MODE, "max_turns": DEFAULT_MAX_TURNS})) + PID_PATH.write_text(str(os.getpid())) + atexit.register(cleanup) + signal.signal(signal.SIGTERM, on_signal) + signal.signal(signal.SIGINT, on_signal) + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sock.bind(("127.0.0.1", 0)) + sock.listen(128) + port = sock.getsockname()[1] + print(json.dumps({"port": port}), flush=True) + + async def serve(): + asyncio.create_task(watch_parent()) + server = uvicorn.Server(uvicorn.Config(app, log_level="warning", lifespan="off")) + await server.serve(sockets=[sock]) + + asyncio.run(serve()) + + +if __name__ == "__main__": + main() diff --git a/pls/requirements.in b/pls/requirements.in new file mode 100644 index 00000000..2227c092 --- /dev/null +++ b/pls/requirements.in @@ -0,0 +1,4 @@ +fastapi +uvicorn +httpx +mlx-vlm diff --git a/pls/requirements.lock b/pls/requirements.lock new file mode 100644 index 00000000..c11b434a --- /dev/null +++ b/pls/requirements.lock @@ -0,0 +1,249 @@ +# This file was autogenerated by uv via the following command: +# uv pip compile requirements.in --python-version 3.12 --universal -o requirements.lock +aiohappyeyeballs==2.7.1 + # via aiohttp +aiohttp==3.14.5 + # via fsspec +aiosignal==1.4.0 + # via aiohttp +annotated-doc==0.0.5 + # via + # fastapi + # typer +annotated-types==0.8.0 + # via pydantic +anyio==4.15.1 + # via + # httpx + # httpx2 + # starlette +attrs==26.1.0 + # via aiohttp +certifi==2026.10.23 + # via + # httpcore + # httpx + # requests +cffi==2.1.1 + # via + # cryptography + # miniaudio + # sounddevice +charset-normalizer==3.5.2 + # via requests +click==8.5.0 + # via + # huggingface-hub + # uvicorn +colorama==0.4.6 ; sys_platform == 'win32' + # via + # tqdm + # typer +cryptography==50.0.2 + # via mlx-vlm +datasets==5.1.0 + # via mlx-vlm +dill==0.4.1 + # via + # datasets + # multiprocess +fastapi==0.162.0 + # via + # -r requirements.in + # mlx-vlm +filelock==4.2.4 + # via + # datasets + # huggingface-hub +frozenlist==1.8.0 + # via + # aiohttp + # aiosignal +fsspec==2026.7.0 + # via + # datasets + # huggingface-hub +h11==0.16.0 + # via + # httpcore + # httpcore2 + # uvicorn +hf-xet==1.8.0 ; platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64' + # via huggingface-hub +httpcore==1.0.9 + # via httpx +httpcore2==2.16.0 ; sys_platform != 'emscripten' + # via httpx2 +httpx==0.28.1 + # via -r requirements.in +httpx2==2.16.0 + # via huggingface-hub +httpx2-jsfetch==1.0 ; sys_platform == 'emscripten' + # via httpx2 +huggingface-hub==2.4.0 + # via + # datasets + # mlx-audio + # tokenizers + # transformers +idna==3.20 + # via + # anyio + # httpx + # httpx2 + # requests + # yarl +jinja2==3.1.6 + # via + # mlx-audio + # mlx-vlm + # transformers +llguidance==1.9.1 + # via mlx-vlm +markdown-it-py==4.2.0 + # via rich +markupsafe==3.0.4 + # via jinja2 +mdurl==0.1.2 + # via markdown-it-py +miniaudio==1.71 + # via + # mlx-audio + # mlx-vlm +mlx==0.32.4 + # via + # mlx-audio + # mlx-vlm +mlx-audio==0.6.3 + # via mlx-vlm +mlx-metal==0.32.4 ; sys_platform == 'darwin' + # via mlx +mlx-vlm==0.7.11 + # via -r requirements.in +multidict==7.2.1 + # via + # aiohttp + # yarl +multiprocess==0.70.19 + # via datasets +numpy==2.5.4 + # via + # datasets + # mlx-audio + # mlx-vlm + # opencv-python + # pandas + # scipy + # transformers +opencv-python==5.0.0.93 + # via mlx-vlm +opentelemetry-api==1.45.2 + # via fastapi +packaging==26.3 + # via + # datasets + # huggingface-hub + # transformers +pandas==3.1.0 + # via datasets +pillow==13.0.0 + # via mlx-vlm +propcache==0.5.4 + # via + # aiohttp + # yarl +pyarrow==26.0.0 + # via datasets +pycparser==3.12 ; implementation_name != 'PyPy' + # via cffi +pydantic==2.14.2 + # via fastapi +pydantic-core==2.50.2 + # via pydantic +pygments==2.21.0 + # via rich +python-dateutil==3.0.0 + # via pandas +python-multipart==0.0.32 + # via mlx-vlm +pyyaml==6.0.3 + # via + # datasets + # huggingface-hub + # transformers +regex==2026.9.29 + # via transformers +requests==2.34.2 + # via mlx-vlm +rich==15.0.0 + # via typer +safetensors==0.8.0 + # via transformers +scipy==1.18.1 + # via mlx-audio +sentencepiece==0.2.2 + # via + # mlx-audio + # mlx-vlm +shellingham==1.5.4 + # via typer +six==1.17.0 + # via python-dateutil +sounddevice==0.5.6 + # via mlx-audio +starlette==1.10.0 + # via + # fastapi + # mlx-vlm +tokenizers==0.23.3 + # via transformers +tqdm==4.70.1 + # via + # datasets + # huggingface-hub + # mlx-audio + # mlx-vlm + # transformers +transformers==5.22.1 + # via + # mlx-audio + # mlx-vlm +truststore==0.10.5 ; sys_platform != 'emscripten' + # via + # httpcore2 + # httpx2 +typer==0.27.3 + # via transformers +typing-extensions==4.16.0 + # via + # aiohttp + # aiosignal + # anyio + # fastapi + # httpx2 + # huggingface-hub + # opentelemetry-api + # pydantic + # pydantic-core + # starlette + # typing-inspection +typing-inspection==0.4.4 + # via + # fastapi + # pydantic +tzdata==2026.6 + # via + # pandas + # python-dateutil +urllib3==2.8.0 + # via requests +uvicorn==0.54.0 + # via + # -r requirements.in + # mlx-vlm +websockets==17.3 + # via mlx-vlm +xxhash==4.0.2 + # via datasets +yarl==1.25.1 + # via aiohttp diff --git a/pls/test_pls.py b/pls/test_pls.py new file mode 100644 index 00000000..adb58823 --- /dev/null +++ b/pls/test_pls.py @@ -0,0 +1,500 @@ +"""Router tests that never touch the model or the network. + +The model server and the cloud are both replaced at the module boundary, so +these run in a second. +""" + +import json +import os +import socket as socket_mod +import tempfile +import unittest +from pathlib import Path + +os.environ.setdefault("WALLY_PROFILE_DIR", tempfile.mkdtemp()) + +import pls # noqa: E402 +from fastapi.testclient import TestClient # noqa: E402 + + +class FakeResponse: + def __init__(self, payload, status=200): + self._payload = payload + self.status_code = status + self.content = json.dumps(payload).encode() + self.text = self.content.decode() + self.headers = {"content-type": "application/json"} + + def json(self): + return self._payload + + async def aread(self): + return self.content + + async def aclose(self): + pass + + +def completion(content="answer", calls=None): + message = {"role": "assistant", "content": content} + if calls: + message["tool_calls"] = calls + return { + "id": "x", + "created": 0, + "model": "m", + "choices": [{"index": 0, "message": message, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + } + + +class RouterTest(unittest.TestCase): + def setUp(self): + self.dir = Path(tempfile.mkdtemp()) + self.config = self.dir / "config.json" + self.config.write_text(json.dumps({"mode": "hybrid", "max_turns": 20})) + self.creds = self.dir / "credentials.json" + self.creds.write_text(json.dumps({"console_url": "http://cloud", "access_token": "t"})) + + pls.CONFIG_PATH = self.config + pls.CREDENTIALS_PATH = self.creds + pls.turns.clear() + pls.ENTITLEMENT_SOCKET = "" + pls.FORCE_DELEGATION = False + pls.waiting = 0 + pls.local_sem = __import__("asyncio").Semaphore(1) + + self.local_bodies = [] + self.client = TestClient(pls.app) + + async def fake_server(): + return 1 + + async def fake_post(url, json=None, headers=None): + self.local_bodies.append(json) + return FakeResponse(completion("local answer")) + + async def fake_creds(): + return {"console_url": "http://cloud", "access_token": "t"} + + pls.ensure_model_server = fake_server + pls.http.post = fake_post + pls.cloud_credentials = fake_creds + + def mode(self, value): + self.config.write_text(json.dumps({"mode": value, "max_turns": 20})) + + def post(self, path, body=None): + return self.client.post( + path, + json=body or {"model": "x", "messages": [{"role": "user", "content": "hi"}]}, + headers={"x-session-id": "s"}, + ) + + def test_local_lane_returns_the_model_answer(self): + response = self.post("/local/v1/chat/completions") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["choices"][0]["message"]["content"], "local answer") + + def test_local_only_withholds_the_answer(self): + response = self.post("/local-only/v1/chat/completions") + self.assertEqual(response.json()["choices"][0]["message"]["content"], pls.WITHHELD) + + def test_tool_calls_pass_through_undisclosed(self): + calls = [{"id": "c", "type": "function", "function": {"name": "f", "arguments": "{}"}}] + + async def with_calls(url, json=None, headers=None): + return FakeResponse(completion(None, calls)) + + pls.http.post = with_calls + response = self.post("/local-only/v1/chat/completions") + message = response.json()["choices"][0]["message"] + self.assertEqual(message["tool_calls"], calls) + self.assertIsNone(message["content"]) + + def test_cap_appends_wrap_up_and_disables_tools(self): + self.config.write_text(json.dumps({"mode": "hybrid", "max_turns": 1})) + self.post("/local/v1/chat/completions") + sent = self.local_bodies[-1] + self.assertEqual(sent["tool_choice"], "none") + self.assertEqual(sent["messages"][-1]["content"], pls.WRAP_UP) + + def test_cloud_mode_forces_the_cloud_lane(self): + self.mode("cloud") + pls.http.send = _fake_send(completion("cloud answer")) + response = self.post("/local/v1/chat/completions") + self.assertEqual(response.json()["choices"][0]["message"]["content"], "cloud answer") + self.assertEqual(self.local_bodies, []) + + def test_local_mode_forces_the_local_lane(self): + self.mode("local") + response = self.post("/v1/chat/completions") + self.assertEqual(response.json()["choices"][0]["message"]["content"], "local answer") + + def test_unknown_mode_falls_back_to_hybrid(self): + self.config.write_text("not json") + self.assertEqual(pls.read_config()["mode"], "hybrid") + + def test_pii_counts_are_per_file_and_never_carry_values(self): + found = pls.scan_pii([{"role": "tool", "content": + "/work/a.csv: alice@x.com 4111 1111 1111 1111\n/work/b.csv: bob@y.com\n"}]) + self.assertEqual(found["files"]["/work/a.csv"], {"email": 1, "phone": 1}) + self.assertEqual(found["files"]["/work/b.csv"], {"email": 1}) + self.assertEqual(found["total"], 3) + self.assertNotIn("@", json.dumps(found)) + + def test_pii_ignores_text_without_pii(self): + self.assertEqual(pls.scan_pii([{"role": "user", "content": "hello"}]), {"files": {}, "total": 0}) + + def test_no_subscription_forces_the_cloud_lane(self): + self.mode("local") + pls.ENTITLEMENT_SOCKET = self.socket(False) + pls.premium_cache.update(value=False, at=0.0) + pls.http.send = _fake_send(completion("cloud answer")) + response = self.post("/local/v1/chat/completions") + self.assertEqual(response.json()["choices"][0]["message"]["content"], "cloud answer") + self.assertEqual(self.local_bodies, []) + + def test_subscription_allows_the_local_lane(self): + pls.ENTITLEMENT_SOCKET = self.socket(True) + pls.premium_cache.update(value=True, at=0.0) + response = self.post("/local/v1/chat/completions") + self.assertEqual(response.json()["choices"][0]["message"]["content"], "local answer") + + def test_shape_drops_parent_file_tools_and_forces_delegation_on_work(self): + pls.FORCE_DELEGATION = True + body = { + "messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "read /w/a.csv"}], + "tools": [{"type": "function", "function": {"name": n}} for n in ("read", "grep", "bash", "subagent")], + } + remaining, removed, forced, _ = pls.shape_hybrid(body) + self.assertEqual(remaining, 2) + self.assertEqual(removed, ["grep", "read"]) + self.assertTrue(forced) + self.assertEqual(body["tool_choice"]["function"]["name"], "subagent") + + def test_shape_forces_on_a_later_user_turn_too(self): + pls.FORCE_DELEGATION = True + body = { + "messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "read a"}, + {"role": "assistant", "content": "ok"}, {"role": "user", "content": "now grep b"}], + "tools": [{"type": "function", "function": {"name": "subagent"}}], + } + _, _, forced, _ = pls.shape_hybrid(body) + self.assertTrue(forced) + + def test_shape_respects_an_existing_pin(self): + pls.FORCE_DELEGATION = True + body = {"messages": [{"role": "user", "content": "read a"}], + "tools": [{"type": "function", "function": {"name": "subagent"}}], + "tool_choice": {"type": "function", "function": {"name": "subagent"}}} + _, _, forced, _ = pls.shape_hybrid(body) + self.assertFalse(forced) + + def test_shape_leaves_a_greeting_alone(self): + pls.FORCE_DELEGATION = True + body = {"messages": [{"role": "user", "content": "hi"}], + "tools": [{"type": "function", "function": {"name": "subagent"}}]} + _, _, forced, _ = pls.shape_hybrid(body) + self.assertFalse(forced) + self.assertNotIn("tool_choice", body) + + def test_pii_forces_delegation_even_without_a_work_verb(self): + pls.FORCE_DELEGATION = True + body = {"messages": [{"role": "user", "content": "here"}], + "tools": [{"type": "function", "function": {"name": "subagent"}}]} + _, _, forced, by_pii = pls.shape_hybrid(body, {"files": {"/w/a.csv": {"email": 1}}, "total": 1}) + self.assertTrue(forced) + self.assertTrue(by_pii) + + def test_the_delegation_prompt_goes_on_the_system_message_once(self): + body = {"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "x"}]} + self.assertTrue(pls.inject_delegation(body, {"files": {"/w/a.csv": {"email": 1}}, "total": 1})) + self.assertFalse(pls.inject_delegation(body)) + self.assertIn("cloud half", body["messages"][0]["content"]) + + def test_the_child_prompt_can_name_the_disclosure_mode(self): + mode, messages = pls.take_disclosure( + [{"role": "user", "content": "disclosure: title\nlist the files"}], "summary") + self.assertEqual(mode, "title") + self.assertEqual(messages[0]["content"], "list the files") + + def test_a_prompt_without_a_marker_keeps_the_path_mode(self): + mode, messages = pls.take_disclosure([{"role": "user", "content": "hi"}], "local_only") + self.assertEqual(mode, "local_only") + self.assertEqual(messages[0]["content"], "hi") + + def test_title_mode_returns_one_line(self): + self.mode("local") + pls.http.post = _fake_return(completion("First line here\nsecond line\nthird")) + response = self.post("/local/v1/chat/completions", + {"model": "x", "messages": [{"role": "user", "content": "disclosure: title\ngo"}]}) + self.assertEqual(response.json()["choices"][0]["message"]["content"], "First line here") + + def test_summary_redacts_the_values_it_keeps(self): + self.mode("local") + blurb = "Row 1 Maya Thornton maya@x.com (555) 010-0101 1988-04-12 " + "pad " * 90 + pls.http.post = _fake_return(completion(blurb)) + response = self.post("/local/v1/chat/completions") + content = response.json()["choices"][0]["message"]["content"] + self.assertNotIn("maya@x.com", content) + self.assertIn("[email]", content) + + def test_disclosure_none_keeps_the_values(self): + self.mode("local") + pls.http.post = _fake_return(completion("maya@x.com")) + response = self.post("/local/v1/chat/completions", + {"model": "x", "messages": [{"role": "user", "content": "disclosure: none\ngo"}]}) + self.assertIn("maya@x.com", response.json()["choices"][0]["message"]["content"]) + + def test_the_child_is_told_the_disclosure_ceiling(self): + self.mode("local") + self.post("/local/v1/chat/completions") + system = [m for m in self.local_bodies[-1]["messages"] if m["role"] == "system"] + self.assertEqual(system, []) # no system message in this fixture + body = {"messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "x"}]} + pls.inject_child_rules(body, "title") + self.assertIn("one line", body["messages"][0]["content"]) + + def test_home_is_shortened_in_a_summary(self): + self.mode("local") + pls.http.post = _fake_return(completion(str(__import__("pathlib").Path.home()) + "/w/a.csv ok")) + response = self.post("/local/v1/chat/completions") + self.assertIn("~/w/a.csv", response.json()["choices"][0]["message"]["content"]) + + def test_models_lists_only_the_hybrid_id(self): + data = self.client.get("/v1/models").json()["data"] + self.assertEqual([m["id"] for m in data], [pls.MODEL_ID]) + + # -- PII guard --------------------------------------------------------- + + def test_the_instruction_names_the_file_the_class_and_the_mode(self): + text = pls.pii_instruction({"files": {"/w/a.csv": {"email": 2}}, "total": 2}, "local_only") + self.assertIn("/w/a.csv", text) + self.assertIn("email", text) + self.assertIn("disclosure: local_only", text) + self.assertIn("subagent", text) + + def test_parse_calls_joins_arguments_split_across_chunks(self): + body = ( + 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":' + '{"name":"subagent","arguments":"{\\"prompt\\":"}}]}}]}\n\n' + 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":' + '{"arguments":"\\"go\\"}"}}]}}]}\n\n' + "data: [DONE]\n\n" + ).encode() + calls = pls.parse_calls(body) + self.assertEqual(calls[0]["name"], "subagent") + self.assertEqual(json.loads(calls[0]["arguments"]), {"prompt": "go"}) + + def test_a_pii_turn_gets_the_instruction_and_a_subagent_call_is_kept(self): + sent = [] + full = json.dumps({"description": "Read the file", "prompt": "disclosure: summary\nread it"}) + pls.http.send = _fake_send_sse(sent, ("subagent", full)) + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv, maya@x.com"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("read", "grep", "subagent")], + }) + self.assertEqual(len(sent), 1) + self.assertIn("disclosure: local_only", sent[0]["messages"][-1]["content"]) + call = pls.parse_calls(response.content)[0] + self.assertEqual(json.loads(call["arguments"])["prompt"], "disclosure: summary\nread it") + + def test_an_empty_subagent_call_gets_its_arguments_filled(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "subagent") + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv, maya@x.com"}], + "tools": [{"type": "function", "function": {"name": "subagent"}}], + }) + self.assertEqual(len(sent), 1) + prompt = json.loads(pls.parse_calls(response.content)[0]["arguments"])["prompt"] + self.assertTrue(prompt.startswith("disclosure: local_only")) + self.assertIn("/w/a.csv", prompt) + + def test_a_read_call_is_dropped_and_asked_again(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "read", "subagent") + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv, maya@x.com"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("read", "subagent")], + }) + self.assertEqual(len(sent), 2) + self.assertIn("Wrong: you answered with read", sent[1]["messages"][-1]["content"]) + self.assertIn('"name": "subagent"', response.text) + + def test_the_router_emits_the_call_when_the_model_never_does(self): + sent = [] + pls.http.send = _fake_send_sse(sent, None, None, None) + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv, maya@x.com"}], + "tools": [{"type": "function", "function": {"name": "subagent"}}], + }) + self.assertEqual(len(sent), pls.GUARD_RETRIES + 1) + call = pls.parse_calls(response.content)[0] + self.assertEqual(call["name"], "subagent") + prompt = json.loads(call["arguments"])["prompt"] + self.assertTrue(prompt.startswith("disclosure: local_only")) + self.assertIn("/w/a.csv", prompt) + self.assertIn("maya@x.com", prompt) + + def test_a_subagent_call_beside_a_read_is_rejected(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "read+subagent", "subagent") + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv, maya@x.com"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("read", "subagent")], + }) + self.assertEqual(len(sent), 2) + self.assertEqual(pls.parse_calls(response.content)[0]["name"], "subagent") + + def test_a_turn_without_pii_gets_no_instruction(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "bash") + self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("bash", "subagent")], + }) + self.assertEqual(len(sent), 1) + self.assertNotIn("disclosure:", sent[0]["messages"][-1]["content"]) + + # -- the same guard on a plain work turn ------------------------------- + + def test_a_bash_only_reply_is_accepted_on_a_work_turn(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "bash") + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv and run it"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("bash", "read", "subagent")], + }) + self.assertEqual(len(sent), 1) + self.assertEqual(pls.parse_calls(response.content)[0]["name"], "bash") + + def test_a_read_call_is_rejected_on_a_work_turn(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "read", "subagent") + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("bash", "read", "subagent")], + }) + self.assertEqual(len(sent), 2) + self.assertIn("Wrong: you answered with read", sent[1]["messages"][-1]["content"]) + self.assertEqual(pls.parse_calls(response.content)[0]["name"], "subagent") + + def test_a_stubborn_work_turn_is_synthesised_in_summary_mode(self): + sent = [] + pls.http.send = _fake_send_sse(sent, "read") + response = self.post("/v1/chat/completions", { + "stream": True, + "messages": [{"role": "user", "content": "read /w/a.csv"}], + "tools": [{"type": "function", "function": {"name": n}} + for n in ("read", "subagent")], + }) + self.assertEqual(len(sent), pls.GUARD_RETRIES + 1) + prompt = json.loads(pls.parse_calls(response.content)[0]["arguments"])["prompt"] + self.assertTrue(prompt.startswith("disclosure: summary")) + self.assertIn("/w/a.csv", prompt) + + + def socket(self, sub): + """A real unix socket answering like wally, so the parser is exercised.""" + path = str(self.dir / "entitlement.sock") + try: + os.unlink(path) + except FileNotFoundError: + pass + server = socket_mod.socket(socket_mod.AF_UNIX, socket_mod.SOCK_STREAM) + server.bind(path) + server.listen(4) + + def serve(): + while True: + try: + conn, _ = server.accept() + except OSError: + return + conn.recv(256) + body = json.dumps({"sub": sub}).encode() + conn.sendall(b"HTTP/1.1 200 OK\r\ncontent-length: " + str(len(body)).encode() + b"\r\n\r\n" + body) + conn.close() + + import threading + + threading.Thread(target=serve, daemon=True).start() + return path + + +class FakeStream: + def __init__(self, body: bytes, status=200): + self._body = body + self.status_code = status + self.headers = {"content-type": "text/event-stream"} + self.content = body + self.text = body.decode() + + async def aiter_bytes(self): + yield self._body + + async def aread(self): + return self._body + + async def aclose(self): + pass + + +def _sse(name, args="{}"): + parts = [] + if name: + for index, one in enumerate(name.split("+")): + parts.append("data: " + json.dumps({"choices": [{"index": 0, "delta": {"tool_calls": [ + {"index": index, "function": {"name": one, "arguments": args}}]}}]}) + "\n\n") + parts.append("data: " + json.dumps({"choices": [{"index": 0, "delta": {}, + "finish_reason": "tool_calls" if name else "stop"}]}) + "\n\n") + parts.append("data: [DONE]\n\n") + return "".join(parts).encode() + + +def _fake_send_sse(sent, *replies): + """Answer successive cloud sends with these tool names; the last repeats.""" + queue = list(replies) + + async def send(request, stream=False): + sent.append(json.loads(request.content)) + reply = queue.pop(0) if len(queue) > 1 else (queue[0] if queue else None) + if isinstance(reply, tuple): + return FakeStream(_sse(*reply)) + return FakeStream(_sse(reply)) + + return send + + +def _fake_return(payload): + async def post(url, json=None, headers=None): + return FakeResponse(payload) + + return post + + +def _fake_send(payload): + async def send(request, stream=False): + return FakeResponse(payload) + + return send + + +if __name__ == "__main__": + unittest.main() diff --git a/src/app.rs b/src/app.rs index 2c8350f1..82eb77a6 100644 --- a/src/app.rs +++ b/src/app.rs @@ -77,6 +77,7 @@ pub fn configure_app(app: &mut App) { crate::commands::register_chatgpt(app); crate::commands::register_openwork(app); crate::commands::register_harness(app); // coding agents + crate::commands::register_pls(app); // hybrid router, development entry crate::commands::register_default_models(app); crate::commands::register_account(app); // account login/logout/whoami/usage @@ -225,7 +226,7 @@ fn root_flags_before_passthrough(argv: &[String]) -> Vec<&str> { /// `--context-window` take a following value; the rest are booleans. The `=` /// forms carry their value inline. fn consumes_following_value(token: &str) -> bool { - token == "-m" || token == "--model" || token == "--context-window" + token == "-m" || token == "--model" || token == "--context-window" || token == "--cloud-model" } fn is_wally_flag(token: &str) -> bool { @@ -238,6 +239,9 @@ fn is_wally_flag(token: &str) -> bool { || token == "--serve" || token == "--restore" || token == "--cloud" + || token == "--hybrid" + || token == "--cloud-model" + || token.starts_with("--cloud-model=") || token == "-h" || token == "--help" } @@ -495,6 +499,40 @@ mod tests { tokens.iter().map(|t| t.to_string()).collect() } + #[test] + fn hybrid_flags_stay_on_wally_side_of_the_passthrough_split() { + // `--hybrid` and `--cloud-model` are wally's own; without them in the + // wally-flag list a `--` is inserted before them and dsh rejects them. + let split = split_passthrough_argv(&argv(&[ + "wally", + "deepseek", + "--hybrid", + "-m", + "qwen3-4b", + "--cloud-model", + "glm-5.3-flash", + "do", + "the", + "thing", + ])); + assert_eq!( + split, + argv(&[ + "wally", + "deepseek", + "--hybrid", + "-m", + "qwen3-4b", + "--cloud-model", + "glm-5.3-flash", + "--", + "do", + "the", + "thing", + ]) + ); + } + #[test] fn update_notice_shows_on_help_page_commands_only() { for name in [ diff --git a/src/commands/cmd_harness.rs b/src/commands/cmd_harness.rs index 5c6bf9a6..30f32cbc 100644 --- a/src/commands/cmd_harness.rs +++ b/src/commands/cmd_harness.rs @@ -200,6 +200,17 @@ pub fn register_harness(app: &mut App) { ValueType::Text, "A model on this machine, or a hosted one from your account", ); + if agent.id == "deepseek" { + command.add_flag( + "--hybrid", + "Route the parent to the cloud and subagents to a local model", + ); + command.add_option( + "--cloud-model", + ValueType::Text, + "The cloud model the parent lane uses (defaults to your default model)", + ); + } command .add_option("args", ValueType::Text, "Passed through to the tool") .multi(); @@ -213,12 +224,18 @@ pub fn register_harness(app: &mut App) { if !harness::ensure_installed(agent.command) { return 127; } - harness::launch_agent( - &agent, - &resolve_default_model(&p.get_str("--model").unwrap_or_default(), g.no_color), - &p.get_strs("args"), - g, - ) + if agent.id == "deepseek" && p.flag("--hybrid") { + // `-m` names the *local* model here, so an absent one must not + // be filled with the cloud default. + let local = p.get_str("--model").unwrap_or_default(); + let cloud = p + .get_str("--cloud-model") + .unwrap_or_else(|| resolve_default_model("", g.no_color)); + return harness::launch_deep_seek_hybrid(&local, &cloud, &p.get_strs("args"), g); + } + let model = + resolve_default_model(&p.get_str("--model").unwrap_or_default(), g.no_color); + harness::launch_agent(&agent, &model, &p.get_strs("args"), g) }); } } diff --git a/src/commands/cmd_pls.rs b/src/commands/cmd_pls.rs new file mode 100644 index 00000000..6dd2f011 --- /dev/null +++ b/src/commands/cmd_pls.rs @@ -0,0 +1,48 @@ +//! `wally pls` — run the hybrid router in the foreground, for development. +//! +//! The harness launcher starts the router itself; this command exists so the +//! router can be exercised without a harness in front of it. + +use crate::cli::{App, ValueType}; +use crate::harness::pls; +use crate::io::output as out; + +pub fn register_pls(app: &mut App) { + let cmd = app.add_subcommand("pls", "Run the hybrid router in the foreground"); + cmd.add_option( + "-m,--model", + ValueType::Text, + "Directory of the local MLX model (defaults to $PLS_MODEL)", + ); + cmd.callback(|parsed, _options| { + let model = parsed + .get_str("--model") + .or_else(|| std::env::var("PLS_MODEL").ok()) + .unwrap_or_default(); + if model.is_empty() { + out::error_line("--model is required (or set PLS_MODEL)"); + return 2; + } + if !std::path::Path::new(&model).is_dir() { + out::error_line(&format!("{model} is not a directory")); + return 2; + } + let Some(router) = pls::start(&model) else { + return 1; + }; + let mut router = router; + out::status_line(&format!( + "mode file: {} (edit it to switch lanes)", + pls::config_file().display() + )); + out::status_line("press ctrl-c to stop"); + // The router owns its own lifetime; park until it exits. + loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + if !router.running() { + break; + } + } + 0 + }); +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index b54f0529..bb5d64e0 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -37,6 +37,7 @@ pub mod cmd_lora; pub mod cmd_maintenance; pub mod cmd_models; pub mod cmd_openwork; +pub mod cmd_pls; pub mod cmd_pull; pub mod cmd_rag; pub mod cmd_rerank; @@ -81,6 +82,7 @@ pub use cmd_lora::register_lora; pub use cmd_maintenance::{register_help, register_uninstall, run_uninstall}; pub use cmd_models::{register_models, register_models_aliases}; pub use cmd_openwork::register_openwork; +pub use cmd_pls::register_pls; pub use cmd_pull::{configure_models_download, pull_model_flow}; pub use cmd_rag::register_rag; pub use cmd_rerank::register_rerank; diff --git a/src/harness/agents.rs b/src/harness/agents.rs index b76c974b..b35d26eb 100644 --- a/src/harness/agents.rs +++ b/src/harness/agents.rs @@ -8,12 +8,14 @@ use serde_json::{json, Value}; use crate::account::{self, ConsoleClient}; use crate::bootstrap::GlobalOptions; +use crate::catalog; use crate::io::json::{dump, dump_pretty}; use crate::io::output as out; use super::catalog_models::{catalog_models_for, CatalogModel}; use super::declared_harness::{harness_header_value, DeclaredHarness, HARNESS_HEADER}; use super::harness::{launch, release, resolve, Endpoint}; +use super::local_models::local_models; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Handoff { @@ -1428,6 +1430,228 @@ pub fn build_deep_seek_patch(llm_config: &str, model: &str) -> String { ) } +/// The model id the router exposes. One id on both providers, so the picker +/// shows one model and the lane is decided by the provider, not the id. +pub const HYBRID_MODEL_ID: &str = "Hybird-Wally-0.1"; + +/// The two-provider `llm-pi-ai` config. Both providers carry the same model; +/// `wally` is the parent lane (cloud) and `wally-local` the child lane (local). +fn build_hybrid_llm_config(base_url: &str, key_variable: &str) -> String { + let model = json!({ + "id": HYBRID_MODEL_ID, + "name": HYBRID_MODEL_ID, + "input": ["text"], + "contextWindow": 57344, + "maxTokens": 8192, + "reasoningEfforts": false, + }); + let provider = |name: &str, path: &str| { + json!({ + "displayName": name, + "api": "openai-completions", + "baseURL": format!("{base_url}{path}"), + "apiKeyEnv": key_variable, + "models": [model.clone()], + }) + }; + dump(&json!({ + "providers": { + PROVIDER_ID: provider("Wally", "/v1"), + "wally-local": provider("Wally (local)", "/local/v1"), + } + })) +} + +/// The patch for a hybrid launch: both providers, the parent on the cloud +/// lane, and every subagent pinned to the local lane. +fn build_hybrid_patch(llm_config: &str) -> String { + let mut patch = format!( + "- id: llm-pi-ai\n config: {llm_config}\n\ + - id: agent-default-model\n config:\n provider: {PROVIDER_ID}\n model: {}\n\ + - id: tool-subagent\n disabled: false\n config:\n provider: spawn\n agentOptions:\n provider: wally-local\n model: {}\n", + yaml_single_quoted(HYBRID_MODEL_ID), + yaml_single_quoted(HYBRID_MODEL_ID), + ); + // The web profile mounts its own copy of the tool from the `standard` + // agent preset, so the row above is inert there. The preset is a root + // entry, and a patch replaces its whole config, so its plugin list is + // copied from the installed preset with the child route injected. + if let Some(preset) = hybrid_preset_patch() { + patch.push_str(&preset); + } + patch +} + +/// `preset-standard` with `agentOptions` added to its `tool-subagent` row, or +/// `None` when the installed preset cannot be read or no longer has that row. +fn hybrid_preset_patch() -> Option { + let dsh = find_on_path("dsh")?; + let root = dsh.canonicalize().ok()?.parent()?.parent()?.to_path_buf(); + let file = root.join("node_modules/@deepseek-ai/dsh-web-app/presets/standard.patch.yml"); + let text = std::fs::read_to_string(file).ok()?; + + let mut block: Vec<&str> = Vec::new(); + let mut inside = false; + for line in text.lines() { + if line.trim_start().starts_with("- id: preset-standard") { + inside = true; + continue; + } + if inside { + let indent = line.len() - line.trim_start().len(); + if !line.trim().is_empty() && indent <= 4 { + break; + } + block.push(line); + } + } + if !block.iter().any(|line| line.trim() == "- id: tool-subagent") { + return None; + } + + let mut out = String::from("- id: preset-standard\n"); + let mut injected = false; + for line in block { + let stripped = line.strip_prefix(" ").unwrap_or(line); + let trimmed = stripped.trim_start(); + if trimmed.starts_with("name:") && !injected && out.ends_with("- id: preset-standard\n") { + continue; + } + out.push_str(stripped); + out.push('\n'); + if !injected && trimmed == "config:" && out.contains("- id: tool-subagent\n") { + let indent = stripped.len() - trimmed.len(); + let pad = " ".repeat(indent + 2); + out.push_str(&format!( + "{pad}agentOptions:\n{pad} provider: wally-local\n{pad} model: {}\n", + yaml_single_quoted(HYBRID_MODEL_ID), + )); + injected = true; + } + } + injected.then_some(out) +} + +fn find_on_path(tool: &str) -> Option { + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path) + .map(|dir| dir.join(tool)) + .find(|candidate| candidate.is_file()) +} + +/// The first downloaded MLX model certified for a harness, as a catalog id. +fn default_hybrid_model(options: &GlobalOptions) -> Option { + let env = crate::bootstrap::bootstrap(options).ok()?; + local_models(&env.home) + .into_iter() + .filter(|candidate| candidate.framework == "MLX") + .find_map(|candidate| { + let entry = catalog::all().iter().find(|entry| { + entry.harness_compatible && candidate.id.contains(entry.id) + })?; + Some(entry.id.to_string()) + }) +} + +/// The directory of the local model `model` names, if it is an MLX model on +/// this machine. +fn hybrid_model_directory(model: &str, options: &GlobalOptions) -> Option { + if Path::new(model).is_dir() { + return Some(model.to_string()); + } + let env = crate::bootstrap::bootstrap(options).ok()?; + let entry = catalog::find(model)?; + let installed = local_models(&env.home); + let found = installed.iter().find(|candidate| { + candidate.framework == "MLX" + && (candidate.id == model + || candidate.id == entry.id + || candidate.id.contains(&entry.id) + || catalog::merge_key_for(&candidate.id) == model) + })?; + if found.dir.is_empty() { + out::error_line(&format!("{model} is on this machine but has no directory")); + return None; + } + Some(found.dir.clone()) +} + +/// `wally deepseek --hybrid`: route the parent to the cloud and every +/// subagent to the local model through the PLS router. +pub fn launch_deep_seek_hybrid( + model: &str, + cloud_model: &str, + args: &[String], + options: &GlobalOptions, +) -> i32 { + clean_leftover_configs(); + // No -m: use the first downloaded MLX model certified for a harness, so + // `wally deepseek --hybrid` alone is enough. + let picked; + let model = if model.is_empty() { + match default_hybrid_model(options) { + Some(id) => { + picked = id; + picked.as_str() + } + None => { + out::error_line("--hybrid needs -m and none is downloaded"); + return 2; + } + } + } else { + model + }; + let Some(directory) = hybrid_model_directory(model, options) else { + out::error_line(&format!("{model} is not a downloaded MLX model")); + out::status_line("pull one first: wally models pull "); + return 1; + }; + if cloud_model.is_empty() { + out::error_line("--hybrid needs a cloud model: pass --cloud-model or set a default"); + return 2; + } + super::pls::configure(&directory, cloud_model); + let Some(router) = super::pls::start(&directory) else { + return 1; + }; + + let llm_config = build_hybrid_llm_config(&router.base_url, KEY_VARIABLE); + let mut config = TemporaryConfig::new(); + if let Err(failure) = config.write(&build_hybrid_patch(&llm_config), ".yaml") { + out::error_line(&failure); + return 1; + } + let key = ScopedEnv::new(KEY_VARIABLE, "local"); + if !key.applied() { + out::error_line("could not set the router key"); + return 1; + } + + let names_profile = args.iter().any(|arg| arg == "--profile"); + let mut launch_args: Vec = if names_profile { + vec!["--patch".to_string(), config.path()] + } else if deep_seek_wants_headless(args) { + vec![ + "--profile".to_string(), + "headless".to_string(), + "--patch".to_string(), + config.path(), + ] + } else { + out::status_line("opening the dsh web ui; pass a prompt to run headless instead"); + deep_seek_web_args(&config.path(), args) + }; + launch_args.extend(args.iter().cloned()); + out::status_line(&format!( + "hybrid: parent on the cloud, subagents on {model} through {}", + router.base_url + )); + let status = launch("dsh", "", &launch_args, options); + drop(router); + status +} + pub fn launch_agent(agent: &Agent, model: &str, args: &[String], options: &GlobalOptions) -> i32 { // Command Code takes its lock and checks for its own subcommands before // an endpoint is resolved, so it runs its own launch from the start. @@ -2308,6 +2532,34 @@ mod tests { } } + #[test] + fn hybrid_patch_registers_both_lanes_and_pins_subagents_local() { + let config = build_hybrid_llm_config("http://127.0.0.1:1234", "WALLY_PLS_KEY"); + let parsed: Value = serde_json::from_str(&config).unwrap(); + assert_eq!( + parsed["providers"][PROVIDER_ID]["baseURL"], + json!("http://127.0.0.1:1234/v1") + ); + assert_eq!( + parsed["providers"]["wally-local"]["baseURL"], + json!("http://127.0.0.1:1234/local/v1") + ); + assert_eq!( + parsed["providers"]["wally-local"]["models"][0]["id"], + json!(HYBRID_MODEL_ID) + ); + + let patch = build_hybrid_patch(&config); + // The row's own provider must survive the overlay, or dsh rejects the + // whole config with "$.provider missing required value". + assert!(patch.contains("provider: spawn")); + // The web profile disables this row; without the override the parent + // has no subagent tool and nothing ever reaches the local lane. + assert!(patch.contains("disabled: false")); + assert!(patch.contains("provider: wally-local")); + assert!(patch.contains(&format!("model: '{HYBRID_MODEL_ID}'"))); + } + #[test] fn dsh_offers_each_models_own_levels_from_the_model_list() { let models = [ diff --git a/src/harness/mod.rs b/src/harness/mod.rs index 98813404..02de4044 100644 --- a/src/harness/mod.rs +++ b/src/harness/mod.rs @@ -19,6 +19,7 @@ pub mod local_models; pub mod opencode; pub mod openwork; pub mod path_reload; +pub mod pls; pub mod shannon; pub mod vvah; diff --git a/src/harness/pls.rs b/src/harness/pls.rs new file mode 100644 index 00000000..de52fa68 --- /dev/null +++ b/src/harness/pls.rs @@ -0,0 +1,425 @@ +//! Lifecycle for the PLS router: locate `pls.py`, build its venv once, spawn +//! it on port 0, read the handshake, and tear it down without leaving an +//! orphan holding the GPU. +//! +//! `pls.py` is Python so it can be edited without rebuilding wally. The copy +//! in the profile directory wins; the one beside the binary is the fallback a +//! clean install uses. + +use std::io::{BufRead, BufReader, Read, Write}; +use std::os::unix::fs::PermissionsExt; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use crate::account; +use crate::io::output as out; + +/// How long the router gets to print its port before the launch is abandoned. +const HANDSHAKE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); + +/// A running router. Dropping it stops the process. +pub struct Router { + child: Child, + pub base_url: String, + #[allow(dead_code)] // held for its Drop; the router reads it over the socket + entitlement: Option, +} + +impl Router { + /// Whether the router process is still alive. + pub fn running(&mut self) -> bool { + matches!(self.child.try_wait(), Ok(None)) + } +} + +impl Drop for Router { + fn drop(&mut self) { + // SIGTERM first: the router kills the model server in its own exit + // path, which a SIGKILL would skip. + #[cfg(unix)] + { + // SAFETY: the pid is this child's, still unreaped, so it cannot + // have been reused yet. + unsafe { + libc::kill(self.child.id() as i32, libc::SIGTERM); + } + } + #[cfg(not(unix))] + { + let _ = self.child.kill(); + } + let _ = self.child.wait(); + } +} + +/// A loopback entitlement server on a unix socket. The router asks it whether +/// the signed-in account may run work locally; wally answers from the last +/// console check so a turn never waits on the network. +pub struct Entitlement { + #[allow(dead_code)] + premium: Arc, + stop: Arc, + socket: PathBuf, + accept: Option>, + refresh: Option>, +} + +impl Entitlement { + fn start() -> Option { + let socket = config_dir().join("entitlement.sock"); + let _ = std::fs::remove_file(&socket); + let listener = UnixListener::bind(&socket).ok()?; + let _ = std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600)); + listener.set_nonblocking(true).ok()?; + + let premium = Arc::new(AtomicBool::new(false)); + let stop = Arc::new(AtomicBool::new(false)); + + let accept = { + let premium = Arc::clone(&premium); + let stop = Arc::clone(&stop); + let listener = listener.try_clone().ok()?; + std::thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + match listener.accept() { + Ok((stream, _)) => answer(stream, premium.load(Ordering::SeqCst)), + Err(_) => std::thread::sleep(std::time::Duration::from_millis(100)), + } + } + }) + }; + let refresh = { + let premium = Arc::clone(&premium); + let stop = Arc::clone(&stop); + std::thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + premium.store(check_entitlement(), Ordering::SeqCst); + for _ in 0..600 { + if stop.load(Ordering::SeqCst) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + } + }) + }; + Some(Entitlement { + premium, + stop, + socket, + accept: Some(accept), + refresh: Some(refresh), + }) + } +} + +impl Drop for Entitlement { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + let _ = std::fs::remove_file(&self.socket); + if let Some(handle) = self.accept.take() { + let _ = handle.join(); + } + if let Some(handle) = self.refresh.take() { + let _ = handle.join(); + } + } +} + +fn answer(mut stream: UnixStream, premium: bool) { + let mut buffer = [0u8; 256]; + let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(2))); + let _ = stream.read(&mut buffer); + let body = format!("{{\"sub\":{premium}}}"); + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n\ + content-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ); +} + +/// Whether the signed-in account may run work on the local model. +/// +/// A plan the console does not describe counts as premium only when it says +/// so; anything else, including a console that cannot be reached twice, is +/// false so the router falls back to the cloud. +fn check_entitlement() -> bool { + let Ok(mut credentials) = account::load() else { + return false; + }; + if credentials.console_url.is_empty() || !credentials.signed_in() { + return false; + } + if let Ok(identity) = account::who_am_i(&credentials.console_url, &credentials.access_token) { + return plan_is_premium(&identity.plan); + } + if credentials.refresh_token.is_empty() { + return false; + } + let Ok(grant) = account::refresh(&credentials.console_url, &credentials.refresh_token) else { + return false; + }; + credentials.access_token = grant.access_token; + if grant.refresh_token.is_empty() { + return false; + } + credentials.refresh_token = grant.refresh_token; + plan_is_premium(&grant.plan) +} + +fn plan_is_premium(plan: &str) -> bool { + matches!(plan.to_ascii_lowercase().as_str(), "pro" | "premium" | "paid" | "beta") +} + +fn config_dir() -> PathBuf { + PathBuf::from(account::profile_directory()).join("pls") +} + +fn pid_path() -> PathBuf { + config_dir().join("pls.pid") +} + +/// The mode/cap file, for a status line. +pub fn config_file() -> PathBuf { + config_dir().join("config.json") +} + +fn script_path() -> Option { + let override_path = config_dir().join("pls.py"); + if override_path.is_file() { + return Some(override_path); + } + let beside = std::env::current_exe().ok()?.parent()?.join("pls.py"); + beside.is_file().then_some(beside) +} + +fn uv_path() -> Option { + if let Ok(value) = std::env::var("UV") { + if !value.is_empty() { + return Some(PathBuf::from(value)); + } + } + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + let candidate = dir.join("uv"); + if candidate.is_file() { + return Some(candidate); + } + } + } + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path) + .map(|dir| dir.join("uv")) + .find(|candidate| candidate.is_file()) +} + +fn venv_python() -> PathBuf { + config_dir().join("venv").join("bin").join("python") +} + +/// Build the venv when it is missing or the lockfile changed. Returns the +/// interpreter to run `pls.py` with. +fn ensure_venv(script: &Path) -> Option { + let python = venv_python(); + let lock = script.with_file_name("requirements.lock"); + if !lock.is_file() { + out::error_line(&format!("missing {}", lock.display())); + return None; + } + let marker = config_dir().join("venv.lock.sha"); + let wanted = std::fs::read(&lock) + .map(|bytes| format!("{:x}", fnv1a(&bytes))) + .unwrap_or_default(); + let current = std::fs::read_to_string(&marker).unwrap_or_default(); + if python.is_file() && current.trim() == wanted { + return Some(python); + } + + let uv = uv_path()?; + std::fs::create_dir_all(config_dir()).ok()?; + let mut bar = crate::progress::progress_bar::Indeterminate::new(true); + bar.set("preparing local runtime"); + + let venv = Command::new(&uv) + .arg("venv") + .arg("--quiet") + .arg("--clear") + .arg("--python") + .arg("3.12") + .arg(config_dir().join("venv")) + .status() + .ok()?; + if !venv.success() { + bar.finish(); + out::error_line("could not create the PLS venv"); + return None; + } + let synced = Command::new(&uv) + .arg("pip") + .arg("sync") + .arg("--quiet") + .arg(&lock) + .arg("--python") + .arg(&python) + .status() + .ok()?; + bar.finish(); + if !synced.success() { + out::error_line("could not install the PLS dependencies"); + return None; + } + std::fs::write(&marker, wanted).ok()?; + Some(python) +} + +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash: u64 = 0xcbf29ce484222325; + for byte in bytes { + hash ^= *byte as u64; + hash = hash.wrapping_mul(0x100000001b3); + } + hash +} + +/// Kill a router left behind by a previous wally that did not get to clean up. +pub fn sweep_stale() { + let Ok(text) = std::fs::read_to_string(pid_path()) else { + return; + }; + let Ok(pid) = text.trim().parse::() else { + let _ = std::fs::remove_file(pid_path()); + return; + }; + #[cfg(unix)] + { + // SAFETY: signal 0 only probes for the pid's existence. + let alive = unsafe { libc::kill(pid, 0) } == 0; + if alive { + // SAFETY: same pid, probed alive immediately above. + unsafe { + libc::kill(pid, libc::SIGTERM); + } + out::status_line(&format!("stopped a leftover router (pid {pid})")); + } + } + let _ = std::fs::remove_file(pid_path()); +} + +/// Record the model paths in the config file, preserving the person's mode and +/// cap. Called before `start`. +pub fn configure(model_path: &str, cloud_model: &str) { + let _ = std::fs::create_dir_all(config_dir()); + let path = config_file(); + let mut value: serde_json::Value = std::fs::read_to_string(&path) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_else(|| serde_json::json!({})); + value["model_path"] = serde_json::json!(model_path); + value["cloud_model"] = serde_json::json!(cloud_model); + let _ = std::fs::write(&path, value.to_string()); +} + +/// Start the router for `model_path`. Returns `None` after reporting why. +pub fn start(model_path: &str) -> Option { + let script = script_path().or_else(|| { + out::error_line("pls.py was not found beside the binary or in the profile directory"); + None + })?; + let python = ensure_venv(&script)?; + + sweep_stale(); + std::fs::create_dir_all(config_dir()).ok()?; + + let mut bar = crate::progress::progress_bar::Indeterminate::new(true); + bar.set("starting router"); + + let mut child = Command::new(&python) + .arg(&script) + .env("PLS_MODEL", model_path) + .env("PLS_PARENT_PID", std::process::id().to_string()) + .env("PLS_ENTITLEMENT_SOCKET", config_dir().join("entitlement.sock")) + // The debug console is temporary; forwarded only when set. + .env("PLS_DEBUG", std::env::var("PLS_DEBUG").unwrap_or_default()) + .env("PYTHONUNBUFFERED", "1") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .ok()?; + + let stdout = child.stdout.take()?; + let mut reader = BufReader::new(stdout); + let mut line = String::new(); + let started = std::time::Instant::now(); + let port = loop { + line.clear(); + match reader.read_line(&mut line) { + Ok(0) => { + bar.finish(); + out::error_line("the router exited before it reported a port"); + let _ = child.wait(); + return None; + } + Ok(_) => { + if let Ok(value) = serde_json::from_str::(&line) { + if let Some(port) = value.get("port").and_then(|p| p.as_u64()) { + break port as u16; + } + } + } + Err(_) => { + bar.finish(); + out::error_line("could not read the router handshake"); + let _ = child.wait(); + return None; + } + } + if started.elapsed() > HANDSHAKE_TIMEOUT { + bar.finish(); + out::error_line("the router did not report a port in time"); + let _ = child.kill(); + let _ = child.wait(); + return None; + } + }; + bar.finish(); + + // Keep draining stdout so the pipe never fills. + std::thread::spawn(move || { + let mut sink = String::new(); + while reader.read_line(&mut sink).unwrap_or(0) > 0 { + sink.clear(); + } + }); + + let _ = std::fs::write(pid_path(), child.id().to_string()); + let base_url = format!("http://127.0.0.1:{port}"); + out::status_line(&format!("router ready on {base_url}")); + if std::env::var("PLS_DEBUG").as_deref() == Ok("1") { + out::status_line(&format!("debug console: {base_url}/debug")); + } + Some(Router { + child, + base_url, + entitlement: Entitlement::start(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_plan_the_console_does_not_describe_is_not_premium() { + assert!(plan_is_premium("pro")); + assert!(plan_is_premium("Premium")); + assert!(plan_is_premium("beta")); + assert!(!plan_is_premium("free")); + assert!(!plan_is_premium("")); + } +} diff --git a/src/progress/progress_bar.rs b/src/progress/progress_bar.rs index 856344e2..6a2618e2 100644 --- a/src/progress/progress_bar.rs +++ b/src/progress/progress_bar.rs @@ -299,6 +299,86 @@ unsafe extern "C" fn callback(proto_bytes: *const u8, proto_size: usize, _user_d }); } +// ----------------------------------------------------------------------------- +// Indeterminate +// ----------------------------------------------------------------------------- + +/// A spinner for work with no measurable fraction: a fixed-width cell cycling +/// braille frames on stderr, cleared before the next line. Non-TTY prints one +/// plain line per label change instead. +pub struct Indeterminate { + interactive: bool, + stop: Arc, + label: Arc>, + handle: Option>, + line_open: bool, +} + +const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; + +impl Indeterminate { + pub fn new(interactive: bool) -> Self { + let interactive = interactive && term::stderr_is_tty(); + let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let label = Arc::new(Mutex::new(String::new())); + let handle = if interactive { + let stop = Arc::clone(&stop); + let label = Arc::clone(&label); + Some(std::thread::spawn(move || { + let mut frame = 0; + while !stop.load(Ordering::SeqCst) { + let text = label.lock().map(|l| l.clone()).unwrap_or_default(); + if !text.is_empty() { + eprint!("\r\x1b[2K{} {text}", SPINNER[frame % SPINNER.len()]); + let _ = std::io::stderr().flush(); + } + frame += 1; + std::thread::sleep(std::time::Duration::from_millis(80)); + } + })) + } else { + None + }; + Indeterminate { + interactive, + stop, + label, + handle, + line_open: false, + } + } + + pub fn set(&mut self, text: &str) { + if let Ok(mut label) = self.label.lock() { + *label = text.to_string(); + } + if self.interactive { + self.line_open = true; + } else { + output::status_line(text); + } + } + + /// Stop the spinner and terminate its line. + pub fn finish(&mut self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + if self.line_open { + eprintln!(); + let _ = std::io::stderr().flush(); + self.line_open = false; + } + } +} + +impl Drop for Indeterminate { + fn drop(&mut self) { + self.finish(); + } +} + #[cfg(test)] mod tests { use super::*; From 7dcbf12da866cb198483d8a7b4bf43f1470cc471 Mon Sep 17 00:00:00 2001 From: Siddhesh Sonar Date: Tue, 3 Nov 2026 22:20:36 +0530 Subject: [PATCH 02/26] fix(harness): close the hybrid router review findings --- pls/README.md | 10 +- pls/model_server.py | 219 ++++++++++++------ pls/pls.py | 206 ++++++++++++---- pls/test_pls.py | 121 +++++++++- src/commands/cmd_harness.rs | 11 + src/harness/agents.rs | 32 ++- src/harness/pls.rs | 195 ++++++++++++---- src/progress/progress_bar.rs | 12 +- tests/golden/expected/help__deepseek.stdout | 4 + .../expected/help__help__deepseek.stdout | 4 + 10 files changed, 608 insertions(+), 206 deletions(-) diff --git a/pls/README.md b/pls/README.md index 8275f4b2..3dd55f86 100644 --- a/pls/README.md +++ b/pls/README.md @@ -24,8 +24,9 @@ wally deepseek --hybrid -m --cloud-model [prompt] The router asks wally for the account's entitlement over a unix socket at `~/.config/wally/pls/entitlement.sock` (mode `0600`). Without a subscription every request goes to the cloud and the local model is never loaded. The -answer is cached five seconds; an unreachable socket keeps the last answer, so -a lost wally fails closed to the cloud. +answer is cached five seconds. An unreachable socket keeps the last answer, so +a premium account keeps the local lanes after wally goes away; only a last +answer of non-premium fails closed to the cloud. Premium accounts get the mode file and the two lanes. @@ -39,8 +40,9 @@ holds the backlog, `/debug/events` is the stream. Remove once the MVP ships. Every request is scanned for emails, phone numbers, API keys, IPv4 addresses and IBANs. Counts are attributed to the file path the text mentions and travel to -the cloud in `x-pls-pii`, plus `/stats`. Only counts leave the machine, never -the values. +the cloud in `x-pls-pii`, plus `/stats`. So paths and counts leave the machine, +never the values: the cloud-bound messages are redacted to `[email]`, `[phone]`, +`[key]`, `[iban]` and `[ipv4]` before they are sent. ## Mode diff --git a/pls/model_server.py b/pls/model_server.py index 9d577088..f225470e 100644 --- a/pls/model_server.py +++ b/pls/model_server.py @@ -22,12 +22,13 @@ import mlx.core as mx import mlx_vlm +from mlx_vlm.models.cache import make_prompt_cache from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, StreamingResponse import uvicorn MODEL_PATH = os.environ["PLS_MODEL"] -MODEL_ID = os.environ.get("PLS_MODEL_ID", "Hybird-Wally-0.1") +MODEL_ID = os.environ.get("PLS_MODEL_ID", "Hybrid-Wally-0.1") MAX_KV = int(os.environ.get("PLS_MAX_KV", "57344")) MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192")) PROMPT_CACHE_MAX = int(os.environ.get("PLS_PROMPT_CACHE_MAX", "8")) @@ -49,6 +50,7 @@ "peak_context": 0, "max_kv": MAX_KV, "trims": 0, + "cache_misses": 0, "last": None, } @@ -70,15 +72,21 @@ def cache_key(request: Request) -> str: return "default" -def trim_cache(cache) -> None: - """Keep the live KV under the cap by dropping the oldest half.""" +def trim_cache(cache, reserve: int = 0) -> None: + """Keep the live KV under the cap by trimming each cache from its end. + + `trim()` removes the newest tokens, not the oldest, so the next prompt is + re-prefilled from what is left. `reserve` is the room the pending + completion still needs, so the cap is checked before generation rather + than after it overflows. + """ try: used = max((c.size() for c in cache if hasattr(c, "size")), default=0) except Exception: return - if used <= MAX_KV: + if used + reserve <= MAX_KV: return - keep = MAX_KV // 2 + keep = max(0, MAX_KV // 2 - reserve) for c in cache: trimmable = getattr(c, "is_trimmable", None) if not hasattr(c, "trim") or (trimmable is not None and not trimmable()): @@ -91,10 +99,10 @@ def trim_cache(cache) -> None: def take_cache(key: str): - cache = PROMPT_CACHES.get(key) - if cache is not None: + entry = PROMPT_CACHES.get(key) + if entry is not None: PROMPT_CACHES.move_to_end(key) - return cache + return entry def put_cache(key: str, cache) -> None: @@ -201,16 +209,20 @@ async def chat(request: Request): ) key = cache_key(request) - cache = take_cache(key) - if cache is None: + entry = take_cache(key) + # The reused cache is only valid when this prompt extends the one it was + # built for. mlx-vlm trims to the common prefix, so a rewritten turn would + # otherwise keep tokens that are no longer there. + if entry is not None and prompt.startswith(entry["prompt"]): + cache = entry["cache"] + else: try: - cache = model.language_model.make_cache() - except AttributeError: - from mlx_vlm.models.cache import make_prompt_cache - + cache = make_prompt_cache(model.language_model, max_kv_size=MAX_KV) + except TypeError: cache = make_prompt_cache(model.language_model) - put_cache(key, cache) - trim_cache(cache) + STATS["cache_misses"] += 1 + put_cache(key, {"cache": cache, "prompt": prompt}) + trim_cache(cache, reserve=max_tokens) kwargs["prompt_cache"] = cache loop = asyncio.get_running_loop() @@ -218,6 +230,7 @@ async def chat(request: Request): created = int(time.time()) started = time.monotonic() STATS["in_flight"] += 1 + streaming = False try: if not stream: @@ -255,6 +268,7 @@ async def chat(request: Request): async def sse(): acc = "" held = "" + pending = "" in_call = False call_index = 0 pt = ct = 0 @@ -306,6 +320,16 @@ def flush_held(): else: yield content_delta(block) + def leave_call(): + """A call just closed: keep text after it, resume streaming.""" + nonlocal held, pending, in_call + if held and not held.lstrip().startswith(""): + pending = held + held = "" + in_call = False + else: + in_call = bool(held) + first = { "id": cid, "object": "chat.completion.chunk", @@ -313,68 +337,108 @@ def flush_held(): "model": MODEL_ID, "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}], } - yield f"data: {json.dumps(first)}\n\n" - - it = await loop.run_in_executor( - POOL, lambda: mlx_vlm.stream_generate(model, processor, prompt, **kwargs) - ) - for chunk in it: - last = chunk - piece = chunk.text if hasattr(chunk, "text") else str(chunk) - pt = getattr(chunk, "prompt_tokens", pt) or pt - ct = getattr(chunk, "generation_tokens", ct) or ct - if not piece: - continue - if not ttft: - ttft = (time.monotonic() - started) * 1000 - acc += piece - - if in_call: - held += piece - for out in flush_held(): - yield f"data: {json.dumps(out)}\n\n" - if "" in held or not held.lstrip().startswith(""): - in_call = held.lstrip().startswith("") - continue - - if "" in piece: - head, _, tail = piece.partition("") - if head: - yield f"data: {json.dumps(content_delta(head))}\n\n" - in_call = True - held = "" + tail + try: + yield f"data: {json.dumps(first)}\n\n" + + # Generation runs on the pool thread; it must not be iterated + # from here or every chunk waits on the event loop. + queue: asyncio.Queue = asyncio.Queue(maxsize=8) + done = object() + + def pump(): + try: + for item in mlx_vlm.stream_generate(model, processor, prompt, **kwargs): + asyncio.run_coroutine_threadsafe(queue.put(item), loop).result() + except BaseException as error: # noqa: BLE001 - relayed below + asyncio.run_coroutine_threadsafe(queue.put(error), loop).result() + finally: + asyncio.run_coroutine_threadsafe(queue.put(done), loop).result() + + loop.run_in_executor(POOL, pump) + + while True: + chunk = await queue.get() + if chunk is done: + break + if isinstance(chunk, BaseException): + raise chunk + last = chunk + piece = chunk.text if hasattr(chunk, "text") else str(chunk) + pt = getattr(chunk, "prompt_tokens", pt) or pt + ct = getattr(chunk, "generation_tokens", ct) or ct + if not piece: + continue + if not ttft: + ttft = (time.monotonic() - started) * 1000 + acc += piece + pending += piece + + if in_call: + held += pending + pending = "" + for out in flush_held(): + yield f"data: {json.dumps(out)}\n\n" + leave_call() + continue + + # The opener can be split across chunks, so a tail the + # length of it is always held back before flushing text. + cut = pending.rfind("") + if cut >= 0: + head, tail = pending[:cut], pending[cut:] + if head: + yield f"data: {json.dumps(content_delta(head))}\n\n" + held = tail + pending = "" + in_call = True + for out in flush_held(): + yield f"data: {json.dumps(out)}\n\n" + leave_call() + continue + keep = len("") - 1 + if len(pending) > keep: + emit = pending[:-keep] + pending = pending[-keep:] + yield f"data: {json.dumps(content_delta(emit))}\n\n" + + if pending: + if in_call: + held += pending + else: + yield f"data: {json.dumps(content_delta(pending))}\n\n" + pending = "" + if held: for out in flush_held(): yield f"data: {json.dumps(out)}\n\n" - if "" in held: - in_call = False - continue - - yield f"data: {json.dumps(content_delta(piece))}\n\n" - - if held: - for out in flush_held(): - yield f"data: {json.dumps(out)}\n\n" - if held: - yield f"data: {json.dumps(content_delta(held))}\n\n" - - calls = parse_tool_calls(acc) - usage = usage_of(last, pt, ct) - record(cid, usage, ttft, (time.monotonic() - started) * 1000, - "tool_calls" if calls else "stop") - final = { - "id": cid, - "object": "chat.completion.chunk", - "created": created, - "model": MODEL_ID, - "choices": [ - {"index": 0, "delta": {}, "finish_reason": "tool_calls" if calls else "stop"} - ], - } - yield f"data: {json.dumps(final)}\n\n" - if want_usage: - yield f"data: {json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'model': MODEL_ID, 'choices': [], 'usage': usage})}\n\n" - yield "data: [DONE]\n\n" - + if held: + yield f"data: {json.dumps(content_delta(held))}\n\n" + + calls = parse_tool_calls(acc) + usage = usage_of(last, pt, ct) + record(cid, usage, ttft, (time.monotonic() - started) * 1000, + "tool_calls" if calls else "stop") + final = { + "id": cid, + "object": "chat.completion.chunk", + "created": created, + "model": MODEL_ID, + "choices": [ + {"index": 0, "delta": {}, "finish_reason": "tool_calls" if calls else "stop"} + ], + } + yield f"data: {json.dumps(final)}\n\n" + if want_usage: + yield f"data: {json.dumps({'id': cid, 'object': 'chat.completion.chunk', 'model': MODEL_ID, 'choices': [], 'usage': usage})}\n\n" + yield "data: [DONE]\n\n" + except Exception as error: + STATS["errors"] += 1 + log({"event": "error", "id": cid, "stream": True, + "error": f"{type(error).__name__}: {error}"}) + raise + finally: + STATS["in_flight"] -= 1 + + streaming = True return StreamingResponse(sse(), media_type="text/event-stream") except Exception as error: @@ -382,7 +446,8 @@ def flush_held(): log({"event": "error", "id": cid, "error": f"{type(error).__name__}: {error}"}) raise finally: - STATS["in_flight"] -= 1 + if not streaming: + STATS["in_flight"] -= 1 @app.on_event("startup") diff --git a/pls/pls.py b/pls/pls.py index 3209c42b..cf500ec6 100644 --- a/pls/pls.py +++ b/pls/pls.py @@ -20,6 +20,7 @@ import json import os import re +import secrets import signal import socket import subprocess @@ -33,7 +34,7 @@ from fastapi.responses import JSONResponse, Response, StreamingResponse import uvicorn -MODEL_ID = "Hybird-Wally-0.1" +MODEL_ID = "Hybrid-Wally-0.1" DEFAULT_MODE = "hybrid" DEFAULT_MAX_TURNS = 20 QUEUE_MAX = 8 @@ -102,7 +103,17 @@ "names and numbers. Answer with the summary only.\n\n" ) +# Returned instead of the raw result when the summariser fails, so a failed +# summary does not silently become a full-content leak. +SUMMARISE_FAILED = ( + "[summary unavailable: the local summariser failed and the full result was " + "not returned]" +) + ENTITLEMENT_SOCKET = os.environ.get("PLS_ENTITLEMENT_SOCKET", "") +# Per-launch secret. The port is loopback but shared, so without it any local +# process could spend the account's cloud quota through this bearer token. +TOKEN = os.environ.get("PLS_TOKEN", "") # Debug console: remove once the MVP ships. DEBUG = os.environ.get("PLS_DEBUG") == "1" EVENTS: "collections.deque[dict]" = collections.deque(maxlen=1000) @@ -192,6 +203,33 @@ def redact(text: str) -> str: return text +def redact_messages(messages: list) -> list: + """Redact every non-system message before it goes to the cloud. + + Counts alone still leave the values in the transcript, and a pasted file + body carries them. Placeholders do not match the patterns, so a turn that + passes through this twice keeps the same text. + """ + out = [] + for message in messages: + content = message.get("content") + if message.get("role") == "system": + out.append(message) + elif isinstance(content, str): + out.append({**message, "content": redact(content)}) + elif isinstance(content, list): + parts = [ + {**part, "text": redact(part["text"])} + if isinstance(part, dict) and isinstance(part.get("text"), str) + else part + for part in content + ] + out.append({**message, "content": parts}) + else: + out.append(message) + return out + + def take_disclosure(messages: list, fallback: str) -> tuple[str, list]: """Pull a `disclosure:` marker off the child prompt and strip it.""" for index in range(len(messages) - 1, -1, -1): @@ -503,7 +541,7 @@ def read_config() -> dict: "mode": mode, "pii_mode": pii_mode, "max_turns": max(1, max_turns), - "model_path": data.get("model_path") or os.environ.get("PLS_MODEL", ""), + "model_path": os.environ.get("PLS_MODEL") or data.get("model_path") or "", "cloud_model": data.get("cloud_model") or os.environ.get("PLS_CLOUD_MODEL", ""), } @@ -689,7 +727,7 @@ async def summarise(text: str) -> str: return ((result.get("choices") or [{}])[0].get("message") or {}).get("content") or "" except Exception as error: log({"event": "summary_failed", "error": str(error)}) - return text + return SUMMARISE_FAILED # -------------------------------------------------------------------------- @@ -752,6 +790,7 @@ def stats_reset():
timeeventlanepath / filedetail
""" - @app.get("/favicon.ico") def favicon(): return Response(b"", media_type="image/x-icon", status_code=204) -@app.get("/debug") -def debug_page(): - if not DEBUG: - return JSONResponse({"error": {"message": "debug console off (start with PLS_DEBUG=1)"}}, status_code=404) - return Response(DEBUG_PAGE, media_type="text/html") - - -@app.get("/debug/state") -def debug_state(request: Request): - if rejected := token_rejected(request): - return rejected - return {"mode": read_config()["mode"], "events": list(EVENTS)} - - -@app.get("/debug/export") -def debug_export(request: Request): - if rejected := token_rejected(request): - return rejected - body = "\n".join(json.dumps(event) for event in EVENTS) - return Response( - body + "\n", - media_type="application/x-ndjson", - headers={"content-disposition": 'attachment; filename="pls-events.ndjson"'}, - ) - - -@app.get("/debug/events") -async def debug_events(request: Request): - if rejected := token_rejected(request): - return rejected - queue: asyncio.Queue = asyncio.Queue() - SUBSCRIBERS.add(queue) - - async def stream(): - try: - while True: - yield "data: " + json.dumps(await queue.get()) + "\n\n" - finally: - SUBSCRIBERS.discard(queue) - - return StreamingResponse(stream(), media_type="text/event-stream") def withheld_completion(stream: bool) -> Response: @@ -2694,6 +2509,8 @@ async def local(path: str, body: dict, request: Request, config: dict): request) summary, messages = resolve_child(list(body.get("messages") or []), config["policy"]) + if kvc is not None: + messages = kvc.order(messages, is_injected) body = {**body, "messages": messages} overflow = False diff --git a/pls/test_pls.py b/pls/test_pls.py index bd60126e..2bc01482 100644 --- a/pls/test_pls.py +++ b/pls/test_pls.py @@ -113,6 +113,7 @@ def setUp(self): pls.CONFIG_PATH = self.config pls.CREDENTIALS_PATH = self.creds pls.TASKS_PATH = self.dir / "tasks.json" + pls.WATCH_DIR = self.dir / "watch" pls.TASKS.clear() pls.TASK_TEXT.clear() pls.SESSION_NEXT.clear() @@ -418,6 +419,20 @@ def test_the_marker_is_stripped_from_the_child_prompt(self): self.assertEqual(next(m for m in sent if m["role"] == "user")["content"], "list the files") self.assertNotIn("pls-task:", json.dumps(sent)) + def test_the_task_is_placed_after_the_harness_context(self): + record = self.seed("read the file") + body = self.dsh_child(record) + body["messages"] = [ + body["messages"][0], + {"role": "user", "content": f"pls-task: {record['id']}\nread the file"}, + {"role": "user", "content": "Current runtime context. This snapshot supersedes earlier ones."}, + ] + self.post("/v1/chat/completions", body) + roles = [(m["role"], m["content"][:24]) for m in self.local_bodies[-1]["messages"]] + self.assertEqual(roles[1][0], "user") + self.assertTrue(roles[1][1].startswith("Current runtime context")) + self.assertEqual(self.local_bodies[-1]["messages"][-1]["content"], "read the file") + def test_a_child_with_an_unknown_id_is_masked_under_privacy(self): record = {"id": "t424242"} self.assertEqual(self.answer(self.post_child(record)), "local answer") @@ -778,20 +793,16 @@ def test_the_subscription_state_is_gone(self): self.assertFalse(hasattr(pls, name)) self.assertNotIn("premium_blocked", pls.STATS) - def test_debug_state_carries_no_subscription_field(self): - self.assertNotIn("sub", self.client.get("/debug/state").json()) + def test_the_watch_log_carries_no_subscription_field(self): + self.assertNotIn("sub", self.client.get("/watch/log").text) - def test_debug_records_what_went_in_and_what_came_out(self): - pls.DEBUG = True - pls.EVENTS.clear() - try: - pls.http.send = _fake_send_json([], completion("cloud answer")) - self.cloud_post(self.later(dsh_first_turn())) - events = list(pls.EVENTS) - page = self.client.get("/debug") - finally: - pls.DEBUG = False - pls.EVENTS.clear() + def test_watch_records_what_went_in_and_what_came_out(self): + pls.http.send = _fake_send_json([], completion("cloud answer")) + self.cloud_post(self.later(dsh_first_turn())) + raw = (pls.WATCH_DIR / "traffic.jsonl").read_text() + events = [json.loads(line) for line in raw.splitlines()] + page = self.client.get("/watch") + log = self.client.get("/watch/log") incoming = [event for event in events if event.get("event") == "in"] outgoing = [event for event in events if event.get("event") == "out"] self.assertEqual(len(incoming), 1) @@ -802,9 +813,10 @@ def test_debug_records_what_went_in_and_what_came_out(self): event.get("event") == "route" and event.get("req") == incoming[0]["req"] for event in events)) self.assertEqual(page.status_code, 200) - self.assertIn("Processed", page.text) - self.assertIn(">In<", page.text) - self.assertIn(">Out<", page.text) + self.assertIn("PLS watch", page.text) + self.assertIn("Raw log", page.text) + self.assertEqual(log.status_code, 200) + self.assertIn("cloud answer", log.text) def through_the_socket(self): """Main chat and a subagent with the real decide and token clients.""" @@ -1620,28 +1632,11 @@ def test_parse_calls_joins_arguments_split_across_chunks(self): # -- launch token ------------------------------------------------------ - def test_stats_and_debug_require_the_launch_token(self): + def test_the_watch_page_is_open_without_the_launch_token(self): pls.TOKEN = "s3cret" try: - for path in ("/stats", "/debug/state", "/debug/export"): - with self.subTest(path=path): - self.assertEqual(self.client.get(path).status_code, 401) - self.assertEqual(self.client.post("/stats/reset").status_code, 401) - self.assertEqual(asyncio.run(self._events_status()), 401) - finally: - pls.TOKEN = "" - - async def _events_status(self): - transport = httpx.ASGITransport(app=pls.app) - async with httpx.AsyncClient(transport=transport, base_url="http://router") as client: - response = await client.get("/debug/events") - return response.status_code - - def test_stats_accepts_the_launch_token(self): - pls.TOKEN = "s3cret" - try: - response = self.client.get("/stats", headers={"x-pls-token": "s3cret"}) - self.assertEqual(response.status_code, 200) + self.assertEqual(self.client.get("/watch").status_code, 200) + self.assertEqual(self.client.get("/watch/log").status_code, 200) finally: pls.TOKEN = "" diff --git a/pls/watch/__init__.py b/pls/watch/__init__.py new file mode 100644 index 00000000..ccbbc457 --- /dev/null +++ b/pls/watch/__init__.py @@ -0,0 +1,40 @@ +"""Traffic log for the router. Delete this package and the router still runs. + +The log file stays on disk, so it can be read after the process exits. +The page and the raw log are open on purpose: no token. +""" + +import json +from pathlib import Path +from typing import Callable + +from fastapi import FastAPI +from fastapi.responses import HTMLResponse, PlainTextResponse + +_directory: Callable[[], Path] | None = None + + +def attach(app: FastAPI, directory: Callable[[], Path]) -> None: + global _directory + _directory = directory + + @app.get("/watch") + def page(): + html = Path(__file__).with_name("page.html").read_text() + return HTMLResponse(html) + + @app.get("/watch/log") + def raw(): + path = directory() / "traffic.jsonl" + text = path.read_text() if path.is_file() else "" + return PlainTextResponse(text) + + +def record(event: dict) -> None: + if _directory is None: + return + folder = _directory() + folder.mkdir(parents=True, exist_ok=True) + path = folder / "traffic.jsonl" + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(event, ensure_ascii=False) + "\n") diff --git a/pls/watch/page.html b/pls/watch/page.html new file mode 100644 index 00000000..ed912a4c --- /dev/null +++ b/pls/watch/page.html @@ -0,0 +1,192 @@ + + + + +PLS watch + + + +
+

PLS watch

+ + + +
+
+
+
+
+ + + +
WhenRequestLaneFirst byteTotalWhat hurt
+
+
+
+ + + diff --git a/src/app.rs b/src/app.rs index 02561430..73af16f5 100644 --- a/src/app.rs +++ b/src/app.rs @@ -228,6 +228,7 @@ fn root_flags_before_passthrough(argv: &[String]) -> Vec<&str> { fn is_hybrid_launch_flag(token: &str) -> bool { token == "--cloud" || token == "--hybrid" + || token == "--custom" || token == "--cloud-model" || token.starts_with("--cloud-model=") || token == "--policy" diff --git a/src/commands/cmd_harness.rs b/src/commands/cmd_harness.rs index 2fdd4bd0..e61af482 100644 --- a/src/commands/cmd_harness.rs +++ b/src/commands/cmd_harness.rs @@ -23,6 +23,10 @@ pub(crate) fn add_hybrid_flags(command: &mut App) { ValueType::Text, "What --hybrid optimises for: privacy (default) or cost", ); + command.add_flag( + "--custom", + "After --hybrid, ask for the local context window and the cloud model", + ); } /// The hybrid launch a parsed command asks for: `Ok(Some((local, cloud, @@ -34,7 +38,14 @@ pub(crate) fn hybrid_request( no_color: bool, ) -> Result, i32> { if !p.flag("--hybrid") { - for flag in ["--cloud-model", "--policy"] { + for flag in ["--cloud-model", "--policy", "--custom"] { + if flag == "--custom" { + if p.flag("--custom") { + out::error_line("--custom only applies with --hybrid"); + return Err(2); + } + continue; + } if p.get_str(flag).is_some_and(|value| !value.is_empty()) { out::error_line(&format!("{flag} only applies with --hybrid")); return Err(2); @@ -45,10 +56,16 @@ pub(crate) fn hybrid_request( // `-m` names the *local* model here, so an absent one must not be filled // with the cloud default. let local = p.get_str("--model").unwrap_or_default(); - let cloud = p - .get_str("--cloud-model") - .unwrap_or_else(|| resolve_default_model("", no_color)); - if harness::refuse_decisions_model(Some(cloud.as_str())) { + let cloud = if p.flag("--custom") { + // A passed id is only a suggestion for the questions. Do not fill in + // the account default before the person has answered. + p.get_str("--cloud-model").unwrap_or_default() + } else { + p.get_str("--cloud-model").unwrap_or_else(|| { + saved_cloud_model().unwrap_or_else(|| resolve_default_model("", no_color)) + }) + }; + if !cloud.is_empty() && harness::refuse_decisions_model(Some(cloud.as_str())) { return Err(2); } let policy = p @@ -270,7 +287,31 @@ pub fn register_harness(app: &mut App) { if harness::HYBRID_COMMANDS.contains(&agent.id) { match hybrid_request(p, g.no_color) { Err(status) => return status, - Ok(Some((local, cloud, policy))) => { + Ok(Some((mut local, mut cloud, policy))) => { + if let Some(context) = saved_local_context() { + std::env::set_var("PLS_MAX_KV", context.to_string()); + local = "mlx-pplx-coder-35b-4bit".to_string(); + if p.get_str("--cloud-model").is_none() { + if let Some(saved) = saved_cloud_model() { + cloud = saved; + } + } + out::status_line(&format!( + "hybrid defaults: context {context}, cloud {cloud}" + )); + } else if p.flag("--custom") { + match custom_hybrid(&agent.id, &cloud) { + Err(status) => return status, + Ok(choice) => { + cloud = choice.cloud; + local = "mlx-pplx-coder-35b-4bit".to_string(); + std::env::set_var("PLS_MAX_KV", choice.context.to_string()); + if choice.save { + save_local_context(choice.context); + } + } + } + } return harness::launch_hybrid( &agent, &local, @@ -289,3 +330,239 @@ pub fn register_harness(app: &mut App) { }); } } + +/// What `--custom` collected. +struct CustomChoice { + context: i64, + cloud: String, + save: bool, +} + +/// Lowest local window. A new sub-agent prompt in this session was about 14k tokens. +const CONTEXT_MIN: i64 = 16_384; +/// `max_position_embeddings` of mlx-pplx-coder-35b. +const CONTEXT_MAX: i64 = 262_144; +/// Hermes will not delegate to a model that advertises under this. +const HERMES_CONTEXT_MIN: i64 = 64_000; +/// Process peak at 16,384 tokens on the 35B coder: 22.156 GiB. +const PPLX_PEAK_AT_16K: u64 = 23_788_551_831; +/// Process-peak growth between the 4,096 and 16,384 runs: 133,256 bytes per token. +const PPLX_PEAK_PER_TOKEN: u64 = 133_256; + +/// The context window whose measured prefill peak fits in `available` bytes. +fn context_for_free_ram(available: u64) -> i64 { + let tokens = + CONTEXT_MIN as u64 + available.saturating_sub(PPLX_PEAK_AT_16K) / PPLX_PEAK_PER_TOKEN; + (tokens as i64).clamp(CONTEXT_MIN, CONTEXT_MAX) +} + +fn context_min_for(harness: &str) -> i64 { + if harness == "hermes" { + HERMES_CONTEXT_MIN + } else { + CONTEXT_MIN + } +} + +fn config_json() -> serde_json::Value { + let path = crate::harness::pls::config_file(); + std::fs::read_to_string(path) + .ok() + .and_then(|text| serde_json::from_str(&text).ok()) + .unwrap_or_else(|| serde_json::json!({})) +} + +fn saved_local_context() -> Option { + config_json() + .get("local_context") + .and_then(|value| value.as_i64()) + .filter(|value| *value > 0) +} + +fn saved_cloud_model() -> Option { + if saved_local_context().is_none() { + return None; + } + config_json() + .get("cloud_model") + .and_then(|value| value.as_str()) + .filter(|value| !value.is_empty()) + .map(str::to_string) +} + +fn save_local_context(context: i64) { + let path = crate::harness::pls::config_file(); + let _ = std::fs::create_dir_all(path.parent().unwrap_or(std::path::Path::new("."))); + let mut value = config_json(); + value["local_context"] = serde_json::json!(context); + let _ = std::fs::write(path, value.to_string()); +} + +fn available_bytes() -> Option { + let out = std::process::Command::new("vm_stat").output().ok()?; + let text = String::from_utf8_lossy(&out.stdout); + let mut page = 16_384u64; + let mut pages = 0u64; + for line in text.lines() { + if let Some(rest) = line.split("page size of ").nth(1) { + if let Some(n) = rest.split_whitespace().next() { + if let Ok(size) = n.parse::() { + page = size; + } + } + } + let interesting = line.contains("Pages free") + || line.contains("Pages inactive") + || line.contains("Pages speculative"); + if !interesting { + continue; + } + let number = line + .split(':') + .nth(1) + .unwrap_or("") + .trim() + .trim_end_matches('.'); + if let Ok(count) = number.parse::() { + pages += count; + } + } + if pages == 0 { + None + } else { + Some(pages.saturating_mul(page)) + } +} + +fn ask(prompt: &str) -> Result { + if !crate::util::term::stdin_is_tty() || !crate::util::term::stderr_is_tty() { + out::error_line("--custom needs a terminal"); + return Err(2); + } + eprint!("{prompt}"); + let _ = std::io::Write::flush(&mut std::io::stderr()); + let mut line = String::new(); + if std::io::stdin().read_line(&mut line).unwrap_or(0) == 0 { + out::error_line("no answer"); + return Err(2); + } + Ok(line.trim().to_string()) +} + +fn cloud_ids() -> Result, i32> { + let mut session = + match crate::account::ConsoleSession::open(crate::account::ConsoleClient::default()) { + Ok(session) => session, + Err(error) => { + let cached = crate::account::cached_model_ids(); + if cached.is_empty() { + out::error_line(&error); + return Err(2); + } + return Ok(cached); + } + }; + match session.call(|client, url, token| client.fetch_models_within(url, token, 8_000)) { + Ok(models) => { + let ids: Vec = models + .into_iter() + .map(|model| model.id) + .filter(|id| !id.is_empty()) + .collect(); + if ids.is_empty() { + out::error_line("the account has no cloud models"); + Err(2) + } else { + Ok(ids) + } + } + Err(error) => { + let cached = crate::account::cached_model_ids(); + if cached.is_empty() { + out::error_line(&error); + Err(2) + } else { + Ok(cached) + } + } + } +} + +fn pick_cloud(passed: &str, ids: &[String]) -> Result { + if !passed.is_empty() { + let use_passed = harness::confirm(&format!("Use {passed} as the cloud model? [y/N] ")); + if use_passed { + return Ok(passed.to_string()); + } + } + out::status_line("Cloud models:"); + for (index, id) in ids.iter().enumerate() { + eprintln!(" {}: {id}", index + 1); + } + loop { + let answer = ask("Type the cloud model id, or its number: ")?; + if let Ok(index) = answer.parse::() { + if let Some(id) = index.checked_sub(1).and_then(|index| ids.get(index)) { + return Ok(id.clone()); + } + } + if ids.iter().any(|id| id == &answer) { + return Ok(answer); + } + out::error_line("that model is not in the list"); + } +} + +fn custom_hybrid(harness: &str, passed_cloud: &str) -> Result { + let min = context_min_for(harness); + let context = loop { + let answer = ask(&format!("Context window ({min}-{CONTEXT_MAX}), or auto: "))?; + if answer.eq_ignore_ascii_case("auto") { + let Some(free) = available_bytes() else { + out::error_line("could not read free memory; type a number"); + continue; + }; + let picked = context_for_free_ram(free).max(min); + out::status_line(&format!( + "auto context window: {picked} ({:.1} GB free)", + free as f64 / 1024.0 / 1024.0 / 1024.0 + )); + break picked; + } + match answer.parse::() { + Ok(value) if (min..=CONTEXT_MAX).contains(&value) => break value, + _ => out::error_line(&format!( + "type a number from {min} to {CONTEXT_MAX}, or auto" + )), + } + }; + + let ids = cloud_ids()?; + let cloud = pick_cloud(passed_cloud, &ids)?; + if harness::refuse_decisions_model(Some(cloud.as_str())) { + return Err(2); + } + let save = harness::confirm("Make this the default hybrid configuration? [y/N] "); + Ok(CustomChoice { + context, + cloud, + save, + }) +} + +#[cfg(test)] +mod custom_tests { + use super::*; + + #[test] + fn auto_context_fits_the_measured_35b_cost() { + let available = PPLX_PEAK_AT_16K + (65_536 - CONTEXT_MIN as u64) * PPLX_PEAK_PER_TOKEN; + assert_eq!(context_for_free_ram(available), 65_536); + } + + #[test] + fn auto_context_stays_inside_the_model_limits() { + assert_eq!(context_for_free_ram(0), CONTEXT_MIN); + assert_eq!(context_for_free_ram(u64::MAX), CONTEXT_MAX); + } +} diff --git a/src/harness/hybrid.rs b/src/harness/hybrid.rs index db4bb9ff..6b6ac5a6 100644 --- a/src/harness/hybrid.rs +++ b/src/harness/hybrid.rs @@ -198,6 +198,15 @@ pub const HYBRID_LOCAL_MODEL_ID: &str = "Hybrid-Wally-0.1-local"; pub(super) const HYBRID_LOCAL_CONTEXT: i64 = 65536; pub(super) const HYBRID_LOCAL_OUTPUT: i64 = 8192; +/// The window `--custom` chose for this launch, or the built-in cap. +fn local_context_window() -> i64 { + std::env::var("PLS_MAX_KV") + .ok() + .and_then(|value| value.parse::().ok()) + .filter(|value| *value > 0) + .unwrap_or(HYBRID_LOCAL_CONTEXT) +} + /// The one-provider `llm-pi-ai` config for a hybrid launch. `cloud` is what /// the console says the parent's cloud model can hold: the parent's model /// entry declares those limits and the subagent's the local ones, because a @@ -223,7 +232,7 @@ fn build_hybrid_llm_config( }; let subagent = model( HYBRID_LOCAL_MODEL_ID, - HYBRID_LOCAL_CONTEXT, + local_context_window(), HYBRID_LOCAL_OUTPUT, false, ); diff --git a/src/harness/pls.rs b/src/harness/pls.rs index dbca3c78..a9787af9 100644 --- a/src/harness/pls.rs +++ b/src/harness/pls.rs @@ -368,6 +368,9 @@ const PII_LABELS: &str = include_str!("../../pls/pii_labels.py"); const PII_VITERBI: &str = include_str!("../../pls/pii_viterbi.py"); const PII_WEIGHTS: &str = include_str!("../../pls/pii_weights.py"); const LOCK: &str = include_str!("../../pls/requirements.lock"); +const WATCH_PY: &str = include_str!("../../pls/watch/__init__.py"); +const WATCH_PAGE: &str = include_str!("../../pls/watch/page.html"); +const KVC: &str = include_str!("../../pls/kvc.py"); /// A running router. Dropping it stops the process. pub struct Router { @@ -755,7 +758,7 @@ fn materialise() -> Option { "{:x}", fnv1a( format!( - "{SCRIPT}\u{0}{MODEL_SERVER}\u{0}{MASK_STORE}\u{0}{PII_MODEL}\u{0}{PII_BACKBONE}\u{0}{PII_LABELS}\u{0}{PII_VITERBI}\u{0}{PII_WEIGHTS}\u{0}{LOCK}" + "{SCRIPT}\u{0}{MODEL_SERVER}\u{0}{MASK_STORE}\u{0}{PII_MODEL}\u{0}{PII_BACKBONE}\u{0}{PII_LABELS}\u{0}{PII_VITERBI}\u{0}{PII_WEIGHTS}\u{0}{LOCK}\u{0}{WATCH_PY}\u{0}{WATCH_PAGE}\u{0}{KVC}" ) .as_bytes(), ) @@ -778,6 +781,11 @@ fn materialise() -> Option { ] { std::fs::write(dir.join(name), body).ok()?; } + let watch_dir = dir.join("watch"); + std::fs::create_dir_all(&watch_dir).ok()?; + std::fs::write(watch_dir.join("__init__.py"), WATCH_PY).ok()?; + std::fs::write(watch_dir.join("page.html"), WATCH_PAGE).ok()?; + std::fs::write(dir.join("kvc.py"), KVC).ok()?; std::fs::write(&marker, wanted).ok()?; Some(script) } @@ -1019,8 +1027,6 @@ fn start_with( .env("PLS_PARENT_PID", std::process::id().to_string()) .env("PLS_TOKEN", &token) .env("PLS_SOCKET", socket_path()) - // The debug console is temporary; forwarded only when set. - .env("PLS_DEBUG", std::env::var("PLS_DEBUG").unwrap_or_default()) .env("PYTHONUNBUFFERED", "1") .stdin(Stdio::null()) .stdout(Stdio::piped()) @@ -1081,9 +1087,7 @@ fn start_with( let _ = std::fs::write(pid_path(), format!("{} {}", child.id(), script.display())); let base_url = format!("http://127.0.0.1:{port}"); out::status_line(&format!("router ready on {base_url}")); - if std::env::var("PLS_DEBUG").as_deref() == Ok("1") { - out::status_line(&format!("debug console: {base_url}/debug")); - } + out::status_line(&format!("watch: {base_url}/watch")); Some(Router { child, base_url, From b2fa168b62e5a10d472b33ed4fad41e59c5a6edd Mon Sep 17 00:00:00 2001 From: Siddhesh Sonar Date: Tue, 10 Nov 2026 20:39:11 +0530 Subject: [PATCH 24/26] fix(pls): drop the watch page and keep the request log --- AGENTS.md | 11 ++- pls/README.md | 16 ++- pls/local_only.py | 3 +- pls/measure_ctx.py | 4 +- pls/model_server.py | 28 ++++++ pls/pls.py | 57 +++++++++-- pls/test_pls.py | 54 +++++++--- pls/watch/__init__.py | 60 +++++++---- pls/watch/page.html | 192 ------------------------------------ src/commands/cmd_harness.rs | 21 +++- src/harness/hybrid.rs | 25 ++++- src/harness/pls.rs | 5 +- 12 files changed, 211 insertions(+), 265 deletions(-) delete mode 100644 pls/watch/page.html diff --git a/AGENTS.md b/AGENTS.md index 6cb53a44..a3f95864 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -208,10 +208,13 @@ never logged. ## Python router, no Rust rebuild `pls/*.py` is the router. The binary embeds those files and writes them to -`~/.config/wally/pls/` when `assets.sha` does not match. A change that stays -inside `pls/` does not need a Rust rebuild: copy the changed files into that -directory and leave `assets.sha` alone, or the next launch puts the embedded -copy back. Rebuild only when `src/` or the launch path changes. +the profile `pls` directory (`~/.config/wally/pls/` unless `WALLY_PROFILE_DIR` +moves the profile) when `assets.sha` does not match. A change that stays +inside `pls/` does not need a Rust rebuild for a local try: copy the changed +files into that directory and leave `assets.sha` alone, or the next launch +puts the embedded copy back. The copy is not what ships. A release still +needs a rebuild so the embedded files are the ones in the binary. Rebuild +when `src/` or the launch path changes too. ## Building against the SDK diff --git a/pls/README.md b/pls/README.md index eb7241fe..dcef0e66 100644 --- a/pls/README.md +++ b/pls/README.md @@ -114,15 +114,13 @@ wally serves the router over a unix socket at `~/.config/wally/pls/pls.sock` (mode `0600`, path in `PLS_SOCKET`): `POST /decide` for the decision model and `GET /token` for the cloud token. Nothing is gated on a plan. -## Watch - -Open `/watch`. Summary shows latency (first byte and total, p50 -and p95), decision failures, guard retries, queue waits and the turns that -will feel slow. Raw log is the same file, one JSON object per line. Nothing -on `/watch` checks the launch token. The file is -`~/.config/wally/pls/watch/traffic.jsonl`, so it can be read after the -router has exited. Delete the `pls/watch` package and the router keeps -running without the page. +## Log + +Each request is one JSON line in the profile `pls/watch/traffic.jsonl` +(`~/.config/wally/pls/watch/` unless `WALLY_PROFILE_DIR` is set). The file is +mode 0600. It keeps roles and lengths, not the raw prompt. Rows older than 7 +days are dropped, and only the newest 2000 lines are kept. Delete the +`pls/watch` package and the router keeps running without the log. ## PII diff --git a/pls/local_only.py b/pls/local_only.py index da851518..9358f4aa 100644 --- a/pls/local_only.py +++ b/pls/local_only.py @@ -54,10 +54,11 @@ def main() -> None: prompt_tokens = len(tokenizer.encode(text)) if prompt_tokens >= MAX_KV: raise SystemExit(f"prompt is {prompt_tokens} tokens; window is {MAX_KV}") + budget = min(64, MAX_OUT, MAX_KV - prompt_tokens) started = time.monotonic() out = mlx_vlm.generate( model, processor, text, - max_tokens=min(64, MAX_OUT), + max_tokens=budget, temperature=0.0, verbose=False, apc_manager=apc, diff --git a/pls/measure_ctx.py b/pls/measure_ctx.py index d36e0c8c..d34a4643 100644 --- a/pls/measure_ctx.py +++ b/pls/measure_ctx.py @@ -104,7 +104,9 @@ def snapshot(stage: str, baseline: ProcessMemory) -> None: def main() -> None: - path = json.loads((Path.home() / ".config" / "wally" / "pls" / "config.json").read_text())["model_path"] + path = os.environ.get("PLS_MODEL") or json.loads( + (Path.home() / ".config" / "wally" / "pls" / "config.json").read_text() + )["model_path"] mx.set_cache_limit(0) baseline = process_memory() snapshot("baseline", baseline) diff --git a/pls/model_server.py b/pls/model_server.py index 860ca77b..313e19a3 100644 --- a/pls/model_server.py +++ b/pls/model_server.py @@ -27,6 +27,7 @@ import mlx.core as mx import mlx_vlm from mlx_vlm.apc import APCManager +from mlx_vlm.models import cache as mlx_cache from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, StreamingResponse import uvicorn @@ -46,6 +47,28 @@ APC_CHECKPOINTS = int(os.environ.get("PLS_APC_CHECKPOINTS", "32")) APC_CHECKPOINT_INTERVAL = int(os.environ.get("PLS_APC_CHECKPOINT_INTERVAL", "4096")) + +def _kv_memory_profile(cache, token_count): + """The library profile reads `keys.shape`. An 8-bit cache stores keys as a list.""" + if cache.keys is None: + return mlx_cache.CacheMemory() + keys = cache.keys[0] if isinstance(cache.keys, (list, tuple)) and cache.keys else cache.keys + if not hasattr(keys, "shape") or len(keys.shape) < 3: + size = mlx_cache.cache_nbytes(cache.keys) + mlx_cache.cache_nbytes(cache.values) + return mlx_cache.CacheMemory( + source_bytes=size, bytes_per_token=0, step=getattr(cache, "step", 1) + ) + capacity = keys.shape[2] + size = mlx_cache.cache_nbytes(cache.keys) + mlx_cache.cache_nbytes(cache.values) + return mlx_cache.CacheMemory( + source_bytes=size, + bytes_per_token=size / capacity if capacity else 0, + step=getattr(cache, "step", 1), + ) + + +mlx_cache._kv_memory_profile = _kv_memory_profile + app = FastAPI() model = None processor = None @@ -195,6 +218,11 @@ async def chat(request: Request): ) kwargs["max_tokens"] = budget kwargs["apc_manager"] = apc + # 8-bit cache. The weights stay 4-bit. Set PLS_KV_BITS=0 to keep full cache. + kv_bits = os.environ.get("PLS_KV_BITS", "8") + if kv_bits not in ("", "0"): + kwargs["kv_bits"] = float(kv_bits) + kwargs["quantized_kv_start"] = 0 loop = asyncio.get_running_loop() cid = "chatcmpl-" + uuid.uuid4().hex[:24] diff --git a/pls/pls.py b/pls/pls.py index 11b6afa8..28a7bc95 100644 --- a/pls/pls.py +++ b/pls/pls.py @@ -333,7 +333,7 @@ def find_marker(messages: list) -> tuple[int, re.Match] | None: app = FastAPI() if watch is not None: - watch.attach(app, lambda: WATCH_DIR) + watch.start(lambda: WATCH_DIR) http = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=10.0)) @@ -791,6 +791,7 @@ async def mask_cloud_text(text: str, session_id: str) -> str | None: note_masking_off("classifier returned no span list") return None spans = [span for span in spans if not _span_is_path(text, span)] + spans = spans + _sensitive_path_spans(text) store = open_mask_store() if store is None: note_masking_off("mask store unavailable") @@ -814,9 +815,31 @@ def _span_is_path(text: str, span: dict) -> bool: if start < 0 or end > len(text) or start >= end: return False piece = text[start:end].strip().strip("`\"'") + name = piece.rstrip("/").rsplit("/", 1)[-1] + if _SENSITIVE_FILE.search(name): + return False return piece.startswith(("/", "~/", "./", "../")) +_SENSITIVE_FILE = re.compile( + r"(?i)(credential|secret|password|passwd|\.pem$|\.env$|id_rsa|api[_-]?key)" +) +_PATH_IN_TEXT = re.compile(r"(?:~|\.\.?|/[A-Za-z0-9._-])[^\s\"'`<>]*") + + +def _sensitive_path_spans(text: str) -> list[dict]: + """Paths whose file name is a secret, even when the classifier skipped them.""" + spans = [] + for match in _PATH_IN_TEXT.finditer(text): + raw = match.group(0).rstrip(".,);]") + name = raw.rstrip("/").rsplit("/", 1)[-1] + if not _SENSITIVE_FILE.search(name): + continue + start = match.start() + spans.append({"start": start, "end": start + len(raw), "category": "path"}) + return spans + + def _remask_content(store, session_id: str, content): """Known values become tokens. A failed piece is left as it arrived.""" if isinstance(content, str): @@ -918,18 +941,21 @@ def map_sse_event(event: bytes, demask: ReplyDemask | None) -> list[bytes]: if not isinstance(delta, dict) or delta.get("tool_calls"): return _flush_then(demask, event) text = delta.get("content") + reasoning = delta.get("reasoning_content") if isinstance(text, str) and text: - found.append(delta) + found.append((delta, "content")) + if isinstance(reasoning, str) and reasoning: + found.append((delta, "reasoning_content")) if not found: return _flush_then(demask, event) emit = finishing - for delta in found: - ready = demask.feed(delta["content"], final=finishing) + for delta, field in found: + ready = demask.feed(delta[field], final=finishing) if ready: - delta["content"] = ready + delta[field] = ready emit = True else: - delta.pop("content", None) + delta.pop(field, None) if not emit: return [] return [sse(payload).encode()] @@ -965,8 +991,10 @@ def demask_reply(parsed: dict, session_id: str) -> None: return for choice in parsed.get("choices") or []: message = choice.get("message") - if isinstance(message, dict) and isinstance(message.get("content"), str): - message["content"] = demask_local_text(message["content"], session_id) + if isinstance(message, dict): + for field in ("content", "reasoning_content"): + if isinstance(message.get(field), str): + message[field] = demask_local_text(message[field], session_id) def attach_mask_safety(messages: list) -> None: @@ -1635,11 +1663,18 @@ def clip_bytes(raw: bytes) -> Any: def trace_body(body: dict) -> dict: - """What a request carried, without headers. The bearer token never arrives here.""" + """What a request carried, without message text. The bearer token never arrives here.""" kept: dict = {} - for key in ("model", "stream", "messages", "tool_choice", "max_tokens"): + for key in ("model", "stream", "tool_choice", "max_tokens"): if key in body: kept[key] = body[key] + messages = body.get("messages") + if isinstance(messages, list): + kept["messages"] = [ + {"role": message.get("role"), "chars": len(message_text(message))} + if isinstance(message, dict) else {"role": "", "chars": 0} + for message in messages + ] tools = body.get("tools") if isinstance(tools, list): kept["tools"] = [ @@ -2522,12 +2557,14 @@ async def local(path: str, body: dict, request: Request, config: dict): waiting += 1 queued = True STATS["queued"] += 1 + log({"event": "queued", "waiting": waiting}) # Under privacy a subagent never overflows to the cloud, or its task # reaches it after all; it waits for the slot instead. if overflow and (config["policy"] == "privacy" or summary == "local_only"): overflow = False if overflow: STATS["overflow"] += 1 + log({"event": "overflow"}) response = await cloud(path, {**body, "messages": strip_marker(body["messages"])}, request) response.headers["x-pls-overflow"] = "1" diff --git a/pls/test_pls.py b/pls/test_pls.py index 2bc01482..8a1f291d 100644 --- a/pls/test_pls.py +++ b/pls/test_pls.py @@ -794,29 +794,28 @@ def test_the_subscription_state_is_gone(self): self.assertNotIn("premium_blocked", pls.STATS) def test_the_watch_log_carries_no_subscription_field(self): - self.assertNotIn("sub", self.client.get("/watch/log").text) + pls.http.send = _fake_send_json([], completion("cloud answer")) + self.cloud_post(self.later(dsh_first_turn())) + for line in (pls.WATCH_DIR / "traffic.jsonl").read_text().splitlines(): + self.assertNotIn("sub", json.loads(line)) def test_watch_records_what_went_in_and_what_came_out(self): pls.http.send = _fake_send_json([], completion("cloud answer")) self.cloud_post(self.later(dsh_first_turn())) raw = (pls.WATCH_DIR / "traffic.jsonl").read_text() events = [json.loads(line) for line in raw.splitlines()] - page = self.client.get("/watch") - log = self.client.get("/watch/log") incoming = [event for event in events if event.get("event") == "in"] outgoing = [event for event in events if event.get("event") == "out"] self.assertEqual(len(incoming), 1) self.assertEqual(outgoing[0]["req"], incoming[0]["req"]) self.assertIn("messages", incoming[0]["body"]) + self.assertNotIn("What does this repo", json.dumps(incoming[0]["body"])) self.assertIn("cloud answer", json.dumps(outgoing[0]["body"])) self.assertTrue(any( event.get("event") == "route" and event.get("req") == incoming[0]["req"] for event in events)) - self.assertEqual(page.status_code, 200) - self.assertIn("PLS watch", page.text) - self.assertIn("Raw log", page.text) - self.assertEqual(log.status_code, 200) - self.assertIn("cloud answer", log.text) + self.assertEqual(self.client.get("/watch").status_code, 404) + self.assertEqual(self.client.get("/watch/log").status_code, 404) def through_the_socket(self): """Main chat and a subagent with the real decide and token clients.""" @@ -1161,6 +1160,35 @@ def test_a_cloud_reply_is_demasked_before_it_reaches_the_chat(self): self.assertIn(value, self.answer(response)) self.assertNotIn("⟦pii:1⟧", self.answer(response)) + def test_reasoning_content_is_demasked_before_it_reaches_the_chat(self): + value = "secret-value" + pls.mask_stores["deepseek"].mask( + "s", value, [{"start": 0, "end": len(value), "category": "other"}]) + body = ( + b'data: ' + json.dumps({"choices": [{"index": 0, "delta": { + "reasoning_content": "\u27e6pii:1\u27e7 are personal"}}]}).encode() + + b"\n\n" + + b'data: ' + json.dumps({"choices": [{"index": 0, "delta": {}, + "finish_reason": "stop"}]}).encode() + + b"\n\ndata: [DONE]\n\n" + ) + async def send(request, stream=False): + return FakeStream(body) + + pls.http.send = send + response = self.cloud_post({**self.later(dsh_first_turn()), "stream": True}) + self.assertIn(value, response.text) + self.assertNotIn("\u27e6pii:1\u27e7", response.text) + + def test_a_credentials_path_is_masked_as_personal(self): + text = "read /Users/home/Downloads/Siddhesh_credentials.csv now" + start = text.index("/") + end = text.index(" ", start) + self.assertFalse(pls._span_is_path(text, {"start": start, "end": end})) + spans = pls._sensitive_path_spans(text) + self.assertEqual(text[spans[0]["start"]:spans[0]["end"]], + "/Users/home/Downloads/Siddhesh_credentials.csv") + def test_a_demasked_reply_is_masked_again_on_the_next_turn(self): value = "9 Nov 2026 12:46" pls.mask_stores["deepseek"].mask( @@ -1632,13 +1660,9 @@ def test_parse_calls_joins_arguments_split_across_chunks(self): # -- launch token ------------------------------------------------------ - def test_the_watch_page_is_open_without_the_launch_token(self): - pls.TOKEN = "s3cret" - try: - self.assertEqual(self.client.get("/watch").status_code, 200) - self.assertEqual(self.client.get("/watch/log").status_code, 200) - finally: - pls.TOKEN = "" + def test_the_watch_routes_are_gone(self): + self.assertEqual(self.client.get("/watch").status_code, 404) + self.assertEqual(self.client.get("/watch/log").status_code, 404) def test_a_request_without_the_launch_token_is_refused(self): pls.TOKEN = "s3cret" diff --git a/pls/watch/__init__.py b/pls/watch/__init__.py index ccbbc457..26c67aaf 100644 --- a/pls/watch/__init__.py +++ b/pls/watch/__init__.py @@ -1,40 +1,60 @@ -"""Traffic log for the router. Delete this package and the router still runs. +"""Request log for the router. Delete this package and the router still runs. -The log file stays on disk, so it can be read after the process exits. -The page and the raw log are open on purpose: no token. +One JSON object per line at /pls/watch/traffic.jsonl, mode 0600. +Rows older than 7 days are dropped, and the file keeps the newest 2000 lines. +There is no page. """ import json +import os +import time from pathlib import Path from typing import Callable -from fastapi import FastAPI -from fastapi.responses import HTMLResponse, PlainTextResponse - _directory: Callable[[], Path] | None = None +_KEEP_SECONDS = 7 * 24 * 60 * 60 +_KEEP_LINES = 2000 -def attach(app: FastAPI, directory: Callable[[], Path]) -> None: +def start(directory: Callable[[], Path]) -> None: global _directory _directory = directory - @app.get("/watch") - def page(): - html = Path(__file__).with_name("page.html").read_text() - return HTMLResponse(html) - - @app.get("/watch/log") - def raw(): - path = directory() / "traffic.jsonl" - text = path.read_text() if path.is_file() else "" - return PlainTextResponse(text) - def record(event: dict) -> None: if _directory is None: return folder = _directory() folder.mkdir(parents=True, exist_ok=True) + os.chmod(folder, 0o700) path = folder / "traffic.jsonl" - with path.open("a", encoding="utf-8") as handle: - handle.write(json.dumps(event, ensure_ascii=False) + "\n") + _drop_old(path) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) + try: + os.chmod(path, 0o600) + with os.fdopen(fd, "a", encoding="utf-8") as handle: + handle.write(json.dumps(event, ensure_ascii=False) + "\n") + except Exception: + pass + + +def _drop_old(path: Path) -> None: + if not path.is_file(): + return + cutoff = time.time() - _KEEP_SECONDS + lines = path.read_text(encoding="utf-8").splitlines() + kept = [] + for line in lines: + try: + event = json.loads(line) + except Exception: + continue + if float(event.get("ts") or 0) >= cutoff: + kept.append(line) + kept = kept[-_KEEP_LINES:] + if kept == lines: + return + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + if kept: + handle.write("\n".join(kept) + "\n") diff --git a/pls/watch/page.html b/pls/watch/page.html deleted file mode 100644 index ed912a4c..00000000 --- a/pls/watch/page.html +++ /dev/null @@ -1,192 +0,0 @@ - - - - -PLS watch - - - -
-

PLS watch

- - - -
-
-
-
-
- - - -
WhenRequestLaneFirst byteTotalWhat hurt
-
-
-
- - - diff --git a/src/commands/cmd_harness.rs b/src/commands/cmd_harness.rs index e61af482..7fc25693 100644 --- a/src/commands/cmd_harness.rs +++ b/src/commands/cmd_harness.rs @@ -289,8 +289,11 @@ pub fn register_harness(app: &mut App) { Err(status) => return status, Ok(Some((mut local, mut cloud, policy))) => { if let Some(context) = saved_local_context() { + let context = context.max(context_min_for(&agent.id)); std::env::set_var("PLS_MAX_KV", context.to_string()); - local = "mlx-pplx-coder-35b-4bit".to_string(); + if p.flag("--custom") { + local = "mlx-pplx-coder-35b-4bit".to_string(); + } if p.get_str("--cloud-model").is_none() { if let Some(saved) = saved_cloud_model() { cloud = saved; @@ -449,6 +452,10 @@ fn ask(prompt: &str) -> Result { Ok(line.trim().to_string()) } +fn printable_model_id(id: &str) -> bool { + !id.is_empty() && id.chars().all(|c| c.is_ascii_graphic()) +} + fn cloud_ids() -> Result, i32> { let mut session = match crate::account::ConsoleSession::open(crate::account::ConsoleClient::default()) { @@ -459,7 +466,10 @@ fn cloud_ids() -> Result, i32> { out::error_line(&error); return Err(2); } - return Ok(cached); + return Ok(cached + .into_iter() + .filter(|id| printable_model_id(id)) + .collect()); } }; match session.call(|client, url, token| client.fetch_models_within(url, token, 8_000)) { @@ -467,7 +477,7 @@ fn cloud_ids() -> Result, i32> { let ids: Vec = models .into_iter() .map(|model| model.id) - .filter(|id| !id.is_empty()) + .filter(|id| printable_model_id(id)) .collect(); if ids.is_empty() { out::error_line("the account has no cloud models"); @@ -482,7 +492,10 @@ fn cloud_ids() -> Result, i32> { out::error_line(&error); Err(2) } else { - Ok(cached) + Ok(cached + .into_iter() + .filter(|id| printable_model_id(id)) + .collect()) } } } diff --git a/src/harness/hybrid.rs b/src/harness/hybrid.rs index 6b6ac5a6..ae3bc5ed 100644 --- a/src/harness/hybrid.rs +++ b/src/harness/hybrid.rs @@ -217,6 +217,7 @@ fn build_hybrid_llm_config( key_variable: &str, token: &str, cloud: &ModelLimits, + local_context: i64, ) -> String { let model = |id: &str, context: i64, output: i64, image: bool| { json!({ @@ -232,7 +233,7 @@ fn build_hybrid_llm_config( }; let subagent = model( HYBRID_LOCAL_MODEL_ID, - local_context_window(), + local_context, HYBRID_LOCAL_OUTPUT, false, ); @@ -505,8 +506,13 @@ pub fn launch_deep_seek_hybrid( }; let router = &hybrid.router; let cloud_limits = &hybrid.cloud; - let llm_config = - build_hybrid_llm_config(&router.base_url, KEY_VARIABLE, &router.token, cloud_limits); + let llm_config = build_hybrid_llm_config( + &router.base_url, + KEY_VARIABLE, + &router.token, + cloud_limits, + local_context_window(), + ); let mut config = TemporaryConfig::new(); if let Err(failure) = config.write(&build_hybrid_patch(&llm_config), ".yaml") { out::error_line(&failure); @@ -546,8 +552,13 @@ mod tests { use serde_json::{json, Value}; fn hybrid_config_with(cloud: &ModelLimits) -> Value { - let config = - build_hybrid_llm_config("http://127.0.0.1:1234", "WALLY_PLS_KEY", "tok", cloud); + let config = build_hybrid_llm_config( + "http://127.0.0.1:1234", + "WALLY_PLS_KEY", + "tok", + cloud, + HYBRID_LOCAL_CONTEXT, + ); serde_json::from_str(&config).unwrap() } @@ -602,6 +613,7 @@ mod tests { "WALLY_PLS_KEY", "tok", &ModelLimits::default(), + HYBRID_LOCAL_CONTEXT, ); let patch = build_hybrid_patch(&config); assert!(!patch.contains("wally-local")); @@ -615,6 +627,7 @@ mod tests { "WALLY_PLS_KEY", "tok", &ModelLimits::default(), + HYBRID_LOCAL_CONTEXT, ); let patch = build_hybrid_patch(&config); // The row's own provider must survive the overlay, or dsh rejects the @@ -632,6 +645,7 @@ mod tests { "K", "tok", &ModelLimits::default(), + HYBRID_LOCAL_CONTEXT, )); let row = patch .split("- id: ") @@ -648,6 +662,7 @@ mod tests { "K", "tok", &ModelLimits::default(), + HYBRID_LOCAL_CONTEXT, )); let row = patch .split("- id: ") diff --git a/src/harness/pls.rs b/src/harness/pls.rs index a9787af9..953ecc75 100644 --- a/src/harness/pls.rs +++ b/src/harness/pls.rs @@ -369,7 +369,6 @@ const PII_VITERBI: &str = include_str!("../../pls/pii_viterbi.py"); const PII_WEIGHTS: &str = include_str!("../../pls/pii_weights.py"); const LOCK: &str = include_str!("../../pls/requirements.lock"); const WATCH_PY: &str = include_str!("../../pls/watch/__init__.py"); -const WATCH_PAGE: &str = include_str!("../../pls/watch/page.html"); const KVC: &str = include_str!("../../pls/kvc.py"); /// A running router. Dropping it stops the process. @@ -758,7 +757,7 @@ fn materialise() -> Option { "{:x}", fnv1a( format!( - "{SCRIPT}\u{0}{MODEL_SERVER}\u{0}{MASK_STORE}\u{0}{PII_MODEL}\u{0}{PII_BACKBONE}\u{0}{PII_LABELS}\u{0}{PII_VITERBI}\u{0}{PII_WEIGHTS}\u{0}{LOCK}\u{0}{WATCH_PY}\u{0}{WATCH_PAGE}\u{0}{KVC}" + "{SCRIPT}\u{0}{MODEL_SERVER}\u{0}{MASK_STORE}\u{0}{PII_MODEL}\u{0}{PII_BACKBONE}\u{0}{PII_LABELS}\u{0}{PII_VITERBI}\u{0}{PII_WEIGHTS}\u{0}{LOCK}\u{0}{WATCH_PY}\u{0}{KVC}" ) .as_bytes(), ) @@ -784,7 +783,6 @@ fn materialise() -> Option { let watch_dir = dir.join("watch"); std::fs::create_dir_all(&watch_dir).ok()?; std::fs::write(watch_dir.join("__init__.py"), WATCH_PY).ok()?; - std::fs::write(watch_dir.join("page.html"), WATCH_PAGE).ok()?; std::fs::write(dir.join("kvc.py"), KVC).ok()?; std::fs::write(&marker, wanted).ok()?; Some(script) @@ -1087,7 +1085,6 @@ fn start_with( let _ = std::fs::write(pid_path(), format!("{} {}", child.id(), script.display())); let base_url = format!("http://127.0.0.1:{port}"); out::status_line(&format!("router ready on {base_url}")); - out::status_line(&format!("watch: {base_url}/watch")); Some(Router { child, base_url, From 4aed8719f6fca07b01f1203a7dd3404cfb335eee Mon Sep 17 00:00:00 2001 From: Siddhesh Sonar Date: Tue, 10 Nov 2026 20:58:55 +0530 Subject: [PATCH 25/26] fix(cli): satisfy clippy and record --custom in help goldens --- src/commands/cmd_harness.rs | 8 +++----- tests/golden/expected/help__deepseek.stdout | 2 ++ tests/golden/expected/help__help__deepseek.stdout | 2 ++ tests/golden/expected/help__help__hermes.stdout | 2 ++ tests/golden/expected/help__hermes.stdout | 2 ++ 5 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/commands/cmd_harness.rs b/src/commands/cmd_harness.rs index 7fc25693..877a3cd0 100644 --- a/src/commands/cmd_harness.rs +++ b/src/commands/cmd_harness.rs @@ -289,7 +289,7 @@ pub fn register_harness(app: &mut App) { Err(status) => return status, Ok(Some((mut local, mut cloud, policy))) => { if let Some(context) = saved_local_context() { - let context = context.max(context_min_for(&agent.id)); + let context = context.max(context_min_for(agent.id)); std::env::set_var("PLS_MAX_KV", context.to_string()); if p.flag("--custom") { local = "mlx-pplx-coder-35b-4bit".to_string(); @@ -303,7 +303,7 @@ pub fn register_harness(app: &mut App) { "hybrid defaults: context {context}, cloud {cloud}" )); } else if p.flag("--custom") { - match custom_hybrid(&agent.id, &cloud) { + match custom_hybrid(agent.id, &cloud) { Err(status) => return status, Ok(choice) => { cloud = choice.cloud; @@ -383,9 +383,7 @@ fn saved_local_context() -> Option { } fn saved_cloud_model() -> Option { - if saved_local_context().is_none() { - return None; - } + saved_local_context()?; config_json() .get("cloud_model") .and_then(|value| value.as_str()) diff --git a/tests/golden/expected/help__deepseek.stdout b/tests/golden/expected/help__deepseek.stdout index ab821ec4..b0c1530a 100644 --- a/tests/golden/expected/help__deepseek.stdout +++ b/tests/golden/expected/help__deepseek.stdout @@ -15,6 +15,8 @@ Options: (default: your default model) --policy TEXT What --hybrid optimises for: privacy (default) or cost + --custom After --hybrid, ask for the local context window + and the cloud model Examples: # Download the certified local model once diff --git a/tests/golden/expected/help__help__deepseek.stdout b/tests/golden/expected/help__help__deepseek.stdout index ab821ec4..b0c1530a 100644 --- a/tests/golden/expected/help__help__deepseek.stdout +++ b/tests/golden/expected/help__help__deepseek.stdout @@ -15,6 +15,8 @@ Options: (default: your default model) --policy TEXT What --hybrid optimises for: privacy (default) or cost + --custom After --hybrid, ask for the local context window + and the cloud model Examples: # Download the certified local model once diff --git a/tests/golden/expected/help__help__hermes.stdout b/tests/golden/expected/help__help__hermes.stdout index 5e703e78..645acd00 100644 --- a/tests/golden/expected/help__help__hermes.stdout +++ b/tests/golden/expected/help__help__hermes.stdout @@ -15,6 +15,8 @@ Options: (default: your default model) --policy TEXT What --hybrid optimises for: privacy (default) or cost + --custom After --hybrid, ask for the local context window + and the cloud model Examples: # Download the certified local model once diff --git a/tests/golden/expected/help__hermes.stdout b/tests/golden/expected/help__hermes.stdout index 5e703e78..645acd00 100644 --- a/tests/golden/expected/help__hermes.stdout +++ b/tests/golden/expected/help__hermes.stdout @@ -15,6 +15,8 @@ Options: (default: your default model) --policy TEXT What --hybrid optimises for: privacy (default) or cost + --custom After --hybrid, ask for the local context window + and the cloud model Examples: # Download the certified local model once From f0a7a7e8dfdb84dbe64bc617f8342d7911ab42bd Mon Sep 17 00:00:00 2001 From: Siddhesh Sonar Date: Tue, 10 Nov 2026 21:24:32 +0530 Subject: [PATCH 26/26] fix(pls): close the remaining review notes on the log and the mask --- pls/README.md | 11 ++--- pls/local_limits.py | 9 +++++ pls/local_only.py | 12 +++--- pls/model_server.py | 37 ++++++++++------- pls/pls.py | 80 ++++++++++++++++++++++++++++--------- pls/watch/__init__.py | 38 +++++++++++------- src/commands/cmd_harness.rs | 45 ++++++++++----------- src/harness/hybrid.rs | 19 ++++----- src/harness/pls.rs | 4 +- 9 files changed, 161 insertions(+), 94 deletions(-) create mode 100644 pls/local_limits.py diff --git a/pls/README.md b/pls/README.md index dcef0e66..a2dc19ef 100644 --- a/pls/README.md +++ b/pls/README.md @@ -116,11 +116,12 @@ wally serves the router over a unix socket at `~/.config/wally/pls/pls.sock` ## Log -Each request is one JSON line in the profile `pls/watch/traffic.jsonl` -(`~/.config/wally/pls/watch/` unless `WALLY_PROFILE_DIR` is set). The file is -mode 0600. It keeps roles and lengths, not the raw prompt. Rows older than 7 -days are dropped, and only the newest 2000 lines are kept. Delete the -`pls/watch` package and the router keeps running without the log. +Each event is one JSON line in the profile `pls/watch/traffic.jsonl` +(`~/.config/wally/pls/watch/` unless `WALLY_PROFILE_DIR` is set). Lines from +the same request share a `req` id. The file is mode 0600. It keeps roles and +lengths, not the raw prompt. Rows older than 7 days are dropped, and only the +newest 2000 lines are kept. Delete the `pls/watch` package and the router +keeps running without the log. ## PII diff --git a/pls/local_limits.py b/pls/local_limits.py new file mode 100644 index 00000000..bfb80f6d --- /dev/null +++ b/pls/local_limits.py @@ -0,0 +1,9 @@ +"""Shared window and prefix-cache settings for the local model.""" + +import os + +MAX_KV = int(os.environ.get("PLS_MAX_KV", "65536")) +MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192")) +APC_BLOCKS = int(os.environ.get("PLS_APC_BLOCKS", "8192")) +APC_CHECKPOINTS = int(os.environ.get("PLS_APC_CHECKPOINTS", "32")) +APC_CHECKPOINT_INTERVAL = int(os.environ.get("PLS_APC_CHECKPOINT_INTERVAL", "4096")) diff --git a/pls/local_only.py b/pls/local_only.py index 9358f4aa..babad36e 100644 --- a/pls/local_only.py +++ b/pls/local_only.py @@ -13,11 +13,13 @@ import mlx_vlm from mlx_vlm.apc import APCManager -MAX_KV = int(os.environ.get("PLS_MAX_KV", "65536")) -MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192")) -APC_BLOCKS = int(os.environ.get("PLS_APC_BLOCKS", "8192")) -APC_CHECKPOINTS = int(os.environ.get("PLS_APC_CHECKPOINTS", "32")) -APC_CHECKPOINT_INTERVAL = int(os.environ.get("PLS_APC_CHECKPOINT_INTERVAL", "4096")) +from local_limits import ( + APC_BLOCKS, + APC_CHECKPOINT_INTERVAL, + APC_CHECKPOINTS, + MAX_KV, + MAX_OUT, +) def model_path() -> str: diff --git a/pls/model_server.py b/pls/model_server.py index 313e19a3..156f8432 100644 --- a/pls/model_server.py +++ b/pls/model_server.py @@ -35,17 +35,26 @@ MODEL_PATH = os.environ["PLS_MODEL"] MODEL_ID = os.environ.get("PLS_MODEL_ID", "Hybrid-Wally-0.1-local") # 64K: Hermes refuses a delegation model with a window under 64,000. -MAX_KV = int(os.environ.get("PLS_MAX_KV", "65536")) -MAX_OUT = int(os.environ.get("PLS_MAX_OUT", "8192")) -# APC's defaults hold 2048 x 16 = 32k tokens and two checkpoints, taken every -# 2048 tokens. Hybrid-attention models (the PPLX 35B) reuse only through -# checkpoints, and one 12k subagent context alone takes six of them, so a -# second subagent evicted the first and every turn re-prefilled past the -# shared system prompt. Fewer, wider checkpoints and a higher cap keep several -# live contexts. -APC_BLOCKS = int(os.environ.get("PLS_APC_BLOCKS", "8192")) -APC_CHECKPOINTS = int(os.environ.get("PLS_APC_CHECKPOINTS", "32")) -APC_CHECKPOINT_INTERVAL = int(os.environ.get("PLS_APC_CHECKPOINT_INTERVAL", "4096")) +from local_limits import ( + APC_BLOCKS, + APC_CHECKPOINT_INTERVAL, + APC_CHECKPOINTS, + MAX_KV, + MAX_OUT, +) + + +def _parse_kv_bits() -> float | None: + raw = os.environ.get("PLS_KV_BITS", "8") + if raw in ("", "0"): + return None + try: + return float(raw) + except ValueError: + raise SystemExit(f"PLS_KV_BITS must be a number, got {raw!r}") + + +KV_BITS = _parse_kv_bits() def _kv_memory_profile(cache, token_count): @@ -218,10 +227,8 @@ async def chat(request: Request): ) kwargs["max_tokens"] = budget kwargs["apc_manager"] = apc - # 8-bit cache. The weights stay 4-bit. Set PLS_KV_BITS=0 to keep full cache. - kv_bits = os.environ.get("PLS_KV_BITS", "8") - if kv_bits not in ("", "0"): - kwargs["kv_bits"] = float(kv_bits) + if KV_BITS is not None: + kwargs["kv_bits"] = KV_BITS kwargs["quantized_kv_start"] = 0 loop = asyncio.get_running_loop() diff --git a/pls/pls.py b/pls/pls.py index 28a7bc95..f4c034c6 100644 --- a/pls/pls.py +++ b/pls/pls.py @@ -791,7 +791,7 @@ async def mask_cloud_text(text: str, session_id: str) -> str | None: note_masking_off("classifier returned no span list") return None spans = [span for span in spans if not _span_is_path(text, span)] - spans = spans + _sensitive_path_spans(text) + spans = _merge_spans(spans + _sensitive_path_spans(text)) store = open_mask_store() if store is None: note_masking_off("mask store unavailable") @@ -824,7 +824,23 @@ def _span_is_path(text: str, span: dict) -> bool: _SENSITIVE_FILE = re.compile( r"(?i)(credential|secret|password|passwd|\.pem$|\.env$|id_rsa|api[_-]?key)" ) -_PATH_IN_TEXT = re.compile(r"(?:~|\.\.?|/[A-Za-z0-9._-])[^\s\"'`<>]*") +_PATH_IN_TEXT = re.compile( + r"(?]*" +) + + +def _merge_spans(spans: list[dict]) -> list[dict]: + """Drop a later span that overlaps one already kept.""" + ordered = sorted(spans, key=lambda span: (span.get("start", 0), span.get("end", 0))) + kept: list[dict] = [] + for span in ordered: + start, end = span.get("start"), span.get("end") + if not isinstance(start, int) or not isinstance(end, int): + continue + if kept and start < kept[-1]["end"]: + continue + kept.append(span) + return kept def _sensitive_path_spans(text: str) -> list[dict]: @@ -917,11 +933,34 @@ def flush(self) -> str: return self.feed("", final=True) +def _field_sse(field: str, text: str) -> bytes: + return sse(chunk("chatcmpl-pls-demask", int(time.time()), {field: text})).encode() + + def _content_sse(text: str) -> bytes: - return sse(chunk("chatcmpl-pls-demask", int(time.time()), {"content": text})).encode() + return _field_sse("content", text) + +class ReplyDemasks: + """Separate restore buffers, so a split token cannot cross fields.""" -def map_sse_event(event: bytes, demask: ReplyDemask | None) -> list[bytes]: + def __init__(self, session_id: str): + self.content = ReplyDemask(session_id) + self.reasoning = ReplyDemask(session_id) + + def for_field(self, field: str) -> ReplyDemask: + if field == "reasoning_content": + return self.reasoning + return self.content + + def flush_all(self) -> list[tuple[str, str]]: + return [ + ("content", self.content.flush()), + ("reasoning_content", self.reasoning.flush()), + ] + + +def map_sse_event(event: bytes, demask: ReplyDemasks | None) -> list[bytes]: """Demask text deltas. A non-text event flushes a held token first.""" if demask is None or not event.strip(): return [event] @@ -950,7 +989,7 @@ def map_sse_event(event: bytes, demask: ReplyDemask | None) -> list[bytes]: return _flush_then(demask, event) emit = finishing for delta, field in found: - ready = demask.feed(delta[field], final=finishing) + ready = demask.for_field(field).feed(delta[field], final=finishing) if ready: delta[field] = ready emit = True @@ -961,17 +1000,22 @@ def map_sse_event(event: bytes, demask: ReplyDemask | None) -> list[bytes]: return [sse(payload).encode()] -def _flush_then(demask: ReplyDemask, event: bytes) -> list[bytes]: - ready = demask.flush() - if not ready: +def _flush_then(demask: ReplyDemasks, event: bytes) -> list[bytes]: + out = [ + _field_sse(field, ready) + for field, ready in demask.flush_all() + if ready + ] + if not out: return [event] - return [_content_sse(ready), event] + out.append(event) + return out def demask_sse_bytes(raw: bytes, session_id: str) -> bytes: if not raw or not session_id: return raw - demask = ReplyDemask(session_id) + demask = ReplyDemasks(session_id) out: list[bytes] = [] pending = raw while b"\n\n" in pending: @@ -979,9 +1023,9 @@ def demask_sse_bytes(raw: bytes, session_id: str) -> bytes: out.extend(map_sse_event(event + b"\n\n", demask)) if pending: out.extend(map_sse_event(pending, demask)) - ready = demask.flush() - if ready: - out.append(_content_sse(ready)) + for field, ready in demask.flush_all(): + if ready: + out.append(_field_sse(field, ready)) return b"".join(out) @@ -2400,7 +2444,7 @@ async def guarded_stream(): if policy == "privacy" and parent: reply_session = mask_session or mask_session_id( request, body.get("messages") or []) - demask = ReplyDemask(reply_session) if reply_session else None + demask = ReplyDemasks(reply_session) if reply_session else None try: async for piece in response.aiter_bytes(): if first_ms is None: @@ -2430,10 +2474,10 @@ async def guarded_stream(): "total_ms": elapsed(), "attempt": attempt, "streamed_text": streamed}) if demask is not None: - rest = demask.flush() - if rest: - yield _content_sse(rest) - streamed = True + for field, rest in demask.flush_all(): + if rest: + yield _field_sse(field, rest) + streamed = True raw = b"".join(held) if reply_session: raw = demask_sse_bytes(raw, reply_session) diff --git a/pls/watch/__init__.py b/pls/watch/__init__.py index 26c67aaf..c5ba670a 100644 --- a/pls/watch/__init__.py +++ b/pls/watch/__init__.py @@ -8,12 +8,15 @@ import json import os import time +from collections import deque from pathlib import Path from typing import Callable _directory: Callable[[], Path] | None = None _KEEP_SECONDS = 7 * 24 * 60 * 60 _KEEP_LINES = 2000 +_PRUNE_EVERY = 64 +_since_prune = 0 def start(directory: Callable[[], Path]) -> None: @@ -22,13 +25,18 @@ def start(directory: Callable[[], Path]) -> None: def record(event: dict) -> None: + global _since_prune if _directory is None: return folder = _directory() folder.mkdir(parents=True, exist_ok=True) os.chmod(folder, 0o700) path = folder / "traffic.jsonl" - _drop_old(path) + _since_prune += 1 + bulky = path.is_file() and path.stat().st_size > 1_500_000 + if _since_prune >= _PRUNE_EVERY or bulky: + _drop_old(path) + _since_prune = 0 fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) try: os.chmod(path, 0o600) @@ -42,19 +50,21 @@ def _drop_old(path: Path) -> None: if not path.is_file(): return cutoff = time.time() - _KEEP_SECONDS - lines = path.read_text(encoding="utf-8").splitlines() - kept = [] - for line in lines: - try: - event = json.loads(line) - except Exception: - continue - if float(event.get("ts") or 0) >= cutoff: - kept.append(line) - kept = kept[-_KEEP_LINES:] - if kept == lines: - return - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + kept: deque[str] = deque(maxlen=_KEEP_LINES) + with path.open(encoding="utf-8") as handle: + for line in handle: + line = line.rstrip("\n") + if not line: + continue + try: + event = json.loads(line) + except Exception: + continue + if float(event.get("ts") or 0) >= cutoff: + kept.append(line) + tmp = path.with_suffix(".jsonl.tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as handle: if kept: handle.write("\n".join(kept) + "\n") + os.replace(tmp, path) diff --git a/src/commands/cmd_harness.rs b/src/commands/cmd_harness.rs index 877a3cd0..4cc0e700 100644 --- a/src/commands/cmd_harness.rs +++ b/src/commands/cmd_harness.rs @@ -288,9 +288,10 @@ pub fn register_harness(app: &mut App) { match hybrid_request(p, g.no_color) { Err(status) => return status, Ok(Some((mut local, mut cloud, policy))) => { + let mut local_context = crate::harness::HYBRID_LOCAL_CONTEXT; if let Some(context) = saved_local_context() { - let context = context.max(context_min_for(agent.id)); - std::env::set_var("PLS_MAX_KV", context.to_string()); + local_context = context.max(context_min_for(agent.id)); + std::env::set_var("PLS_MAX_KV", local_context.to_string()); if p.flag("--custom") { local = "mlx-pplx-coder-35b-4bit".to_string(); } @@ -300,7 +301,7 @@ pub fn register_harness(app: &mut App) { } } out::status_line(&format!( - "hybrid defaults: context {context}, cloud {cloud}" + "hybrid defaults: context {local_context}, cloud {cloud}" )); } else if p.flag("--custom") { match custom_hybrid(agent.id, &cloud) { @@ -308,6 +309,7 @@ pub fn register_harness(app: &mut App) { Ok(choice) => { cloud = choice.cloud; local = "mlx-pplx-coder-35b-4bit".to_string(); + local_context = choice.context; std::env::set_var("PLS_MAX_KV", choice.context.to_string()); if choice.save { save_local_context(choice.context); @@ -320,6 +322,7 @@ pub fn register_harness(app: &mut App) { &local, &cloud, &policy, + local_context, &p.get_strs("args"), g, ); @@ -454,20 +457,25 @@ fn printable_model_id(id: &str) -> bool { !id.is_empty() && id.chars().all(|c| c.is_ascii_graphic()) } +fn cached_or_error(error: &str) -> Result, i32> { + let ids: Vec = crate::account::cached_model_ids() + .into_iter() + .filter(|id| printable_model_id(id)) + .collect(); + if ids.is_empty() { + out::error_line(error); + Err(2) + } else { + Ok(ids) + } +} + fn cloud_ids() -> Result, i32> { let mut session = match crate::account::ConsoleSession::open(crate::account::ConsoleClient::default()) { Ok(session) => session, Err(error) => { - let cached = crate::account::cached_model_ids(); - if cached.is_empty() { - out::error_line(&error); - return Err(2); - } - return Ok(cached - .into_iter() - .filter(|id| printable_model_id(id)) - .collect()); + return cached_or_error(&error); } }; match session.call(|client, url, token| client.fetch_models_within(url, token, 8_000)) { @@ -484,18 +492,7 @@ fn cloud_ids() -> Result, i32> { Ok(ids) } } - Err(error) => { - let cached = crate::account::cached_model_ids(); - if cached.is_empty() { - out::error_line(&error); - Err(2) - } else { - Ok(cached - .into_iter() - .filter(|id| printable_model_id(id)) - .collect()) - } - } + Err(error) => cached_or_error(&error), } } diff --git a/src/harness/hybrid.rs b/src/harness/hybrid.rs index ae3bc5ed..43524c1d 100644 --- a/src/harness/hybrid.rs +++ b/src/harness/hybrid.rs @@ -34,12 +34,15 @@ pub fn launch_hybrid( model: &str, cloud_model: &str, policy: &str, + local_context: i64, args: &[String], options: &GlobalOptions, ) -> i32 { match agent.id { "hermes" => launch_hermes_hybrid(agent, model, cloud_model, policy, args, options), - "deepseek" => launch_deep_seek_hybrid(model, cloud_model, policy, args, options), + "deepseek" => { + launch_deep_seek_hybrid(model, cloud_model, policy, local_context, args, options) + } _ => { out::error_line(&format!("{} has no hybrid launch", agent.id)); 2 @@ -195,18 +198,9 @@ pub const HYBRID_MODEL_ID: &str = "Hybrid-Wally-0.1"; pub const HYBRID_LOCAL_MODEL_ID: &str = "Hybrid-Wally-0.1-local"; /// The local lane's limits: the model server's KV cap and reply cap. -pub(super) const HYBRID_LOCAL_CONTEXT: i64 = 65536; +pub(crate) const HYBRID_LOCAL_CONTEXT: i64 = 65536; pub(super) const HYBRID_LOCAL_OUTPUT: i64 = 8192; -/// The window `--custom` chose for this launch, or the built-in cap. -fn local_context_window() -> i64 { - std::env::var("PLS_MAX_KV") - .ok() - .and_then(|value| value.parse::().ok()) - .filter(|value| *value > 0) - .unwrap_or(HYBRID_LOCAL_CONTEXT) -} - /// The one-provider `llm-pi-ai` config for a hybrid launch. `cloud` is what /// the console says the parent's cloud model can hold: the parent's model /// entry declares those limits and the subagent's the local ones, because a @@ -491,6 +485,7 @@ pub fn launch_deep_seek_hybrid( model: &str, cloud_model: &str, policy: &str, + local_context: i64, args: &[String], options: &GlobalOptions, ) -> i32 { @@ -511,7 +506,7 @@ pub fn launch_deep_seek_hybrid( KEY_VARIABLE, &router.token, cloud_limits, - local_context_window(), + local_context, ); let mut config = TemporaryConfig::new(); if let Err(failure) = config.write(&build_hybrid_patch(&llm_config), ".yaml") { diff --git a/src/harness/pls.rs b/src/harness/pls.rs index 953ecc75..857c2385 100644 --- a/src/harness/pls.rs +++ b/src/harness/pls.rs @@ -370,6 +370,7 @@ const PII_WEIGHTS: &str = include_str!("../../pls/pii_weights.py"); const LOCK: &str = include_str!("../../pls/requirements.lock"); const WATCH_PY: &str = include_str!("../../pls/watch/__init__.py"); const KVC: &str = include_str!("../../pls/kvc.py"); +const LOCAL_LIMITS: &str = include_str!("../../pls/local_limits.py"); /// A running router. Dropping it stops the process. pub struct Router { @@ -757,7 +758,7 @@ fn materialise() -> Option { "{:x}", fnv1a( format!( - "{SCRIPT}\u{0}{MODEL_SERVER}\u{0}{MASK_STORE}\u{0}{PII_MODEL}\u{0}{PII_BACKBONE}\u{0}{PII_LABELS}\u{0}{PII_VITERBI}\u{0}{PII_WEIGHTS}\u{0}{LOCK}\u{0}{WATCH_PY}\u{0}{KVC}" + "{SCRIPT}\u{0}{MODEL_SERVER}\u{0}{MASK_STORE}\u{0}{PII_MODEL}\u{0}{PII_BACKBONE}\u{0}{PII_LABELS}\u{0}{PII_VITERBI}\u{0}{PII_WEIGHTS}\u{0}{LOCK}\u{0}{WATCH_PY}\u{0}{KVC}\u{0}{LOCAL_LIMITS}" ) .as_bytes(), ) @@ -784,6 +785,7 @@ fn materialise() -> Option { std::fs::create_dir_all(&watch_dir).ok()?; std::fs::write(watch_dir.join("__init__.py"), WATCH_PY).ok()?; std::fs::write(dir.join("kvc.py"), KVC).ok()?; + std::fs::write(dir.join("local_limits.py"), LOCAL_LIMITS).ok()?; std::fs::write(&marker, wanted).ok()?; Some(script) }