Files
devandClaude Opus 5.5 0e98638bc6 eval: gobang as a Track B native agent
gobang, the Aji-native harness, joins Codex, Claude Code and OpenCode in
ajieval native. Like them it is an agent product: its runs are never
evidence for H4. Model ids choose the provider: claude-* the Anthropic
API, any other GLM via z.ai, fixture:PATH a scenario without network
(self-tests).

gobang reaches the model over its API, so the key's variable is passed
into the sandbox environment; NativeAgent.env supplies it, its value
never enters the run record, and a missing key stops the run before
anything is created. Tool processes run in gobang's own networkless
bubblewrap sandbox, so no shell wrapper is used. The transcript is
gobang's journal: usage, tool calls and the model come from its events,
the repair metrics from its toolchain tools (aji_check, aji_run,
run_tests with aji's exit codes), and its documentation tools count as
reads of /docs files.

Checked end to end on dev-echo (aji_source) with a fixture model: the
dev evaluator accepts the solution, the workspace holds only the
solution, and the first-check and first-test metrics are exact. With a
fake key the run reaches z.ai from the sandbox and ends INFRA_FAILED
(auth) without the key in any file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 15:00:36 +03:00

683 lines
31 KiB
Python

"""Track B: native coding agents (protocol §39b).
The agent product (Codex, Claude Code, OpenCode) is the scaffold: it brings
its own system prompt, tools, context management and compaction, so these
runs are never evidence for H4. The harness only prepares the workspace,
starts the CLI with one shared task message, collects the repository and
runs the same independent evaluator.
Isolation (bubblewrap): the network is shared, because the CLI must reach
its model backend; everything else is confined:
- the workspace at /work (read-write), documentation at /docs (read-only),
the language toolchain and the agent CLI read-only;
- a fresh HOME holding only the agent's credential file and a minimal
configuration written by the harness, so user-level skills, MCP
servers, memory, custom agents and global instructions do not exist;
- neither the evaluator nor the Aji repository is visible.
Web and search tools, MCP and subagents are disabled where the CLI allows.
Shell commands never have network. Codex runs them in its own
`workspace-write` sandbox. For Claude Code and OpenCode, `/usr/bin/bash`
and `/usr/bin/sh` inside the sandbox are wrappers that run every command
in a nested bubblewrap with a fresh, empty network namespace and no
resolver socket. The CLI process itself keeps the network to reach its
model backend, and every process a tool starts through a shell is
networkless.
"""
import datetime
import json
import os
import re
import shutil
import subprocess
import sys
import time
from . import __version__, agent, context, languages, record, task as task_mod, util
PREAMBLE = """You are working alone in a fresh repository at /work (the current directory).
Implement the task below in the language named here. Use only the files in /work, the local
documentation under /docs (read-only) and the toolchain installed on PATH. Do not use the web.
Work until the public tests described in the task pass. Hidden tests will also check your solution
against the stated requirements, so implement the requirements, not just the public tests.
{language}
---
"""
class NativeAgent:
"""One CLI: how to configure and start it, and where its credentials are."""
name = ""
binary = ""
# (host path relative to the real HOME, same path inside the sandbox HOME)
credentials = []
command_network = "disabled (networkless shell wrapper)"
# Whether the harness must make the shell networkless itself.
netless_shell = True
def version(self):
r = subprocess.run([self.binary, "--version"], capture_output=True, text=True, timeout=60)
return (r.stdout + r.stderr).strip()
def account_mode(self):
return None
def configure(self, home, model, effort):
"""Writes the agent's minimal configuration into the fresh HOME."""
return {}
def env(self, model):
"""Environment variables the agent needs inside the sandbox (an API
key). Their values are never written to the run record."""
return {}
def argv(self, model, effort, prompt):
raise NotImplementedError
def parse(self, transcript_path):
"""Best-effort facts from the CLI's JSON event stream."""
return {}
def _jsonl(path):
out = []
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if line.startswith("{"):
try:
out.append(json.loads(line))
except json.JSONDecodeError:
pass
return out
CODEX_FEATURES_OFF = ["multi_agent", "apps", "browser_use", "browser_use_external", "browser_use_full_cdp_access", "computer_use",
"image_generation", "plugins", "remote_plugin", "plugin_sharing", "skill_search", "skill_mcp_dependency_install",
"tool_suggest", "goals", "worktrees", "in_app_browser", "realtime_conversation", "hooks"]
class Codex(NativeAgent):
name = "codex"
binary = "codex"
credentials = [".codex/auth.json"]
command_network = "disabled (Codex workspace-write sandbox)"
netless_shell = False
def account_mode(self):
try:
return "codex auth_mode=" + str(util.read_json(os.path.expanduser("~/.codex/auth.json")).get("auth_mode"))
except (OSError, ValueError):
return None
def configure(self, home, model, effort):
cfg = "\n".join([
f'model = "{model}"',
f'model_reasoning_effort = "{effort}"' if effort else "",
'approval_policy = "never"',
'sandbox_mode = "workspace-write"',
'web_search = "disabled"',
"",
"[sandbox_workspace_write]",
"network_access = false",
"",
# Product features beyond model + shell + files are off for the smoke (protocol §39b).
"[features]",
] + [f"{feat} = false" for feat in CODEX_FEATURES_OFF] + [""])
os.makedirs(os.path.join(home, ".codex"), exist_ok=True)
with open(os.path.join(home, ".codex", "config.toml"), "w") as f:
f.write(cfg)
return {".codex/config.toml": cfg}
def argv(self, model, effort, prompt):
return [self.binary, "exec", "--json", "--skip-git-repo-check", "-m", model, "-s", "workspace-write", "-C", "/work", prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {}}
for e in _jsonl(path):
t = e.get("type", "")
item = e.get("item") or {}
if t == "item.completed" and item.get("type") in ("command_execution", "file_change", "mcp_tool_call", "web_search"):
facts["tool_calls"] += 1
if t == "turn.completed" and e.get("usage"):
for k, v in e["usage"].items():
if isinstance(v, int):
facts["usage"][k] = facts["usage"].get(k, 0) + v
if e.get("model"):
facts["model"] = e["model"]
return facts
class Claude(NativeAgent):
name = "claude"
binary = "claude"
credentials = [".claude/.credentials.json"]
def account_mode(self):
p = os.path.expanduser("~/.claude/.credentials.json")
return "claude.ai OAuth credentials (subscription)" if os.path.exists(p) else None
def configure(self, home, model, effort):
settings = {"permissions": {"deny": ["WebSearch", "WebFetch"]}, "enableAllProjectMcpServers": False}
os.makedirs(os.path.join(home, ".claude"), exist_ok=True)
util.write_json(os.path.join(home, ".claude", "settings.json"), settings)
# Marks onboarding as done so the non-interactive run does not stop.
util.write_json(os.path.join(home, ".claude.json"), {"hasCompletedOnboarding": True})
return {".claude/settings.json": settings}
def argv(self, model, effort, prompt):
a = [self.binary, "-p", "--output-format", "stream-json", "--verbose", "--model", model,
"--dangerously-skip-permissions", "--strict-mcp-config", "--disable-slash-commands",
"--tools", "Bash", "Read", "Edit", "Write"]
if effort:
a += ["--effort", effort]
return a + ["--", prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {}}
for e in _jsonl(path):
if e.get("type") == "assistant":
msg = e.get("message") or {}
if msg.get("model"):
facts["model"] = msg["model"]
facts["tool_calls"] += sum(1 for b in msg.get("content", []) if b.get("type") == "tool_use")
if e.get("type") == "result":
facts["usage"] = e.get("usage") or {}
facts["cost_usd_reported"] = e.get("total_cost_usd")
facts["num_turns"] = e.get("num_turns")
facts["result_subtype"] = e.get("subtype")
if e.get("type") == "system" and e.get("model"):
facts["model"] = e["model"]
return facts
class OpenCode(NativeAgent):
name = "opencode"
binary = "opencode"
credentials = [".local/share/opencode/auth.json"]
def account_mode(self):
return "opencode provider credential (see model id prefix, e.g. zai-coding-plan = Z.AI Coding Plan)"
def configure(self, home, model, effort):
cfg = {"$schema": "https://opencode.ai/config.json", "model": model, "autoupdate": False, "share": "disabled",
"mcp": {}, "permission": {"webfetch": "deny", "websearch": "deny", "edit": "allow", "bash": "allow"},
"tools": {"webfetch": False, "websearch": False, "task": False}}
d = os.path.join(home, ".config", "opencode")
os.makedirs(d, exist_ok=True)
util.write_json(os.path.join(d, "opencode.json"), cfg)
return {".config/opencode/opencode.json": cfg}
def argv(self, model, effort, prompt):
a = [self.binary, "run", "--pure", "--auto", "--format", "json", "-m", model, "--dir", "/work"]
if effort:
a += ["--variant", effort]
return a + [prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {}}
for e in _jsonl(path):
part = e.get("part") or {}
if e.get("type") == "tool_use" or part.get("type") == "tool":
facts["tool_calls"] += 1
tokens = part.get("tokens") if part.get("type") == "step-finish" else None
if isinstance(tokens, dict):
cache = tokens.get("cache") or {}
flat = {"input": tokens.get("input", 0), "output": tokens.get("output", 0) + tokens.get("reasoning", 0),
"cache_read": cache.get("read", 0), "cache_creation": cache.get("write", 0)}
for k, v in flat.items():
facts["usage"][k] = facts["usage"].get(k, 0) + (v or 0)
for key in ("modelID", "model"):
v = part.get(key) or (e.get("info") or {}).get(key)
if isinstance(v, str):
facts["model"] = v
return facts
GOBANG_ZAI_URL = "https://api.z.ai/api/coding/paas/v4"
class Gobang(NativeAgent):
"""gobang, the Aji-native harness (a sibling repository). The
scaffold is the agent product here too, so these runs
are never evidence for H4 (protocol §39b); they measure the harness
against the other agents on the same model where possible.
The model gives no shell commands: gobang runs aji and test commands
itself, in its own networkless bubblewrap sandbox nested in this one,
so no shell wrapper is needed. It reaches the model over its API, so
the key is passed as an environment variable; the configuration names
only the variable.
Model ids: `claude-*` uses the Anthropic API (ANTHROPIC_API_KEY); any
other id uses GLM via z.ai (ZAI_API_KEY); `fixture:PATH` replays a
gobang scenario file without a network (harness self-tests)."""
name = "gobang"
binary = "gobang"
credentials = []
command_network = "disabled (gobang's own bubblewrap sandbox; the model has no shell)"
netless_shell = False
def _provider(self, model):
if model.startswith("fixture:"):
return "fixture", None, None
if model.startswith("claude"):
return "anthropic", "ANTHROPIC_API_KEY", None
return "openai", "ZAI_API_KEY", GOBANG_ZAI_URL
def account_mode(self):
return "API key from the environment (ZAI_API_KEY or ANTHROPIC_API_KEY)"
def configure(self, home, model, effort):
provider, key_env, base = self._provider(model)
d = os.path.join(home, ".config", "gobang")
os.makedirs(d, exist_ok=True)
lines = ["version = 1", "", "[toolchain]", 'aji = "aji"', "", "[model]", f'provider = "{provider}"']
if provider == "fixture":
shutil.copyfile(model[len("fixture:"):], os.path.join(d, "scenario.jsonl"))
lines.append('fixture = "scenario.jsonl"')
else:
lines += [f'model = "{model}"', f'key_env = "{key_env}"']
if base:
lines.append(f'base_url = "{base}"')
if effort:
lines.append(f'extra = {{ reasoning_effort = "{effort}" }}')
lines += ["", "[sandbox]", 'mode = "required"', "", "[context]", 'docs = "/docs"', ""]
cfg = "\n".join(lines)
with open(os.path.join(d, "gobang.toml"), "w") as f:
f.write(cfg)
return {".config/gobang/gobang.toml": cfg}
def env(self, model):
_, key_env, _ = self._provider(model)
if key_env is None:
return {}
key = os.environ.get(key_env)
if not key:
raise SystemExit(f"gobang: {key_env} is not set")
return {key_env: key}
def argv(self, model, effort, prompt):
return [self.binary, "run", "--json-events", "--in-place", "/work", "--state-dir", "/tmp/gobang",
"--config", "/home/agent/.config/gobang/gobang.toml", "--task", prompt]
def parse(self, path):
facts = {"tool_calls": 0, "usage": {"input_tokens": 0, "cached_input_tokens": 0, "output_tokens": 0}}
for e in _jsonl(path):
t, d = e.get("type"), e.get("data") or {}
if t == "TOOL_REQUESTED":
facts["tool_calls"] += 1
elif t == "MODEL_RESPONDED":
r = d.get("response") or {}
u = r.get("usage") or {}
facts["usage"]["input_tokens"] += u.get("input", 0)
facts["usage"]["cached_input_tokens"] += u.get("cache_read", 0)
facts["usage"]["output_tokens"] += u.get("output", 0)
if r.get("model_reported"):
facts["model"] = r["model_reported"]
elif t == "SESSION_CREATED":
facts["prompt_sha256"] = d.get("prompt_sha256")
elif t == "SESSION_FINISHED":
facts["gobang_state"] = d.get("state")
facts["gobang_reason"] = d.get("reason")
return facts
# aji exit codes for gobang's run outcomes (AGENTS.md of the aji repository).
_GOBANG_OUTCOME_CODE = {"accepted": 0, "returned": 0, "rejected": 1, "trapped": 4, "limit_exceeded": 5, "not_instantiated": 6, "blocked": 7}
def gobang_events(transcript_path):
"""(tool, arguments, result) for every tool call in a gobang transcript,
and the test commands of the session."""
calls, results, tests = {}, [], []
for e in _jsonl(transcript_path):
t, d = e.get("type"), e.get("data") or {}
if t == "CONFIG_RESOLVED":
tests = d.get("test_command_argv") or []
elif t == "TOOL_REQUESTED":
calls[d.get("call_id")] = (d.get("tool"), d.get("arguments") or "")
elif t == "TOOL_COMPLETED" and d.get("call_id") in calls:
tool, args = calls.pop(d.get("call_id"))
results.append((tool, args, d.get("output") or ""))
return results, tests
AGENTS = {a.name: a for a in (Codex(), Claude(), OpenCode(), Gobang())}
def available():
return sorted(AGENTS)
NETLESS_WRAPPER = """#!/opt/aji-real/{shell}
# Runs the command in a nested namespace without network (Track B, protocol §39b).
if [ -n "$AJI_NETLESS" ]; then exec /opt/aji-real/{shell} "$@"; fi
exec /usr/bin/bwrap --unshare-net --dev-bind / / --tmpfs /run/systemd/resolve --setenv AJI_NETLESS 1 /opt/aji-real/{shell} "$@"
"""
def netless_binds(run_dir):
"""bwrap arguments that replace the system shells by networkless wrappers.
Symlinks such as /usr/bin/sh -> bash are followed, so each real shell
binary is wrapped once, at its real path."""
d = os.path.join(run_dir, "netless")
os.makedirs(d, exist_ok=True)
out = []
for real in sorted({os.path.realpath("/usr/bin/" + s) for s in ("bash", "sh")}):
shell = os.path.basename(real)
path = os.path.join(d, shell)
with open(path, "w") as f:
f.write(NETLESS_WRAPPER.format(shell=shell))
os.chmod(path, 0o755)
out += ["--ro-bind", real, "/opt/aji-real/" + shell, "--ro-bind", path, real]
return out + ["--setenv", "SHELL", "/usr/bin/bash", "--setenv", "OPENCODE_DISABLE_LSP_DOWNLOAD", "true"]
def sandbox_argv(workspace, home, binds, path_dirs, docs, env):
a = ["bwrap", "--unshare-all", "--share-net", "--die-with-parent", "--new-session"]
for d in ("/usr", "/etc"):
a += ["--ro-bind", d, d]
for src, dst in (("usr/lib", "/lib"), ("usr/lib64", "/lib64"), ("usr/bin", "/bin"), ("usr/sbin", "/sbin")):
if os.path.exists("/" + src):
a += ["--symlink", src, dst]
if os.path.isdir("/run/systemd/resolve"):
a += ["--ro-bind", "/run/systemd/resolve", "/run/systemd/resolve"]
a += ["--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp"]
for d in binds:
a += ["--ro-bind", d, d]
if docs:
a += ["--tmpfs", "/docs"]
for name, p in docs:
a += ["--ro-bind", p, "/docs/" + name if name else "/docs"]
a += ["--remount-ro", "/docs"]
a += ["--bind", home, "/home/agent", "--bind", workspace, "/work", "--chdir", "/work", "--clearenv"]
base = {"PATH": ":".join(path_dirs + ["/usr/bin", "/bin"]), "HOME": "/home/agent", "TMPDIR": "/tmp", "LANG": "C.UTF-8", "TERM": "dumb"}
base.update(env)
for k, v in sorted(base.items()):
a += ["--setenv", k, v]
return a
def command_events(agent_name, transcript_path):
"""(command, exit code, output) for every shell command in a transcript."""
out = []
pending = {}
for line in open(transcript_path, encoding="utf-8", errors="replace"):
line = line.strip()
if not line.startswith("{"):
continue
try:
e = json.loads(line)
except json.JSONDecodeError:
continue
if agent_name == "codex":
item = e.get("item") or {}
if e.get("type") == "item.completed" and item.get("type") == "command_execution":
out.append((item.get("command") or "", item.get("exit_code"), item.get("aggregated_output") or ""))
elif agent_name == "claude":
msg = e.get("message") or {}
for b in msg.get("content", []) if isinstance(msg.get("content"), list) else []:
if b.get("type") == "tool_use" and b.get("name") == "Bash":
pending[b.get("id")] = (b.get("input") or {}).get("command", "")
elif b.get("type") == "tool_result" and b.get("tool_use_id") in pending:
c = b.get("content")
text = c if isinstance(c, str) else "\n".join(x.get("text", "") for x in (c or []) if isinstance(x, dict))
m = re.match(r"Exit code (\d+)", text)
code = int(m.group(1)) if m else (1 if b.get("is_error") else 0)
out.append((pending.pop(b.get("tool_use_id")), code, text))
elif agent_name == "gobang":
continue # handled below from whole tool calls
elif agent_name == "opencode":
part = e.get("part") or {}
if e.get("type") == "tool_use" and part.get("tool") == "bash":
st = part.get("state") or {}
meta = st.get("metadata") or {}
out.append(((st.get("input") or {}).get("command", ""), meta.get("exit"), st.get("output") or meta.get("output") or ""))
if agent_name == "gobang":
# gobang's model gives no shell commands; its toolchain tools stand
# for the commands they run, with aji's exit code for their outcome.
results, tests = gobang_events(transcript_path)
for tool, _, output in results:
try:
o = json.loads(output)
except json.JSONDecodeError:
continue
outcome = o.get("outcome")
if tool == "aji_check":
out.append(("aji check", _GOBANG_OUTCOME_CODE.get(outcome, 2), output))
elif tool == "aji_run":
out.append(("aji run", _GOBANG_OUTCOME_CODE.get(outcome, 2), output))
elif tool == "run_tests" and o.get("ok"):
bad = (o.get("failed") or 0) + (o.get("errors") or 0)
out.append(("aji run; " + "; ".join(tests), 0 if bad == 0 else 1, output))
return out
def cycles(profile, test_command, commands):
"""Repair-loop metrics (protocol §14, §15) derived from shell commands.
A command counts as a toolchain invocation if it contains a verifier,
compiler or test command of the language profile, or the task's public
test command. A failing invocation whose output carries a diagnostic of
the language is a failed verifier cycle; any other failing invocation
with a test is a failed test cycle."""
pat = re.compile(profile.get("diagnostic_pattern") or "$^")
cls = profile.get("classify", {})
checks = [p for k in ("check", "build") for p in cls.get(k, [])]
tests = list(cls.get("test", [])) + ([test_command] if test_command else [])
m = {"toolchain_invocations": 0, "failed_verifier_cycles": 0, "failed_test_cycles": 0,
"first_check_accepted": None, "first_public_test_passed": None}
for cmd, code, output in commands:
has_check = any(p in cmd for p in checks)
has_test = any(p in cmd for p in tests)
if not (has_check or has_test):
continue
m["toolchain_invocations"] += 1
diag = bool(pat.search(output or ""))
failed = code not in (0, None) or diag
if has_check and m["first_check_accepted"] is None:
m["first_check_accepted"] = not diag and code in (0, None)
if has_test and test_command and test_command in cmd and m["first_public_test_passed"] is None:
m["first_public_test_passed"] = not failed
if failed and diag:
m["failed_verifier_cycles"] += 1
elif failed and has_test:
m["failed_test_cycles"] += 1
return m
_FINISH = re.compile(r'"(?:finish_reason|stop_reason|finish|reason)"\s*:\s*"([a-z_]+)"')
_RATE_LIMIT = re.compile(r"\b429\b|rate[ _-]?limit|usage limit|too many requests", re.IGNORECASE)
def agent_status(termination, transcript_path, stderr_path):
"""How the agent's session ended, apart from what the evaluator says
about the repository (protocol §28):
finished / exited the CLI ended normally
max_tokens the last model reply stopped at its length
limit (finish_reason length / max_tokens)
provider_rate_limited the provider refused further requests (429,
usage limit); the CLI then exited with an error
error_exit, wall_time otherwise as recorded in `termination`
"""
def tail(path, n=200_000):
try:
with open(path, encoding="utf-8", errors="replace") as f:
return f.read()[-n:]
except OSError:
return ""
t = tail(transcript_path)
reasons = _FINISH.findall(t)
if reasons and reasons[-1] in ("length", "max_tokens"):
return "max_tokens"
if termination == "error_exit" and _RATE_LIMIT.search(tail(stderr_path) + t[-20_000:]):
return "provider_rate_limited"
return termination
def evaluation_status(verdict):
"""accepted / rejected / evaluator_error / infrastructure_failure /
not_evaluated. An evaluator reports an infrastructure failure with
`"infrastructure": true` in its verdict (harness.md, evaluator contract)."""
if verdict is None:
return "not_evaluated"
if verdict.get("infrastructure"):
return "infrastructure_failure"
if verdict.get("accepted"):
return "accepted"
if "gates" not in verdict and verdict.get("error"):
return "evaluator_error"
return "rejected"
def normalize_usage(u):
"""Input (including cached), output and cached-input tokens from the
differently named usage fields of the CLIs; None when not reported."""
if not u:
return {"input": None, "output": None, "cached_input": None}
cached = sum(v for k, v in u.items() if isinstance(v, int) and ("cache_read" in k or k in ("cached_input_tokens", "cached")))
created = sum(v for k, v in u.items() if isinstance(v, int) and "cache_creation" in k)
plain = u.get("input_tokens", u.get("input", 0)) or 0
# Codex reports cached tokens as part of input_tokens; Claude reports them separately.
total_in = plain + (0 if "cached_input_tokens" in u else cached + created)
out = u.get("output_tokens", u.get("output", 0)) or 0
return {"input": total_in, "output": out, "cached_input": cached}
def diff_tree(before, after):
r = subprocess.run(["diff", "-ruN", "-x", "target", "-x", ".zig-cache", "-x", "zig-out", os.path.basename(before), os.path.basename(after)],
capture_output=True, text=True, cwd=os.path.dirname(before))
return r.stdout
def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, seed=0, evaluator=None, evaluator_hash_path=None, label=None, limits=None):
if shutil.which("bwrap") is None:
raise SystemExit("native runs need bubblewrap")
ag = AGENTS[agent_name]
agent_env = ag.env(model) # fails before anything is created when a key is missing
task = task_mod.Task(task_dir)
profile = languages.load(lang_name)
lang = task.language(lang_name)
lim = dict(task.limits, **(limits or {}))
stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
run_id = f"{record.slug(task.id)}.{lang_name}.{agent_name}-{record.slug(model)}.s{seed}.{stamp}"
run_dir = os.path.join(out_dir, run_id)
os.makedirs(run_dir)
workspace = os.path.join(run_dir, "workspace")
agent.copy_workspace(lang["workspace"], workspace)
pristine = os.path.join(run_dir, "initial")
agent.copy_workspace(lang["workspace"], pristine)
home = os.path.join(run_dir, "home")
os.makedirs(home)
# Credentials: bound read-write at their usual place in the fresh HOME
# (token refresh writes them); nothing else from the real HOME exists.
cred_binds = []
for rel in ag.credentials:
src = os.path.join(os.path.expanduser("~"), rel)
if not os.path.exists(src):
raise SystemExit(f"{agent_name}: credential file ~/{rel} not found; log in with the CLI first")
dst = os.path.join(home, rel)
os.makedirs(os.path.dirname(dst), exist_ok=True)
open(dst, "a").close()
cred_binds.append((src, "/home/agent/" + rel))
config = ag.configure(home, model, effort)
_, binds = languages.resolve_binaries(profile)
cli = os.path.realpath(shutil.which(ag.binary) or "")
if not cli:
raise SystemExit(f"{agent_name}: CLI {ag.binary!r} not on PATH")
cli_dir = os.path.dirname(cli)
binds = sorted(set(binds) | {os.path.dirname(cli_dir) if os.path.basename(cli_dir) == "bin" else cli_dir})
path_dirs = languages.sandbox_path(binds)
docs = languages.docs_mounts(profile)
message = PREAMBLE.format(language=profile["instructions"]) + agent.task_message(task, workspace)
argv = ag.argv(model, effort, message)
env = dict(profile.get("env", {}))
env.update(agent_env) # values never enter the run record
sb = sandbox_argv(workspace, home, binds, path_dirs, docs, env)
for src, dst in cred_binds:
sb[sb.index("--chdir"):sb.index("--chdir")] = ["--bind", src, dst]
if ag.netless_shell:
# Binds go before --chdir; environment variables after --clearenv.
extra = netless_binds(run_dir)
triples = [extra[i:i + 3] for i in range(0, len(extra), 3)]
at = sb.index("--chdir")
for t in triples:
if t[0] == "--ro-bind":
sb[at:at] = t
at += 3
else:
sb += t
transcript = os.path.join(run_dir, "transcript.jsonl")
started = datetime.datetime.now(datetime.timezone.utc).isoformat()
t0 = time.monotonic()
with open(transcript, "w") as out, open(os.path.join(run_dir, "stderr.log"), "w") as err:
try:
p = subprocess.run(sb + argv, stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=lim["wall_seconds"])
code, termination = p.returncode, ("exited" if p.returncode == 0 else "error_exit")
except subprocess.TimeoutExpired:
code, termination = None, "wall_time"
elapsed = round(time.monotonic() - t0, 3)
ended = datetime.datetime.now(datetime.timezone.utc).isoformat()
facts = ag.parse(transcript)
tokens = normalize_usage(facts.get("usage") or {})
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens, profile.get("doc_groups"))
cyc = cycles(profile, lang.get("test"), command_events(agent_name, transcript))
with open(os.path.join(run_dir, "patch.diff"), "w") as f:
f.write(diff_tree(pristine, workspace))
verdict = record.evaluate(evaluator, workspace, lang_name, task.dir, lim["command_timeout"] * 4, os.path.join(run_dir, "evaluator.log")) if evaluator else None
status = agent_status(termination, transcript, os.path.join(run_dir, "stderr.log"))
if status == "max_tokens":
termination = "max_tokens"
rec = {
"schema": "aji-eval-native/1",
"track": "B",
"run_id": run_id,
"started": started,
"ended": ended,
"task": {"id": task.id, "version": task.version, "set": task.set, "family": task.spec.get("family"), "hash": task.hash(), "concurrency": bool(task.spec.get("concurrency"))},
"evaluator": None if not evaluator else {"command": evaluator, "hash": util.sha256_path(evaluator_hash_path or evaluator[0])},
"language": {"name": lang_name, "profile_hash": profile["profile_hash"], "toolchain": languages.versions(profile),
"docs": [{"mount": "/docs/" + n, "path": p, "hash": util.sha256_path_cached(p)} for n, p in docs]},
"agent": {"name": agent_name, "label": label, "cli_version": ag.version(), "cli_path": cli, "requested_model": model,
"model": facts.get("model") or model, "model_source": "transcript" if facts.get("model") else "requested",
"effort": effort, "account_mode": ag.account_mode(), "configuration": config,
"command_line": [a if a != message else "<task message>" for a in argv], "command_network": ag.command_network},
"scaffold": {"version": __version__, "commit": util.git_commit(), "isolation": "bwrap, shared network, fresh HOME"},
"task_prompt_hash": util.sha256_text(message),
"limits": lim,
"hardware": util.hardware(),
"seed": seed,
"metrics": {"elapsed_seconds": elapsed, "exit_code": code, "termination": termination,
"agent_status": status, "evaluation_status": evaluation_status(verdict), "tool_calls": facts.get("tool_calls"),
"usage": facts.get("usage"), "agent_facts": {k: v for k, v in facts.items() if k not in ("usage", "tool_calls", "model")},
"input_tokens": tokens["input"], "output_tokens": tokens["output"], "cached_input_tokens": tokens["cached_input"], "context": ctx,
"toolchain_invocations": cyc["toolchain_invocations"],
"failed_verifier_cycles": cyc["failed_verifier_cycles"], "failed_test_cycles": cyc["failed_test_cycles"],
"first_check_accepted": cyc["first_check_accepted"], "first_build_accepted": None,
"first_public_test_passed": cyc["first_public_test_passed"], "cycles_source": "derived from transcript"},
"transcript": "transcript.jsonl",
"patch": "patch.diff",
"final_repository": {"path": "workspace", "files": record.file_hashes(workspace)},
"verdict": verdict,
"accepted": None if verdict is None else verdict["accepted"],
"cost_usd": None,
"classification": None,
}
util.write_json(os.path.join(run_dir, "run.json"), rec)
return run_dir, rec