- providers: per-model request extras (e.g. reasoning_effort), key_env, token_param (max_completion_tokens on api.openai.com); recorded - docs pinned to the toolchain being run: Rust offline docs from the sysroot, Zig langref and std source of the same installation; several mounts under a read-only /docs; hashes recorded (cached for big trees) - protocol: neutral model labels and calibration before classes (§2); smoke gates, fixed Aji commit, fixed per-model reasoning mode, slope of degradation (§39a); Track A controlled vs Track B native agents (§39b) - plan: E-C calibration, E-G gates, E-N native-agent run
272 lines
13 KiB
Python
272 lines
13 KiB
Python
"""The agent loop and its tools (protocol §5): one loop for every language.
|
|
|
|
Tools: list_files, read_file, write_file, edit_file, run, finish. Paths are
|
|
`/work/...` (the repository, writable) or `/docs/...` (local documentation,
|
|
read-only); relative paths are under /work.
|
|
|
|
The model ending its turn without a tool call ends the run (`model_end`);
|
|
the scaffold does not nudge, so stopping early is part of what is measured.
|
|
"""
|
|
|
|
import difflib
|
|
import json
|
|
import os
|
|
import shutil
|
|
import time
|
|
|
|
from . import languages, util
|
|
|
|
TOOLS = [
|
|
{"name": "list_files", "description": "List files under a directory (default /work), recursively.",
|
|
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": []}},
|
|
{"name": "read_file", "description": "Read a text file. Optional 1-based `offset` line and `limit` lines.",
|
|
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}}, "required": ["path"]}},
|
|
{"name": "write_file", "description": "Create or overwrite a file under /work.",
|
|
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}},
|
|
{"name": "edit_file", "description": "Replace the single exact occurrence of `old` with `new` in a file under /work.",
|
|
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"}}, "required": ["path", "old", "new"]}},
|
|
{"name": "run", "description": "Run a shell command in /work (no network). Returns the exit code and combined output.",
|
|
"parameters": {"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}},
|
|
{"name": "finish", "description": "End the task when your solution is complete.",
|
|
"parameters": {"type": "object", "properties": {"summary": {"type": "string"}}, "required": []}},
|
|
]
|
|
|
|
SYSTEM = """You are a software engineer working alone in a fresh repository at /work.
|
|
Implement the task described in the first message, in the language named below.
|
|
Tools: list, read, write and edit files; run shell commands in /work (no network access); finish.
|
|
Local documentation is under /docs (read-only). Nothing else is available.
|
|
Work until the public tests described in the task pass, then call `finish`. Hidden tests will also check
|
|
your solution against the stated requirements, so implement the requirements, not just the public tests.
|
|
Limits: at most {tool_calls} tool calls and {total_tokens} total tokens.
|
|
|
|
{language}"""
|
|
|
|
|
|
class ToolError(Exception):
|
|
pass
|
|
|
|
|
|
class Agent:
|
|
def __init__(self, provider, profile, task, lang, sandbox, workspace, docs, recorder, limits):
|
|
self.provider, self.profile, self.task, self.lang = provider, profile, task, lang
|
|
self.sandbox, self.workspace, self.docs, self.rec, self.limits = sandbox, workspace, docs, recorder, limits
|
|
self.system = SYSTEM.format(language=profile["instructions"], **limits)
|
|
self.m = {
|
|
"model_calls": 0, "tool_calls": 0, "input_tokens": 0, "output_tokens": 0, "cached_input_tokens": 0,
|
|
"patches": 0, "files_opened": [], "repository_bytes_read": 0, "documentation_bytes_read": 0,
|
|
"commands": 0, "check_runs": 0, "build_runs": 0, "test_runs": 0,
|
|
"failed_verifier_cycles": 0, "failed_test_cycles": 0,
|
|
"first_check_accepted": None, "first_build_accepted": None, "first_public_test_passed": None,
|
|
}
|
|
self.first_snapshot = None
|
|
|
|
# ---------------------------------------------------------------- paths
|
|
|
|
def host_path(self, path, write=False):
|
|
p = path or "/work"
|
|
if not p.startswith("/"):
|
|
p = "/work/" + p
|
|
p = os.path.normpath(p)
|
|
if p == "/work" or p.startswith("/work/"):
|
|
base, rel, kind = self.workspace, p[len("/work"):].lstrip("/"), "repository"
|
|
elif p == "/docs" or p.startswith("/docs/"):
|
|
if write:
|
|
raise ToolError("/docs is read-only")
|
|
if not self.docs:
|
|
raise ToolError("no documentation is mounted")
|
|
rel = p[len("/docs"):].lstrip("/")
|
|
if len(self.docs) == 1 and self.docs[0][0] == "":
|
|
base, kind = self.docs[0][1], "documentation"
|
|
else:
|
|
if rel == "":
|
|
raise ToolError("/docs is a directory")
|
|
head, _, rest = rel.partition("/")
|
|
match = [m for m in self.docs if m[0] == head]
|
|
if not match:
|
|
raise ToolError(f"no such file: {p}")
|
|
if os.path.isfile(match[0][1]):
|
|
if rest:
|
|
raise ToolError(f"no such file: {p}")
|
|
return match[0][1], "documentation"
|
|
base, rel, kind = match[0][1], rest, "documentation"
|
|
else:
|
|
raise ToolError("paths must be under /work or /docs")
|
|
full = os.path.realpath(os.path.join(base, rel))
|
|
if full != os.path.realpath(base) and not full.startswith(os.path.realpath(base) + os.sep):
|
|
raise ToolError("path escapes its root")
|
|
return full, kind
|
|
|
|
# ---------------------------------------------------------------- tools
|
|
|
|
def tool_list_files(self, inp):
|
|
path = os.path.normpath(inp.get("path") or "/work")
|
|
if path == "/docs" and self.docs and not (len(self.docs) == 1 and self.docs[0][0] == ""):
|
|
return "\n".join("/docs/" + n for n, _ in self.docs)
|
|
full, kind = self.host_path(inp.get("path"))
|
|
if os.path.isfile(full):
|
|
return os.path.basename(full)
|
|
root_virtual, base = "/work", self.workspace
|
|
if kind == "documentation":
|
|
for n, p in self.docs:
|
|
if full == p or full.startswith(p + os.sep):
|
|
root_virtual, base = ("/docs/" + n if n else "/docs"), p
|
|
out = []
|
|
for root, dirs, files in os.walk(full):
|
|
dirs[:] = sorted(d for d in dirs if d not in (".git", "target", "zig-cache", ".zig-cache", "zig-out"))
|
|
for name in sorted(files):
|
|
out.append(root_virtual + "/" + os.path.relpath(os.path.join(root, name), base))
|
|
if len(out) > 2000:
|
|
out.append("... (truncated)")
|
|
break
|
|
return "\n".join(out) or "(empty)"
|
|
|
|
def tool_read_file(self, inp):
|
|
full, kind = self.host_path(inp["path"])
|
|
if not os.path.isfile(full):
|
|
raise ToolError(f"no such file: {inp['path']}")
|
|
with open(full, encoding="utf-8", errors="replace") as f:
|
|
lines = f.read().split("\n")
|
|
start = max(int(inp.get("offset") or 1), 1) - 1
|
|
count = int(inp.get("limit") or len(lines))
|
|
text = "\n".join(lines[start:start + count])
|
|
if len(text) > self.limits["output_chars"] * 4:
|
|
text = text[: self.limits["output_chars"] * 4] + "\n... (truncated; use offset/limit)"
|
|
self.m[kind + "_bytes_read"] += len(text.encode())
|
|
if inp["path"] not in self.m["files_opened"]:
|
|
self.m["files_opened"].append(inp["path"])
|
|
return text
|
|
|
|
def _write(self, path, content, before):
|
|
full, _ = self.host_path(path, write=True)
|
|
os.makedirs(os.path.dirname(full), exist_ok=True)
|
|
with open(full, "w", encoding="utf-8") as f:
|
|
f.write(content)
|
|
rel = os.path.relpath(full, self.workspace)
|
|
diff = "".join(difflib.unified_diff((before or "").splitlines(True), content.splitlines(True), "a/" + rel, "b/" + rel))
|
|
self.m["patches"] += 1
|
|
self.rec.event("patch", path=rel, diff=diff)
|
|
return f"wrote {rel} ({len(content.encode())} bytes)"
|
|
|
|
def tool_write_file(self, inp):
|
|
full, _ = self.host_path(inp["path"], write=True)
|
|
before = None
|
|
if os.path.isfile(full):
|
|
with open(full, encoding="utf-8", errors="replace") as f:
|
|
before = f.read()
|
|
return self._write(inp["path"], inp["content"], before)
|
|
|
|
def tool_edit_file(self, inp):
|
|
full, _ = self.host_path(inp["path"], write=True)
|
|
if not os.path.isfile(full):
|
|
raise ToolError(f"no such file: {inp['path']}")
|
|
with open(full, encoding="utf-8", errors="replace") as f:
|
|
before = f.read()
|
|
n = before.count(inp["old"])
|
|
if n != 1:
|
|
raise ToolError(f"`old` occurs {n} times; it must occur exactly once")
|
|
return self._write(inp["path"], before.replace(inp["old"], inp["new"], 1), before)
|
|
|
|
def tool_run(self, inp):
|
|
command = inp["command"]
|
|
kind = languages.classify(self.profile, command)
|
|
if kind is None and self.lang.get("test") and command.strip().startswith(self.lang["test"]):
|
|
kind = "test"
|
|
if kind and self.first_snapshot is None:
|
|
# First-generation state (protocol §14): before the first
|
|
# toolchain invocation, i.e. before any compiler-driven repair.
|
|
self.first_snapshot = self.rec.snapshot(self.workspace, "first_generation")
|
|
t0 = time.monotonic()
|
|
code, out, truncated = self.sandbox.run(command, self.limits["command_timeout"], self.limits["output_chars"])
|
|
self.m["commands"] += 1
|
|
ok = code == 0
|
|
if kind in ("check", "build"):
|
|
self.m[kind + "_runs"] += 1
|
|
key = "first_" + kind + "_accepted"
|
|
if self.m[key] is None:
|
|
self.m[key] = ok
|
|
if not ok:
|
|
self.m["failed_verifier_cycles"] += 1
|
|
elif kind == "test":
|
|
self.m["test_runs"] += 1
|
|
if self.m["first_public_test_passed"] is None:
|
|
self.m["first_public_test_passed"] = ok
|
|
if not ok:
|
|
self.m["failed_test_cycles"] += 1
|
|
self.rec.event("command", command=command, kind=kind, exit=code, seconds=round(time.monotonic() - t0, 3), output=out, truncated=truncated)
|
|
status = "timed out" if code is None else f"exit code {code}"
|
|
return f"[{status}]\n{out}"
|
|
|
|
# ---------------------------------------------------------------- loop
|
|
|
|
def run(self, task_prompt):
|
|
messages = [{"role": "user", "content": [{"type": "text", "text": task_prompt}]}]
|
|
t0 = time.monotonic()
|
|
reason = None
|
|
while reason is None:
|
|
if self.m["tool_calls"] >= self.limits["tool_calls"]:
|
|
reason = "budget_tool_calls"
|
|
break
|
|
if self.m["input_tokens"] + self.m["output_tokens"] >= self.limits["total_tokens"]:
|
|
reason = "budget_tokens"
|
|
break
|
|
if time.monotonic() - t0 >= self.limits["wall_seconds"]:
|
|
reason = "wall_time"
|
|
break
|
|
try:
|
|
reply = self.provider.complete(self.system, messages, TOOLS)
|
|
except Exception as e: # provider errors end the run and are recorded
|
|
self.rec.event("provider_error", error=f"{type(e).__name__}: {e}")
|
|
reason = "provider_error"
|
|
break
|
|
self.m["model_calls"] += 1
|
|
u = reply["usage"]
|
|
self.m["input_tokens"] += u["input"]
|
|
self.m["output_tokens"] += u["output"]
|
|
self.m["cached_input_tokens"] += u["cached_input"]
|
|
self.rec.event("model", model=reply.get("model"), stop=reply["stop"], usage=u, content=reply["content"])
|
|
messages.append({"role": "assistant", "content": reply["content"]})
|
|
calls = [b for b in reply["content"] if b["type"] == "tool_call"]
|
|
if not calls:
|
|
reason = "max_tokens" if reply["stop"] == "max_tokens" else "model_end"
|
|
break
|
|
results = []
|
|
for c in calls:
|
|
self.m["tool_calls"] += 1
|
|
if c["name"] == "finish":
|
|
reason = "finished"
|
|
self.rec.event("tool", name="finish", input=c["input"], output="", is_error=False)
|
|
results.append({"type": "tool_result", "id": c["id"], "output": "ok", "is_error": False})
|
|
continue
|
|
fn = getattr(self, "tool_" + c["name"], None)
|
|
try:
|
|
if fn is None:
|
|
raise ToolError(f"unknown tool {c['name']!r}")
|
|
out, err = fn(c["input"]), False
|
|
except ToolError as e:
|
|
out, err = str(e), True
|
|
except (KeyError, TypeError, ValueError) as e:
|
|
out, err = f"invalid arguments: {e}", True
|
|
self.rec.event("tool", name=c["name"], input=c["input"], output=out if c["name"] != "run" else None, is_error=err)
|
|
results.append({"type": "tool_result", "id": c["id"], "output": out, "is_error": err})
|
|
messages.append({"role": "user", "content": results})
|
|
self.m["elapsed_seconds"] = round(time.monotonic() - t0, 3)
|
|
self.m["termination"] = reason
|
|
return self.m
|
|
|
|
|
|
def initial_listing(workspace):
|
|
out = []
|
|
for root, dirs, files in os.walk(workspace):
|
|
dirs.sort()
|
|
for name in sorted(files):
|
|
out.append("/work/" + os.path.relpath(os.path.join(root, name), workspace))
|
|
return "\n".join(out) or "(empty)"
|
|
|
|
|
|
def task_message(task, workspace):
|
|
return task.prompt.rstrip() + "\n\nThe repository /work initially contains:\n" + initial_listing(workspace) + "\n"
|
|
|
|
|
|
def copy_workspace(src, dst):
|
|
shutil.copytree(src, dst, symlinks=False)
|