feat: local drafter (pi against a self-run model server)
drafter: local runs the pi coding agent against the model resident on an OpenAI-compatible server at the new local_url input, keyed by the LOCAL_MODEL_API_KEY secret. It asks the server which model is loaded and names exactly that one, so it never evicts the resident model. An unreachable server or no loaded model posts the stage 1 flags with a note and exits 0; a drafter that ran and failed still exits 1. pi runs in the existing sandbox with read, ls, edit and write, every project-local pi file and AGENTS.md ignored, stdin from /dev/null, the task passed as an @file, and an allowlisted environment. As root with DOCS_REVIEW_DRAFTER_USER set, it runs as that unprivileged user, which owns only the sandbox and pi's temporary home. Both drafters now hash the checkout's .git/config and .git/hooks before drafting and stop with no further git command if either changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9dea56ce98
commit
28b993cb23
14 files changed
+1042
-30
No files matched your search
@@ -107,6 +107,8 @@ class DraftResult:
|
||||
turns: int | None
|
||||
text: str
|
||||
error: str | None
|
||||
# Who drafted, for the PR body; None means Claude Code, which reports a cost.
|
||||
drafted_by: str | None = None
|
||||
|
||||
|
||||
def parse_claude_output(stdout: str, returncode: int) -> DraftResult:
|
||||
@@ -207,6 +209,9 @@ def render_pr_body(
|
||||
if stage1:
|
||||
parts.append("### Flags from stage 1\n\n" + "\n\n".join(stage1))
|
||||
turns = "unknown" if result.turns is None else result.turns
|
||||
cost = "unknown" if result.cost_usd is None else f"{result.cost_usd:.2f}"
|
||||
parts.append(f"Drafted by Claude Code: {turns} turns, ${cost} estimated.")
|
||||
if result.drafted_by is not None:
|
||||
parts.append(f"Drafted by {result.drafted_by}: {turns} turns.")
|
||||
else:
|
||||
cost = "unknown" if result.cost_usd is None else f"{result.cost_usd:.2f}"
|
||||
parts.append(f"Drafted by Claude Code: {turns} turns, ${cost} estimated.")
|
||||
return "\n\n".join(parts) + "\n"
|
||||
+75
-6
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -10,7 +11,7 @@ from collections.abc import Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from docs_review import git, sandbox
|
||||
from docs_review import git, local, sandbox
|
||||
from docs_review.draft import DraftResult, claude_argv, parse_claude_output
|
||||
from docs_review.inputs import Inputs, expand_patterns, matches_any
|
||||
from docs_review.secrets import secret_values
|
||||
@@ -28,6 +29,8 @@ EXPORT_NOTE = "drafter failed: could not export the tree for drafting: {reason}"
|
||||
EXPORT_REASON_MAX = 200
|
||||
NO_CREDENTIAL_NOTE = "drafter: claude but no Claude credential is set"
|
||||
CREDENTIAL_VARS = ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")
|
||||
NO_LOCAL_KEY_NOTE = "drafter: local but LOCAL_MODEL_API_KEY is not set"
|
||||
GIT_METADATA_NOTE = "drafter changed git metadata; nothing committed"
|
||||
REFUSED_NOTE = "drafter failed: refusing to copy back `{path}` (symlink or outside the repository)"
|
||||
|
||||
|
||||
@@ -106,10 +109,17 @@ def write_step_summary(result: DraftResult, env: Mapping[str, str]) -> None:
|
||||
|
||||
|
||||
def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
|
||||
system_prompt_file: Path | None) -> DraftResult:
|
||||
"""Run the configured drafter in cwd. Task 12 adds `local`."""
|
||||
if inputs.drafter != "claude":
|
||||
return DraftResult(False, None, None, "", "local drafter not built yet")
|
||||
system_prompt_file: Path | None, *, local_model: str | None = None,
|
||||
run_as: tuple[int, int] | None = None) -> DraftResult:
|
||||
"""Run the configured drafter in cwd. `local` needs the resident model's id."""
|
||||
if inputs.drafter == "local":
|
||||
if local_model is None or inputs.local_url is None:
|
||||
return DraftResult(False, None, None, "", "no local model to draft with")
|
||||
result = local.run_local(
|
||||
prompt, base_url=inputs.local_url, key=env.get(local.KEY_VAR, ""),
|
||||
model=local_model, cwd=cwd, system_prompt_file=system_prompt_file, env=env,
|
||||
timeout=DRAFT_TIMEOUT_S, run_as=run_as)
|
||||
return dataclasses.replace(result, drafted_by=f"pi with {local_model}")
|
||||
argv = claude_argv(env.get("DOCS_REVIEW_CLAUDE_BIN", "claude"), inputs.model,
|
||||
str(system_prompt_file) if system_prompt_file else None)
|
||||
try:
|
||||
@@ -123,6 +133,36 @@ def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
|
||||
return parse_claude_output(proc.stdout, proc.returncode)
|
||||
|
||||
|
||||
def git_metadata(cwd: Path) -> dict[str, str]:
|
||||
"""Hashes of the checkout's .git/config and of everything under .git/hooks: the
|
||||
files that make a later git command run code. The drafter runs outside the
|
||||
checkout, but nothing else stops it writing here."""
|
||||
gitdir = cwd / ".git"
|
||||
if not gitdir.is_dir() or gitdir.is_symlink():
|
||||
return {".git": _entry(gitdir)}
|
||||
out = {"config": _entry(gitdir / "config")}
|
||||
hooks = gitdir / "hooks"
|
||||
out["hooks"] = _entry(hooks)
|
||||
if hooks.is_dir() and not hooks.is_symlink():
|
||||
for dirpath, dirnames, filenames in os.walk(hooks):
|
||||
for name in dirnames + filenames:
|
||||
path = Path(dirpath) / name
|
||||
out["hooks/" + path.relative_to(hooks).as_posix()] = _entry(path)
|
||||
return out
|
||||
|
||||
|
||||
def _entry(path: Path) -> str:
|
||||
"""A file's or link's hash, `dir` for a directory, `missing` when absent."""
|
||||
if path.is_symlink() or path.is_file():
|
||||
try:
|
||||
return sandbox.digest(path)
|
||||
except OSError as err:
|
||||
return f"unreadable:{err.errno}"
|
||||
if path.is_dir():
|
||||
return "dir"
|
||||
return "missing" if not os.path.lexists(path) else "other"
|
||||
|
||||
|
||||
def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
|
||||
patterns: tuple[str, ...], root: Path,
|
||||
review_only: tuple[str, ...] = ()) -> list[str]:
|
||||
@@ -155,6 +195,22 @@ class Drafted:
|
||||
result: DraftResult | None
|
||||
changed: tuple[str, ...]
|
||||
note: str | None # why the run failed; None when it succeeded
|
||||
soft: bool = False # the drafter was unavailable: report the note, do not fail
|
||||
|
||||
|
||||
def _local_preflight(inputs: Inputs, env: Mapping[str, str]):
|
||||
"""For `local`: (model, run_as, None) or (None, None, Drafted) when it cannot run."""
|
||||
if not (env.get(local.KEY_VAR) or "").strip():
|
||||
return None, None, Drafted(None, (), NO_LOCAL_KEY_NOTE)
|
||||
try:
|
||||
run_as = local.drafter_user(env)
|
||||
except local.DrafterUserError as err:
|
||||
return None, None, Drafted(None, (), f"drafter failed: {err}")
|
||||
found = local.probe(inputs.local_url or "", env[local.KEY_VAR])
|
||||
if found.model is None:
|
||||
return None, None, Drafted(None, (), found.note, soft=found.soft)
|
||||
print(f"local drafter: resident model {found.model}")
|
||||
return found.model, run_as, None
|
||||
|
||||
|
||||
def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
@@ -162,6 +218,11 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
"""Run the drafter on an export of HEAD and copy its allowed changes into cwd."""
|
||||
if inputs.drafter == "claude" and not has_claude_credential(env):
|
||||
return Drafted(None, (), NO_CREDENTIAL_NOTE)
|
||||
model = run_as = None
|
||||
if inputs.drafter == "local":
|
||||
model, run_as, stop = _local_preflight(inputs, env)
|
||||
if stop is not None:
|
||||
return stop
|
||||
if git.run(["status", "--porcelain"], cwd).strip():
|
||||
return Drafted(None, (), DIRTY_NOTE)
|
||||
box = prompt_file = None
|
||||
@@ -175,7 +236,15 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
||||
listed = frozenset(expand_patterns(inputs.docs, box))
|
||||
before = sandbox.snapshot(box)
|
||||
prompt_file = write_system_prompt(box, inputs.doc_guide, env)
|
||||
result = run_drafter(inputs, prompt, box, env, prompt_file)
|
||||
if run_as is not None:
|
||||
local.chown_tree(box, run_as)
|
||||
metadata = git_metadata(cwd)
|
||||
result = run_drafter(inputs, prompt, box, env, prompt_file, local_model=model,
|
||||
run_as=run_as)
|
||||
# Checked first, and on failure no further git command runs: a hook or a
|
||||
# config change would run on the next one.
|
||||
if git_metadata(cwd) != metadata:
|
||||
return Drafted(result, (), GIT_METADATA_NOTE)
|
||||
write_step_summary(result, env)
|
||||
if not result.ok:
|
||||
return Drafted(result, (), f"drafter failed: {result.error}")
|
||||
|
||||
+20
-1
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import urllib.parse
|
||||
from collections.abc import Iterable, Mapping
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
@@ -27,6 +28,8 @@ class Inputs:
|
||||
model: str
|
||||
# Listed documents the drafter may read but not edit; each entry is within docs.
|
||||
review_only: tuple[str, ...] = ()
|
||||
# The local drafter's OpenAI-compatible base URL; set only when drafter is local.
|
||||
local_url: str | None = None
|
||||
|
||||
|
||||
def normalize_drafter(raw: str | None) -> str:
|
||||
@@ -35,6 +38,18 @@ def normalize_drafter(raw: str | None) -> str:
|
||||
return value if value in DRAFTERS else "none"
|
||||
|
||||
|
||||
def parse_local_url(raw: str | None) -> str:
|
||||
"""The local_url input without a trailing slash. Raises ValueError unless it is an
|
||||
http(s) URL with a host."""
|
||||
url = (raw or "").strip().rstrip("/")
|
||||
if not url:
|
||||
raise ValueError("input 'local_url' is required when drafter is local")
|
||||
parts = urllib.parse.urlsplit(url)
|
||||
if parts.scheme not in ("http", "https") or not parts.hostname:
|
||||
raise ValueError(f"input 'local_url' must be an http or https URL, got {url!r}")
|
||||
return url
|
||||
|
||||
|
||||
def _lines(raw: str | None) -> tuple[str, ...]:
|
||||
"""Split a newline-separated input, trimming and dropping blank lines."""
|
||||
return tuple(line.strip() for line in (raw or "").splitlines() if line.strip())
|
||||
@@ -64,8 +79,11 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs:
|
||||
except ValueError:
|
||||
raise ValueError(f"input 'tracking_issue' must be an integer, got {issue_raw!r}") from None
|
||||
|
||||
drafter = normalize_drafter(env.get("INPUT_DRAFTER"))
|
||||
local_url = parse_local_url(env.get("INPUT_LOCAL_URL")) if drafter == "local" else None
|
||||
|
||||
return Inputs(
|
||||
drafter=normalize_drafter(env.get("INPUT_DRAFTER")),
|
||||
drafter=drafter,
|
||||
docs=docs,
|
||||
generated=_lines(env.get("INPUT_GENERATED")),
|
||||
top_level=_lines(env.get("INPUT_TOP_LEVEL")) or DEFAULT_TOP_LEVEL,
|
||||
@@ -75,6 +93,7 @@ def parse_inputs(env: Mapping[str, str]) -> Inputs:
|
||||
doc_guide=_text(env, "INPUT_DOC_GUIDE") or None,
|
||||
model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL,
|
||||
review_only=review_only,
|
||||
local_url=local_url,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
"""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 json
|
||||
import os
|
||||
import pwd
|
||||
import shutil
|
||||
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
|
||||
|
||||
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"
|
||||
|
||||
|
||||
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):
|
||||
"""DOCS_REVIEW_DRAFTER_USER names a user that does not exist."""
|
||||
|
||||
|
||||
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 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."""
|
||||
request = urllib.request.Request(
|
||||
server_root(base_url) + LOADED_MODELS_PATH,
|
||||
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, UNREACHABLE_NOTE, True)
|
||||
except (OSError, ValueError):
|
||||
return Probe(None, UNREACHABLE_NOTE, True)
|
||||
models = data.get("data") if isinstance(data, dict) else None
|
||||
if isinstance(models, list):
|
||||
for item in models:
|
||||
model = item.get("id") if isinstance(item, dict) else None
|
||||
if isinstance(model, str) and model.strip():
|
||||
return Probe(model.strip(), 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] = os.geteuid,
|
||||
getpwnam: Callable = pwd.getpwnam) -> tuple[int, int] | None:
|
||||
"""(uid, gid) to run pi as: the DOCS_REVIEW_DRAFTER_USER account when this process
|
||||
is root and the variable is set, otherwise None (run as the current user). Raises
|
||||
DrafterUserError when the named account does not exist."""
|
||||
name = (env.get(USER_VAR) or "").strip()
|
||||
if not name or geteuid() != 0:
|
||||
return None
|
||||
try:
|
||||
entry = getpwnam(name)
|
||||
except KeyError:
|
||||
raise DrafterUserError(f"drafter user {name!r} 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."""
|
||||
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:
|
||||
lines = text.strip().splitlines()
|
||||
line = lines[0] if lines else ""
|
||||
return line if len(line) <= ERROR_MAX else line[:ERROR_MAX] + "..."
|
||||
|
||||
|
||||
def parse_pi_events(stdout: str, returncode: int) -> DraftResult:
|
||||
"""Read pi's JSON event stream: the last assistant message is the answer, and each
|
||||
turn_end is a turn. pi exits 0 after a model error, so the message's stopReason
|
||||
decides that. Nothing here raises."""
|
||||
final, turns = None, 0
|
||||
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
|
||||
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 final is not None and final.get("stopReason") in ("error", "aborted"):
|
||||
reason = _first_line(str(final.get("errorMessage") or final.get("stopReason")))
|
||||
return DraftResult(False, None, turns, text, f"pi reported an error: {reason}")
|
||||
if returncode != 0:
|
||||
return DraftResult(False, None, turns, text, f"pi exited with code {returncode}")
|
||||
if not text.strip():
|
||||
return DraftResult(False, None, turns, text, "pi gave no final text")
|
||||
return DraftResult(True, None, turns, text, None)
|
||||
|
||||
|
||||
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:
|
||||
return DraftResult(False, None, None, "", "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)
|
||||
finally:
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
@@ -133,7 +133,7 @@ def run_monthly(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path,
|
||||
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
|
||||
if drafted.note is not None:
|
||||
post_issue(forge, flags, month, drafted.note)
|
||||
return 1
|
||||
return 0 if drafted.soft else 1
|
||||
result, changed = drafted.result, list(drafted.changed)
|
||||
if not changed:
|
||||
post_issue(forge, flags, month)
|
||||
|
||||
@@ -219,7 +219,7 @@ def run_pr(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path, args: PrArg
|
||||
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
|
||||
if drafted.note is not None:
|
||||
post_stage1(forge, args.number, flags, args.head_sha, drafted.note, docs_pr=pr_no)
|
||||
return 1
|
||||
return 0 if drafted.soft else 1
|
||||
result, changed = drafted.result, list(drafted.changed)
|
||||
if not changed:
|
||||
if flags:
|
||||
|
||||
@@ -70,7 +70,7 @@ class CopyRefused(RuntimeError):
|
||||
"""A change cannot be copied back safely; the message names the path."""
|
||||
|
||||
|
||||
def _digest(path: Path) -> str:
|
||||
def digest(path: Path) -> str:
|
||||
"""A content hash; a symlink hashes its target text and is marked as a link."""
|
||||
if path.is_symlink():
|
||||
return "link:" + os.readlink(path)
|
||||
@@ -89,7 +89,7 @@ def snapshot(root: Path) -> dict[str, str]:
|
||||
names = list(filenames) + [d for d in dirnames if (base / d).is_symlink()]
|
||||
for name in names:
|
||||
path = base / name
|
||||
out[path.relative_to(root).as_posix()] = _digest(path)
|
||||
out[path.relative_to(root).as_posix()] = digest(path)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user