Files
aji/tools/eval/ajieval/native.py
T
dev 00cbb65447 E-N0: native-agent mode (Track B) and the native dev-echo gate
ajieval native: Codex, Claude Code and OpenCode in bubblewrap with a
shared network (backend only matters), a fresh HOME holding only the
credential file and a harness-written minimal config (no user skills,
MCP, memory, agents, plugins, global instructions), /work, read-only
/docs and toolchain; evaluator and Aji repository invisible. Codex:
workspace-write sandbox (shell without network), web search and product
features off. Claude Code: tools Bash/Read/Edit/Write, strict MCP,
slash commands off. OpenCode: pure, no MCP, webfetch/websearch/task off.
Record aji-eval-native/1: CLI version, requested/transcript model,
effort, account mode, config, command line, times, transcript, usage
(normalized), patch, final repository, verdict.

Gate on dev-echo (Aji/AIR) accepted for all three: codex 0.160.0 +
gpt-6.1-sol (high), Claude Code 2.1.288 + claude-opus-5-5 (high),
OpenCode 1.18.34 + zai-coding-plan/glm-5.3-flash. Protocol §39b and
plan: Track B first (E-N0 done, E-N 18 runs), Track A after analysis.
2026-10-04 17:48:43 +03:00

380 lines
17 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;
whether shell commands themselves have network depends on the CLI and is
recorded (`command_network`).
"""
import datetime
import json
import os
import shutil
import subprocess
import sys
import time
from . import __version__, agent, 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 = "allowed"
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 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)"
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"]
command_network = "allowed (Claude Code does not restrict Bash network here)"
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"]
command_network = "allowed (OpenCode does not restrict shell network)"
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
AGENTS = {a.name: a for a in (Codex(), Claude(), OpenCode())}
def available():
return sorted(AGENTS)
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 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]
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)
sb = sandbox_argv(workspace, home, binds, path_dirs, docs, profile.get("env", {}))
for src, dst in cred_binds:
sb[sb.index("--chdir"):sb.index("--chdir")] = ["--bind", src, dst]
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 {})
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) if evaluator else None
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, "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"], "failed_verifier_cycles": None, "failed_test_cycles": None,
"first_check_accepted": None, "first_build_accepted": None},
"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