Track B: networkless shell, context metrics, freeze, journal
- Claude Code and OpenCode: system shells replaced inside the sandbox by wrappers that run every command in a nested bubblewrap with an empty network namespace and no resolver socket; the CLI keeps its backend connection. dev-netprobe (new dev task) passes for all three agents: no network, no DNS from the shell - context metrics for both tracks: provider input (cached/uncached), cumulative context through the tool loop, unique reference tokens and bundle coverage; report shows them; no dollar cost for Track B - ajieval freeze: frozen state (clean Aji commit, binary, bundle, toolchains, docs, CLI versions and config fingerprints, tasks, evaluator, limits) and a shuffled cell order; matrix verifies it and runs cells sequentially in that order; ajieval journal - docs: benchmark-authoring.md (roles, clean-context brief, E-G checklist); harness.md, protocol §39b, plan updated
This commit is contained in:
1 parent
00cbb65447
commit
8b7911669d
16 files changed
+574
-43
No files matched your search
+62
-25
@@ -13,7 +13,9 @@ import os
|
||||
import shlex
|
||||
import sys
|
||||
|
||||
from . import languages, native, record, report, util
|
||||
import datetime
|
||||
|
||||
from . import freeze, languages, native, record, report, util
|
||||
|
||||
CATEGORIES = ["SPEC_UNDERSTANDING", "SYNTAX", "TYPE", "OWNERSHIP", "BORROW", "RESOURCE", "BOUNDS", "FUNCTIONAL", "CONCURRENCY",
|
||||
"DEADLOCK", "ATOMIC_ORDERING", "PERFORMANCE", "BUDGET", "TIMEOUT", "AGENT_GAVE_UP", "TOOL_FAILURE"]
|
||||
@@ -47,12 +49,21 @@ def cmd_native(a):
|
||||
|
||||
|
||||
def cmd_matrix(a):
|
||||
"""Runs every cell of a plan; finished runs (a run.json with the same
|
||||
task, language, model and seed) are skipped, so a plan can be resumed."""
|
||||
"""Runs every cell of a plan sequentially; finished runs (a run.json with
|
||||
the same task, language, model and seed) are skipped, so a plan can be
|
||||
resumed. With a freeze file (`ajieval freeze`) the frozen state is
|
||||
verified first and the cells run in the frozen random order."""
|
||||
plan = util.read_json(a.plan)
|
||||
base = os.path.dirname(os.path.abspath(a.plan))
|
||||
out = os.path.join(base, plan.get("out", "runs"))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
if os.path.exists(freeze.freeze_path(a.plan)):
|
||||
order = freeze.check(a.plan)["order"]
|
||||
print(f"frozen plan: {len(order)} cells in frozen order", file=sys.stderr)
|
||||
elif plan.get("require_freeze"):
|
||||
raise SystemExit(f"{a.plan} requires a freeze file; run `ajieval freeze {a.plan}` first")
|
||||
else:
|
||||
order = freeze.cells(plan, base)
|
||||
done = {(r["task"]["id"], r["language"]["name"], (r["agent"]["name"] + ":" + r["agent"]["requested_model"]) if r.get("track") == "B" else r["model"]["id"], r["seed"]) for r in report.load([out])}
|
||||
pricing = load_pricing(os.path.join(base, plan["pricing"])) if plan.get("pricing") else None
|
||||
evaluator = shlex.split(plan["evaluator"]) if plan.get("evaluator") else None
|
||||
@@ -60,31 +71,46 @@ def cmd_matrix(a):
|
||||
if evaluator:
|
||||
evaluator[0] = rel(evaluator[0])
|
||||
hash_path = rel(plan["evaluator_hash_path"]) if plan.get("evaluator_hash_path") else None
|
||||
from . import task as task_mod
|
||||
for tdir in plan["tasks"]:
|
||||
tpath = os.path.join(base, tdir)
|
||||
tid = task_mod.Task(tpath).id
|
||||
for lang in plan["languages"]:
|
||||
for mdl in plan["models"]:
|
||||
for seed in range(plan.get("runs", 1)):
|
||||
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
|
||||
if (tid, lang, key, seed) in done:
|
||||
continue
|
||||
print(f"run {tid} {lang} {key} seed {seed}", file=sys.stderr)
|
||||
if mdl.get("agent"):
|
||||
run_dir, rec = native.run_native(tpath, lang, mdl["agent"], mdl["model"], out, effort=mdl.get("effort"), seed=seed,
|
||||
evaluator=evaluator, evaluator_hash_path=hash_path, label=mdl.get("label"), limits=plan.get("limits"))
|
||||
else:
|
||||
run_dir, rec = record.run_one(
|
||||
tpath, lang, mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=seed,
|
||||
sandbox_kind=plan.get("sandbox", "bwrap"), evaluator=evaluator, evaluator_hash_path=hash_path,
|
||||
pricing=pricing, base_url=mdl.get("base_url"), max_tokens=mdl.get("max_tokens", 8192), temperature=mdl.get("temperature"),
|
||||
limits=plan.get("limits"),
|
||||
provider_options={k: mdl[k] for k in ("extra", "key_env", "key_file", "token_param") if k in mdl})
|
||||
print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr)
|
||||
models = {((m["agent"] + ":" + m["model"]) if m.get("agent") else m["model"]): m for m in plan["models"]}
|
||||
for i, cell in enumerate(order):
|
||||
if (cell["task_id"], cell["language"], cell["model"], cell["seed"]) in done:
|
||||
continue
|
||||
mdl = models[cell["model"]]
|
||||
tpath = os.path.join(base, cell["task"])
|
||||
print(f"[{i + 1}/{len(order)}] {cell['task_id']} {cell['language']} {cell['model']} seed {cell['seed']}", file=sys.stderr)
|
||||
if mdl.get("agent"):
|
||||
run_dir, rec = native.run_native(tpath, cell["language"], mdl["agent"], mdl["model"], out, effort=mdl.get("effort"), seed=cell["seed"],
|
||||
evaluator=evaluator, evaluator_hash_path=hash_path, label=mdl.get("label"), limits=plan.get("limits"))
|
||||
else:
|
||||
run_dir, rec = record.run_one(
|
||||
tpath, cell["language"], mdl["provider"], mdl["model"], out, model_class=mdl.get("class"), seed=cell["seed"],
|
||||
sandbox_kind=plan.get("sandbox", "bwrap"), evaluator=evaluator, evaluator_hash_path=hash_path,
|
||||
pricing=pricing, base_url=mdl.get("base_url"), max_tokens=mdl.get("max_tokens", 8192), temperature=mdl.get("temperature"),
|
||||
limits=plan.get("limits"),
|
||||
provider_options={k: mdl[k] for k in ("extra", "key_env", "key_file", "token_param") if k in mdl})
|
||||
rec["cell"] = {"index": i, "of": len(order)}
|
||||
util.write_json(os.path.join(run_dir, "run.json"), rec)
|
||||
print(f" -> {rec['metrics']['termination']}, accepted={rec['accepted']}", file=sys.stderr)
|
||||
report.print_report([out])
|
||||
|
||||
|
||||
def cmd_freeze(a):
|
||||
path, frozen = freeze.write(a.plan, a.order_seed)
|
||||
print(json.dumps({"freeze": path, "cells": len(frozen["order"]), "order_seed": frozen["order_seed"], "aji_commit": frozen["state"]["aji_commit"]}))
|
||||
|
||||
|
||||
def cmd_journal(a):
|
||||
"""Appends an observation to the plan's journal. During a frozen
|
||||
experiment problems are recorded here and acted on only afterwards."""
|
||||
plan = util.read_json(a.plan)
|
||||
out = os.path.join(os.path.dirname(os.path.abspath(a.plan)), plan.get("out", "runs"))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
stamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
|
||||
with open(os.path.join(out, "journal.md"), "a") as f:
|
||||
f.write(f"- {stamp}" + (f" [{a.run}]" if a.run else "") + f" {a.text}\n")
|
||||
print(os.path.join(out, "journal.md"))
|
||||
|
||||
|
||||
def cmd_classify(a):
|
||||
path = os.path.join(a.run, "run.json")
|
||||
rec = util.read_json(path)
|
||||
@@ -135,6 +161,17 @@ def main(argv=None):
|
||||
m.add_argument("plan")
|
||||
m.set_defaults(fn=cmd_matrix)
|
||||
|
||||
fz = sub.add_parser("freeze", help="freeze a plan: record its state and a random cell order")
|
||||
fz.add_argument("plan")
|
||||
fz.add_argument("--order-seed", type=int)
|
||||
fz.set_defaults(fn=cmd_freeze)
|
||||
|
||||
jn = sub.add_parser("journal", help="record an observation during a frozen experiment")
|
||||
jn.add_argument("plan")
|
||||
jn.add_argument("text")
|
||||
jn.add_argument("--run")
|
||||
jn.set_defaults(fn=cmd_journal)
|
||||
|
||||
rp = sub.add_parser("report", help="aggregate run records")
|
||||
rp.add_argument("paths", nargs="+")
|
||||
rp.add_argument("--json", action="store_true")
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Context metrics (protocol §16), the same for both tracks.
|
||||
|
||||
provider_input_tokens what the model provider counted: input,
|
||||
cached and uncached separately
|
||||
cumulative_context_tokens the text returned to the agent through its
|
||||
tool loop (every tool output, plus the task
|
||||
message), counted each time it was returned
|
||||
unique_reference_tokens the distinct documentation text the agent
|
||||
actually saw: distinct lines in the outputs
|
||||
of tool calls that touched /docs
|
||||
reference_coverage for a single-file reference (the Aji Agent
|
||||
Reference Bundle): the fraction of its
|
||||
non-empty lines that appeared in those outputs
|
||||
|
||||
The gap between them shows where context is amplified: rereading the same
|
||||
documentation, verbose tool output, or the provider resending history.
|
||||
Tokens are counted with tiktoken `cl100k_base` when it is installed,
|
||||
otherwise estimated as bytes / 4; the record says which.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
from . import util
|
||||
|
||||
_PREFIX = re.compile(r"^\s*\d+\s*[:\t→│|]\s?")
|
||||
|
||||
|
||||
def _tokenizer():
|
||||
try:
|
||||
import tiktoken
|
||||
|
||||
enc = tiktoken.get_encoding("cl100k_base")
|
||||
return "cl100k_base", lambda s: len(enc.encode(s, disallowed_special=()))
|
||||
except Exception:
|
||||
return "estimate(bytes/4)", lambda s: util.estimate_tokens(len(s.encode()))
|
||||
|
||||
|
||||
def _norm(line):
|
||||
return _PREFIX.sub("", line).strip()
|
||||
|
||||
|
||||
def tool_events_track_a(events_path):
|
||||
"""(input text, output text) per tool call from a Track A event log."""
|
||||
out = []
|
||||
for line in open(events_path, encoding="utf-8"):
|
||||
e = json.loads(line)
|
||||
if e["event"] == "command":
|
||||
out.append((e["command"], e.get("output") or ""))
|
||||
elif e["event"] == "tool" and e["name"] != "run":
|
||||
out.append((json.dumps(e.get("input")), e.get("output") or ""))
|
||||
return out
|
||||
|
||||
|
||||
def tool_events_native(agent_name, transcript_path):
|
||||
"""(input text, output text) per tool call from a native CLI 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("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":
|
||||
pending[b.get("id")] = json.dumps(b.get("input"))
|
||||
elif b.get("type") == "tool_result":
|
||||
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))
|
||||
out.append((pending.pop(b.get("tool_use_id"), ""), text))
|
||||
elif agent_name == "opencode":
|
||||
part = e.get("part") or {}
|
||||
if e.get("type") == "tool_use":
|
||||
st = part.get("state") or {}
|
||||
out.append((json.dumps(st.get("input")), st.get("output") or ""))
|
||||
return out
|
||||
|
||||
|
||||
def metrics(tool_events, task_message, docs, provider):
|
||||
"""`docs` is [(mount name, host path)]; `provider` holds input, output,
|
||||
cached_input as counted by the provider (None when unknown)."""
|
||||
name, count = _tokenizer()
|
||||
cumulative = count(task_message) + sum(count(o) for _, o in tool_events)
|
||||
seen = set()
|
||||
for inp, outp in tool_events:
|
||||
if "/docs" in inp:
|
||||
for line in outp.splitlines():
|
||||
n = _norm(line)
|
||||
if n:
|
||||
seen.add(n)
|
||||
unique = count("\n".join(sorted(seen)))
|
||||
coverage = None
|
||||
files = [p for _, p in docs if os.path.isfile(p)]
|
||||
if len(files) == 1 and len(docs) == 1:
|
||||
with open(files[0], encoding="utf-8", errors="replace") as f:
|
||||
ref = {_norm(x) for x in f.read().splitlines() if _norm(x)}
|
||||
coverage = round(len(ref & seen) / len(ref), 4) if ref else None
|
||||
inp, cached = provider.get("input"), provider.get("cached_input")
|
||||
return {
|
||||
"tokenizer": name,
|
||||
"provider_input_tokens": {"total": inp, "cached": cached, "uncached": None if inp is None or cached is None else inp - cached, "output": provider.get("output")},
|
||||
"cumulative_context_tokens": cumulative,
|
||||
"unique_reference_tokens": unique,
|
||||
"reference_coverage": coverage,
|
||||
"tool_outputs": len(tool_events),
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Freezing an experiment (protocol §39a, §39b).
|
||||
|
||||
`ajieval freeze PLAN.json` writes PLAN.freeze.json. It records everything
|
||||
that must not change until the last run of the plan:
|
||||
|
||||
- the Aji commit (the repository must be clean), the `aji` binary and the
|
||||
Agent Reference Bundle;
|
||||
- each language profile, toolchain version and documentation hash;
|
||||
- each native agent's CLI version and binary hash, and a fingerprint of
|
||||
its configuration: written config, command line template, task
|
||||
preamble, networkless shell wrapper;
|
||||
- the harness commit, the task hashes and the evaluator hash;
|
||||
- the cell order: every cell (task × language × model × run) shuffled
|
||||
once with a recorded seed.
|
||||
|
||||
`ajieval matrix` refuses to run a plan whose freeze file no longer matches,
|
||||
and runs the cells sequentially in the frozen order.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from . import languages, native, task as task_mod, util
|
||||
|
||||
|
||||
def _agent_fingerprint(mdl):
|
||||
ag = native.AGENTS[mdl["agent"]]
|
||||
home = tempfile.mkdtemp()
|
||||
try:
|
||||
config = ag.configure(home, mdl["model"], mdl.get("effort"))
|
||||
finally:
|
||||
shutil.rmtree(home, ignore_errors=True)
|
||||
material = {
|
||||
"config": config,
|
||||
"argv": ag.argv(mdl["model"], mdl.get("effort"), "<task message>"),
|
||||
"preamble": native.PREAMBLE,
|
||||
"netless_wrapper": native.NETLESS_WRAPPER if ag.netless_shell else None,
|
||||
"codex_features_off": native.CODEX_FEATURES_OFF if mdl["agent"] == "codex" else None,
|
||||
"credentials": ag.credentials,
|
||||
}
|
||||
cli = os.path.realpath(shutil.which(ag.binary) or ag.binary)
|
||||
return {
|
||||
"cli_version": ag.version(),
|
||||
"cli_hash": util.sha256_path(cli) if os.path.exists(cli) else None,
|
||||
"configuration_hash": util.sha256_text(json.dumps(material, sort_keys=True)),
|
||||
}
|
||||
|
||||
|
||||
def snapshot(plan, base):
|
||||
"""The current state of everything a plan depends on."""
|
||||
commit = util.git_commit()
|
||||
aji = os.path.join(util.REPO, "zig-out", "bin", "aji")
|
||||
bundle = os.path.join(util.REPO, "zig-out", "agent", "reference-bundle.md")
|
||||
langs = {}
|
||||
for name in plan["languages"]:
|
||||
prof = languages.load(name)
|
||||
langs[name] = {
|
||||
"profile_hash": prof["profile_hash"],
|
||||
"toolchain": [v.get("output") for v in languages.versions(prof)],
|
||||
"docs": {("/docs/" + n): util.sha256_path_cached(p) for n, p in languages.docs_mounts(prof)},
|
||||
}
|
||||
tasks = {}
|
||||
for t in plan["tasks"]:
|
||||
tk = task_mod.Task(os.path.join(base, t))
|
||||
tasks[tk.id] = {"version": tk.version, "hash": tk.hash()}
|
||||
evaluator = None
|
||||
if plan.get("evaluator"):
|
||||
ev = plan["evaluator"].split()[0]
|
||||
ev = ev if os.path.isabs(ev) else os.path.join(base, ev)
|
||||
hp = plan.get("evaluator_hash_path")
|
||||
hp = (hp if os.path.isabs(hp) else os.path.join(base, hp)) if hp else ev
|
||||
evaluator = util.sha256_path(hp)
|
||||
models = {}
|
||||
for mdl in plan["models"]:
|
||||
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
|
||||
models[key] = _agent_fingerprint(mdl) if mdl.get("agent") else {"provider": mdl["provider"], "options": {k: mdl.get(k) for k in ("extra", "base_url", "token_param", "max_tokens", "temperature")}}
|
||||
return {
|
||||
"aji_commit": commit,
|
||||
"aji_binary": util.sha256_path(aji) if os.path.exists(aji) else None,
|
||||
"agent_reference_bundle": util.sha256_path(bundle) if os.path.exists(bundle) else None,
|
||||
"harness_commit": commit,
|
||||
"languages": langs,
|
||||
"tasks": tasks,
|
||||
"evaluator": evaluator,
|
||||
"models": models,
|
||||
"limits": plan.get("limits"),
|
||||
}
|
||||
|
||||
|
||||
def cells(plan, base):
|
||||
out = []
|
||||
for t in plan["tasks"]:
|
||||
tid = task_mod.Task(os.path.join(base, t)).id
|
||||
for lang in plan["languages"]:
|
||||
for mdl in plan["models"]:
|
||||
key = (mdl["agent"] + ":" + mdl["model"]) if mdl.get("agent") else mdl["model"]
|
||||
for seed in range(plan.get("runs", 1)):
|
||||
out.append({"task": t, "task_id": tid, "language": lang, "model": key, "seed": seed})
|
||||
return out
|
||||
|
||||
|
||||
def freeze_path(plan_path):
|
||||
return os.path.splitext(plan_path)[0] + ".freeze.json"
|
||||
|
||||
|
||||
def write(plan_path, order_seed=None):
|
||||
plan = util.read_json(plan_path)
|
||||
base = os.path.dirname(os.path.abspath(plan_path))
|
||||
snap = snapshot(plan, base)
|
||||
if snap["aji_commit"] is None or snap["aji_commit"].endswith("+dirty"):
|
||||
raise SystemExit("freeze needs a clean, committed repository (no +dirty)")
|
||||
seed = order_seed if order_seed is not None else random.SystemRandom().randrange(2 ** 32)
|
||||
order = cells(plan, base)
|
||||
random.Random(seed).shuffle(order)
|
||||
frozen = {"schema": "aji-eval-freeze/1", "plan_hash": util.sha256_path(plan_path), "state": snap, "order_seed": seed, "order": order}
|
||||
util.write_json(freeze_path(plan_path), frozen)
|
||||
return freeze_path(plan_path), frozen
|
||||
|
||||
|
||||
def check(plan_path):
|
||||
"""Returns the frozen record, or exits naming what changed."""
|
||||
path = freeze_path(plan_path)
|
||||
frozen = util.read_json(path)
|
||||
plan = util.read_json(plan_path)
|
||||
base = os.path.dirname(os.path.abspath(plan_path))
|
||||
problems = []
|
||||
if util.sha256_path(plan_path) != frozen["plan_hash"]:
|
||||
problems.append("plan file")
|
||||
now = snapshot(plan, base)
|
||||
for key, value in frozen["state"].items():
|
||||
if now.get(key) != value:
|
||||
problems.append(key)
|
||||
if problems:
|
||||
raise SystemExit(f"{plan_path}: frozen state changed ({', '.join(problems)}); a frozen experiment cannot continue")
|
||||
return frozen
|
||||
@@ -14,9 +14,15 @@ its model backend; everything else is confined:
|
||||
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`).
|
||||
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
|
||||
@@ -27,7 +33,7 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from . import __version__, agent, languages, record, task as task_mod, util
|
||||
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
|
||||
@@ -49,7 +55,9 @@ class NativeAgent:
|
||||
binary = ""
|
||||
# (host path relative to the real HOME, same path inside the sandbox HOME)
|
||||
credentials = []
|
||||
command_network = "allowed"
|
||||
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)
|
||||
@@ -93,6 +101,7 @@ class Codex(NativeAgent):
|
||||
binary = "codex"
|
||||
credentials = [".codex/auth.json"]
|
||||
command_network = "disabled (Codex workspace-write sandbox)"
|
||||
netless_shell = False
|
||||
|
||||
def account_mode(self):
|
||||
try:
|
||||
@@ -142,7 +151,6 @@ 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")
|
||||
@@ -186,7 +194,6 @@ 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)"
|
||||
@@ -233,6 +240,30 @@ 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"):
|
||||
@@ -325,6 +356,17 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
|
||||
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]
|
||||
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()
|
||||
@@ -340,6 +382,7 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
|
||||
|
||||
facts = ag.parse(transcript)
|
||||
tokens = normalize_usage(facts.get("usage") or {})
|
||||
ctx = context.metrics(context.tool_events_native(agent_name, transcript), message, docs, tokens)
|
||||
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
|
||||
@@ -365,7 +408,7 @@ def run_native(task_dir, lang_name, agent_name, model, out_dir, effort=None, see
|
||||
"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,
|
||||
"input_tokens": tokens["input"], "output_tokens": tokens["output"], "cached_input_tokens": tokens["cached_input"], "context": ctx, "failed_verifier_cycles": None, "failed_test_cycles": None,
|
||||
"first_check_accepted": None, "first_build_accepted": None},
|
||||
"transcript": "transcript.jsonl",
|
||||
"patch": "patch.diff",
|
||||
|
||||
@@ -9,7 +9,7 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from . import __version__, agent, languages, providers, sandbox, task as task_mod, util
|
||||
from . import __version__, agent, context, languages, providers, sandbox, task as task_mod, util
|
||||
|
||||
|
||||
class Recorder:
|
||||
@@ -104,6 +104,8 @@ def run_one(task_dir, lang_name, provider_name, model, out_dir, model_class=None
|
||||
for key in ("files_opened",):
|
||||
metrics[key + "_count"] = len(metrics[key])
|
||||
metrics["documentation_tokens_estimate"] = util.estimate_tokens(metrics["documentation_bytes_read"])
|
||||
metrics["context"] = context.metrics(context.tool_events_track_a(os.path.join(run_dir, "events.jsonl")), message, docs,
|
||||
{"input": metrics["input_tokens"], "output": metrics["output_tokens"], "cached_input": metrics["cached_input_tokens"]})
|
||||
metrics["repository_tokens_estimate"] = util.estimate_tokens(metrics["repository_bytes_read"])
|
||||
|
||||
verdict = first_verdict = None
|
||||
|
||||
@@ -45,6 +45,11 @@ def aggregate(runs):
|
||||
"verified_success_rate": round(len(acc) / len(rs), 3),
|
||||
"repair_cycles_accepted": mean([r["metrics"]["failed_verifier_cycles"] + r["metrics"]["failed_test_cycles"] for r in acc if r["metrics"].get("failed_verifier_cycles") is not None]),
|
||||
"context_tokens_mean": mean([r["metrics"].get("input_tokens") for r in rs]),
|
||||
"uncached_input_tokens_mean": mean([((r["metrics"].get("context") or {}).get("provider_input_tokens") or {}).get("uncached") for r in rs]),
|
||||
"cumulative_context_tokens_mean": mean([(r["metrics"].get("context") or {}).get("cumulative_context_tokens") for r in rs]),
|
||||
"unique_reference_tokens_mean": mean([(r["metrics"].get("context") or {}).get("unique_reference_tokens") for r in rs]),
|
||||
"reference_coverage_mean": mean([(r["metrics"].get("context") or {}).get("reference_coverage") for r in rs]),
|
||||
"elapsed_seconds_mean": mean([r["metrics"].get("elapsed_seconds") for r in rs]),
|
||||
"output_tokens_mean": mean([r["metrics"].get("output_tokens") for r in rs]),
|
||||
"tool_calls_mean": mean([r["metrics"]["tool_calls"] for r in rs]),
|
||||
"first_check_accepted": sum(1 for r in rs if r["metrics"].get("first_check_accepted") or r["metrics"].get("first_build_accepted")),
|
||||
@@ -57,10 +62,16 @@ def aggregate(runs):
|
||||
|
||||
|
||||
def markdown(rows):
|
||||
head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "context tokens", "cost/correct USD", "unclassified failures"]
|
||||
head = ["task", "language", "class", "model", "runs", "accepted", "VSR", "repair cycles (accepted)", "tool calls",
|
||||
"provider input (uncached)", "cumulative context", "unique reference", "ref. coverage", "seconds", "cost/correct USD", "unclassified failures"]
|
||||
out = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
|
||||
for r in rows:
|
||||
out.append("| " + " | ".join(str(x) for x in [r["task"], r["language"], r["class"], r["model"], r["runs"], r["accepted"], r["verified_success_rate"], r["repair_cycles_accepted"], r["context_tokens_mean"], r["cost_per_correct_usd"], r["unclassified_failures"]]) + " |")
|
||||
# Track B runs on subscriptions: no honest cost per solution (protocol §39b).
|
||||
cost = "n/a (Track B)" if r["class"].startswith("B:") else r["cost_per_correct_usd"]
|
||||
out.append("| " + " | ".join(str(x) for x in [
|
||||
r["task"], r["language"], r["class"], r["model"], r["runs"], r["accepted"], r["verified_success_rate"], r["repair_cycles_accepted"],
|
||||
r["tool_calls_mean"], f"{r['context_tokens_mean']} ({r['uncached_input_tokens_mean']})", r["cumulative_context_tokens_mean"],
|
||||
r["unique_reference_tokens_mean"], r["reference_coverage_mean"], r["elapsed_seconds_mean"], cost, r["unclassified_failures"]]) + " |")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
|
||||
@@ -114,6 +114,24 @@ class RunTest(unittest.TestCase):
|
||||
self.assertAlmostEqual(rec["cost_usd"], (m["input_tokens"] + 10 * m["output_tokens"]) / 1e6, places=6)
|
||||
|
||||
|
||||
class FreezeTest(unittest.TestCase):
|
||||
@unittest.skipIf((util.git_commit() or "+dirty").endswith("+dirty"), "repository has uncommitted changes")
|
||||
def test_freeze_order_and_check(self):
|
||||
from ajieval import freeze
|
||||
d = tempfile.mkdtemp()
|
||||
plan = {"tasks": [TASK], "languages": ["rust", "zig"], "runs": 2, "sandbox": SANDBOX, "evaluator": EVALUATOR[0],
|
||||
"models": [{"provider": "scripted", "model": os.path.join(HERE, "scripts", "rust.json"), "class": "test"}]}
|
||||
path = os.path.join(d, "plan.json")
|
||||
util.write_json(path, plan)
|
||||
_, frozen = freeze.write(path, order_seed=7)
|
||||
self.assertEqual(len(frozen["order"]), 4)
|
||||
self.assertEqual(freeze.check(path)["order"], frozen["order"])
|
||||
plan["runs"] = 3
|
||||
util.write_json(path, plan)
|
||||
with self.assertRaises(SystemExit):
|
||||
freeze.check(path)
|
||||
|
||||
|
||||
class MatrixTest(unittest.TestCase):
|
||||
def test_resume(self):
|
||||
d = tempfile.mkdtemp()
|
||||
|
||||
Reference in new issue
Block a user