"""The local drafter: the pi coding agent against an OpenAI-compatible model server. The server keeps one model resident and every client shares it. Naming any other model makes the server load that one and evict the resident model for everyone, so the drafter always asks which model is loaded and uses exactly that one. """ from __future__ import annotations import errno import json import os import pwd import shutil import socket import subprocess import tempfile import urllib.error import urllib.request from collections.abc import Callable, Mapping from pathlib import Path from typing import NamedTuple from docs_review.draft import DraftResult from docs_review.secrets import redact KEY_VAR = "LOCAL_MODEL_API_KEY" USER_VAR = "DOCS_REVIEW_DRAFTER_USER" PI_BIN_VAR = "DOCS_REVIEW_PI_BIN" PROVIDER = "docs-review-local" LOADED_MODELS_PATH = "/api/inference/loaded-models" PROBE_TIMEOUT_S = 5 THINKING = "medium" # ls lists a directory, which the monthly enumeration check needs; it is pure file # reading, like read. There is no bash. TOOLS = "read,ls,edit,write" # Project-local pi files (.pi/ settings, extensions, skills, prompt templates) and # AGENTS.md come from the pull request, so none of them load. The repository's # CLAUDE.md and the guide arrive in the appended system prompt instead. ISOLATION_FLAGS = ("--no-approve", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files", "--no-mcp", "--offline") LOCAL_ENV = frozenset({"PATH", "LANG", "TMPDIR", "TERM", KEY_VAR}) ERROR_MAX = 200 INSTRUCTION = ("Your task is in the attached file {path}. Read and follow it; " "edit files only in the current directory.") UNREACHABLE_NOTE = "local drafter unavailable: model server unreachable" NO_MODEL_NOTE = "local drafter unavailable: no model loaded" REJECTED_NOTE = "local drafter: the model server rejected LOCAL_MODEL_API_KEY" NOT_SERVER_NOTE = "{url} does not look like the model server: {reason}" BAD_ID_NOTE = "local drafter: the model server reported an unusable model id {model!r}" # Failures to reach anything at all. Anything else that answers is the wrong server. _UNREACHABLE = (ConnectionError, TimeoutError, socket.timeout, socket.gaierror) _UNREACHABLE_ERRNOS = frozenset({errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN, errno.EHOSTDOWN}) class Probe(NamedTuple): model: str | None note: str | None # why there is no model; None when there is one soft: bool # the run should report the note and still succeed class DrafterUserError(RuntimeError): """Running as root without an existing DOCS_REVIEW_DRAFTER_USER account.""" class _NoRedirect(urllib.request.HTTPRedirectHandler): """Refuse redirects, so the key in the Authorization header goes to one host only.""" def redirect_request(self, req, fp, code, msg, headers, newurl): return None _OPENER = urllib.request.build_opener(_NoRedirect) def server_root(base_url: str) -> str: """The server's own address: the OpenAI-compatible base URL without `/v1`.""" url = base_url.rstrip("/") return url[: -len("/v1")] if url.endswith("/v1") else url def _unreachable(err: BaseException) -> bool: """True when nothing answered: refused, reset, timed out or a name that does not resolve. URLError wraps the socket error in .reason.""" reason = err.reason if isinstance(err, urllib.error.URLError) else err if isinstance(reason, _UNREACHABLE): return True return isinstance(reason, OSError) and reason.errno in _UNREACHABLE_ERRNOS def probe(base_url: str, key: str, *, urlopen: Callable = _OPENER.open) -> Probe: """Ask the server which model is resident. The key travels in a header only. Nothing answering, or no model loaded, is soft; a rejected key, or an answer that is not this server's (an HTTP error, a redirect, a body that is not the expected JSON), is a hard failure.""" url = server_root(base_url) + LOADED_MODELS_PATH request = urllib.request.Request( url, headers={"Authorization": f"Bearer {key}", "Accept": "application/json"}) try: with urlopen(request, timeout=PROBE_TIMEOUT_S) as response: data = json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as err: if err.code in (401, 403): return Probe(None, REJECTED_NOTE, False) return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=f"HTTP {err.code}"), False) except ValueError: return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="the reply is not JSON"), False) except OSError as err: if _unreachable(err): return Probe(None, UNREACHABLE_NOTE, True) return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=type(err).__name__), False) models = data.get("data") if isinstance(data, dict) else None if not isinstance(models, list): return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="no `data` list"), False) for item in models: model = item.get("id") if isinstance(item, dict) else None if isinstance(model, str) and model.strip(): model = model.strip() if model.startswith("-"): return Probe(None, BAD_ID_NOTE.format(model=model), False) return Probe(model, None, True) return Probe(None, NO_MODEL_NOTE, True) def resident_model(base_url: str, key: str, *, urlopen: Callable = _OPENER.open) -> str | None: """The id of the model the server has loaded; None on any error or when none is.""" return probe(base_url, key, urlopen=urlopen).model def drafter_user(env: Mapping[str, str], *, geteuid: Callable[[], int] | None = None, getpwnam: Callable | None = None) -> tuple[int, int] | None: """(uid, gid) to run pi as. Not root: None, run as the current user. Root: the DOCS_REVIEW_DRAFTER_USER account, and DrafterUserError when it is unset or does not exist, since pi as root could write anywhere.""" geteuid = geteuid or os.geteuid getpwnam = getpwnam or pwd.getpwnam if geteuid() != 0: return None name = (env.get(USER_VAR) or "").strip() if not name: raise DrafterUserError(f"running as root and {USER_VAR} is not set; " "refusing to run pi as root") try: entry = getpwnam(name) except KeyError: raise DrafterUserError(f"drafter user {name!r} ({USER_VAR}) does not exist") \ from None return entry.pw_uid, entry.pw_gid def chown_tree(root: Path, ids: tuple[int, int]) -> None: """Give root and everything under it to ids, without following symlinks.""" os.chown(root, *ids, follow_symlinks=False) for dirpath, dirnames, filenames in os.walk(root): for name in dirnames + filenames: os.chown(Path(dirpath) / name, *ids, follow_symlinks=False) def models_config(base_url: str, model: str) -> dict: """pi's models.json: one provider at base_url, whose key pi reads from KEY_VAR, and the one resident model.""" return {"providers": {PROVIDER: { "baseUrl": base_url, "api": "openai-completions", "apiKey": "${" + KEY_VAR + "}", "compat": {"supportsDeveloperRole": True, "supportsReasoningEffort": True, "supportsUsageInStreaming": True}, "models": [{"id": model, "name": model, "reasoning": True, "input": ["text"]}], }}} def pi_argv(binary: str, model: str, task_file: Path, system_prompt_file: Path | None) -> list[str]: """The pi command line. The task goes in as an @file, so a long prompt never lands in argv; the key is never in it. Each option and its value are separate elements: pi 1.5.2 rejects `--model=` as an unknown option. probe() refuses a model id starting with `-`, so the id cannot be read as an option.""" argv = [binary, "-p", "--mode", "json", "--provider", PROVIDER, "--model", model, "--thinking", THINKING, "--tools", TOOLS, *ISOLATION_FLAGS] if system_prompt_file is not None: argv += ["--append-system-prompt", str(system_prompt_file)] return argv + ["--", f"@{task_file}", INSTRUCTION.format(path=task_file)] def pi_env(env: Mapping[str, str], home: Path) -> dict[str, str]: """The allowlist, a fresh HOME, and pi's own switches for no network but the model.""" out = {k: v for k, v in env.items() if k in LOCAL_ENV or k.startswith("LC_")} out.update(HOME=str(home), PI_OFFLINE="1", PI_TELEMETRY="0") return out def _first_line(text: str) -> str: """The first non-blank line, cut to ERROR_MAX characters.""" lines = [l.strip() for l in text.splitlines() if l.strip()] line = lines[0] if lines else "" return line if len(line) <= ERROR_MAX else line[:ERROR_MAX] + "..." def _text(raw: str | bytes | None) -> str: if raw is None: return "" return raw.decode("utf-8", "replace") if isinstance(raw, bytes) else raw def _count(usage: object, key: str) -> int | None: value = usage.get(key) if isinstance(usage, dict) else None return value if isinstance(value, int) and not isinstance(value, bool) else None def parse_pi_events(stdout: str, returncode: int | None, *, stderr: str = "", env: Mapping[str, str] | None = None, error: str | None = None) -> DraftResult: """Read pi's JSON event stream: the last assistant message is the answer, and each turn_end is a turn. Tokens: output summed over assistant messages, input as the maximum (each turn's input is the whole conversation so far, so a sum would count it many times). pi exits 0 after a model error, so the message's stopReason decides that. `error` (a timeout) fails the run whatever the stream says; the first stderr line, credential values redacted, joins any failure. Nothing here raises.""" final, turns, tokens_in, tokens_out = None, 0, None, None for line in stdout.splitlines(): try: event = json.loads(line) except ValueError: continue if not isinstance(event, dict): continue if event.get("type") == "turn_end": turns += 1 message = event.get("message") if (event.get("type") == "message_end" and isinstance(message, dict) and message.get("role") == "assistant"): final = message usage = message.get("usage") used_in, used_out = _count(usage, "input"), _count(usage, "output") if used_in is not None: tokens_in = max(tokens_in or 0, used_in) if used_out is not None: tokens_out = (tokens_out or 0) + used_out text = "" if final is not None and isinstance(final.get("content"), list): text = "".join(c.get("text", "") for c in final["content"] if isinstance(c, dict) and c.get("type") == "text" and isinstance(c.get("text"), str)) if error is None and final is not None and final.get("stopReason") in ("error", "aborted"): reason = _first_line(str(final.get("errorMessage") or final.get("stopReason"))) error = f"pi reported an error: {reason}" if error is None and returncode != 0: error = f"pi exited with code {returncode}" if error is None and not text.strip(): error = "pi gave no final text" if error is not None: line = _first_line(redact(stderr, env or {})) if line: error += f"; stderr: {line}" return DraftResult(error is None, None, turns, text, error, input_tokens=tokens_in, output_tokens=tokens_out) def _write(path: Path, text: str) -> None: fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(text) def run_local(prompt: str, *, base_url: str, key: str, model: str, cwd: Path, system_prompt_file: Path | None, env: Mapping[str, str], timeout: float, run_as: tuple[int, int] | None = None) -> DraftResult: """Run pi on the sandbox at cwd with the resident model. Its HOME is a fresh directory under RUNNER_TEMP holding models.json, the task and the system prompt, removed afterwards. With run_as, pi runs as that (uid, gid) and owns the HOME.""" home = Path(tempfile.mkdtemp(prefix="docs-review-pi-home-", dir=env.get("RUNNER_TEMP") or None)) try: agent = home / ".pi" / "agent" agent.mkdir(parents=True) _write(agent / "models.json", json.dumps(models_config(base_url, model), indent=2)) task = home / "task.md" _write(task, prompt) system = None if system_prompt_file is not None: system = home / "system-prompt.md" _write(system, Path(system_prompt_file).read_text(encoding="utf-8")) if run_as is not None: chown_tree(home, run_as) argv = pi_argv(env.get(PI_BIN_VAR, "pi"), model, task, system) user = {} if run_as is None else {"user": run_as[0], "group": run_as[1], "extra_groups": []} child_env = {**pi_env(env, home), KEY_VAR: key} try: proc = subprocess.run(argv, cwd=cwd, env=child_env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout, check=False, **user) except subprocess.TimeoutExpired as err: # Whatever pi streamed before the kill: the turns, the last message and # the tokens survive in the record. return parse_pi_events(_text(err.stdout), None, stderr=_text(err.stderr), env=child_env, error="timed out") except OSError as err: return DraftResult(False, None, None, "", f"could not start pi: {err}") return parse_pi_events(proc.stdout, proc.returncode, stderr=proc.stderr, env=child_env) finally: shutil.rmtree(home, ignore_errors=True)