Skip to content

Official Codebase of 3DCodeVerse

Python

agents: ten files become four — one session machine, one backends file

gaoypeng7fd060812c2e
diff --git a/harness/codeverse/agents/__init__.py b/harness/codeverse/agents/__init__.py
index 2f3987bf..2edaa3e6 100644
--- a/harness/codeverse/agents/__init__.py
+++ b/harness/codeverse/agents/__init__.py
@@ -4,7 +4,6 @@ Ids: ``gemini-cli:<model>`` · ``claude-code:<model>`` · ``codex:<model>`` ·
``agy:<model>``.
"""
-from codeverse.agents.base import CodingAgent
-from codeverse.agents.registry import get_coding_agent, parse_agent_id
+from codeverse.agents.registry import CodingAgent, get_coding_agent, parse_agent_id
__all__ = ["CodingAgent", "get_coding_agent", "parse_agent_id"]
diff --git a/harness/codeverse/agents/antigravity.py b/harness/codeverse/agents/antigravity.py
deleted file mode 100644
index 7b06adfb..00000000
--- a/harness/codeverse/agents/antigravity.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""``agy:<model>`` — Antigravity CLI (Google) headless session on a workspace.
-
-argv: ``agy --print <prompt> --model <model> --dangerously-skip-permissions
---print-timeout <N>m --output-format json --add-dir <ws>``
-
-Observed (agy 1.1.x) JSON envelope::
-
- {"conversation_id": "...", "status": "SUCCESS" | "ERROR", "response": "...", ["error": "..."],
- "duration_seconds": 2.3, "num_turns": 1,
- "usage": {"input_tokens", "output_tokens", "thinking_tokens", "cache_read_tokens", "total_tokens"}}
-
-MCP: agy only supports *global* registration (``agy mcp add``), so no
-per-workspace server is wired; the materialised body tells the agent to call
-``python -m codeverse.cli.main tools <name> --json ...`` from the shell instead.
-Cost: subscription-billed → ``cost_usd`` 0 with a note. Plain-text output is
-accepted when the JSON envelope is missing.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-from functools import lru_cache
-from pathlib import Path
-from typing import Any
-
-from codeverse.agents.cli_common import (
- Session,
- begin_session,
- deliver_prompt,
- exists_on_path,
- failed,
- finish_session,
- hardened_env,
- invoke,
- release_session,
- tail,
- watchdog_error,
-)
-from codeverse.config import get_settings
-from codeverse.contracts.agent import AgentJob, AgentResult
-from codeverse.contracts.common import Usage
-from codeverse.proc import run_subprocess
-
-log = logging.getLogger(__name__)
-
-#: reasoning efforts agy exposes for the models that have them
-EFFORTS = ("low", "medium", "high")
-#: what a bare id is resolved to when agy offers only effort-suffixed spellings
-DEFAULT_EFFORT = "medium"
-_EFFORT_SUFFIXES = tuple(f"-{e}" for e in EFFORTS)
-
-
-@lru_cache(maxsize=4)
-def available_models(binary: str) -> tuple[str, ...]:
- """The model ids ``agy models`` offers, or ``()`` when it cannot be reached.
-
- Cached: one lookup per binary per process, and only for an id that needs it.
- """
- try:
- r = run_subprocess([binary, "models"], cwd=Path.cwd(), timeout_s=30.0)
- except OSError as e: # pragma: no cover - defensive
- log.debug("agy models unavailable: %s", e)
- return ()
- if r.returncode != 0:
- return ()
- ids = []
- for line in r.stdout.splitlines():
- head = line.split("\t", 1)[0].strip()
- if head and " " not in head:
- ids.append(head)
- return tuple(ids)
-
-
-def resolve_model(model: str, binary: str) -> str:
- """Map a bare model id onto the effort-suffixed one agy actually accepts.
-
- agy 1.1.19 rejects ``--model gemini-3.7-flash`` outright ("requires --effort
- (available: low, medium, high)") and equally rejects ``--effort`` for a model that
- has none ("--effort is not supported for model claude-sonnet-4-6"), so the effort
- cannot be a blanket flag — it belongs in the MODEL ID, which is the only spelling
- ``agy models`` lists (gemini-3.7-flash-low/-medium/-high).
-
- A bare id agy DOES offer (claude-sonnet-4-6) is passed through untouched, and so is
- anything we cannot check, so this can only turn a guaranteed failure into a run.
- """
- if not model or model.endswith(_EFFORT_SUFFIXES):
- return model
- offered = available_models(binary)
- if not offered or model in offered:
- return model
- for effort in (DEFAULT_EFFORT, *EFFORTS):
- if f"{model}-{effort}" in offered:
- log.info("agy has no bare %r; using the %s-effort id %r", model, effort, f"{model}-{effort}")
- return f"{model}-{effort}"
- return model
-
-
-def parse_agy_json(stdout: str) -> dict[str, Any] | None:
- s = stdout.strip()
- if not s:
- return None
- for cand in (s, *reversed([ln for ln in s.splitlines() if ln.strip().startswith("{")])):
- try:
- obj = json.loads(cand)
- except json.JSONDecodeError:
- continue
- if isinstance(obj, dict) and ("response" in obj or "status" in obj):
- return obj
- return None
-
-
-def usage_from_agy(env: dict[str, Any], model: str) -> Usage:
- u = env.get("usage") or {}
- return Usage(
- backend="agy", model=model,
- input_tokens=int(u.get("input_tokens") or 0),
- output_tokens=int(u.get("output_tokens") or 0),
- cached_tokens=int(u.get("cache_read_tokens") or 0),
- thoughts_tokens=int(u.get("thinking_tokens") or 0),
- cost_usd=0.0, # subscription; no USD exposed
- latency_ms=int(float(env.get("duration_seconds") or 0.0) * 1000),
- )
-
-
-class AntigravityAgent:
- kind = "agy"
-
- def __init__(self, model: str, binary: str | None = None):
- self.model = model
- self.binary = binary or get_settings().binaries.agy_cli
-
- @property
- def id(self) -> str:
- return f"{self.kind}:{self.model}"
-
- def served_model(self) -> str:
- """The id actually sent to agy (a bare one gains its effort suffix)."""
- return resolve_model(self.model, self.binary)
-
- def available(self) -> tuple[bool, str]:
- if not exists_on_path(self.binary):
- return False, f"agy CLI not found: {self.binary!r}"
- return True, "ok"
-
- def build_argv(self, s: Session, prompt: str) -> list[str]:
- minutes = max(1, int(s.job.timeout_s // 60) + 1)
- argv = [self.binary, "--print", prompt, "--dangerously-skip-permissions",
- "--print-timeout", f"{minutes}m", "--output-format", "json",
- "--add-dir", str(s.ws.root), "--disable-slash-commands"]
- if self.model:
- argv += ["--model", self.served_model()]
- return argv
-
- def build_env(self, s: Session) -> dict[str, str]:
- return hardened_env(s.ws, s.job)
-
- def run(self, job: AgentJob) -> AgentResult:
- ok, why = self.available()
- s = begin_session(job, self.kind)
- try:
- if not ok:
- return failed(s, "error", why)
- prompt = deliver_prompt(s, _compose_prompt(s))
- proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
- env = parse_agy_json(proc.stdout)
- served = self.served_model()
- usage = usage_from_agy(env, served) if env else Usage(backend=self.kind, model=served)
- usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
- text = str(env.get("response", "")) if env else proc.stdout.strip()
- errors: list[str] = []
- if env is None:
- s.notes.append("no JSON envelope from agy; usage unknown (zeros), response taken from plain stdout")
- s.notes.append("agy is subscription-billed: cost_usd=0")
- if proc.timed_out:
- ok, reason = False, "timeout"
- errors.append(watchdog_error(proc))
- elif proc.rc != 0 or (env is not None and str(env.get("status", "SUCCESS")).upper() not in ("SUCCESS", "OK")):
- ok, reason = False, "error"
- errors.append(f"rc={proc.rc}; status={(env or {}).get('status')}; error={(env or {}).get('error', '')}; "
- f"stderr tail: {tail(proc.stderr, 1500)}")
- elif not text.strip():
- ok, reason = False, "error"
- errors.append("empty response")
- else:
- ok, reason = True, "completed"
- return finish_session(
- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0, errors=errors,
- rc=proc.rc, killed_reason=proc.killed_reason,
- conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
- )
- finally:
- release_session(s)
-
-
-def _compose_prompt(s: Session) -> str:
- """agy has no system-prompt flag; prepend harness instructions + the absolute workspace path."""
- job = s.job
- head = f"Workspace root: {s.ws.root}\nWork ONLY inside it, using your file tools."
- if (s.ws.root / "AGENTS.md").is_file():
- head += " Read AGENTS.md there first and follow it."
- head += "\n"
- if job.system_append:
- head += f"\n<harness_instructions>\n{job.system_append}\n</harness_instructions>\n"
- return f"{head}\n{job.prompt}"
-
-
-__all__ = ["AntigravityAgent", "parse_agy_json", "usage_from_agy"]
diff --git a/harness/codeverse/agents/backends.py b/harness/codeverse/agents/backends.py
new file mode 100644
index 00000000..68dbbeb9
--- /dev/null
+++ b/harness/codeverse/agents/backends.py
@@ -0,0 +1,781 @@
+"""``gemini-cli:<model>`` — headless Gemini CLI session on a workspace.
+
+argv: ``gemini -p <prompt> -m <model> --approval-mode yolo --skip-trust --output-format json``
+
+* env hardening: host secrets stripped, one pool key as ``GEMINI_API_KEY``,
+ ``GEMINI_CLI_SYSTEM_SETTINGS_PATH`` (per session, in the trajectory dir) forcing
+ api-key auth + dynamic model configuration (otherwise an unknown model is *silently*
+ substituted), the 3dcv MCP server and ``mcp.allowed``, Node heap cap, no self-relaunch.
+* JSON envelope ``{session_id, response, stats:{models:{<m>:{tokens:{prompt,
+ input, candidates, cached, thoughts}}}, tools:{totalCalls}}}`` → Usage (+ cost
+ via pricing). ``tokens.prompt`` is the TOTAL prompt size and ``tokens.input``
+ the UNCACHED part (``prompt - cached``); ``Usage.input_tokens`` follows the
+ pricing convention (total prompt, cached re-priced). Each served model is
+ priced at its own rate. Requested model absent from ``stats.models`` →
+ ``model_substituted``.
+* one retry (rotated key when the pool has one, else the same key) on transient
+ failures (429 / 503 / empty response); a throttled/empty pool never raises.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import time
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+from codeverse.agents.cli_common import (
+ CompletedProc,
+ Session,
+ begin_session,
+ deliver_prompt,
+ estimate_cost_safe,
+ exists_on_path,
+ failed,
+ finish_session,
+ hardened_env,
+ invoke,
+ is_quota_failure,
+ is_transient_failure,
+ mcp_command_for,
+ release_session,
+ tail,
+ watchdog_error,
+)
+from codeverse.agents.materialize import MCP_SERVER_NAME, MCP_TOOL_TIMEOUT_MS, codex_mcp_overrides
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import Usage
+from codeverse.models.retry import KeyPool, KeyPoolExhausted
+from codeverse.proc import run_subprocess
+
+log = logging.getLogger(__name__)
+
+SYSTEM_SETTINGS = {
+ # folderTrust must be OFF: with it on, gemini-cli silently disables the workspace
+ # .gemini/settings.json mcpServers (even with --skip-trust) → no 3dcv tools.
+ "security": {"auth": {"selectedType": "gemini-api-key"}, "folderTrust": {"enabled": False}},
+ "experimental": {"dynamicModelConfiguration": True},
+ "general": {"topicUpdateNarration": False},
+}
+#: how long a retry waits for a *different* healthy key before reusing the same one
+RETRY_KEY_WAIT_S = 10.0
+
+
+def retry_window_left(timeout_s: float, elapsed_s: float) -> float | None:
+ """Seconds of the session window a retry may still use, or ``None`` when too little
+ is left to be worth an invoke. A retry never restarts the window: chair_bl
+ (loop_w1, 2026-08-28) got a FULL fresh window on attempt 2 and ran 32 more minutes
+ against a run wall that had expired before the retry began."""
+ min_window = min(120.0, float(timeout_s) * 0.25)
+ left = float(timeout_s) - float(elapsed_s)
+ return None if left < min_window else left
+
+
+def _key_pool(keys: list[str]) -> KeyPool:
+ """THE process-wide pool for these keys — ``models.gemini.shared_pool``, i.e. the
+ same limiter the API path uses, with quotas from ``Settings.rate``. This module
+ used to build its own ``KeyPool(keys)`` with library defaults (900 RPM, no TPM
+ bucket), so the CLI agent and the API path scheduled the same 22 keys under two
+ different quotas (found by review 2026-08-28)."""
+ from codeverse.models.gemini import shared_pool
+
+ return shared_pool(keys)
+
+
+def write_system_settings(path: Path | None = None, *, mcp_command: list[str] | None = None) -> Path:
+ """Write the gemini-cli system-settings json (api-key auth + dynamic models) and return its path.
+
+ gemini-cli applies this file LAST and ``mcp.allowed`` REPLACES rather than merges, so the
+ 3dcv server and the allow-list belong here, not in the agent-writable
+ ``ws/.gemini/settings.json``: a server the agent planted there is Blocked."""
+ path = path or (get_settings().cache_dir / "gemini_cli_settings.json")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ data: dict[str, Any] = {**SYSTEM_SETTINGS, "mcp": {"allowed": [MCP_SERVER_NAME]}}
+ if mcp_command:
+ data["mcpServers"] = {MCP_SERVER_NAME: {"command": mcp_command[0], "args": list(mcp_command[1:]),
+ "timeout": MCP_TOOL_TIMEOUT_MS}}
+ want = json.dumps(data, indent=2)
+ if not path.is_file() or path.read_text() != want:
+ path.write_text(want)
+ return path
+
+
+def parse_gemini_json(stdout: str) -> dict[str, Any] | None:
+ """The CLI prints one JSON object (possibly after log noise); find it."""
+ s = stdout.strip()
+ if not s:
+ return None
+ try:
+ return json.loads(s)
+ except json.JSONDecodeError:
+ pass
+ start = s.find("{")
+ while start != -1:
+ try:
+ obj = json.loads(s[start:])
+ return obj if isinstance(obj, dict) else None
+ except json.JSONDecodeError:
+ start = s.find("{", start + 1)
+ return None
+
+
+def _model_usage(tok: dict[str, Any], name: str) -> Usage:
+ """One served model's counters in pricing semantics (``input_tokens`` = total prompt)."""
+ cached = int(tok.get("cached") or 0)
+ prompt = tok.get("prompt")
+ # gemini-cli: tokens.prompt = promptTokenCount (total), tokens.input = prompt - cached
+ total = int(prompt) if prompt is not None else int(tok.get("input") or 0) + cached
+ return Usage(backend="gemini-cli", model=name, input_tokens=total, cached_tokens=cached,
+ output_tokens=int(tok.get("candidates") or 0), thoughts_tokens=int(tok.get("thoughts") or 0))
+
+
+def usage_from_stats(stats: dict[str, Any], model: str) -> Usage:
+ """Sum tokens across every served model (normally just ``model``); cost is the
+ sum of each served model priced at its own rate (unknown → requested model's)."""
+ u = Usage(backend="gemini-cli", model=model)
+ cost = 0.0
+ for name, m in (stats.get("models") or {}).items():
+ part = _model_usage((m or {}).get("tokens") or {}, str(name))
+ c = estimate_cost_safe("gemini", str(name), part)
+ if c == 0.0 and name != model and (part.input_tokens or part.output_tokens):
+ c = estimate_cost_safe("gemini", model, part) # utility model missing from the price table
+ cost += c
+ u.input_tokens += part.input_tokens
+ u.output_tokens += part.output_tokens
+ u.cached_tokens += part.cached_tokens
+ u.thoughts_tokens += part.thoughts_tokens
+ u.tool_calls = int(((stats.get("tools") or {}).get("totalCalls")) or 0)
+ u.cost_usd = cost
+ return u
+
+
+def _retry_key(pool: KeyPool, used: set[str]) -> str | None:
+ """Key for a retry: a different healthy key if one frees up within
+ ``RETRY_KEY_WAIT_S``, else the same key again (single-key pools, 5xx), else
+ ``None`` when every key is throttled (429 cooldown) — the caller then stops."""
+ for exclude in (used, None):
+ try:
+ return pool.acquire(exclude=exclude or None, timeout_s=RETRY_KEY_WAIT_S)
+ except KeyPoolExhausted:
+ continue
+ return None
+
+
+class GeminiCliAgent:
+ kind = "gemini-cli"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.gemini_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"gemini CLI not found: {self.binary!r}"
+ if not get_settings().gemini_api_keys:
+ return False, "no Gemini API keys configured"
+ return True, "ok"
+
+ # ------------------------------------------------------------------ build
+ def build_argv(self, prompt: str) -> list[str]:
+ return [self.binary, "-p", prompt, "-m", self.model, "--approval-mode", "yolo",
+ "--skip-trust", "--output-format", "json"]
+
+ def build_env(self, s: Session, api_key: str) -> dict[str, str]:
+ env = hardened_env(s.ws, s.job)
+ env["GEMINI_API_KEY"] = api_key
+ # per SESSION, in the harness-owned trajectory dir: the command is per-run
+ # (``--workspace <ws>``) and it is rewritten immediately before every invoke
+ env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(write_system_settings(
+ s.traj.dir / "gemini_settings.json",
+ mcp_command=mcp_command_for(s.ws, s.job) if s.job.spatial_tools else None))
+ env["GEMINI_CLI_NO_RELAUNCH"] = "1"
+ node_opts = env.get("NODE_OPTIONS", "")
+ if "--max-old-space-size" not in node_opts:
+ env["NODE_OPTIONS"] = f"{node_opts} --max-old-space-size=6144".strip()
+ return env
+
+ # ------------------------------------------------------------------ run
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, _compose_prompt(job))
+ pool = _key_pool(get_settings().gemini_api_keys)
+ try:
+ key = pool.acquire()
+ except KeyPoolExhausted as e: # every key throttled for the whole wait budget
+ return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")
+ attempts = 0
+ used: set[str] = set()
+ t0 = time.monotonic()
+ next_soft: float | None = None # attempt 1 uses the job's own window
+ usage_total = Usage(backend=self.kind, model=self.model)
+ while True:
+ attempts += 1
+ used.add(key)
+ proc = self._invoke(s, prompt, key, attempt=attempts, soft_timeout_s=next_soft)
+ outcome = self._interpret(s, proc)
+ usage_total = usage_total + outcome["usage"]
+ pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))
+ pool.release() # one acquire per attempt: keep the pool's in-flight gauge honest
+ if outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:
+ break
+ next_soft = retry_window_left(job.timeout_s, time.monotonic() - t0)
+ if next_soft is None:
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); "
+ "no session window left — not retrying past the wall")
+ break
+ next_key = _retry_key(pool, used)
+ if next_key is None:
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); no usable key for a retry")
+ break
+ key = next_key
+ how = "rotated key" if key not in used else "same key (no alternative available)"
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with {how}")
+ s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])
+ usage_total.cost_usd = round(usage_total.cost_usd, 6)
+ return finish_session(
+ s, ok=outcome["ok"], exit_reason=outcome["exit_reason"], text=outcome["text"],
+ usage=usage_total, tool_calls=usage_total.tool_calls, errors=outcome["errors"],
+ attempts=attempts, rc=proc.rc, killed_reason=proc.killed_reason, session_id=outcome.get("session_id", ""),
+ )
+ finally:
+ release_session(s)
+
+ def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int,
+ soft_timeout_s: float | None = None) -> CompletedProc:
+ return invoke(s, self.build_argv(prompt), self.build_env(s, key), prompt=prompt, attempt=attempt,
+ soft_timeout_s=soft_timeout_s, model=self.model, key_tail=key[-4:])
+
+ def _interpret(self, s: Session, proc: CompletedProc) -> dict[str, Any]:
+ parsed = parse_gemini_json(proc.stdout)
+ stats = (parsed or {}).get("stats") or {}
+ usage = usage_from_stats(stats, self.model) if stats else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = int(proc.duration_s * 1000)
+ text = str((parsed or {}).get("response") or "")
+ errors: list[str] = []
+ served = list((stats.get("models") or {}).keys())
+ out: dict[str, Any] = {"usage": usage, "text": text, "ok": False, "exit_reason": "error",
+ "transient": False, "quota": False, "errors": errors,
+ "session_id": (parsed or {}).get("session_id", "")}
+ if proc.timed_out:
+ out["exit_reason"] = "timeout"
+ errors.append(watchdog_error(proc))
+ return out
+ if served and self.model not in served:
+ out["exit_reason"] = "model_substituted"
+ errors.append(f"requested {self.model!r} but CLI served {served}")
+ return out
+ if parsed is None or proc.rc != 0 or not text.strip():
+ out["transient"] = is_transient_failure(proc.stderr, proc.stdout) or (parsed is not None and not text.strip())
+ out["quota"] = is_quota_failure(proc.stderr, proc.stdout)
+ errors.append(f"rc={proc.rc}; response={'<empty>' if not text.strip() else 'ok'}; stderr tail: {tail(proc.stderr, 1500)}")
+ out["exit_reason"] = "budget" if out["quota"] else "error"
+ return out
+ out["ok"] = True
+ out["exit_reason"] = "completed"
+ return out
+
+
+def _compose_prompt(job: AgentJob) -> str:
+ """gemini-cli and codex have no system-prompt flag: prepend ``system_append``."""
+ if not job.system_append:
+ return job.prompt
+ return f"<harness_instructions>\n{job.system_append}\n</harness_instructions>\n\n{job.prompt}"
+
+
+# ===================================================================== claude_code
+# (merged from codeverse/agents/claude_code.py, 2026-08-28)
+#: ``--allowedTools``. "Skill" is claude-code 2.1's model-invoked skill tool: without it
+#: the bundles the harness materialises into ``ws/.claude/skills/`` are listed at session
+#: start and then DENIED on activation, which reads in the transcript as the model
+#: ignoring them. It only ever opens files already inside the workspace.
+ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep", "Skill",
+ "Bash(node:*)", "Bash(python:*)", "Bash(python3:*)", "Bash(ls:*)", "mcp__c3v__*")
+
+
+def parse_claude_json(stdout: str) -> dict[str, Any] | None:
+ """Envelope is one JSON object; tolerate leading log noise and stream-json arrays."""
+ s = stdout.strip()
+ if not s:
+ return None
+ try:
+ obj = json.loads(s)
+ except json.JSONDecodeError:
+ obj = None
+ for line in reversed(s.splitlines()):
+ line = line.strip()
+ if line.startswith("{"):
+ try:
+ cand = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(cand, dict) and cand.get("type") == "result":
+ return cand
+ obj = obj or cand
+ return obj if isinstance(obj, dict) else None
+ if isinstance(obj, list): # stream-json array: last result event wins
+ results = [e for e in obj if isinstance(e, dict) and e.get("type") == "result"]
+ return results[-1] if results else None
+ return obj if isinstance(obj, dict) else None
+
+
+def usage_from_envelope(env: dict[str, Any], model: str) -> Usage:
+ u = env.get("usage") or {}
+ usage = Usage(
+ backend="claude-code", model=model,
+ input_tokens=int(u.get("input_tokens") or 0),
+ output_tokens=int(u.get("output_tokens") or 0),
+ cached_tokens=int(u.get("cache_read_input_tokens") or 0),
+ thoughts_tokens=int(((u.get("output_tokens_details") or {}).get("thinking_tokens")) or 0),
+ tool_calls=max(int(env.get("num_turns") or 0) - 1, 0),
+ cost_usd=float(env.get("total_cost_usd") or 0.0),
+ latency_ms=int(env.get("duration_ms") or 0),
+ )
+ usage.model = primary_served_model(env, model)
+ return usage
+
+
+def primary_served_model(env: dict[str, Any], model: str) -> str:
+ """The model that actually did the WORK, of the (up to two) that one session bills.
+
+ ``claude -p`` bills the work model PLUS the small background model the CLI uses for
+ its own housekeeping, and claude 2.1.243 lists the AUXILIARY one first — so taking
+ ``served[0]`` recorded a model that did ~1% of the tokens whenever ``--model`` was an
+ ALIAS ('sonnet', 'opus', or the default arm). A sonnet-vs-default comparison was
+ therefore labelled haiku-vs-haiku, in CallCost.model and in OneShotResult.usage.
+
+ The envelope's top-level ``usage`` block reports the MAIN conversation only, so the
+ entry whose token counts match it is the work model; otherwise take the dearest.
+ An id we passed verbatim is already a served name and is kept as-is.
+ """
+ served: dict[str, Any] = env.get("modelUsage") or {}
+ if not served or model in served:
+ return model
+ u = env.get("usage") or {}
+ want = (int(u.get("input_tokens") or 0), int(u.get("output_tokens") or 0))
+ if any(want):
+ for name, row in served.items():
+ r = row or {}
+ if (int(r.get("inputTokens") or 0), int(r.get("outputTokens") or 0)) == want:
+ return name
+ return max(served, key=lambda n: float((served[n] or {}).get("costUSD") or 0.0))
+
+
+class ClaudeCodeAgent:
+ kind = "claude-code"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.claude_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"claude CLI not found: {self.binary!r}"
+ return True, "ok"
+
+ def build_argv(self, s: Session, prompt: str) -> list[str]:
+ job = s.job
+ argv = [self.binary, "-p", prompt, "--output-format", "json", "--dangerously-skip-permissions",
+ "--max-turns", str(job.max_turns), "--no-session-persistence",
+ "--allowedTools", ",".join(ALLOWED_TOOLS)]
+ if self.model:
+ argv += ["--model", self.model]
+ if job.spatial_tools:
+ # written fresh into the harness-owned trajectory dir for THIS session, from
+ # the typed job — never the workspace's .mcp.json, which the agent can rewrite
+ # between rounds to choose what the next session launches (audit 2026-08-27)
+ cfg = s.traj.dir / "mcp.json"
+ cmd = mcp_command_for(s.ws, job)
+ cfg.write_text(json.dumps(
+ {"mcpServers": {MCP_SERVER_NAME: {"type": "stdio", "command": cmd[0], "args": cmd[1:],
+ "timeout": MCP_TOOL_TIMEOUT_MS}}}, indent=2))
+ argv += ["--mcp-config", str(cfg), "--strict-mcp-config"]
+ else:
+ argv += ["--strict-mcp-config"] # never inherit the user's ambient MCP servers
+ if job.system_append:
+ argv += ["--append-system-prompt", job.system_append]
+ return argv
+
+ def build_env(self, s: Session) -> dict[str, str]:
+ # keep ANTHROPIC_API_KEY if the user relies on it; subscription auth needs nothing
+ return hardened_env(s.ws, s.job, keep={"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"})
+
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, job.prompt)
+ proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
+ env = parse_claude_json(proc.stdout)
+ usage = usage_from_envelope(env, self.model) if env else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str((env or {}).get("result") or "")
+ turns = int((env or {}).get("num_turns") or 0)
+ errors: list[str] = []
+ if proc.timed_out:
+ reason, ok = "timeout", False
+ errors.append(watchdog_error(proc))
+ elif env is None or proc.rc != 0:
+ reason, ok = "error", False
+ errors.append(f"rc={proc.rc}; no result envelope; stderr tail: {tail(proc.stderr, 1500)}")
+ if is_transient_failure(proc.stderr, proc.stdout):
+ reason = "budget" if "rate" in proc.stderr.lower() else "error"
+ elif env.get("is_error") or str(env.get("subtype", "")).startswith("error"):
+ ok = False
+ sub = str(env.get("subtype", ""))
+ reason = "budget" if "max_turns" in sub else "error"
+ errors.append(f"claude reported {sub or 'is_error'}: {tail(text, 800)}")
+ else:
+ reason, ok = "completed", True
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0),
+ errors=errors, rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns,
+ session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),
+ model_usage=(env or {}).get("modelUsage", {}),
+ )
+ finally:
+ release_session(s)
+
+
+# ===================================================================== codex
+# (merged from codeverse/agents/codex.py, 2026-08-28)
+STDIN_PROMPT_BYTES = 100_000
+_TOOL_ITEMS = ("command_execution", "file_change", "mcp_tool_call", "web_search", "tool_call")
+
+#: what ``-c model_reasoning_effort=`` accepts; ``""`` means "leave it to ~/.codex/config.toml"
+REASONING_EFFORTS = ("", "minimal", "low", "medium", "high", "xhigh")
+
+
+def split_model_effort(model: str, effort: str | None = None) -> tuple[str, str]:
+ """``('gpt-5.6-sol@low', None) -> ('gpt-5.6-sol', 'low')``.
+
+ Precedence: an explicit ``effort`` argument, then an ``@<effort>`` suffix on the
+ model id, then ``Settings.agents.codex_reasoning_effort`` (default ``high`` — the
+ codex CLI's own default is *medium*, and the harness would rather pay for thinking).
+ ``""`` at any level means "pass no override and let ~/.codex/config.toml decide".
+ """
+ name, _, suffix = model.partition("@")
+ chosen = effort if effort is not None else (suffix or get_settings().agents.codex_reasoning_effort)
+ chosen = chosen.strip().lower()
+ if chosen not in REASONING_EFFORTS:
+ raise ValueError(f"bad codex reasoning effort {chosen!r}; expected one of {REASONING_EFFORTS}")
+ return name.strip(), chosen
+
+
+def effort_overrides(effort: str) -> list[str]:
+ """The ``-c`` pair for a reasoning effort (empty when nothing should be forced)."""
+ return ["-c", f"model_reasoning_effort={effort}"] if effort else []
+
+
+class CodexEvents:
+ """Folded view over the JSONL event stream."""
+
+ def __init__(self) -> None:
+ self.messages: list[str] = []
+ self.errors: list[str] = []
+ self.tool_calls = 0
+ self.turns_completed = 0
+ self.usage_raw: dict[str, int] = {"input_tokens": 0, "cached_input_tokens": 0, "output_tokens": 0,
+ "reasoning_output_tokens": 0, "cache_write_input_tokens": 0}
+ self.thread_id = ""
+ self.n_events = 0
+
+ def feed(self, line: str) -> None:
+ line = line.strip()
+ if not line.startswith("{"):
+ return
+ try:
+ ev = json.loads(line)
+ except json.JSONDecodeError:
+ return
+ self.n_events += 1
+ t = ev.get("type", "")
+ if t == "thread.started":
+ self.thread_id = str(ev.get("thread_id", ""))
+ elif t == "item.completed":
+ item = ev.get("item") or {}
+ it = item.get("type", "")
+ if it == "agent_message":
+ self.messages.append(str(item.get("text", "")))
+ elif it in _TOOL_ITEMS:
+ self.tool_calls += 1
+ elif t == "turn.completed":
+ self.turns_completed += 1
+ for k in self.usage_raw:
+ self.usage_raw[k] += int((ev.get("usage") or {}).get(k) or 0)
+ elif t == "turn.failed":
+ self.errors.append(str((ev.get("error") or {}).get("message") or ev))
+ elif t == "error":
+ self.errors.append(str(ev.get("message") or ev))
+
+ def usage(self, model: str) -> Usage:
+ # `output_tokens` from the Responses API already CONTAINS
+ # `reasoning_output_tokens` (measured: output − reasoning tracks the answer
+ # length across every recorded cell). `estimate_cost` bills output +
+ # thoughts, so the reasoning share is subtracted here instead of being
+ # charged twice — it stays visible in `thoughts_tokens`.
+ reasoning = self.usage_raw["reasoning_output_tokens"]
+ u = Usage(
+ backend="codex", model=model,
+ input_tokens=self.usage_raw["input_tokens"],
+ output_tokens=max(0, self.usage_raw["output_tokens"] - reasoning),
+ cached_tokens=self.usage_raw["cached_input_tokens"], tool_calls=self.tool_calls,
+ thoughts_tokens=reasoning,
+ )
+ u.cost_usd = estimate_cost_safe("openai", model, u)
+ return u
+
+
+def parse_codex_jsonl(stdout: str) -> CodexEvents:
+ ev = CodexEvents()
+ for line in stdout.splitlines():
+ ev.feed(line)
+ return ev
+
+
+class CodexAgent:
+ kind = "codex"
+
+ def __init__(self, model: str, binary: str | None = None, reasoning_effort: str | None = None):
+ self.model, self.reasoning_effort = split_model_effort(model, reasoning_effort)
+ self.binary = binary or get_settings().binaries.codex_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"codex CLI not found: {self.binary!r}"
+ return True, "ok"
+
+ def build_argv(self, s: Session, prompt: str | None) -> list[str]:
+ """``prompt=None`` means 'read it from stdin' (``-`` positional)."""
+ job = s.job
+ argv = [self.binary, "exec", "--json", "-C", str(s.ws.root), "--sandbox", "workspace-write",
+ "--skip-git-repo-check", "--ephemeral", "--color", "never"]
+ if self.model:
+ argv += ["--model", self.model]
+ argv += effort_overrides(self.reasoning_effort)
+ if job.spatial_tools:
+ argv += codex_mcp_overrides(mcp_command_for(s.ws, job))
+ argv.append(prompt if prompt is not None else "-")
+ return argv
+
+ def build_env(self, s: Session) -> dict[str, str]:
+ return hardened_env(s.ws, s.job, keep={"OPENAI_API_KEY", "CODEX_API_KEY"})
+
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = _compose_prompt(job)
+ via_stdin = len(prompt.encode("utf-8")) > STDIN_PROMPT_BYTES
+ argv = self.build_argv(s, None if via_stdin else prompt)
+ events = CodexEvents()
+ proc = invoke(s, argv, self.build_env(s), prompt=prompt, stdout_name="stdout.jsonl",
+ on_stdout=events.feed, stdin=prompt if via_stdin else None)
+ usage = events.usage(self.model)
+ usage.latency_ms = int(proc.duration_s * 1000)
+ text = "\n\n".join(m for m in events.messages if m.strip())
+ errors = list(events.errors)
+ if proc.timed_out:
+ ok, reason = False, "timeout"
+ errors.append(watchdog_error(proc))
+ elif proc.rc != 0 or events.n_events == 0:
+ ok, reason = False, "error"
+ errors.append(f"rc={proc.rc}; events={events.n_events}; stderr tail: {tail(proc.stderr, 1500)}")
+ elif events.errors and events.turns_completed == 0:
+ ok, reason = False, "error"
+ else:
+ ok, reason = True, "completed"
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls, errors=errors,
+ rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
+ turns_completed=events.turns_completed, usage_raw=events.usage_raw,
+ )
+ finally:
+ release_session(s)
+
+
+# ===================================================================== antigravity
+# (merged from codeverse/agents/antigravity.py, 2026-08-28)
+log = logging.getLogger(__name__)
+
+#: reasoning efforts agy exposes for the models that have them
+EFFORTS = ("low", "medium", "high")
+#: what a bare id is resolved to when agy offers only effort-suffixed spellings
+DEFAULT_EFFORT = "medium"
+_EFFORT_SUFFIXES = tuple(f"-{e}" for e in EFFORTS)
+
+
+@lru_cache(maxsize=4)
+def available_models(binary: str) -> tuple[str, ...]:
+ """The model ids ``agy models`` offers, or ``()`` when it cannot be reached.
+
+ Cached: one lookup per binary per process, and only for an id that needs it.
+ """
+ try:
+ r = run_subprocess([binary, "models"], cwd=Path.cwd(), timeout_s=30.0)
+ except OSError as e: # pragma: no cover - defensive
+ log.debug("agy models unavailable: %s", e)
+ return ()
+ if r.returncode != 0:
+ return ()
+ ids = []
+ for line in r.stdout.splitlines():
+ head = line.split("\t", 1)[0].strip()
+ if head and " " not in head:
+ ids.append(head)
+ return tuple(ids)
+
+
+def resolve_model(model: str, binary: str) -> str:
+ """Map a bare model id onto the effort-suffixed one agy actually accepts.
+
+ agy 1.1.19 rejects ``--model gemini-3.7-flash`` outright ("requires --effort
+ (available: low, medium, high)") and equally rejects ``--effort`` for a model that
+ has none ("--effort is not supported for model claude-sonnet-4-6"), so the effort
+ cannot be a blanket flag — it belongs in the MODEL ID, which is the only spelling
+ ``agy models`` lists (gemini-3.7-flash-low/-medium/-high).
+
+ A bare id agy DOES offer (claude-sonnet-4-6) is passed through untouched, and so is
+ anything we cannot check, so this can only turn a guaranteed failure into a run.
+ """
+ if not model or model.endswith(_EFFORT_SUFFIXES):
+ return model
+ offered = available_models(binary)
+ if not offered or model in offered:
+ return model
+ for effort in (DEFAULT_EFFORT, *EFFORTS):
+ if f"{model}-{effort}" in offered:
+ log.info("agy has no bare %r; using the %s-effort id %r", model, effort, f"{model}-{effort}")
+ return f"{model}-{effort}"
+ return model
+
+
+def parse_agy_json(stdout: str) -> dict[str, Any] | None:
+ s = stdout.strip()
+ if not s:
+ return None
+ for cand in (s, *reversed([ln for ln in s.splitlines() if ln.strip().startswith("{")])):
+ try:
+ obj = json.loads(cand)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(obj, dict) and ("response" in obj or "status" in obj):
+ return obj
+ return None
+
+
+def usage_from_agy(env: dict[str, Any], model: str) -> Usage:
+ u = env.get("usage") or {}
+ return Usage(
+ backend="agy", model=model,
+ input_tokens=int(u.get("input_tokens") or 0),
+ output_tokens=int(u.get("output_tokens") or 0),
+ cached_tokens=int(u.get("cache_read_tokens") or 0),
+ thoughts_tokens=int(u.get("thinking_tokens") or 0),
+ cost_usd=0.0, # subscription; no USD exposed
+ latency_ms=int(float(env.get("duration_seconds") or 0.0) * 1000),
+ )
+
+
+class AntigravityAgent:
+ kind = "agy"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.agy_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def served_model(self) -> str:
+ """The id actually sent to agy (a bare one gains its effort suffix)."""
+ return resolve_model(self.model, self.binary)
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"agy CLI not found: {self.binary!r}"
+ return True, "ok"
+
+ def build_argv(self, s: Session, prompt: str) -> list[str]:
+ minutes = max(1, int(s.job.timeout_s // 60) + 1)
+ argv = [self.binary, "--print", prompt, "--dangerously-skip-permissions",
+ "--print-timeout", f"{minutes}m", "--output-format", "json",
+ "--add-dir", str(s.ws.root), "--disable-slash-commands"]
+ if self.model:
+ argv += ["--model", self.served_model()]
+ return argv
+
+ def build_env(self, s: Session) -> dict[str, str]:
+ return hardened_env(s.ws, s.job)
+
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ try:
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, _compose_prompt_agy(s))
+ proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
+ env = parse_agy_json(proc.stdout)
+ served = self.served_model()
+ usage = usage_from_agy(env, served) if env else Usage(backend=self.kind, model=served)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str(env.get("response", "")) if env else proc.stdout.strip()
+ errors: list[str] = []
+ if env is None:
+ s.notes.append("no JSON envelope from agy; usage unknown (zeros), response taken from plain stdout")
+ s.notes.append("agy is subscription-billed: cost_usd=0")
+ if proc.timed_out:
+ ok, reason = False, "timeout"
+ errors.append(watchdog_error(proc))
+ elif proc.rc != 0 or (env is not None and str(env.get("status", "SUCCESS")).upper() not in ("SUCCESS", "OK")):
+ ok, reason = False, "error"
+ errors.append(f"rc={proc.rc}; status={(env or {}).get('status')}; error={(env or {}).get('error', '')}; "
+ f"stderr tail: {tail(proc.stderr, 1500)}")
+ elif not text.strip():
+ ok, reason = False, "error"
+ errors.append("empty response")
+ else:
+ ok, reason = True, "completed"
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0, errors=errors,
+ rc=proc.rc, killed_reason=proc.killed_reason,
+ conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
+ )
+ finally:
+ release_session(s)
+
+
+def _compose_prompt_agy(s: Session) -> str:
+ """agy has no system-prompt flag; prepend harness instructions + the absolute workspace path."""
+ job = s.job
+ head = f"Workspace root: {s.ws.root}\nWork ONLY inside it, using your file tools."
+ if (s.ws.root / "AGENTS.md").is_file():
+ head += " Read AGENTS.md there first and follow it."
+ head += "\n"
+ if job.system_append:
+ head += f"\n<harness_instructions>\n{job.system_append}\n</harness_instructions>\n"
+ return f"{head}\n{job.prompt}"
diff --git a/harness/codeverse/agents/base.py b/harness/codeverse/agents/base.py
deleted file mode 100644
index a4589669..00000000
--- a/harness/codeverse/agents/base.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""The CodingAgent protocol every agentic backend implements."""
-
-from __future__ import annotations
-
-from typing import Protocol, runtime_checkable
-
-from codeverse.contracts.agent import AgentJob, AgentResult
-
-
-@runtime_checkable
-class CodingAgent(Protocol):
- """Runs ONE headless agent session in ``job.workspace``.
-
- Contract for implementations:
- * the agent may only write under ``job.write_roots`` (harness materialises
- AGENTS.md/GEMINI.md/CLAUDE.md + MCP config before the call; see
- ``agents/materialize.py``),
- * never raise for agent failures — return ``AgentResult(ok=False, exit_reason=...)``,
- * fill ``usage`` (tokens + cost) as precisely as the CLI allows,
- * write the full transcript to ``job.workspace/trajectories/...`` and set
- ``transcript_path``,
- * compute ``files_changed`` via ``Workspace.changed_files`` (git), not by
- trusting the agent's claims,
- * respect ``job.timeout_s`` with an activity-aware watchdog (kill the whole
- process group on timeout).
- """
-
- kind: str # gemini-cli | claude-code | codex | agy
- model: str
-
- @property
- def id(self) -> str: ...
-
- def run(self, job: AgentJob) -> AgentResult: ...
-
- def available(self) -> tuple[bool, str]:
- """(is_usable, reason) — binary found / auth present / model known."""
- ...
diff --git a/harness/codeverse/agents/claude_code.py b/harness/codeverse/agents/claude_code.py
deleted file mode 100644
index 5b8523af..00000000
--- a/harness/codeverse/agents/claude_code.py
+++ /dev/null
@@ -1,199 +0,0 @@
-"""``claude-code:<model>`` — headless Claude Code session on a workspace.
-
-argv: ``claude -p <prompt> --output-format json --dangerously-skip-permissions
---model <model> --max-turns N --allowedTools ... [--mcp-config ws/.mcp.json
---strict-mcp-config] [--append-system-prompt ...]``
-
-JSON envelope (claude 2.1.x, observed): ``{type:"result", subtype:"success",
-is_error, result, session_id, num_turns, duration_ms, total_cost_usd,
-stop_reason, terminal_reason, usage:{input_tokens, output_tokens,
-cache_read_input_tokens, cache_creation_input_tokens,
-output_tokens_details:{thinking_tokens}}, modelUsage:{<model>:{costUSD,...}}}``.
-Auth: whatever the user's ``claude`` login is (subscription or
-``ANTHROPIC_API_KEY``); we pass that variable through untouched if present.
-"""
-
-from __future__ import annotations
-
-import json
-from typing import Any
-
-from codeverse.agents.cli_common import (
- Session,
- begin_session,
- deliver_prompt,
- exists_on_path,
- failed,
- finish_session,
- hardened_env,
- invoke,
- is_transient_failure,
- mcp_command_for,
- release_session,
- tail,
- watchdog_error,
-)
-from codeverse.agents.materialize import MCP_SERVER_NAME, MCP_TOOL_TIMEOUT_MS
-from codeverse.config import get_settings
-from codeverse.contracts.agent import AgentJob, AgentResult
-from codeverse.contracts.common import Usage
-
-#: ``--allowedTools``. "Skill" is claude-code 2.1's model-invoked skill tool: without it
-#: the bundles the harness materialises into ``ws/.claude/skills/`` are listed at session
-#: start and then DENIED on activation, which reads in the transcript as the model
-#: ignoring them. It only ever opens files already inside the workspace.
-ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep", "Skill",
- "Bash(node:*)", "Bash(python:*)", "Bash(python3:*)", "Bash(ls:*)", "mcp__c3v__*")
-
-
-def parse_claude_json(stdout: str) -> dict[str, Any] | None:
- """Envelope is one JSON object; tolerate leading log noise and stream-json arrays."""
- s = stdout.strip()
- if not s:
- return None
- try:
- obj = json.loads(s)
- except json.JSONDecodeError:
- obj = None
- for line in reversed(s.splitlines()):
- line = line.strip()
- if line.startswith("{"):
- try:
- cand = json.loads(line)
- except json.JSONDecodeError:
- continue
- if isinstance(cand, dict) and cand.get("type") == "result":
- return cand
- obj = obj or cand
- return obj if isinstance(obj, dict) else None
- if isinstance(obj, list): # stream-json array: last result event wins
- results = [e for e in obj if isinstance(e, dict) and e.get("type") == "result"]
- return results[-1] if results else None
- return obj if isinstance(obj, dict) else None
-
-
-def usage_from_envelope(env: dict[str, Any], model: str) -> Usage:
- u = env.get("usage") or {}
- usage = Usage(
- backend="claude-code", model=model,
- input_tokens=int(u.get("input_tokens") or 0),
- output_tokens=int(u.get("output_tokens") or 0),
- cached_tokens=int(u.get("cache_read_input_tokens") or 0),
- thoughts_tokens=int(((u.get("output_tokens_details") or {}).get("thinking_tokens")) or 0),
- tool_calls=max(int(env.get("num_turns") or 0) - 1, 0),
- cost_usd=float(env.get("total_cost_usd") or 0.0),
- latency_ms=int(env.get("duration_ms") or 0),
- )
- usage.model = primary_served_model(env, model)
- return usage
-
-
-def primary_served_model(env: dict[str, Any], model: str) -> str:
- """The model that actually did the WORK, of the (up to two) that one session bills.
-
- ``claude -p`` bills the work model PLUS the small background model the CLI uses for
- its own housekeeping, and claude 2.1.243 lists the AUXILIARY one first — so taking
- ``served[0]`` recorded a model that did ~1% of the tokens whenever ``--model`` was an
- ALIAS ('sonnet', 'opus', or the default arm). A sonnet-vs-default comparison was
- therefore labelled haiku-vs-haiku, in CallCost.model and in OneShotResult.usage.
-
- The envelope's top-level ``usage`` block reports the MAIN conversation only, so the
- entry whose token counts match it is the work model; otherwise take the dearest.
- An id we passed verbatim is already a served name and is kept as-is.
- """
- served: dict[str, Any] = env.get("modelUsage") or {}
- if not served or model in served:
- return model
- u = env.get("usage") or {}
- want = (int(u.get("input_tokens") or 0), int(u.get("output_tokens") or 0))
- if any(want):
- for name, row in served.items():
- r = row or {}
- if (int(r.get("inputTokens") or 0), int(r.get("outputTokens") or 0)) == want:
- return name
- return max(served, key=lambda n: float((served[n] or {}).get("costUSD") or 0.0))
-
-
-class ClaudeCodeAgent:
- kind = "claude-code"
-
- def __init__(self, model: str, binary: str | None = None):
- self.model = model
- self.binary = binary or get_settings().binaries.claude_cli
-
- @property
- def id(self) -> str:
- return f"{self.kind}:{self.model}"
-
- def available(self) -> tuple[bool, str]:
- if not exists_on_path(self.binary):
- return False, f"claude CLI not found: {self.binary!r}"
- return True, "ok"
-
- def build_argv(self, s: Session, prompt: str) -> list[str]:
- job = s.job
- argv = [self.binary, "-p", prompt, "--output-format", "json", "--dangerously-skip-permissions",
- "--max-turns", str(job.max_turns), "--no-session-persistence",
- "--allowedTools", ",".join(ALLOWED_TOOLS)]
- if self.model:
- argv += ["--model", self.model]
- if job.spatial_tools:
- # written fresh into the harness-owned trajectory dir for THIS session, from
- # the typed job — never the workspace's .mcp.json, which the agent can rewrite
- # between rounds to choose what the next session launches (audit 2026-08-27)
- cfg = s.traj.dir / "mcp.json"
- cmd = mcp_command_for(s.ws, job)
- cfg.write_text(json.dumps(
- {"mcpServers": {MCP_SERVER_NAME: {"type": "stdio", "command": cmd[0], "args": cmd[1:],
- "timeout": MCP_TOOL_TIMEOUT_MS}}}, indent=2))
- argv += ["--mcp-config", str(cfg), "--strict-mcp-config"]
- else:
- argv += ["--strict-mcp-config"] # never inherit the user's ambient MCP servers
- if job.system_append:
- argv += ["--append-system-prompt", job.system_append]
- return argv
-
- def build_env(self, s: Session) -> dict[str, str]:
- # keep ANTHROPIC_API_KEY if the user relies on it; subscription auth needs nothing
- return hardened_env(s.ws, s.job, keep={"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"})
-
- def run(self, job: AgentJob) -> AgentResult:
- ok, why = self.available()
- s = begin_session(job, self.kind)
- try:
- if not ok:
- return failed(s, "error", why)
- prompt = deliver_prompt(s, job.prompt)
- proc = invoke(s, self.build_argv(s, prompt), self.build_env(s), prompt=prompt)
- env = parse_claude_json(proc.stdout)
- usage = usage_from_envelope(env, self.model) if env else Usage(backend=self.kind, model=self.model)
- usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
- text = str((env or {}).get("result") or "")
- turns = int((env or {}).get("num_turns") or 0)
- errors: list[str] = []
- if proc.timed_out:
- reason, ok = "timeout", False
- errors.append(watchdog_error(proc))
- elif env is None or proc.rc != 0:
- reason, ok = "error", False
- errors.append(f"rc={proc.rc}; no result envelope; stderr tail: {tail(proc.stderr, 1500)}")
- if is_transient_failure(proc.stderr, proc.stdout):
- reason = "budget" if "rate" in proc.stderr.lower() else "error"
- elif env.get("is_error") or str(env.get("subtype", "")).startswith("error"):
- ok = False
- sub = str(env.get("subtype", ""))
- reason = "budget" if "max_turns" in sub else "error"
- errors.append(f"claude reported {sub or 'is_error'}: {tail(text, 800)}")
- else:
- reason, ok = "completed", True
- return finish_session(
- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0),
- errors=errors, rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns,
- session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),
- model_usage=(env or {}).get("modelUsage", {}),
- )
- finally:
- release_session(s)
-
-
-__all__ = ["ClaudeCodeAgent", "parse_claude_json", "primary_served_model", "usage_from_envelope", "ALLOWED_TOOLS"]
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
index 862134c0..08930f9d 100644
--- a/harness/codeverse/agents/cli_common.py
+++ b/harness/codeverse/agents/cli_common.py
@@ -1,38 +1,258 @@
-"""Shared plumbing for subprocess-based CodingAgent backends.
-
-* :func:`hardened_env` — child environment without unrelated secrets.
-* :func:`begin_session` / :func:`finish_session` — trajectory dir (a retry of
- the same label+round gets ``<label>.a2_rNN`` instead of overwriting attempt 1),
- git snapshot before/after, ``files_changed`` from git *attributed to this
- session* (see :func:`attribute_changes`), ``result.json``.
-* :func:`deliver_prompt` — argv prompt or "read the prompt file" stub.
-* :func:`invoke` / :func:`watchdog_error` — one CLI process under the watchdog,
- recorded in the trajectory (``invoke`` line, every output line, stdout/stderr
- captures); ``IDLE_GRACE_S`` is the shared idle kill threshold.
-* :func:`estimate_cost_safe` — lazy bridge to ``codeverse.models.pricing``.
-* :func:`is_transient_failure` — 429 / 503 / empty-response detection.
+"""Trajectory folder helper: prompt.md, transcript.jsonl, stdout/stderr, result.json.
+
+Every CodingAgent backend writes its session here
+(``ws.trajectory_dir(label, round)``) so the flywheel and ``3dcv status`` can
+read one uniform layout regardless of backend.
"""
from __future__ import annotations
+import json
import logging
import os
import re
import sys
import threading
import time
-from collections.abc import Callable, Mapping
+from collections.abc import Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
-from codeverse.agents.transcript import Trajectory
-from codeverse.agents.watchdog import CompletedProc, run_with_watchdog
+from pydantic import BaseModel
+
from codeverse.contracts.agent import AgentJob, AgentResult, FileChange
from codeverse.contracts.common import Usage
-from codeverse.proc import scrub_secrets
+from codeverse.proc import ManagedProcess, append_jsonl_line, read_jsonl_lenient, scrub_secrets
from codeverse.workspace import Workspace
+#: per-session transcript caps. Rows are byte-capped individually but nothing capped
+#: the file: a child emitting 100k lines wrote 27 MB, ~406 MB at the per-row cap. The
+#: unabridged (bounded) stream still lands in stdout.json.
+LINE_BUDGET_BYTES = 64 * 1024 * 1024
+LINE_BUDGET_ROWS = 200_000
+
+
+class Trajectory:
+ """Append-only writer for one agent session's files."""
+
+ def __init__(self, directory: Path | str):
+ self.dir = Path(directory)
+ self.dir.mkdir(parents=True, exist_ok=True)
+ self._lock = threading.Lock()
+ self._budget = threading.Lock() # guards the counters below, never nested in _lock
+ self._rows = self._bytes = 0
+ self._spent = False
+
+ # ------------------------------------------------------------------ paths
+ @property
+ def prompt_path(self) -> Path:
+ return self.dir / "prompt.md"
+
+ @property
+ def transcript_path(self) -> Path:
+ return self.dir / "transcript.jsonl"
+
+ @property
+ def result_path(self) -> Path:
+ return self.dir / "result.json"
+
+ # ------------------------------------------------------------------ writes
+ def write_prompt(self, prompt: str, system: str = "") -> Path:
+ body = prompt if not system else f"<!-- system -->\n{system}\n\n<!-- prompt -->\n{prompt}"
+ self.prompt_path.write_text(body)
+ return self.prompt_path
+
+ def write_text(self, name: str, text: str) -> Path:
+ p = self.dir / name
+ p.write_text(text)
+ return p
+
+ def write_json(self, name: str, data: BaseModel | dict[str, Any] | list[Any]) -> Path:
+ p = self.dir / name
+ payload = data.model_dump(mode="json") if isinstance(data, BaseModel) else data
+ tmp = p.with_suffix(p.suffix + ".tmp")
+ tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False, default=str))
+ tmp.replace(p)
+ return p
+
+ def append(self, kind: str, **data: Any) -> None:
+ """Append one JSONL turn: ``{"t": epoch, "kind": kind, **data}``, until the
+ session's byte/row budget trips — then one marker row and nothing more."""
+ rec: dict[str, Any] = {"t": round(time.time(), 3), "kind": kind, **data}
+ with self._budget:
+ if self._spent:
+ return
+ self._rows += 1
+ self._bytes += len(json.dumps(rec, ensure_ascii=False, default=str))
+ self._spent = self._rows > LINE_BUDGET_ROWS or self._bytes > LINE_BUDGET_BYTES
+ if self._spent:
+ rec = {"t": rec["t"], "kind": "line_budget_exhausted",
+ "rows": self._rows - 1, "bytes": self._bytes}
+ append_jsonl_line(self.transcript_path, rec, self._lock)
+
+ def write_result(self, result: BaseModel, **extra: Any) -> Path:
+ """Write ``result.json`` = AgentResult fields + any extra diagnostics."""
+ data = result.model_dump(mode="json")
+ data.update(extra)
+ return self.write_json("result.json", data)
+
+ def read_transcript(self) -> list[dict[str, Any]]:
+ return read_jsonl_lenient(self.transcript_path)
+
+
+# ===================================================================== watchdog
+# (merged from codeverse/agents/watchdog.py, 2026-08-28)
+_SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".gemini", ".gemini_home"}
+
+
+@dataclass
+class CompletedProc:
+ """Outcome of :func:`run_with_watchdog`.
+
+ ``stdout``/``stderr`` are bounded to ``codeverse.proc.STREAM_BUDGET_BYTES`` per
+ stream (head + tail kept, truncation marker in between); the ``*_lines`` lists
+ are derived from those bounded texts — streaming consumers that must see every
+ line unconditionally use ``on_line``.
+ """
+
+ rc: int
+ stdout: str
+ stderr: str
+ duration_s: float
+ timed_out: bool = False
+ killed_reason: str = "" # "" | idle | hard_timeout
+ stdout_lines: list[str] = field(default_factory=list, repr=False)
+ stderr_lines: list[str] = field(default_factory=list, repr=False)
+
+
+class ActivityTracker:
+ """Thread-safe 'last time something happened' clock."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._last = time.monotonic()
+
+ def touch(self) -> None:
+ with self._lock:
+ self._last = time.monotonic()
+
+ def idle_for(self) -> float:
+ with self._lock:
+ return time.monotonic() - self._last
+
+
+def _latest_mtime(dirs: Iterable[Path]) -> float:
+ latest = 0.0
+ for d in dirs:
+ if not d.is_dir():
+ continue
+ for root, subdirs, files in os.walk(d):
+ subdirs[:] = [s for s in subdirs if s not in _SKIP_DIRS]
+ for f in files:
+ try:
+ latest = max(latest, os.stat(os.path.join(root, f)).st_mtime)
+ except OSError:
+ continue
+ return latest
+
+
+
+
+def run_with_watchdog(
+ cmd: Sequence[str],
+ *,
+ cwd: Path | str,
+ env: Mapping[str, str] | None,
+ soft_timeout_s: float,
+ idle_grace_s: float = 300.0,
+ hard_timeout_s: float | None = None,
+ on_line: Callable[[str, str], None] | None = None,
+ stdin: str | None = None,
+ activity_dirs: Sequence[Path] | None = None,
+ poll_s: float = 1.0,
+ scan_s: float = 5.0,
+) -> CompletedProc:
+ """Run ``cmd`` streaming output; kill the process group on idle/hard timeout.
+
+ ``on_line(stream, line)`` is called for every line (stream is ``"stdout"``
+ or ``"stderr"``). ``activity_dirs`` (default ``cwd/src``) are polled for
+ mtime changes (every ``scan_s``) that also count as activity.
+
+ Since 2026-08-27 the process lifecycle lives in
+ :class:`codeverse.proc.ManagedProcess`; this function keeps only the clocks.
+ Fixed by that move: a KeyboardInterrupt anywhere in the poll loop kills the
+ group before propagating (it used to orphan the whole node → chrome tree —
+ SIGINT never reaches a ``start_new_session`` child); stdin is written from a
+ helper thread, so a child that never reads a >64 KiB prompt (codex pipes
+ prompts >100 kB via stdin) can no longer wedge the main thread before the
+ clocks start; captured output is bounded per stream (head+tail + marker).
+ """
+ if hard_timeout_s is None:
+ hard_timeout_s = max(soft_timeout_s * 1.5, soft_timeout_s + 600.0)
+ cwd = Path(cwd)
+ dirs = list(activity_dirs) if activity_dirs is not None else [cwd / "src"]
+ tracker = ActivityTracker()
+ t0 = time.monotonic()
+ _reject_control_chars(cmd, cwd)
+
+ def observe(stream: str, line: str) -> None:
+ tracker.touch()
+ if on_line is not None:
+ on_line(stream, line) # ManagedProcess suppresses observer exceptions
+
+ killed = ""
+ with ManagedProcess(cmd, cwd=cwd, env=env, stdin_text=stdin, on_line=observe) as mp:
+ last_mtime = _latest_mtime(dirs)
+ next_scan = t0 + scan_s
+ while mp.poll() is None:
+ now = time.monotonic()
+ elapsed = now - t0
+ if now >= next_scan:
+ m = _latest_mtime(dirs)
+ if m > last_mtime:
+ last_mtime = m
+ tracker.touch()
+ next_scan = now + scan_s
+ if elapsed >= hard_timeout_s:
+ killed = "hard_timeout"
+ elif elapsed >= soft_timeout_s and tracker.idle_for() >= idle_grace_s:
+ killed = "idle"
+ if killed:
+ mp.terminate() # TERM → 5 s grace → KILL: the kill_process_group contract
+ break
+ time.sleep(poll_s)
+ rc = mp.returncode if mp.returncode is not None else -9
+ out_text, err_text = mp.stdout_text, mp.stderr_text
+ return CompletedProc(
+ rc=rc, stdout=out_text, stderr=err_text, duration_s=time.monotonic() - t0,
+ timed_out=bool(killed), killed_reason=killed,
+ stdout_lines=out_text.splitlines(), stderr_lines=err_text.splitlines(),
+ )
+
+
+def _reject_control_chars(cmd: Sequence[str], cwd: object) -> None:
+ """Fail with an argv position and an excerpt instead of a bare "embedded null byte".
+
+ ``subprocess.Popen`` raises ``ValueError: embedded null byte`` naming nothing at all —
+ not the argument, not the offset, not the value. On 2026-08-24 that cost an hour to
+ trace back to five ``\\u0000`` escapes a planner had written into plan.json four stages
+ earlier (see ``schema_utils.strip_control_chars``, which is the actual cure). This is
+ the backstop: if one ever leaks again, the error says where.
+ """
+ for i, arg in enumerate(cmd):
+ text = str(arg)
+ j = text.find("\x00")
+ if j != -1:
+ raise ValueError(
+ f"argv[{i}] contains a NUL at offset {j} of {len(text)} — a model almost "
+ f"certainly emitted \\u0000 in structured output and it was not sanitised "
+ f"(cwd={cwd}). Context: {text[max(0, j - 60):j + 40]!r}"
+ )
+
+
+# ===================================================================== cli_common
+# (merged from codeverse/agents/cli_common.py, 2026-08-28)
log = logging.getLogger(__name__)
#: argv prompts above this many bytes are written to a file instead.
diff --git a/harness/codeverse/agents/codex.py b/harness/codeverse/agents/codex.py
deleted file mode 100644
index f455183d..00000000
--- a/harness/codeverse/agents/codex.py
+++ /dev/null
@@ -1,208 +0,0 @@
-"""``codex:<model>`` — headless OpenAI Codex CLI session on a workspace.
-
-argv: ``codex exec --json -C <ws> --sandbox workspace-write --skip-git-repo-check
-[--model <model>] [-c model_reasoning_effort=<effort>]
-[-c mcp_servers.3dcv.command=... -c mcp_servers.3dcv.args=[...]] <prompt>``
-(prompt on stdin when long). stdout is JSONL:
-
-* ``{"type":"thread.started","thread_id":...}`` / ``turn.started``
-* ``{"type":"item.completed","item":{"type":"agent_message"|"reasoning"|
- "command_execution"|"file_change"|"mcp_tool_call", ...}}``
-* ``{"type":"turn.completed","usage":{"input_tokens","cached_input_tokens","output_tokens",
- "reasoning_output_tokens","cache_write_input_tokens"}}``
-* ``{"type":"turn.failed","error":{"message":...}}`` / ``{"type":"error","message":...}``
-"""
-
-from __future__ import annotations
-
-import json
-
-from codeverse.agents.cli_common import (
- Session,
- begin_session,
- estimate_cost_safe,
- exists_on_path,
- failed,
- finish_session,
- hardened_env,
- invoke,
- mcp_command_for,
- release_session,
- tail,
- watchdog_error,
-)
-from codeverse.agents.materialize import codex_mcp_overrides
-from codeverse.config import get_settings
-from codeverse.contracts.agent import AgentJob, AgentResult
-from codeverse.contracts.common import Usage
-
-STDIN_PROMPT_BYTES = 100_000
-_TOOL_ITEMS = ("command_execution", "file_change", "mcp_tool_call", "web_search", "tool_call")
-
-#: what ``-c model_reasoning_effort=`` accepts; ``""`` means "leave it to ~/.codex/config.toml"
-REASONING_EFFORTS = ("", "minimal", "low", "medium", "high", "xhigh")
-
-
-def split_model_effort(model: str, effort: str | None = None) -> tuple[str, str]:
- """``('gpt-5.6-sol@low', None) -> ('gpt-5.6-sol', 'low')``.
-
- Precedence: an explicit ``effort`` argument, then an ``@<effort>`` suffix on the
- model id, then ``Settings.agents.codex_reasoning_effort`` (default ``high`` — the
- codex CLI's own default is *medium*, and the harness would rather pay for thinking).
- ``""`` at any level means "pass no override and let ~/.codex/config.toml decide".
- """
- name, _, suffix = model.partition("@")
- chosen = effort if effort is not None else (suffix or get_settings().agents.codex_reasoning_effort)
- chosen = chosen.strip().lower()
- if chosen not in REASONING_EFFORTS:
- raise ValueError(f"bad codex reasoning effort {chosen!r}; expected one of {REASONING_EFFORTS}")
- return name.strip(), chosen
-
-
-def effort_overrides(effort: str) -> list[str]:
- """The ``-c`` pair for a reasoning effort (empty when nothing should be forced)."""
- return ["-c", f"model_reasoning_effort={effort}"] if effort else []
-
-
-class CodexEvents:
- """Folded view over the JSONL event stream."""
-
- def __init__(self) -> None:
- self.messages: list[str] = []
- self.errors: list[str] = []
- self.tool_calls = 0
- self.turns_completed = 0
- self.usage_raw: dict[str, int] = {"input_tokens": 0, "cached_input_tokens": 0, "output_tokens": 0,
- "reasoning_output_tokens": 0, "cache_write_input_tokens": 0}
- self.thread_id = ""
- self.n_events = 0
-
- def feed(self, line: str) -> None:
- line = line.strip()
- if not line.startswith("{"):
- return
- try:
- ev = json.loads(line)
- except json.JSONDecodeError:
- return
- self.n_events += 1
- t = ev.get("type", "")
- if t == "thread.started":
- self.thread_id = str(ev.get("thread_id", ""))
- elif t == "item.completed":
- item = ev.get("item") or {}
- it = item.get("type", "")
- if it == "agent_message":
- self.messages.append(str(item.get("text", "")))
- elif it in _TOOL_ITEMS:
- self.tool_calls += 1
- elif t == "turn.completed":
- self.turns_completed += 1
- for k in self.usage_raw:
- self.usage_raw[k] += int((ev.get("usage") or {}).get(k) or 0)
- elif t == "turn.failed":
- self.errors.append(str((ev.get("error") or {}).get("message") or ev))
- elif t == "error":
- self.errors.append(str(ev.get("message") or ev))
-
- def usage(self, model: str) -> Usage:
- # `output_tokens` from the Responses API already CONTAINS
- # `reasoning_output_tokens` (measured: output − reasoning tracks the answer
- # length across every recorded cell). `estimate_cost` bills output +
- # thoughts, so the reasoning share is subtracted here instead of being
- # charged twice — it stays visible in `thoughts_tokens`.
- reasoning = self.usage_raw["reasoning_output_tokens"]
- u = Usage(
- backend="codex", model=model,
- input_tokens=self.usage_raw["input_tokens"],
- output_tokens=max(0, self.usage_raw["output_tokens"] - reasoning),
- cached_tokens=self.usage_raw["cached_input_tokens"], tool_calls=self.tool_calls,
- thoughts_tokens=reasoning,
- )
- u.cost_usd = estimate_cost_safe("openai", model, u)
- return u
-
-
-def parse_codex_jsonl(stdout: str) -> CodexEvents:
- ev = CodexEvents()
- for line in stdout.splitlines():
- ev.feed(line)
- return ev
-
-
-class CodexAgent:
- kind = "codex"
-
- def __init__(self, model: str, binary: str | None = None, reasoning_effort: str | None = None):
- self.model, self.reasoning_effort = split_model_effort(model, reasoning_effort)
- self.binary = binary or get_settings().binaries.codex_cli
-
- @property
- def id(self) -> str:
- return f"{self.kind}:{self.model}"
-
- def available(self) -> tuple[bool, str]:
- if not exists_on_path(self.binary):
- return False, f"codex CLI not found: {self.binary!r}"
- return True, "ok"
-
- def build_argv(self, s: Session, prompt: str | None) -> list[str]:
- """``prompt=None`` means 'read it from stdin' (``-`` positional)."""
- job = s.job
- argv = [self.binary, "exec", "--json", "-C", str(s.ws.root), "--sandbox", "workspace-write",
- "--skip-git-repo-check", "--ephemeral", "--color", "never"]
- if self.model:
- argv += ["--model", self.model]
- argv += effort_overrides(self.reasoning_effort)
- if job.spatial_tools:
- argv += codex_mcp_overrides(mcp_command_for(s.ws, job))
- argv.append(prompt if prompt is not None else "-")
- return argv
-
- def build_env(self, s: Session) -> dict[str, str]:
- return hardened_env(s.ws, s.job, keep={"OPENAI_API_KEY", "CODEX_API_KEY"})
-
- def run(self, job: AgentJob) -> AgentResult:
- ok, why = self.available()
- s = begin_session(job, self.kind)
- try:
- if not ok:
- return failed(s, "error", why)
- prompt = _compose_prompt(job)
- via_stdin = len(prompt.encode("utf-8")) > STDIN_PROMPT_BYTES
- argv = self.build_argv(s, None if via_stdin else prompt)
- events = CodexEvents()
- proc = invoke(s, argv, self.build_env(s), prompt=prompt, stdout_name="stdout.jsonl",
- on_stdout=events.feed, stdin=prompt if via_stdin else None)
- usage = events.usage(self.model)
- usage.latency_ms = int(proc.duration_s * 1000)
- text = "\n\n".join(m for m in events.messages if m.strip())
- errors = list(events.errors)
- if proc.timed_out:
- ok, reason = False, "timeout"
- errors.append(watchdog_error(proc))
- elif proc.rc != 0 or events.n_events == 0:
- ok, reason = False, "error"
- errors.append(f"rc={proc.rc}; events={events.n_events}; stderr tail: {tail(proc.stderr, 1500)}")
- elif events.errors and events.turns_completed == 0:
- ok, reason = False, "error"
- else:
- ok, reason = True, "completed"
- return finish_session(
- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls, errors=errors,
- rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
- turns_completed=events.turns_completed, usage_raw=events.usage_raw,
- )
- finally:
- release_session(s)
-
-
-def _compose_prompt(job: AgentJob) -> str:
- """codex exec has no system-prompt flag: prepend ``system_append``."""
- if not job.system_append:
- return job.prompt
- return f"<harness_instructions>\n{job.system_append}\n</harness_instructions>\n\n{job.prompt}"
-
-
-__all__ = ["REASONING_EFFORTS", "CodexAgent", "CodexEvents", "effort_overrides", "parse_codex_jsonl",
- "split_model_effort"]
diff --git a/harness/codeverse/agents/gemini_cli.py b/harness/codeverse/agents/gemini_cli.py
deleted file mode 100644
index 36103d25..00000000
--- a/harness/codeverse/agents/gemini_cli.py
+++ /dev/null
@@ -1,294 +0,0 @@
-"""``gemini-cli:<model>`` — headless Gemini CLI session on a workspace.
-
-argv: ``gemini -p <prompt> -m <model> --approval-mode yolo --skip-trust --output-format json``
-
-* env hardening: host secrets stripped, one pool key as ``GEMINI_API_KEY``,
- ``GEMINI_CLI_SYSTEM_SETTINGS_PATH`` (per session, in the trajectory dir) forcing
- api-key auth + dynamic model configuration (otherwise an unknown model is *silently*
- substituted), the 3dcv MCP server and ``mcp.allowed``, Node heap cap, no self-relaunch.
-* JSON envelope ``{session_id, response, stats:{models:{<m>:{tokens:{prompt,
- input, candidates, cached, thoughts}}}, tools:{totalCalls}}}`` → Usage (+ cost
- via pricing). ``tokens.prompt`` is the TOTAL prompt size and ``tokens.input``
- the UNCACHED part (``prompt - cached``); ``Usage.input_tokens`` follows the
- pricing convention (total prompt, cached re-priced). Each served model is
- priced at its own rate. Requested model absent from ``stats.models`` →
- ``model_substituted``.
-* one retry (rotated key when the pool has one, else the same key) on transient
- failures (429 / 503 / empty response); a throttled/empty pool never raises.
-"""
-
-from __future__ import annotations
-
-import json
-import logging
-import time
-from pathlib import Path
-from typing import Any
-
-from codeverse.agents.cli_common import (
- Session,
- begin_session,
- deliver_prompt,
- estimate_cost_safe,
- exists_on_path,
- failed,
- finish_session,
- hardened_env,
- invoke,
- is_quota_failure,
- is_transient_failure,
- mcp_command_for,
- release_session,
- tail,
- watchdog_error,
-)
-from codeverse.agents.materialize import MCP_SERVER_NAME, MCP_TOOL_TIMEOUT_MS
-from codeverse.agents.watchdog import CompletedProc
-from codeverse.config import get_settings
-from codeverse.contracts.agent import AgentJob, AgentResult
-from codeverse.contracts.common import Usage
-from codeverse.models.retry import KeyPool, KeyPoolExhausted
-
-log = logging.getLogger(__name__)
-
-SYSTEM_SETTINGS = {
- # folderTrust must be OFF: with it on, gemini-cli silently disables the workspace
- # .gemini/settings.json mcpServers (even with --skip-trust) → no 3dcv tools.
- "security": {"auth": {"selectedType": "gemini-api-key"}, "folderTrust": {"enabled": False}},
- "experimental": {"dynamicModelConfiguration": True},
- "general": {"topicUpdateNarration": False},
-}
-#: how long a retry waits for a *different* healthy key before reusing the same one
-RETRY_KEY_WAIT_S = 10.0
-
-
-def retry_window_left(timeout_s: float, elapsed_s: float) -> float | None:
- """Seconds of the session window a retry may still use, or ``None`` when too little
- is left to be worth an invoke. A retry never restarts the window: chair_bl
- (loop_w1, 2026-08-28) got a FULL fresh window on attempt 2 and ran 32 more minutes
- against a run wall that had expired before the retry began."""
- min_window = min(120.0, float(timeout_s) * 0.25)
- left = float(timeout_s) - float(elapsed_s)
- return None if left < min_window else left
-
-
-def _key_pool(keys: list[str]) -> KeyPool:
- """THE process-wide pool for these keys — ``models.gemini.shared_pool``, i.e. the
- same limiter the API path uses, with quotas from ``Settings.rate``. This module
- used to build its own ``KeyPool(keys)`` with library defaults (900 RPM, no TPM
- bucket), so the CLI agent and the API path scheduled the same 22 keys under two
- different quotas (found by review 2026-08-28)."""
- from codeverse.models.gemini import shared_pool
-
- return shared_pool(keys)
-
-
-def write_system_settings(path: Path | None = None, *, mcp_command: list[str] | None = None) -> Path:
- """Write the gemini-cli system-settings json (api-key auth + dynamic models) and return its path.
-
- gemini-cli applies this file LAST and ``mcp.allowed`` REPLACES rather than merges, so the
- 3dcv server and the allow-list belong here, not in the agent-writable
- ``ws/.gemini/settings.json``: a server the agent planted there is Blocked."""
- path = path or (get_settings().cache_dir / "gemini_cli_settings.json")
- path.parent.mkdir(parents=True, exist_ok=True)
- data: dict[str, Any] = {**SYSTEM_SETTINGS, "mcp": {"allowed": [MCP_SERVER_NAME]}}
- if mcp_command:
- data["mcpServers"] = {MCP_SERVER_NAME: {"command": mcp_command[0], "args": list(mcp_command[1:]),
- "timeout": MCP_TOOL_TIMEOUT_MS}}
- want = json.dumps(data, indent=2)
- if not path.is_file() or path.read_text() != want:
- path.write_text(want)
- return path
-
-
-def parse_gemini_json(stdout: str) -> dict[str, Any] | None:
- """The CLI prints one JSON object (possibly after log noise); find it."""
- s = stdout.strip()
- if not s:
- return None
- try:
- return json.loads(s)
- except json.JSONDecodeError:
- pass
- start = s.find("{")
- while start != -1:
- try:
- obj = json.loads(s[start:])
- return obj if isinstance(obj, dict) else None
- except json.JSONDecodeError:
- start = s.find("{", start + 1)
- return None
-
-
-def _model_usage(tok: dict[str, Any], name: str) -> Usage:
- """One served model's counters in pricing semantics (``input_tokens`` = total prompt)."""
- cached = int(tok.get("cached") or 0)
- prompt = tok.get("prompt")
- # gemini-cli: tokens.prompt = promptTokenCount (total), tokens.input = prompt - cached
- total = int(prompt) if prompt is not None else int(tok.get("input") or 0) + cached
- return Usage(backend="gemini-cli", model=name, input_tokens=total, cached_tokens=cached,
- output_tokens=int(tok.get("candidates") or 0), thoughts_tokens=int(tok.get("thoughts") or 0))
-
-
-def usage_from_stats(stats: dict[str, Any], model: str) -> Usage:
- """Sum tokens across every served model (normally just ``model``); cost is the
- sum of each served model priced at its own rate (unknown → requested model's)."""
- u = Usage(backend="gemini-cli", model=model)
- cost = 0.0
- for name, m in (stats.get("models") or {}).items():
- part = _model_usage((m or {}).get("tokens") or {}, str(name))
- c = estimate_cost_safe("gemini", str(name), part)
- if c == 0.0 and name != model and (part.input_tokens or part.output_tokens):
- c = estimate_cost_safe("gemini", model, part) # utility model missing from the price table
- cost += c
- u.input_tokens += part.input_tokens
- u.output_tokens += part.output_tokens
- u.cached_tokens += part.cached_tokens
- u.thoughts_tokens += part.thoughts_tokens
- u.tool_calls = int(((stats.get("tools") or {}).get("totalCalls")) or 0)
- u.cost_usd = cost
- return u
-
-
-def _retry_key(pool: KeyPool, used: set[str]) -> str | None:
- """Key for a retry: a different healthy key if one frees up within
- ``RETRY_KEY_WAIT_S``, else the same key again (single-key pools, 5xx), else
- ``None`` when every key is throttled (429 cooldown) — the caller then stops."""
- for exclude in (used, None):
- try:
- return pool.acquire(exclude=exclude or None, timeout_s=RETRY_KEY_WAIT_S)
- except KeyPoolExhausted:
- continue
- return None
-
-
-class GeminiCliAgent:
- kind = "gemini-cli"
-
- def __init__(self, model: str, binary: str | None = None):
- self.model = model
- self.binary = binary or get_settings().binaries.gemini_cli
-
- @property
- def id(self) -> str:
- return f"{self.kind}:{self.model}"
-
- def available(self) -> tuple[bool, str]:
- if not exists_on_path(self.binary):
- return False, f"gemini CLI not found: {self.binary!r}"
- if not get_settings().gemini_api_keys:
- return False, "no Gemini API keys configured"
- return True, "ok"
-
- # ------------------------------------------------------------------ build
- def build_argv(self, prompt: str) -> list[str]:
- return [self.binary, "-p", prompt, "-m", self.model, "--approval-mode", "yolo",
- "--skip-trust", "--output-format", "json"]
-
- def build_env(self, s: Session, api_key: str) -> dict[str, str]:
- env = hardened_env(s.ws, s.job)
- env["GEMINI_API_KEY"] = api_key
- # per SESSION, in the harness-owned trajectory dir: the command is per-run
- # (``--workspace <ws>``) and it is rewritten immediately before every invoke
- env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(write_system_settings(
- s.traj.dir / "gemini_settings.json",
- mcp_command=mcp_command_for(s.ws, s.job) if s.job.spatial_tools else None))
- env["GEMINI_CLI_NO_RELAUNCH"] = "1"
- node_opts = env.get("NODE_OPTIONS", "")
- if "--max-old-space-size" not in node_opts:
- env["NODE_OPTIONS"] = f"{node_opts} --max-old-space-size=6144".strip()
- return env
-
- # ------------------------------------------------------------------ run
- def run(self, job: AgentJob) -> AgentResult:
- ok, why = self.available()
- s = begin_session(job, self.kind)
- try:
- if not ok:
- return failed(s, "error", why)
- prompt = deliver_prompt(s, _compose_prompt(job))
- pool = _key_pool(get_settings().gemini_api_keys)
- try:
- key = pool.acquire()
- except KeyPoolExhausted as e: # every key throttled for the whole wait budget
- return failed(s, "budget", f"Gemini key pool exhausted before the first attempt: {e}")
- attempts = 0
- used: set[str] = set()
- t0 = time.monotonic()
- next_soft: float | None = None # attempt 1 uses the job's own window
- usage_total = Usage(backend=self.kind, model=self.model)
- while True:
- attempts += 1
- used.add(key)
- proc = self._invoke(s, prompt, key, attempt=attempts, soft_timeout_s=next_soft)
- outcome = self._interpret(s, proc)
- usage_total = usage_total + outcome["usage"]
- pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))
- pool.release() # one acquire per attempt: keep the pool's in-flight gauge honest
- if outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:
- break
- next_soft = retry_window_left(job.timeout_s, time.monotonic() - t0)
- if next_soft is None:
- s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); "
- "no session window left — not retrying past the wall")
- break
- next_key = _retry_key(pool, used)
- if next_key is None:
- s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); no usable key for a retry")
- break
- key = next_key
- how = "rotated key" if key not in used else "same key (no alternative available)"
- s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with {how}")
- s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])
- usage_total.cost_usd = round(usage_total.cost_usd, 6)
- return finish_session(
- s, ok=outcome["ok"], exit_reason=outcome["exit_reason"], text=outcome["text"],
- usage=usage_total, tool_calls=usage_total.tool_calls, errors=outcome["errors"],
- attempts=attempts, rc=proc.rc, killed_reason=proc.killed_reason, session_id=outcome.get("session_id", ""),
- )
- finally:
- release_session(s)
-
- def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int,
- soft_timeout_s: float | None = None) -> CompletedProc:
- return invoke(s, self.build_argv(prompt), self.build_env(s, key), prompt=prompt, attempt=attempt,
- soft_timeout_s=soft_timeout_s, model=self.model, key_tail=key[-4:])
-
- def _interpret(self, s: Session, proc: CompletedProc) -> dict[str, Any]:
- parsed = parse_gemini_json(proc.stdout)
- stats = (parsed or {}).get("stats") or {}
- usage = usage_from_stats(stats, self.model) if stats else Usage(backend=self.kind, model=self.model)
- usage.latency_ms = int(proc.duration_s * 1000)
- text = str((parsed or {}).get("response") or "")
- errors: list[str] = []
- served = list((stats.get("models") or {}).keys())
- out: dict[str, Any] = {"usage": usage, "text": text, "ok": False, "exit_reason": "error",
- "transient": False, "quota": False, "errors": errors,
- "session_id": (parsed or {}).get("session_id", "")}
- if proc.timed_out:
- out["exit_reason"] = "timeout"
- errors.append(watchdog_error(proc))
- return out
- if served and self.model not in served:
- out["exit_reason"] = "model_substituted"
- errors.append(f"requested {self.model!r} but CLI served {served}")
- return out
- if parsed is None or proc.rc != 0 or not text.strip():
- out["transient"] = is_transient_failure(proc.stderr, proc.stdout) or (parsed is not None and not text.strip())
- out["quota"] = is_quota_failure(proc.stderr, proc.stdout)
- errors.append(f"rc={proc.rc}; response={'<empty>' if not text.strip() else 'ok'}; stderr tail: {tail(proc.stderr, 1500)}")
- out["exit_reason"] = "budget" if out["quota"] else "error"
- return out
- out["ok"] = True
- out["exit_reason"] = "completed"
- return out
-
-
-def _compose_prompt(job: AgentJob) -> str:
- """gemini-cli has no system-prompt flag: prepend ``system_append`` to the prompt."""
- if not job.system_append:
- return job.prompt
- return f"<harness_instructions>\n{job.system_append}\n</harness_instructions>\n\n{job.prompt}"
-
-
-__all__ = ["GeminiCliAgent", "parse_gemini_json", "usage_from_stats", "write_system_settings"]
diff --git a/harness/codeverse/agents/registry.py b/harness/codeverse/agents/registry.py
index 29c7ae6d..25317592 100644
--- a/harness/codeverse/agents/registry.py
+++ b/harness/codeverse/agents/registry.py
@@ -1,11 +1,46 @@
-"""Agent id parsing + factory."""
+"""The CodingAgent protocol every agentic backend implements."""
from __future__ import annotations
from functools import lru_cache
+from typing import Protocol, runtime_checkable
-from codeverse.agents.base import CodingAgent
+from codeverse.contracts.agent import AgentJob, AgentResult
+
+@runtime_checkable
+class CodingAgent(Protocol):
+ """Runs ONE headless agent session in ``job.workspace``.
+
+ Contract for implementations:
+ * the agent may only write under ``job.write_roots`` (harness materialises
+ AGENTS.md/GEMINI.md/CLAUDE.md + MCP config before the call; see
+ ``agents/materialize.py``),
+ * never raise for agent failures — return ``AgentResult(ok=False, exit_reason=...)``,
+ * fill ``usage`` (tokens + cost) as precisely as the CLI allows,
+ * write the full transcript to ``job.workspace/trajectories/...`` and set
+ ``transcript_path``,
+ * compute ``files_changed`` via ``Workspace.changed_files`` (git), not by
+ trusting the agent's claims,
+ * respect ``job.timeout_s`` with an activity-aware watchdog (kill the whole
+ process group on timeout).
+ """
+
+ kind: str # gemini-cli | claude-code | codex | agy
+ model: str
+
+ @property
+ def id(self) -> str: ...
+
+ def run(self, job: AgentJob) -> AgentResult: ...
+
+ def available(self) -> tuple[bool, str]:
+ """(is_usable, reason) — binary found / auth present / model known."""
+ ...
+
+
+# ===================================================================== registry
+# (merged from codeverse/agents/registry.py, 2026-08-28)
KINDS = ("gemini-cli", "claude-code", "codex", "agy")
@@ -23,19 +58,19 @@ def parse_agent_id(agent_id: str) -> tuple[str, str]:
def get_coding_agent(agent_id: str) -> CodingAgent:
kind, model = parse_agent_id(agent_id)
if kind == "gemini-cli":
- from codeverse.agents.gemini_cli import GeminiCliAgent
+ from codeverse.agents.backends import GeminiCliAgent
return GeminiCliAgent(model)
if kind == "claude-code":
- from codeverse.agents.claude_code import ClaudeCodeAgent
+ from codeverse.agents.backends import ClaudeCodeAgent
return ClaudeCodeAgent(model)
if kind == "codex":
- from codeverse.agents.codex import CodexAgent
+ from codeverse.agents.backends import CodexAgent
return CodexAgent(model)
if kind == "agy":
- from codeverse.agents.antigravity import AntigravityAgent
+ from codeverse.agents.backends import AntigravityAgent
return AntigravityAgent(model)
raise ValueError(f"unknown agent kind {kind!r}; known: {KINDS}")
diff --git a/harness/codeverse/agents/transcript.py b/harness/codeverse/agents/transcript.py
deleted file mode 100644
index ca685216..00000000
--- a/harness/codeverse/agents/transcript.py
+++ /dev/null
@@ -1,92 +0,0 @@
-"""Trajectory folder helper: prompt.md, transcript.jsonl, stdout/stderr, result.json.
-
-Every CodingAgent backend writes its session here
-(``ws.trajectory_dir(label, round)``) so the flywheel and ``3dcv status`` can
-read one uniform layout regardless of backend.
-"""
-
-from __future__ import annotations
-
-import json
-import threading
-import time
-from pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel
-
-from codeverse.proc import append_jsonl_line, read_jsonl_lenient
-
-#: per-session transcript caps. Rows are byte-capped individually but nothing capped
-#: the file: a child emitting 100k lines wrote 27 MB, ~406 MB at the per-row cap. The
-#: unabridged (bounded) stream still lands in stdout.json.
-LINE_BUDGET_BYTES = 64 * 1024 * 1024
-LINE_BUDGET_ROWS = 200_000
-
-
-class Trajectory:
- """Append-only writer for one agent session's files."""
-
- def __init__(self, directory: Path | str):
- self.dir = Path(directory)
- self.dir.mkdir(parents=True, exist_ok=True)
- self._lock = threading.Lock()
- self._budget = threading.Lock() # guards the counters below, never nested in _lock
- self._rows = self._bytes = 0
- self._spent = False
-
- # ------------------------------------------------------------------ paths
- @property
- def prompt_path(self) -> Path:
- return self.dir / "prompt.md"
-
- @property
- def transcript_path(self) -> Path:
- return self.dir / "transcript.jsonl"
-
- @property
- def result_path(self) -> Path:
- return self.dir / "result.json"
-
- # ------------------------------------------------------------------ writes
- def write_prompt(self, prompt: str, system: str = "") -> Path:
- body = prompt if not system else f"<!-- system -->\n{system}\n\n<!-- prompt -->\n{prompt}"
- self.prompt_path.write_text(body)
- return self.prompt_path
-
- def write_text(self, name: str, text: str) -> Path:
- p = self.dir / name
- p.write_text(text)
- return p
-
- def write_json(self, name: str, data: BaseModel | dict[str, Any] | list[Any]) -> Path:
- p = self.dir / name
- payload = data.model_dump(mode="json") if isinstance(data, BaseModel) else data
- tmp = p.with_suffix(p.suffix + ".tmp")
- tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False, default=str))
- tmp.replace(p)
- return p
-
- def append(self, kind: str, **data: Any) -> None:
- """Append one JSONL turn: ``{"t": epoch, "kind": kind, **data}``, until the
- session's byte/row budget trips — then one marker row and nothing more."""
- rec: dict[str, Any] = {"t": round(time.time(), 3), "kind": kind, **data}
- with self._budget:
- if self._spent:
- return
- self._rows += 1
- self._bytes += len(json.dumps(rec, ensure_ascii=False, default=str))
- self._spent = self._rows > LINE_BUDGET_ROWS or self._bytes > LINE_BUDGET_BYTES
- if self._spent:
- rec = {"t": rec["t"], "kind": "line_budget_exhausted",
- "rows": self._rows - 1, "bytes": self._bytes}
- append_jsonl_line(self.transcript_path, rec, self._lock)
-
- def write_result(self, result: BaseModel, **extra: Any) -> Path:
- """Write ``result.json`` = AgentResult fields + any extra diagnostics."""
- data = result.model_dump(mode="json")
- data.update(extra)
- return self.write_json("result.json", data)
-
- def read_transcript(self) -> list[dict[str, Any]]:
- return read_jsonl_lenient(self.transcript_path)
diff --git a/harness/codeverse/agents/watchdog.py b/harness/codeverse/agents/watchdog.py
deleted file mode 100644
index 131e0253..00000000
--- a/harness/codeverse/agents/watchdog.py
+++ /dev/null
@@ -1,174 +0,0 @@
-"""Activity-aware subprocess runner for headless agent CLIs.
-
-Three clocks govern a run:
-
-* ``soft_timeout_s`` — the nominal budget. After it elapses the process may
- keep going *only while it is visibly working*.
-* ``idle_grace_s`` — past the soft timeout, if nothing happened (no stdout /
- stderr line, no file mtime change under ``activity_dirs``) for this long,
- the process group is killed (``killed_reason="idle"``).
-* ``hard_timeout_s`` — absolute ceiling; kill regardless (``"hard_timeout"``).
-
-The child is started in its own session so ``os.killpg`` takes the whole
-tree (node → chrome, blender, mcp servers ...). The process lifecycle itself
-(pipes, pump threads, stdin writer, kill-on-exception, drain, reap) lives in
-:class:`codeverse.proc.ManagedProcess`; this module owns only the clocks.
-"""
-
-from __future__ import annotations
-
-import os
-import threading
-import time
-from collections.abc import Callable, Iterable, Mapping, Sequence
-from dataclasses import dataclass, field
-from pathlib import Path
-
-from codeverse.proc import ManagedProcess
-
-_SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".gemini", ".gemini_home"}
-
-
-@dataclass
-class CompletedProc:
- """Outcome of :func:`run_with_watchdog`.
-
- ``stdout``/``stderr`` are bounded to ``codeverse.proc.STREAM_BUDGET_BYTES`` per
- stream (head + tail kept, truncation marker in between); the ``*_lines`` lists
- are derived from those bounded texts — streaming consumers that must see every
- line unconditionally use ``on_line``.
- """
-
- rc: int
- stdout: str
- stderr: str
- duration_s: float
- timed_out: bool = False
- killed_reason: str = "" # "" | idle | hard_timeout
- stdout_lines: list[str] = field(default_factory=list, repr=False)
- stderr_lines: list[str] = field(default_factory=list, repr=False)
-
-
-class ActivityTracker:
- """Thread-safe 'last time something happened' clock."""
-
- def __init__(self) -> None:
- self._lock = threading.Lock()
- self._last = time.monotonic()
-
- def touch(self) -> None:
- with self._lock:
- self._last = time.monotonic()
-
- def idle_for(self) -> float:
- with self._lock:
- return time.monotonic() - self._last
-
-
-def _latest_mtime(dirs: Iterable[Path]) -> float:
- latest = 0.0
- for d in dirs:
- if not d.is_dir():
- continue
- for root, subdirs, files in os.walk(d):
- subdirs[:] = [s for s in subdirs if s not in _SKIP_DIRS]
- for f in files:
- try:
- latest = max(latest, os.stat(os.path.join(root, f)).st_mtime)
- except OSError:
- continue
- return latest
-
-
-
-
-def run_with_watchdog(
- cmd: Sequence[str],
- *,
- cwd: Path | str,
- env: Mapping[str, str] | None,
- soft_timeout_s: float,
- idle_grace_s: float = 300.0,
- hard_timeout_s: float | None = None,
- on_line: Callable[[str, str], None] | None = None,
- stdin: str | None = None,
- activity_dirs: Sequence[Path] | None = None,
- poll_s: float = 1.0,
- scan_s: float = 5.0,
-) -> CompletedProc:
- """Run ``cmd`` streaming output; kill the process group on idle/hard timeout.
-
- ``on_line(stream, line)`` is called for every line (stream is ``"stdout"``
- or ``"stderr"``). ``activity_dirs`` (default ``cwd/src``) are polled for
- mtime changes (every ``scan_s``) that also count as activity.
-
- Since 2026-08-27 the process lifecycle lives in
- :class:`codeverse.proc.ManagedProcess`; this function keeps only the clocks.
- Fixed by that move: a KeyboardInterrupt anywhere in the poll loop kills the
- group before propagating (it used to orphan the whole node → chrome tree —
- SIGINT never reaches a ``start_new_session`` child); stdin is written from a
- helper thread, so a child that never reads a >64 KiB prompt (codex pipes
- prompts >100 kB via stdin) can no longer wedge the main thread before the
- clocks start; captured output is bounded per stream (head+tail + marker).
- """
- if hard_timeout_s is None:
- hard_timeout_s = max(soft_timeout_s * 1.5, soft_timeout_s + 600.0)
- cwd = Path(cwd)
- dirs = list(activity_dirs) if activity_dirs is not None else [cwd / "src"]
- tracker = ActivityTracker()
- t0 = time.monotonic()
- _reject_control_chars(cmd, cwd)
-
- def observe(stream: str, line: str) -> None:
- tracker.touch()
- if on_line is not None:
- on_line(stream, line) # ManagedProcess suppresses observer exceptions
-
- killed = ""
- with ManagedProcess(cmd, cwd=cwd, env=env, stdin_text=stdin, on_line=observe) as mp:
- last_mtime = _latest_mtime(dirs)
- next_scan = t0 + scan_s
- while mp.poll() is None:
- now = time.monotonic()
- elapsed = now - t0
- if now >= next_scan:
- m = _latest_mtime(dirs)
- if m > last_mtime:
- last_mtime = m
- tracker.touch()
- next_scan = now + scan_s
- if elapsed >= hard_timeout_s:
- killed = "hard_timeout"
- elif elapsed >= soft_timeout_s and tracker.idle_for() >= idle_grace_s:
- killed = "idle"
- if killed:
- mp.terminate() # TERM → 5 s grace → KILL: the kill_process_group contract
- break
- time.sleep(poll_s)
- rc = mp.returncode if mp.returncode is not None else -9
- out_text, err_text = mp.stdout_text, mp.stderr_text
- return CompletedProc(
- rc=rc, stdout=out_text, stderr=err_text, duration_s=time.monotonic() - t0,
- timed_out=bool(killed), killed_reason=killed,
- stdout_lines=out_text.splitlines(), stderr_lines=err_text.splitlines(),
- )
-
-
-def _reject_control_chars(cmd: Sequence[str], cwd: object) -> None:
- """Fail with an argv position and an excerpt instead of a bare "embedded null byte".
-
- ``subprocess.Popen`` raises ``ValueError: embedded null byte`` naming nothing at all —
- not the argument, not the offset, not the value. On 2026-08-24 that cost an hour to
- trace back to five ``\\u0000`` escapes a planner had written into plan.json four stages
- earlier (see ``schema_utils.strip_control_chars``, which is the actual cure). This is
- the backstop: if one ever leaks again, the error says where.
- """
- for i, arg in enumerate(cmd):
- text = str(arg)
- j = text.find("\x00")
- if j != -1:
- raise ValueError(
- f"argv[{i}] contains a NUL at offset {j} of {len(text)} — a model almost "
- f"certainly emitted \\u0000 in structured output and it was not sanitised "
- f"(cwd={cwd}). Context: {text[max(0, j - 60):j + 40]!r}"
- )
diff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
index e90ed14b..4bcd3215 100644
--- a/harness/codeverse/cli/doctor.py
+++ b/harness/codeverse/cli/doctor.py
@@ -269,7 +269,7 @@ def check_skills() -> list[Row]:
A CLI upgrade that moves its skills root ships an empty index and the run still
passes — the failure is invisible except as a read rate of zero a battery later. So
the wiring gets a check you can run before spending money."""
- from codeverse.agents.claude_code import ALLOWED_TOOLS
+ from codeverse.agents.backends import ALLOWED_TOOLS
from codeverse.skills import bundle_dirs, skills_dir, validate_bundle
from codeverse.skills.config import skills_enabled
from codeverse.skills.materialize import SKILL_ROOTS
diff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.py
index 0f9b1aa6..83962cc6 100644
--- a/harness/codeverse/cost/instrument.py
+++ b/harness/codeverse/cost/instrument.py
@@ -8,7 +8,7 @@ Two thin proxies do the whole job:
cache hit, outcome). Because ``models.registry.get_chat_model`` returns the
proxy, this covers the planner, the judges, the captioner and single-shot
generation.
-* :class:`MeteredAgent` wraps a :class:`~codeverse.agents.base.CodingAgent`.
+* :class:`MeteredAgent` wraps a :class:`~codeverse.agents.registry.CodingAgent`.
It sets the ambient attribution (round / stage / label) for the session so
the model rows above land in the right bucket, applies the profile's turn cap
and, for backends whose calls we cannot see (every subscription CLI that does
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 06dd9c8a..6bf88f65 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -99,10 +99,11 @@ codeverse/
shared 503 storm gate — ships OFF, docs/COST.md §21 — and the prompt-token
estimate); pricing.py (version-suffix-only fallback), health.py (preflight
probe: no retries, no backoff), schema_utils.py (strict schema), registry.py
- agents/ CodingAgent (base.py); gemini_cli.py claude_code.py codex.py antigravity.py
- (api_agent.py + api_tools.py + api_skills.py deleted 2026-08-28 —
- the vendors already ship the loop), materialize.py, cli_common.py (sessions, retry
- trajectory naming, files_changed attribution), watchdog.py, transcript.py, registry.py
+ agents/ registry.py (the CodingAgent protocol + dispatch — every backend is a
+ vendor CLI; the in-process api-agent died 2026-08-28), backends.py
+ (gemini-cli / claude-code / codex / antigravity), cli_common.py (sessions,
+ the watchdog clocks, the transcript, retry trajectory naming,
+ files_changed attribution), materialize.py
languages/ LanguageRuntime (base.py); blender/ (multi-file: layout.py, model.py + parts/*.py) cadquery/
threejs/ (+ templates.py) urdf/ scene_threejs/ glsl_shader/ (wrap.py header+line-map)
opengl_python/ (wrappers/run_gl.py) — each runtime.py, lint.py, skeleton.py, wrappers/;
diff --git a/harness/docs/REVIEW_2026-08-26.md b/harness/docs/REVIEW_2026-08-26.md
index 06c9edb5..e98c84dd 100644
--- a/harness/docs/REVIEW_2026-08-26.md
+++ b/harness/docs/REVIEW_2026-08-26.md
@@ -186,7 +186,7 @@ with `-p no:cacheprovider -m "not live"`. After every deletion item also run `ru
idle_grace_s=None, **invoke_extra) -> CompletedProc` — masks the prompt in the 'invoke' line, forwards
`invoke_extra` (gemini's `model`/`key_tail`, codex's stdin flag), reads `cli_common.IDLE_GRACE_S` at call time,
writes `stdout{suffix}.<ext>` / `stderr{suffix}.log` with suffix `''` or `.{attempt}`.
-- Must keep: `tests/agents/test_gemini_cli.py:143` monkeypatches `codeverse.agents.gemini_cli.IDLE_GRACE_S` → retarget
+- Must keep: `tests/agents/test_gemini_cli.py:143` monkeypatches `codeverse.agents.backends.IDLE_GRACE_S` → retarget
to `cli_common.IDLE_GRACE_S`; `test_gemini_cli.py:92/107` assert `key_tail` on invoke lines; `test_codex.py:99/127` assert `stdout.jsonl`.
- Why: the four blocks are the same expression set verbatim (argv mask, watchdog kwargs, file writes, error line);
`cli_common.py` is documented as "shared plumbing for subprocess backends" and stays under 400 (297+~30).
diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.py
index cacec06a..3aae48e3 100644
--- a/harness/tests/agents/test_antigravity.py
+++ b/harness/tests/agents/test_antigravity.py
@@ -7,7 +7,7 @@ import shutil
import pytest
-from codeverse.agents.antigravity import (
+from codeverse.agents.backends import (
AntigravityAgent,
available_models,
parse_agy_json,
diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.py
index 418a8c99..b8b0a26b 100644
--- a/harness/tests/agents/test_claude_code.py
+++ b/harness/tests/agents/test_claude_code.py
@@ -8,7 +8,7 @@ from pathlib import Path
import pytest
-from codeverse.agents.claude_code import (
+from codeverse.agents.backends import (
ClaudeCodeAgent,
parse_claude_json,
primary_served_model,
diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.py
index 4fbc250f..5e80cefa 100644
--- a/harness/tests/agents/test_cli_common.py
+++ b/harness/tests/agents/test_cli_common.py
@@ -7,6 +7,7 @@ import os
import threading
from codeverse.agents.cli_common import (
+ Trajectory,
attribute_changes,
begin_session,
deliver_prompt,
@@ -16,7 +17,6 @@ from codeverse.agents.cli_common import (
is_secret_env,
is_transient_failure,
)
-from codeverse.agents.transcript import Trajectory
from codeverse.contracts.agent import AgentJob, FileChange
from codeverse.contracts.common import Usage
from codeverse.workspace import Workspace
@@ -163,7 +163,7 @@ def test_mcp_command_resolution(tmp_ws: Workspace):
def test_gemini_system_settings_disable_folder_trust(tmp_path):
- from codeverse.agents.gemini_cli import write_system_settings
+ from codeverse.agents.backends import write_system_settings
p = write_system_settings(tmp_path / "s.json")
data = json.loads(p.read_text())
diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.py
index ffe9394b..9fab89fe 100644
--- a/harness/tests/agents/test_codex.py
+++ b/harness/tests/agents/test_codex.py
@@ -8,8 +8,8 @@ from pathlib import Path
import pytest
+from codeverse.agents.backends import CodexAgent, parse_codex_jsonl, split_model_effort
from codeverse.agents.cli_common import begin_session
-from codeverse.agents.codex import CodexAgent, parse_codex_jsonl, split_model_effort
from codeverse.contracts.agent import AgentJob
from codeverse.workspace import Workspace
@@ -103,7 +103,7 @@ def test_fake_run(tmp_ws: Workspace, fake_bin, monkeypatch):
def test_long_prompt_goes_via_stdin(tmp_ws: Workspace, fake_bin, monkeypatch):
- monkeypatch.setattr("codeverse.agents.codex.STDIN_PROMPT_BYTES", 10)
+ monkeypatch.setattr("codeverse.agents.backends.STDIN_PROMPT_BYTES", 10)
a = CodexAgent("gpt-5.6-sol", binary=fake_bin("codex", FAKE_CODEX))
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello world this is long", label="z", timeout_s=30))
assert res.ok and (tmp_ws.src / "hello.txt").read_text() == "hello"
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index d87c4546..7496ffce 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -7,7 +7,7 @@ from pathlib import Path
import pytest
-from codeverse.agents.gemini_cli import GeminiCliAgent, parse_gemini_json, usage_from_stats
+from codeverse.agents.backends import GeminiCliAgent, parse_gemini_json, usage_from_stats
from codeverse.config import get_settings
from codeverse.contracts.agent import AgentJob
from codeverse.workspace import Workspace
@@ -55,7 +55,7 @@ def agent(fake_bin, monkeypatch):
def test_retry_window_never_restarts():
"""The retry rule itself: what is LEFT of the window, or None when < min(120, T/4)."""
- from codeverse.agents.gemini_cli import retry_window_left
+ from codeverse.agents.backends import retry_window_left
assert retry_window_left(1800, 1700) is None # 100s left < 120 floor
assert retry_window_left(1800, 900) == 900 # half the window remains
@@ -150,7 +150,7 @@ def test_single_key_transient_failure_retries_same_key_and_never_raises(tmp_ws:
def test_single_key_quota_failure_returns_budget_without_retry(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
"""429 puts the only key into cooldown: no alternative → return the failed outcome (ok=False), do not raise."""
- from codeverse.agents import gemini_cli as gc
+ from codeverse.agents import backends as gc
monkeypatch.setattr(get_settings(), "gemini_api_keys", ["solo"])
monkeypatch.setattr(gc, "RETRY_KEY_WAIT_S", 0.2)
@@ -166,7 +166,7 @@ def test_single_key_quota_failure_returns_budget_without_retry(tmp_ws: Workspace
def test_pool_exhausted_before_first_attempt_is_a_budget_result(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- from codeverse.agents import gemini_cli as gc
+ from codeverse.agents import backends as gc
from codeverse.models.retry import KeyPoolExhausted
class Dead:
diff --git a/harness/tests/agents/test_transcript.py b/harness/tests/agents/test_transcript.py
index d0cc4185..f4bad8fd 100644
--- a/harness/tests/agents/test_transcript.py
+++ b/harness/tests/agents/test_transcript.py
@@ -4,8 +4,8 @@ from __future__ import annotations
from pathlib import Path
-from codeverse.agents import transcript as tr
-from codeverse.agents.transcript import Trajectory
+from codeverse.agents import cli_common as tr
+from codeverse.agents.cli_common import Trajectory
def test_the_transcript_stops_at_its_budget_with_a_marker_row(tmp_path: Path, monkeypatch):
diff --git a/harness/tests/agents/test_watchdog.py b/harness/tests/agents/test_watchdog.py
index 8469d284..f05546da 100644
--- a/harness/tests/agents/test_watchdog.py
+++ b/harness/tests/agents/test_watchdog.py
@@ -13,7 +13,7 @@ from pathlib import Path
import pytest
-from codeverse.agents.watchdog import run_with_watchdog
+from codeverse.agents.cli_common import run_with_watchdog
from tests.conftest import assert_pid_gone
PY = sys.executable
diff --git a/harness/tests/models/test_control_chars.py b/harness/tests/models/test_control_chars.py
index 3cd0ce1d..765c5622 100644
--- a/harness/tests/models/test_control_chars.py
+++ b/harness/tests/models/test_control_chars.py
@@ -64,7 +64,7 @@ def test_the_subprocess_backstop_names_the_offender(tmp_path):
"embedded null byte" from Popen names no argument, offset or value."""
import pytest
- from codeverse.agents.watchdog import run_with_watchdog
+ from codeverse.agents.cli_common import run_with_watchdog
poisoned = "harness_instructions: envelope is 0.078 \x00 0.300 m"
with pytest.raises(ValueError, match=r"argv\[2\] contains a NUL at offset \d+"):