Skip to content

Official Codebase of 3DCodeVerse

Python

agy replaces gemini-cli: Gemini-API mode on a pool key with its own HOME and the 3dcode MCP server; gemini-cli and its retry layers deleted (D103)

gaoypeng97c66662a3cc
diff --git a/eval/README.md b/eval/README.md
index f8aa7b30..0bb19bde 100644
--- a/eval/README.md
+++ b/eval/README.md
@@ -17,9 +17,9 @@ ask one-shot from there (`llm/config.py: HARNESS_BATTERIES`).
```bash
cd eval
pip install -e ../harness # once; both evaluations import codeverse3d
-python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator gemini-cli:gemini-3.7-flash
+python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator agy:gemini-3.7-flash
python -m bench.report bench/out/static_objects_v1 # rebuild report.md + report.html
-python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:gemini-cli:gemini-3.7-flash,oneshot:gemini:gemini-3.7-flash --out bench/out/compare_v1
+python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:agy:gemini-3.7-flash,oneshot:gemini:gemini-3.7-flash --out bench/out/compare_v1
python -m llm.config # doctor for the LLM evaluation: tools and assets it can / cannot find
python -m pytest # the bench tests (offline)
ruff check .
diff --git a/eval/bench/_bare_agent.py b/eval/bench/_bare_agent.py
index 69f6cd5d..25e43a8d 100644
--- a/eval/bench/_bare_agent.py
+++ b/eval/bench/_bare_agent.py
@@ -2,7 +2,7 @@
The strongest objection to the harness is not "a model asked once does worse" — it is "give the SAME
agent the SAME minutes and a Blender, and it does as well on its own". This arm answers that: the same
-vendor CLI and model the harness drives (``agent:gemini-cli:gemini-3.7-flash``), the one-shot arm's
+vendor CLI and model the harness drives (``agent:agy:gemini-3.7-flash``), the one-shot arm's
brief and minimal contract, a shell with the machine's own tools (Blender, node + three + puppeteer,
python + moderngl, glslangValidator) and the harness arm's wall clock. It gets no plan, no 3dcode MCP
tools, no cookbook, no gates, no judge, no starter library and no deterministic repairs — the agent
diff --git a/eval/bench/_infra.py b/eval/bench/_infra.py
index 7a9d0328..1654bfa3 100644
--- a/eval/bench/_infra.py
+++ b/eval/bench/_infra.py
@@ -69,7 +69,7 @@ def _looks_infra(exc: BaseException) -> bool:
"""The outage rules, applied to ONE exception. Typed first: the harness's own verdict
(``RoundFailed`` / ``GenerationResult`` ``.transient`` — a provider storm, a dropped socket
— and ``.quota`` — the vendor's usage limit, "not ours") decided from the CLI's own record,
- which the bench must not re-guess from the message (N76: a gemini-cli 503 storm that killed a
+ which the bench must not re-guess from the message (N76: a gemini-cli (pre-D103) 503 storm that killed a
baseline twice matched no marker and was scored as an error). Then the HTTP status, from the
harness's one table (``models.parts.retryable_status``: 408/409/429/5xx), and a spent key
pool. The string markers are the fallback, for exceptions nobody typed and for the error
diff --git a/eval/bench/compare_backends.py b/eval/bench/compare_backends.py
index debde89c..a53382ea 100644
--- a/eval/bench/compare_backends.py
+++ b/eval/bench/compare_backends.py
@@ -1,7 +1,7 @@
"""Harness vs raw one-shot generation under ONE fixed judge (methodology bench).
python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \\
- --arms harness:gemini-cli:gemini-3.6-flash,harness:gemini-cli:gemini-3.7-flash,\\
+ --arms harness:agy:gemini-3.6-flash,harness:agy:gemini-3.7-flash,\\
oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash \\
--judge gemini:gemini-3.1-pro-preview --out <dir> [--parallel 8] [--limit N]
diff --git a/eval/bench/plan_stage_bench.py b/eval/bench/plan_stage_bench.py
index 7f0022d2..145d8c03 100644
--- a/eval/bench/plan_stage_bench.py
+++ b/eval/bench/plan_stage_bench.py
@@ -32,7 +32,7 @@ from pathlib import Path
DEFAULT_BATTERY = "bench/prompts/articulated_v2.yaml"
DEFAULT_PLANNER = "gemini:gemini-3.7-flash"
-DEFAULT_GENERATOR = "gemini-cli:gemini-3.7-flash"
+DEFAULT_GENERATOR = "agy:gemini-3.7-flash"
DEFAULT_JUDGE = "gemini:gemini-3.1-pro-preview"
diff --git a/eval/bench/prompts/complexity_v3.yaml b/eval/bench/prompts/complexity_v3.yaml
index 965c5ec0..4e9317e1 100644
--- a/eval/bench/prompts/complexity_v3.yaml
+++ b/eval/bench/prompts/complexity_v3.yaml
@@ -15,7 +15,7 @@
# (extra keys are ignored); `bench/complexity_report.py --battery` reads it.
#
# python -m bench.run_bench bench/prompts/complexity_v3.yaml --out bench/out/complexity_v3 \
-# --generator gemini-cli:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview
+# --generator agy:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview
# python bench/complexity_report.py bench/out/complexity_v3 --battery bench/prompts/complexity_v3.yaml
#
# Ladder (measured index of the nearest corpus run is in brackets):
diff --git a/eval/bench/prompts/teaser_v1_articulated.yaml b/eval/bench/prompts/teaser_v1_articulated.yaml
index aff02e54..d94f677b 100644
--- a/eval/bench/prompts/teaser_v1_articulated.yaml
+++ b/eval/bench/prompts/teaser_v1_articulated.yaml
@@ -2,7 +2,7 @@
# one track + language (bench/run_bench.py). Cross-language prompts inside a track use
# the per-prompt `language:` override. These four files ARE the source; edit them here.
# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py
-# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): (none)
+# Heroes (run with codex:gpt-5.6-sol, everything else agy:gemini-3.6-flash): (none)
name: teaser_v1_articulated
track: articulated_object
language: urdf_blender
diff --git a/eval/bench/prompts/teaser_v1_graphics.yaml b/eval/bench/prompts/teaser_v1_graphics.yaml
index 6c6f1b64..094c4347 100644
--- a/eval/bench/prompts/teaser_v1_graphics.yaml
+++ b/eval/bench/prompts/teaser_v1_graphics.yaml
@@ -2,7 +2,7 @@
# one track + language (bench/run_bench.py). Cross-language prompts inside a track use
# the per-prompt `language:` override. These four files ARE the source; edit them here.
# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py
-# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): (none)
+# Heroes (run with codex:gpt-5.6-sol, everything else agy:gemini-3.6-flash): (none)
name: teaser_v1_graphics
track: graphics
language: glsl_shader
diff --git a/eval/bench/prompts/teaser_v1_scene.yaml b/eval/bench/prompts/teaser_v1_scene.yaml
index 06d2e714..51139f06 100644
--- a/eval/bench/prompts/teaser_v1_scene.yaml
+++ b/eval/bench/prompts/teaser_v1_scene.yaml
@@ -2,7 +2,7 @@
# one track + language (bench/run_bench.py). Cross-language prompts inside a track use
# the per-prompt `language:` override. These four files ARE the source; edit them here.
# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py
-# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): tsr_scn_temple_night
+# Heroes (run with codex:gpt-5.6-sol, everything else agy:gemini-3.6-flash): tsr_scn_temple_night
name: teaser_v1_scene
track: scene
language: scene_threejs
diff --git a/eval/bench/prompts/teaser_v1_static.yaml b/eval/bench/prompts/teaser_v1_static.yaml
index 9977a8d1..c2acb9db 100644
--- a/eval/bench/prompts/teaser_v1_static.yaml
+++ b/eval/bench/prompts/teaser_v1_static.yaml
@@ -2,7 +2,7 @@
# one track + language (bench/run_bench.py). Cross-language prompts inside a track use
# the per-prompt `language:` override. These four files ARE the source; edit them here.
# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py
-# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): tsr_obj_penny_farthing, tsr_cad_radial_engine
+# Heroes (run with codex:gpt-5.6-sol, everything else agy:gemini-3.6-flash): tsr_obj_penny_farthing, tsr_cad_radial_engine
name: teaser_v1_static
track: static_object
language: blender
diff --git a/eval/bench/session_stats.py b/eval/bench/session_stats.py
index cce50672..a52dd711 100644
--- a/eval/bench/session_stats.py
+++ b/eval/bench/session_stats.py
@@ -28,8 +28,9 @@ from bench._records import records # noqa: E402
from codeverse3d.proc import read_json_or_none # noqa: E402
from codeverse3d.record.record import unique_files # noqa: E402
-#: gemini-cli names an MCP tool ``mcp_<server>_<tool>``; ours is the ``3dcode`` server
-#: (``3dcv`` in every session recorded before the 2026-09-21 rename).
+#: gemini-cli (the backend deleted in D103, 2026-10-13 — this file reads the sessions it
+#: recorded before then) names an MCP tool ``mcp_<server>_<tool>``; ours is the ``3dcode``
+#: server (``3dcv`` in every session recorded before the 2026-09-21 rename).
MCP_PREFIXES = ("mcp_3dcode_", "mcp_3dcv_")
@@ -67,27 +68,34 @@ def tool_rates(sessions: list[Path]) -> tuple[Counter, Counter]:
return calls, failed
+def _prompt_cached(tok: dict) -> tuple[int, int]:
+ """(total prompt, cached) tokens of one served model in a pre-D103 gemini-cli stats block.
+ ``tokens.prompt`` is the total; the older schema has only ``tokens.input`` = prompt − cached,
+ which would otherwise read as zero."""
+ cached = int(tok.get("cached") or 0)
+ prompt = tok.get("prompt")
+ return (int(prompt) if prompt is not None else int(tok.get("input") or 0) + cached), cached
+
+
def token_rates(sessions: list[Path]) -> dict[str, float]:
"""Prompt/cached tokens and requests for each session's MAIN model.
- ``agents.backends.gemini_model_usage`` owns the envelope — including the older
- ``tokens.input`` schema this file would otherwise read as zero — so the tokens come
- from it rather than from a second parser. A session's ``models`` map also carries
- gemini-cli's own bookkeeping model (one request per session for the session title),
- and docs/COST.md §30 counts main-role requests: the model with the most requests IS
- the main role, and mixing the other in moves ``uncached per request`` by ~3 %.
+ Reads gemini-cli sessions recorded before D103 (2026-10-13), when the harness's own
+ parser for this envelope was deleted with the backend — hence :func:`_prompt_cached`
+ here. A session's ``models`` map also carries gemini-cli's own bookkeeping model (one
+ request per session for the session title), and docs/COST.md §30 counts main-role
+ requests: the model with the most requests IS the main role, and mixing the other in
+ moves ``uncached per request`` by ~3 %.
"""
- from codeverse3d.agents.backends import gemini_model_usage
-
prompt = cached = requests = 0
for path in sessions:
models = (((read_json_or_none(path) or {}).get("stats") or {}).get("models")) or {}
if not models:
continue
main = max(models, key=lambda n: int(((models[n] or {}).get("api") or {}).get("totalRequests") or 0))
- usage = gemini_model_usage((models[main] or {}).get("tokens") or {}, main)
- prompt += usage.input_tokens
- cached += usage.cached_tokens
+ p, c = _prompt_cached((models[main] or {}).get("tokens") or {})
+ prompt += p
+ cached += c
requests += int(((models[main] or {}).get("api") or {}).get("totalRequests") or 0)
return {"requests": requests, "prompt": prompt, "cached": cached,
"cache_hit": cached / prompt if prompt else float("nan"),
diff --git a/eval/docs/COMPLEXITY.md b/eval/docs/COMPLEXITY.md
index 0c7e96ee..7637ecf8 100644
--- a/eval/docs/COMPLEXITY.md
+++ b/eval/docs/COMPLEXITY.md
@@ -301,7 +301,7 @@ expected to reach:
```
python -m bench.run_bench bench/prompts/complexity_v3.yaml --out bench/out/complexity_v3 \
- --generator gemini-cli:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview
+ --generator agy:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview
python bench/complexity_report.py bench/out/complexity_v3 --battery bench/prompts/complexity_v3.yaml
```
diff --git a/eval/docs/EVAL.md b/eval/docs/EVAL.md
index c250cfa9..1dcd42ed 100644
--- a/eval/docs/EVAL.md
+++ b/eval/docs/EVAL.md
@@ -59,9 +59,9 @@ deterministic contract check.
```bash
cd eval # was `3dcode bench run|report` until 2026-09-22: the launcher lives with the evaluation now
python -m bench.run_bench bench/prompts/static_objects_v1.yaml \
- --generator gemini-cli:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \
+ --generator agy:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \
--rounds 2 --parallel 4 --out bench/out/static_v1_apiagent
-python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator gemini-cli:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview --out bench/out/static_v1_gemcli
+python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator agy:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview --out bench/out/static_v1_gemcli
python -m bench.report bench/out/static_v1_apiagent
```
Like every bench script it imports THIS tree's `codeverse3d` (`../harness`), so a battery
@@ -98,7 +98,7 @@ cheaply.
```bash
python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \
- --arms harness:gemini-cli:gemini-3.6-flash,harness:gemini-cli:gemini-3.7-flash,oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \
+ --arms harness:agy:gemini-3.6-flash,harness:agy:gemini-3.7-flash,oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \
--judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1 [--parallel 3] [--limit N] [--ids a,b]
[--rounds 3] [--loop-judge gemini:gemini-3.7-flash] [--repair-attempts 2] [--gen-timeout 900]
[--no-pairwise] [--no-resume] [--report-only]
@@ -118,9 +118,10 @@ Arms:
judge, no starter library, no deterministic repairs. It answers "give the same agent the same
minutes and a Blender": the harness's lift over it is what the harness itself adds. Smoke
(dining chair, 15 min): the agent wrote its own test + render scripts, looked at its PNGs, 0.682.
- Two known asymmetries: a session killed by a 503 storm has no single-shot fallback (the harness
- has D68), so on a storm day this arm loses more cells to `infra_failed`; and its USD is 0 when
- the CLI dies before printing stats.
+ One known asymmetry: its USD is 0 when the CLI dies before printing stats. (Until D103,
+ 2026-10-13, there was a second: the harness had a single-shot fallback for a session killed by a
+ 503 storm (D68) and this arm did not, so on a storm day it lost more cells to `infra_failed`.
+ D103 deleted that fallback with the gemini-cli backend.)
Every arm ends with a `src/model.py` copied into a fresh eval workspace and scored by
the same `FixedEvaluator` (the cell's runtime lint+build → measure → connectivity →
@@ -178,7 +179,8 @@ Pending: rerun the parked sol battery, then terra, then luna, then the claude-co
## 5. Comparing backends inside the harness
Same battery, same `--judge`, different `--generator` (`single-shot:*`,
-`gemini-cli:*`, `claude-code:*`, `codex:*`, `agy:*`). Report baseline, picked, delta,
+`claude-code:*`, `codex:*`, `agy:*`; `gemini-cli:*` was deleted in D103, 2026-10-13 —
+Google's models run as `agy:gemini-*`). Report baseline, picked, delta,
cost, time per tier; optionally feed the picked rounds of two arms through
`PairwiseJudge.compare(spec, renders_a, renders_b)` (`flywheel pairs` already emits
cross-backend candidate pairs keyed by prompt hash).
diff --git a/eval/docs/PAPER_WRITING.md b/eval/docs/PAPER_WRITING.md
index 03bd3ffd..839df7b0 100644
--- a/eval/docs/PAPER_WRITING.md
+++ b/eval/docs/PAPER_WRITING.md
@@ -586,9 +586,11 @@ truncation and degenerate-plan re-asks around the planner (§5.1).
```bash
cd eval # the bench scripts live here since 2026-09-22 (they were harness/bench/)
+# the measurements above ran on `gemini-cli:*`, deleted in D103 (2026-10-13); its successor for
+# Google's models is `agy:*`, so a rerun is a new measurement, not a replay
# the instrument
python bench/ab_plan.py --prompts bench/prompts/articulated_v2.yaml --aa --pin-plan \
- --generator gemini-cli:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \
+ --generator agy:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \
--n-samples 3 --rounds 3 --out bench/out/aa_articulated
# a switch A/B (generation-side switches only; plan-side is refused for --pin-plan). The arm
# measured in §4 was C3D_FEWER_TURNS=1, a switch deleted since; name a live Settings flag instead
@@ -596,7 +598,7 @@ python bench/ab_plan.py --prompts bench/prompts/articulated_v2.yaml \
--variant-env C3D_<SWITCH>=1 --pin-plan --out bench/out/<switch>
# harness vs one-shot
python bench/compare_backends.py --prompts bench/prompts/articulated_v2.yaml \
- --arms harness:gemini-cli:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \
+ --arms harness:agy:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \
--judge gemini:gemini-3.1-pro-preview --judge-samples 3 --out bench/out/art
# the loss-event channel: the plan stage alone, one row per call
python bench/plan_stage_bench.py --tree ../harness --label restart_on --reps 20 \
diff --git a/eval/tests/test_bare_agent.py b/eval/tests/test_bare_agent.py
index be6594bd..a8df860e 100644
--- a/eval/tests/test_bare_agent.py
+++ b/eval/tests/test_bare_agent.py
@@ -26,9 +26,9 @@ def _spec(track: Track = Track.STATIC_OBJECT, language: Language = Language.BLEN
def test_parse_agent_arm():
- arm = parse_arm("agent:gemini-cli:gemini-3.7-flash")
- assert arm.kind == "agent" and arm.target == "gemini-cli:gemini-3.7-flash"
- assert arm.slug == "agent_gemini-cli_gemini-3.7-flash"
+ arm = parse_arm("agent:agy:gemini-3.7-flash")
+ assert arm.kind == "agent" and arm.target == "agy:gemini-3.7-flash"
+ assert arm.slug == "agent_agy_gemini-3.7-flash"
with pytest.raises(ValueError):
parse_arm("agent:nope:model")
@@ -65,12 +65,12 @@ def test_run_copies_the_deliverable_and_resumes(tmp_path, monkeypatch):
monkeypatch.setattr("bench._bare_agent.get_coding_agent", lambda target: agent)
eval_ws = Workspace(tmp_path / "eval").create()
started = time.monotonic()
- r = run_bare_agent(_spec(), "gemini-cli:gemini-3.7-flash", tmp_path, eval_ws, minutes=10)
+ r = run_bare_agent(_spec(), "agy:gemini-3.7-flash", tmp_path, eval_ws, minutes=10)
assert r.ok and (eval_ws.root / "src" / "model.py").read_text() == "import bpy\n"
job = agent.jobs[0]
assert job.spatial_tools is False and job.timeout_s == 600 and job.write_roots == ["src", "tmp"]
assert started + 600 <= job.hard_deadline_s <= time.monotonic() + 600
- run_bare_agent(_spec(), "gemini-cli:gemini-3.7-flash", tmp_path, eval_ws, minutes=10)
+ run_bare_agent(_spec(), "agy:gemini-3.7-flash", tmp_path, eval_ws, minutes=10)
assert len(agent.jobs) == 1 # a finished session is not re-run
@@ -84,6 +84,6 @@ def test_a_storm_killed_session_is_not_cached_so_a_redo_runs_it(tmp_path, monkey
monkeypatch.setattr("bench._bare_agent.get_coding_agent", lambda target: Storm())
eval_ws = Workspace(tmp_path / "eval").create()
- run_bare_agent(_spec(), "gemini-cli:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
- run_bare_agent(_spec(), "gemini-cli:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
+ run_bare_agent(_spec(), "agy:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
+ run_bare_agent(_spec(), "agy:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
assert len(calls) == 2 and not (tmp_path / "agent" / ".bare_done.json").exists()
diff --git a/eval/tests/test_bench.py b/eval/tests/test_bench.py
index c827eeab..74225a3c 100644
--- a/eval/tests/test_bench.py
+++ b/eval/tests/test_bench.py
@@ -55,7 +55,7 @@ def test_run_battery_resume_and_report(tmp_path: Path):
battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"
out = tmp_path / "bench_out"
scores = {"furn_easy_stool": (0.6, 0.85), "furn_med_dining_chair": (0.5, 0.7), "furn_hard_rolltop_desk": (0.4, 0.6)}
- opts = BenchOptions(parallel=2, limit=4, judge="gemini:gemini-3.7-flash", generator="gemini-cli:gemini-3.6-flash")
+ opts = BenchOptions(parallel=2, limit=4, judge="gemini:gemini-3.7-flash", generator="agy:gemini-3.6-flash")
res = run_battery(battery, out, opts, run_fn=_fake_run_fn(scores, fail_ids={"veh_easy_toy_car"}))
assert len(res) == 4
by_id = {r.id: r for r in res}
diff --git a/eval/tests/test_bench_shared.py b/eval/tests/test_bench_shared.py
index ffb79474..857b5eff 100644
--- a/eval/tests/test_bench_shared.py
+++ b/eval/tests/test_bench_shared.py
@@ -29,8 +29,8 @@ def test_select_prompts_ids_tiers_limit():
def test_spec_for_routes_through_settings_backends():
b = _battery()
s = rb.get_settings()
- spec = spec_for(b, b.prompts[0], BenchOptions(generator="gemini-cli:gemini-3.7-flash"))
- assert spec.backends.generator == "gemini-cli:gemini-3.7-flash"
+ spec = spec_for(b, b.prompts[0], BenchOptions(generator="agy:gemini-3.7-flash"))
+ assert spec.backends.generator == "agy:gemini-3.7-flash"
# unset roles fall through to the settings defaults, not the Backends() literals
assert spec.backends.planner == s.default_planner and spec.backends.judge == s.default_judge
assert spec.backends.captioner == s.default_captioner
diff --git a/eval/tests/test_compare_matrix.py b/eval/tests/test_compare_matrix.py
index 0564a5c8..6ffd16d3 100644
--- a/eval/tests/test_compare_matrix.py
+++ b/eval/tests/test_compare_matrix.py
@@ -40,13 +40,13 @@ from tests.conftest import ( # noqa: E402
fake_run_track,
)
-ARMS = "harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code,oneshot+repair:codex,oneshot:gemini:gemini-3.7-flash"
+ARMS = "harness:agy:gemini-3.6-flash,oneshot:claude-code,oneshot+repair:codex,oneshot:gemini:gemini-3.7-flash"
def test_parse_arms():
arms = parse_arms(ARMS)
assert [a.kind for a in arms] == ["harness", "oneshot", "oneshot+repair", "oneshot"]
- assert arms[0].target == "gemini-cli:gemini-3.6-flash" and arms[2].target == "codex"
+ assert arms[0].target == "agy:gemini-3.6-flash" and arms[2].target == "codex"
assert arms[2].slug == "oneshot_plus_repair_codex"
for bad in ("harness", "foo:bar", "oneshot:gemini-cli:x", "oneshot:nope"):
with pytest.raises(ValueError):
@@ -58,9 +58,9 @@ def test_parse_arms():
def test_spec_for_and_acceptance():
b = Battery.load(BATTERY)
opts = CompareOptions(judge="gemini:gemini-3.1-pro-preview", loop_judge="gemini:gemini-3.7-flash")
- harness = spec_for(b, b.prompts[0], parse_arm("harness:gemini-cli:gemini-3.7-flash"), opts)
+ harness = spec_for(b, b.prompts[0], parse_arm("harness:agy:gemini-3.7-flash"), opts)
one = spec_for(b, b.prompts[0], parse_arm("oneshot:codex"), opts)
- assert harness.backends.generator == "gemini-cli:gemini-3.7-flash" and harness.backends.judge == "gemini:gemini-3.7-flash"
+ assert harness.backends.generator == "agy:gemini-3.7-flash" and harness.backends.judge == "gemini:gemini-3.7-flash"
assert harness.budget.max_rounds == 3
assert one.backends.generator == "single-shot:codex" and one.constraints.must_have == b.prompts[0].must_have
@@ -91,7 +91,7 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
rows = run_matrix(BATTERY, out, parse_arms(ARMS), opts, deps)
assert len(rows) == 8 and (out / "matrix.json").is_file()
by = {(r.prompt_id, r.arm): r for r in rows}
- h = by[("cmp_easy_stool", "harness:gemini-cli:gemini-3.6-flash")]
+ h = by[("cmp_easy_stool", "harness:agy:gemini-3.6-flash")]
assert h.status == "scored" and h.score == pytest.approx(0.9) and h.passed and h.build_ok
assert h.gen_cost_usd == pytest.approx(0.9) and h.harness_status == "max_rounds" and h.harness_loop_score == pytest.approx(0.8)
assert h.judge_cost_usd == pytest.approx(0.01) and h.tris == 900 and Path(h.sheet).is_file()
@@ -123,11 +123,11 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
# the arm row is n | dropped | over budget | mean: the two loss columns stay blank when
# nothing was lost, but must always be PRESENT so a drop can never hide (docs/EVAL.md §7)
assert "| arm | kind | n | dropped | over budget | mean |" in md, md
- assert "| harness:gemini-cli:gemini-3.6-flash | harness | 2 | | | 0.900 |" in md, md
+ assert "| harness:agy:gemini-3.6-flash | harness | 2 | | | 0.900 |" in md, md
assert "| cmp_easy_stool | easy | 0.90✓ | 0.60 | 0.75✓ | 0.00 ✗build |" in md
- assert "| harness:gemini-cli:gemini-3.6-flash | oneshot:claude-code | 2 | 2 | 0 | 0 | 100% |" in md
+ assert "| harness:agy:gemini-3.6-flash | oneshot:claude-code | 2 | 2 | 0 | 0 | 100% |" in md
page = (out / "report.html").read_text()
- assert "report_assets/cmp_easy_stool__harness_gemini-cli_gemini-3.6-flash.png" in page
+ assert "report_assets/cmp_easy_stool__harness_agy_gemini-3.6-flash.png" in page
assert len(list((out / "report_assets").glob("*.png"))) == 6
# ---- resume: nothing re-runs, nothing re-judged, results identical
@@ -155,10 +155,10 @@ def test_cell_errors_are_recorded_not_raised(tmp_path: Path):
deps = CompareDeps(Exploding(), run_track=failing_track, oneshot_backend=lambda t: FakeBackend([GOOD.format(score=0.5)]),
pairwise_judge=FakePairwise)
- rows = run_matrix(BATTERY, tmp_path / "o", parse_arms("harness:gemini-cli:gemini-3.6-flash,oneshot:codex"),
+ rows = run_matrix(BATTERY, tmp_path / "o", parse_arms("harness:agy:gemini-3.6-flash,oneshot:codex"),
CompareOptions(limit=1, parallel=1), deps)
by = {r.arm: r for r in rows}
- assert by["harness:gemini-cli:gemini-3.6-flash"].status == "error" and "planner down" in by["harness:gemini-cli:gemini-3.6-flash"].error
+ assert by["harness:agy:gemini-3.6-flash"].status == "error" and "planner down" in by["harness:agy:gemini-3.6-flash"].error
assert by["oneshot:codex"].status == "error" and "blender missing" in by["oneshot:codex"].error
assert (tmp_path / "o" / "report.md").is_file()
@@ -233,11 +233,11 @@ def test_every_cell_and_its_harness_run_open_a_ledger(tmp_path: Path):
deps = _deps(ev, {"claude-code": FakeBackend(["```python\n" + GOOD.format(score=0.6) + "```"])}, run_track)
out = tmp_path / "cmp"
opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=2, pairwise=False)
- rows = run_matrix(BATTERY, out, parse_arms("harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code"),
+ rows = run_matrix(BATTERY, out, parse_arms("harness:agy:gemini-3.6-flash,oneshot:claude-code"),
opts, deps)
assert len(rows) == 2
cells = {r.arm: Path(r.workspace) for r in rows}
- harness = cells["harness:gemini-cli:gemini-3.6-flash"]
+ harness = cells["harness:agy:gemini-3.6-flash"]
assert [r.label for r in load_ledger(harness / "run")] == ["baseline"]
assert [r.label for r in load_ledger(harness)] == ["judge:static_object_v1:r00:s0"]
oneshot = cells["oneshot:claude-code"]
@@ -256,7 +256,7 @@ def test_no_resume_starts_the_harness_arm_fresh(tmp_path: Path):
return inner(spec, ws, resume)
out = tmp_path / "cmp"
- arms = parse_arms("harness:gemini-cli:gemini-3.6-flash")
+ arms = parse_arms("harness:agy:gemini-3.6-flash")
deps = _deps(ev, {}, run)
opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=1, pairwise=False)
cell = Path(run_matrix(BATTERY, out, arms, opts, deps)[0].workspace)
diff --git a/eval/tests/test_degraded.py b/eval/tests/test_degraded.py
index 62487c36..d73a4f2f 100644
--- a/eval/tests/test_degraded.py
+++ b/eval/tests/test_degraded.py
@@ -47,7 +47,7 @@ def test_flag_degraded_rule(tmp_path, status, stop, rounds, cost, aborted, expec
battery = Battery.load(BATTERY)
opts = CompareOptions(judge="gemini:x", loop_judge="gemini:x", degraded_min_wall_s=0)
deps = CompareDeps(FakeEvaluator(), run_track=_track(status, stop, rounds, cost, aborted))
- r = run_cell(battery, battery.prompts[0], parse_arm("harness:gemini-cli:gemini-3.6-flash"), tmp_path, opts, deps)
+ r = run_cell(battery, battery.prompts[0], parse_arm("harness:agy:gemini-3.6-flash"), tmp_path, opts, deps)
assert r.status == "scored" and r.score is not None
assert (r.harness_stop_reason, r.harness_rounds, r.harness_aborted_rounds) == (stop, rounds, aborted)
assert r.degraded is expect, r
diff --git a/eval/tests/test_infra_failures.py b/eval/tests/test_infra_failures.py
index 83b37bd9..1d11f7ec 100644
--- a/eval/tests/test_infra_failures.py
+++ b/eval/tests/test_infra_failures.py
@@ -20,7 +20,7 @@ def test_pairwise_outage_is_unavailable_even_with_cached_win(tmp_path, monkeypat
battery = Battery.load(BATTERY)
battery = battery.model_copy(update={"prompts": battery.prompts[:1]})
prompt = battery.prompts[0].id
- arms = cb.parse_arms("harness:codex:gpt-6-astra@high,agent:gemini-cli:gemini-3.8-flash")
+ arms = cb.parse_arms("harness:codex:gpt-6-astra@high,agent:agy:gemini-3.8-flash")
rows = [CellResult(prompt_id=prompt, arm=a.raw, kind=a.kind, status="scored", score=0.6) for a in arms]
rows[failed_side] = rows[failed_side].model_copy(update={"status": "infra_failed", "error_is_infra": True, "score": None})
cells = {(r.prompt_id, r.arm): r for r in rows}
@@ -51,7 +51,7 @@ def test_scene_pairwise_uses_the_same_track_rubric_as_fixed_evaluation(tmp_path,
battery = Battery.load(BATTERY)
battery = battery.model_copy(update={"prompts": battery.prompts[:1], "track": Track.SCENE,
"language": Language.SCENE_THREEJS})
- arms = cb.parse_arms("harness:codex:gpt-6-astra@high,agent:gemini-cli:gemini-3.8-flash")
+ arms = cb.parse_arms("harness:codex:gpt-6-astra@high,agent:agy:gemini-3.8-flash")
cells = {(battery.prompts[0].id, a.raw): CellResult(prompt_id=battery.prompts[0].id,
arm=a.raw, kind=a.kind, status="scored", score=0.6) for a in arms}
monkeypatch.setattr(cb, "_renders_of", lambda *args: object())
@@ -149,7 +149,7 @@ def test_both_failure_paths_classify_the_same_way(tmp_path):
oneshot_backend=lambda t: ApiOneShot("gemini:gemini-3.7-flash", chat_model=DeadModel()))
opts = CompareOptions(judge="gemini:x", loop_judge="gemini:x")
got = {}
- for raw in ("harness:gemini-cli:gemini-3.6-flash", "oneshot:gemini:gemini-3.7-flash"):
+ for raw in ("harness:agy:gemini-3.6-flash", "oneshot:gemini:gemini-3.7-flash"):
arm = parse_arm(raw)
r = run_cell(battery, battery.prompts[0], arm, out, opts, deps)
got[arm.kind] = (r.status, r.score)
@@ -270,7 +270,7 @@ def test_a_harness_planning_failure_is_a_zero_not_a_dropped_cell(tmp_path):
battery = Battery.load(BATTERY)
opts = CompareOptions(judge="gemini:x", loop_judge="gemini:x")
- r = run_cell(battery, battery.prompts[0], parse_arm("harness:gemini-cli:gemini-3.6-flash"), tmp_path, opts,
+ r = run_cell(battery, battery.prompts[0], parse_arm("harness:agy:gemini-3.6-flash"), tmp_path, opts,
CompareDeps(FakeEvaluator(), run_track=no_plan))
assert (r.status, r.score, r.passed, r.build_ok) == ("no_code", 0.0, False, False)
assert r.error.startswith("PlanningError:")
@@ -297,7 +297,7 @@ def test_a_classifier_crash_still_records_the_cell(tmp_path):
raise ClassifierTrap("planner died")
battery = Battery.load(BATTERY)
- r = cb.run_cell(battery, battery.prompts[0], cb.parse_arm("harness:gemini-cli:gemini-3.6-flash"), tmp_path,
+ r = cb.run_cell(battery, battery.prompts[0], cb.parse_arm("harness:agy:gemini-3.6-flash"), tmp_path,
cb.CompareOptions(judge="gemini:x", loop_judge="gemini:x"), cb.CompareDeps(FakeEvaluator(), run_track=boom))
assert r.status == "error" and "planner died" in r.error
assert (Path(r.workspace) / "cell.json").is_file()
@@ -356,7 +356,7 @@ def test_a_harness_run_whose_judge_never_answered_is_dropped_and_redone_fresh(tm
battery = Battery.load(BATTERY)
opts = CompareOptions(judge="gemini:x", loop_judge="gemini:x")
- arm = parse_arm("harness:gemini-cli:gemini-3.8-flash")
+ arm = parse_arm("harness:agy:gemini-3.8-flash")
ev = FakeEvaluator()
r = run_cell(battery, battery.prompts[0], arm, tmp_path, opts, CompareDeps(ev, run_track=judge_down))
assert (r.status, r.score, r.passed) == ("infra_failed", None, None), r
@@ -391,7 +391,7 @@ def test_a_harness_run_that_picked_a_round_before_its_judge_went_down_is_scored(
battery = Battery.load(BATTERY)
ev = FakeEvaluator()
- r = run_cell(battery, battery.prompts[0], parse_arm("harness:gemini-cli:gemini-3.8-flash"), tmp_path,
+ r = run_cell(battery, battery.prompts[0], parse_arm("harness:agy:gemini-3.8-flash"), tmp_path,
CompareOptions(judge="gemini:x", loop_judge="gemini:x"), CompareDeps(ev, run_track=judged_then_down))
assert r.status == "scored" and ev.evaluated, r
@@ -416,7 +416,7 @@ def test_bare_agent_provider_failure_with_a_partial_file_is_not_a_quality_zero(t
monkeypatch.setattr('bench._bare_agent.run_bare_agent', interrupted)
battery=Battery.load(BATTERY)
evaluator=FakeEvaluator()
- result=run_cell(battery,battery.prompts[0],parse_arm('agent:gemini-cli:gemini-3.8-flash'),
+ result=run_cell(battery,battery.prompts[0],parse_arm('agent:agy:gemini-3.8-flash'),
tmp_path,CompareOptions(judge='gemini:x',loop_judge='gemini:x'),CompareDeps(evaluator))
if outage and reason == 'error':
assert (result.status,result.score,result.error_is_infra)==('infra_failed',None,True)
diff --git a/eval/tests/test_paired_compare.py b/eval/tests/test_paired_compare.py
index 8fe4f207..449cecab 100644
--- a/eval/tests/test_paired_compare.py
+++ b/eval/tests/test_paired_compare.py
@@ -15,7 +15,7 @@ from bench._jsonl import latest # noqa: E402
from bench.paired_compare import analyse, main, paired, rows_from_bench_run # noqa: E402
from bench.stats import t975 # noqa: E402
-HA, OA = "harness:gemini-cli:gemini-3.6-flash", "oneshot:gemini:x"
+HA, OA = "harness:agy:gemini-3.6-flash", "oneshot:gemini:x"
def _cell(pid: str, arm: str, score: float | None, *, tier: str = "hard", status: str = "scored",
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
index 93a199f9..bddb4ef3 100644
--- a/harness/CLAUDE.md
+++ b/harness/CLAUDE.md
@@ -4,8 +4,8 @@ Backend harness (python package `codeverse3d`, CLI `3dcodeverse` / short alias `
repo path `/home/yipeng/3dcodeverse/harness`) for LLM-written **raw** 3D code:
Blender bpy · CadQuery · Three.js · URDF · GLSL / OpenGL, across four tracks
(`static_object`, `articulated_object`, `scene`, `graphics`), with pluggable
-backends. **The coding agent is always a VENDOR's** — gemini-cli / claude-code /
-codex / antigravity — and the harness supplies the workspace, the prompt and the
+backends. **The coding agent is always a VENDOR's** — antigravity (`agy`, Google's
+models) / claude-code / codex — and the harness supplies the workspace, the prompt and the
3D tools its track can use (over MCP; 16 in the registry, filtered per track — D48
review), then reads the result. The harness's OWN api use is planning,
judging, single-shot file generation and the texture pass (Gemini/Anthropic/OpenAI).
@@ -61,17 +61,16 @@ push, with `set -o pipefail` so a `| tail` cannot swallow a red exit. The versi
(`spatial.node.run_node(three_hook=True)`) — `NODE_PATH` alone does not work;
that hook is `module.registerHooks` on node ≥ 22.15, `module.register` below.
The `graphics` track renders with moderngl (d3d12 GPU context, llvmpipe fallback).
-- CLIs: `gemini` 0.53 (api-key auth + `dynamicModelConfiguration` + `folderTrust.enabled=false`
- via the system settings file the harness writes — else it silently substitutes models /
- drops workspace MCP servers), `codex` 0.147+ (MCP needs
- `default_tools_approval_mode="approve"`), `claude` 2.1, `agy` 1.1 — the last three run
- on local subscriptions: test lightly. No Anthropic/OpenAI API keys here.
-- Main test model: `gemini-3.7-flash` — and since 2026-08-28 it is also the DEFAULT
- generator (`gemini-cli:gemini-3.7-flash`), verified live through the harness on both
- vendor paths: gemini-cli completes and is not silently substituted, and `agy` 1.1.22
- lists and serves `gemini-3.7-flash-{high,medium,low}`. A BARE `gemini -m ...` is
- substituted down to 3.5-flash — the harness's per-session system settings file is
- what prevents that, so never judge model availability with a raw CLI probe.
+- CLIs: `agy` 1.3.4 (Antigravity; gemini-cli was deleted in D103, 2026-10-13) — an `agy:gemini-*`
+ session runs in Gemini-API mode: one key from the shared pool, a per-session HOME carrying
+ `modelProvider: gemini` + the 3dcode MCP server, priced; without keys, or for a non-Gemini model,
+ it runs on the local subscription sign-in with no MCP. `codex` 0.147+ (MCP needs
+ `default_tools_approval_mode="approve"`) and `claude` 2.1 run on local subscriptions: test
+ lightly. No Anthropic/OpenAI API keys here.
+- Main test model: `gemini-3.7-flash` — also the DEFAULT generator, `agy:gemini-3.7-flash`
+ since 2026-10-13 (D103; `gemini-cli:` from 2026-08-28), verified live through agy's API mode
+ (which lists gemini-3.8/3.7/3.6-flash and 3.1-pro; the subscription sign-in no longer serves
+ 3.7-flash, so never judge model availability by a sign-in probe).
(lenient judge; needs the defect checklist for
range). Judge default `gemini-3.1-pro-preview` (`Settings.default_judge`; tracks use
n_samples=1); flash + `--n 3` is the cheap fallback, pro for calibration/eval.
@@ -87,7 +86,7 @@ cd /home/yipeng/3dcodeverse/harness
3dcodeverse doctor [--live] [--no-gpu] [--json]
3dcodeverse make "a mid-century wooden dining chair" --track static_object --language blender
3dcodeverse make "..." --profile economy|balanced|quality # one dial: models, judge n, rounds, candidates, texture, ceilings (--profile == C3D_PROFILE)
-3dcodeverse make "..." --track static_object --language threejs --generator gemini-cli:gemini-3.7-flash
+3dcodeverse make "..." --track static_object --language threejs --generator agy:gemini-3.7-flash
3dcodeverse make "..." --track articulated_object --language urdf_blender
3dcodeverse make "..." --track scene --language scene_threejs --rounds 2 --max-minutes 60
3dcodeverse make "neon rain on a window" --track graphics --language glsl_shader
@@ -105,7 +104,7 @@ cd /home/yipeng/3dcodeverse/harness
(cd ../eval && python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-3.1-pro-preview) # report: python -m bench.report bench/out/<battery>
python -m codeverse3d.addons.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/
python ../eval/bench/complexity_report.py ../eval/bench/out --recursive # score-vs-complexity + $/complexity point (eval/docs/COMPLEXITY.md)
-python ../eval/bench/compare_backends.py --prompts ../eval/bench/prompts/compare_v1.yaml --arms harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out ../eval/bench/out/compare_v1
+python ../eval/bench/compare_backends.py --prompts ../eval/bench/prompts/compare_v1.yaml --arms harness:agy:gemini-3.6-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out ../eval/bench/out/compare_v1
python -m tests.prompts.manifest [--bless | --dump DIR] # what every model is shown, pinned (RUNBOOK §8): bless only a change a model is MEANT to see
python -m pytest tests -q -m "not live" # the offline suite (real Blender + headless Chrome + CadQuery)
python -m pytest tests -q -m "not live and not blender and not node" # pure python (the bench tests: `cd ../eval && python -m pytest`)
diff --git a/harness/codeverse3d/__init__.py b/harness/codeverse3d/__init__.py
index b68630bd..6608d63c 100644
--- a/harness/codeverse3d/__init__.py
+++ b/harness/codeverse3d/__init__.py
@@ -13,8 +13,8 @@ Package map (each sub-package has its own docstring):
- ``contracts`` pydantic models shared by everything (Spec, Plan, Gate,
Judgment, Usage, RunRecord ...). No logic lives here.
- ``models`` ChatModel backends: Gemini / Anthropic / OpenAI (+ key pool).
-- ``agents`` CodingAgent backends: the vendor CLIs — gemini-cli /
- claude-code / codex / antigravity.
+- ``agents`` CodingAgent backends: the vendor CLIs — antigravity (agy,
+ Google's models) / claude-code / codex.
- ``languages`` LanguageRuntime per raw language: lint, build, export.
- ``spatial`` language-agnostic 3D tools on GLB/scene: measure, render,
slice, isolate, silhouette, joints, probes — also served as
diff --git a/harness/codeverse3d/agents/__init__.py b/harness/codeverse3d/agents/__init__.py
index 7f4ef72b..eb8ffb0d 100644
--- a/harness/codeverse3d/agents/__init__.py
+++ b/harness/codeverse3d/agents/__init__.py
@@ -1,7 +1,6 @@
"""CodingAgent backends (agentic sessions on a workspace).
-Ids: ``gemini-cli:<model>`` · ``claude-code:<model>`` · ``codex:<model>`` ·
-``agy:<model>``.
+Ids: ``agy:<model>`` (Google's models) · ``claude-code:<model>`` · ``codex:<model>``.
"""
from codeverse3d.agents.registry import get_coding_agent
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index 7febd908..93abb412 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -1,33 +1,10 @@
-"""``gemini-cli:<model>`` — headless Gemini CLI session on a workspace.
-
-argv: ``gemini -m <model> --approval-mode yolo --skip-trust --output-format json`` with the
-prompt on stdin (every backend: ``cli_common.invoke``).
-
-* 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), ``skills.enabled`` with the CLI's own built-in skills disabled, the 3dcode
- MCP server and ``mcp.allowed``, Node heap cap, no self-relaunch.
-* gemini-cli's own chat record of the attempt (``~/.gemini/tmp/<project>/chats/
- session-*.jsonl``, found by ``gemini_chat_records``) is read once (``read_gemini_chats``):
- its tool calls become the transcript's ``tool_call`` rows (``cli_common.record_tool_calls``;
- ``--output-format json`` carries only per-tool COUNTS), and its per-message tokens are the
- usage of an attempt that printed no envelope — the CLI prints its JSON once, at the end,
- so a session the watchdog killed printed nothing, and one that gave up on a 503 printed
- only an error object on stderr with no stats (every gemini-cli session of the 2026-09-22
- live runs, booked at $0 before this). ``stream-json`` would cost the per-model
- ``thoughts`` tokens pricing needs.
-* 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``.
-* provider wait: the CLI's own stderr line for each API attempt it retries, timed as it
- arrives, against the chat record's message times (``cli_common.provider_wait``).
-* one retry (rotated key when the pool has one, else the same key) on transient
- failures (503 / empty response), two on a rate-limit 429; a throttled/empty pool never raises.
+"""The three vendor CLI backends: ``claude-code:<model>``, ``codex:<model>``, ``agy:<model>``.
+
+Each one runs ONE headless session with the prompt on stdin (``cli_common.invoke``), reads its
+CLI's own wire format back into an ``AgentResult`` and leaves retrying to the CLI itself: the
+harness never loops over a session (one round-level transport retry lives in
+``tracks/lifecycle``). Google's models go through ``agy`` — Antigravity in Gemini-API mode,
+one key per session from the shared pool (see the antigravity section).
"""
from __future__ import annotations
@@ -38,10 +15,9 @@ import json
import logging
import os
import re
+import shutil
import sqlite3
import time
-from collections.abc import Iterable, Mapping
-from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Any
@@ -72,238 +48,13 @@ from codeverse3d.contracts.agent import AgentJob, AgentResult
from codeverse3d.contracts.common import Usage
from codeverse3d.models.pricing import EFFORTS, cache_write_surcharge, estimate_cost, openai_usage
from codeverse3d.models.retry import KeyPool, KeyPoolExhausted
-from codeverse3d.proc import read_jsonl_lenient, run_subprocess
+from codeverse3d.proc import run_subprocess
log = logging.getLogger(__name__)
-#: the skills gemini-cli 0.53 ships in its own install (``bundle/builtin/``): listed to the model
-#: next to the routed bundles, and ``skills.disabled`` is the only switch — by name (2026-09-22).
-#: The user-level roots (``~/.gemini/skills``, ``~/.agents/skills``) have no settings switch at
-#: all; none exist on this machine.
-GEMINI_BUILTIN_SKILLS = ("skill-creator", "antigravity-support")
-
-SYSTEM_SETTINGS = {
- # folderTrust must be OFF: with it on, gemini-cli silently disables the workspace
- # .gemini/settings.json mcpServers (even with --skip-trust) → no 3dcode tools. It is
- # also what keeps the WORKSPACE skill roots visible: 0.53's SkillManager.discoverSkills
- # skips <ws>/.gemini/skills and <ws>/.agents/skills when the folder is not trusted, and
- # isTrustedFolder() is true exactly when folderTrust is off.
- "security": {"auth": {"selectedType": "gemini-api-key"}, "folderTrust": {"enabled": False}},
- "experimental": {"dynamicModelConfiguration": True},
- "general": {"topicUpdateNarration": False},
- # default true in 0.53, but a user's ~/.gemini/settings.json (or an agent-written
- # ws/.gemini/settings.json) could turn it off; this file is merged LAST, so the routed
- # bundles stay indexed and ``activate_skill`` stays registered (2026-09-22). The
- # CLI's own built-ins are off: a session sees the bundles the harness routed, nothing else
- "skills": {"enabled": True, "disabled": list(GEMINI_BUILTIN_SKILLS)},
-}
-#: gemini-cli's skill-activation tool (0.53: ``activate_skill``, arg ``name``); the body
-#: comes back in the tool result, so its call — not a file read — is the activation
-GEMINI_SKILL_TOOL = "activate_skill"
-#: how long a retry waits for a *different* healthy key before reusing the same one
-RETRY_KEY_WAIT_S = 10.0
-#: attempts allowed when the failure is a quota 429 (transient non-quota failures keep 2)
-QUOTA_MAX_ATTEMPTS = 3
-
-
-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 cooldowns and dead-key bench the API path uses (a session takes its key with
- ``session_key``: no in-flight slot). This module used to build its own
- ``KeyPool(keys)`` with library defaults, so the CLI agent and the API path scheduled
- the same 22 keys under two different quotas (found by review 2026-08-28)."""
- from codeverse3d.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
- 3dcode 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 (indented, multi-line) JSON object, possibly after log noise."""
- return find_json_object(stdout, lambda d: True)
-
-
-def gemini_chat_records(ws_root: Path, since: float, env: Mapping[str, str] | None = None) -> list[Path]:
- """gemini-cli's OWN record of the sessions it ran in ``ws_root`` since ``since`` (epoch s).
-
- 0.53 appends every session to ``<home>/.gemini/tmp/<project>/chats/session-<ts>-<id8>.jsonl``
- (``<home>`` is ``GEMINI_CLI_HOME`` or ``~``) and names the project dir's workspace in its
- ``.project_root``. Found by that marker plus mtime rather than by ``session_id``: a
- session the watchdog killed printed no JSON envelope, and its record is still on disk.
- Sessions on one workspace are serialised (``cli_common.EXCLUSIVE_KINDS``), so every
- record written after ``since`` is this session's."""
- home = Path((env if env is not None else os.environ).get("GEMINI_CLI_HOME") or Path.home())
- want = {str(ws_root), str(Path(ws_root).resolve())}
- for marker in (home / ".gemini" / "tmp").glob("*/.project_root"):
- try:
- if marker.read_text().strip() not in want:
- continue
- except OSError:
- continue
- return sorted(p for p in (marker.parent / "chats").rglob("session-*.json*")
- if p.is_file() and p.stat().st_mtime >= since)
- return []
-
-
-class GeminiChatLog:
- """What gemini-cli's own chat records of one attempt hold: its tool calls, each served
- model's tokens (``tokens`` in the envelope's ``stats.models`` shape) and when each
- message landed (epoch seconds — the session's progress, for ``provider_wait``)."""
-
- calls: list[ToolCall]
- tokens: dict[str, dict[str, int]]
- times: list[float]
-
- def stats(self) -> dict[str, Any]:
- return {"models": {m: {"tokens": t} for m, t in self.tokens.items()}}
-
-
-def read_gemini_chats(records: Iterable[Path]) -> GeminiChatLog:
- """One pass over the chat records. The record is append-only — a message is re-written
- as it progresses — so every tool call counts once per call id and every model message
- once per message id, the last copy winning. A model message's ``tokens`` are the API's
- own usage metadata (``input`` = promptTokenCount, the TOTAL prompt), so their sum is the
- envelope's ``stats.models`` to the token: checked on two completed sessions of the
- 2026-09-22 live runs (917 248 / 704 375 cached / 18 767 / 5 306, and 1 056 300 / 907 666
- / 5 464 / 5 047). What it misses: a utility call outside the main chat (none in either)
- and a subagent's own record (``chats/<session id>/``; none on this machine)."""
- calls: dict[str, ToolCall] = {}
- replies: dict[str, dict[str, Any]] = {}
- times: list[float] = []
- for path in records:
- for row in read_jsonl_lenient(path, dicts_only=True):
- update = row.get("$set") if isinstance(row.get("$set"), dict) else {}
- for msg in (row, *(update.get("messages") or [])):
- if not isinstance(msg, dict):
- continue
- if msg.get("timestamp"):
- with contextlib.suppress(TypeError, ValueError):
- times.append(datetime.fromisoformat(str(msg["timestamp"]).replace("Z", "+00:00")).timestamp())
- if msg.get("type") == "gemini" and msg.get("id"):
- replies[str(msg["id"])] = msg
- for tc in msg.get("toolCalls") or []:
- if not isinstance(tc, dict):
- continue
- name = str(tc.get("name") or "")
- args = tc.get("args") if isinstance(tc.get("args"), dict) else {}
- calls[str(tc.get("id") or f"{path.name}#{len(calls)}")] = ToolCall(
- tool=name, args=args, skill=str(args.get("name") or "") if name == GEMINI_SKILL_TOOL else "",
- failed=tc.get("status") in ("error", "cancelled"))
- tokens: dict[str, dict[str, int]] = {}
- for msg in replies.values():
- tok = msg.get("tokens") if isinstance(msg.get("tokens"), dict) else None
- if not tok:
- continue # a reply the session died in the middle of: never counted
- t = tokens.setdefault(str(msg.get("model") or ""), {"prompt": 0, "cached": 0, "candidates": 0, "thoughts": 0})
- for ours, theirs in (("prompt", "input"), ("cached", "cached"), ("candidates", "output"), ("thoughts", "thoughts")):
- t[ours] += int(tok.get(theirs) or 0)
- return GeminiChatLog(calls=list(calls.values()), tokens=tokens, times=sorted(set(times)))
-
-
-#: what gemini-cli 0.53 prints on stderr for each failed API attempt it is about to retry — with
-#: the HTTP status when it has one ("... with status 503", "... with 5xx error"), with the delay
-#: when the server named one ("Retrying after 2500ms") — and the first line of its give-up
-_GEMINI_RETRY_LINE = re.compile(r"Attempt \d+ failed(?: with status (?P<status>\d{3})| with (?P<kind>429|5xx) error)?"
- r"(?:.*Retrying after (?P<ms>\d+)ms)?")
-_GEMINI_GIVE_UP = "Error when talking to Gemini API"
-
-
-class GeminiRetries:
- """gemini-cli's own report of its failed API attempts, timed as its stderr lines arrive:
- ``rows`` = ``(t, announced back-off s, status)`` — ``"503"`` / ``"429"`` / ``"5xx"``,
- ``"network"`` for a transport failure ("fetch failed"), ``"gave up"`` for the last line."""
-
- def __init__(self) -> None:
- self.rows: list[tuple[float, float, str]] = []
-
- def feed(self, line: str) -> None:
- m = _GEMINI_RETRY_LINE.search(line)
- if m:
- status = m.group("status") or m.group("kind") or "network"
- self.rows.append((time.time(), int(m.group("ms") or 0) / 1000.0, status))
- elif _GEMINI_GIVE_UP in line:
- self.rows.append((time.time(), 0.0, "gave up"))
-
- def tally(self) -> str:
- """``4 x 503, 2 x network`` — what the storm was made of."""
- counts: dict[str, int] = {}
- for _, _, status in self.rows:
- counts[status] = counts.get(status, 0) + 1
- return ", ".join(f"{n} x {k}" for k, n in counts.items())
-
-
-def gemini_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 = gemini_model_usage((m or {}).get("tokens") or {}, str(name))
- c = estimate_cost("gemini", str(name), part)
- if c == 0.0 and name != model and (part.input_tokens or part.output_tokens):
- c = estimate_cost("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.session_key(exclude=exclude or None, timeout_s=RETRY_KEY_WAIT_S)
- except KeyPoolExhausted:
- continue
- return None
-
class _CliAgent:
- """What all four vendor backends share.
+ """What the vendor backends share.
Everything that MATTERS about a CLI backend differs — argv vocabulary, JSON wire
format, usage/pricing shape, key handling — and stays in the subclass. What they
@@ -327,195 +78,8 @@ class _CliAgent:
return True, "ok"
-class GeminiCliAgent(_CliAgent):
- kind = "gemini-cli"
- cli_label = "gemini"
-
- def __init__(self, model: str, binary: str | None = None):
- self.model = model
- self.binary = binary or get_settings().binaries.gemini_cli
-
- def available(self) -> tuple[bool, str]:
- ok, why = super().available()
- if not ok:
- return ok, why
- if not get_settings().gemini_api_keys:
- return False, "no Gemini API keys configured" # the only backend with a key pool
- return True, "ok"
-
- # ------------------------------------------------------------------ build
- def build_argv(self) -> list[str]:
- """No ``-p``: the prompt comes on stdin, and a piped stdin is what makes 0.53 headless
- (``isHeadlessMode``); with no ``-p`` the input IS the stdin text, byte for byte."""
- return [self.binary, "-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 = _compose_prompt(job)
- pool = _key_pool(get_settings().gemini_api_keys)
- try:
- key = pool.session_key() # no in-flight slot: the CLI makes its own calls
- 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)
- wait_s, retry_from, usage_from = 0.0, 0.0, []
- while True:
- attempts += 1
- used.add(key)
- started, env = time.time(), self.build_env(s, key)
- if retry_from: # rotating off a failed key is time the provider cost, too
- wait_s += max(0.0, started - retry_from)
- retries = GeminiRetries()
- proc = invoke(s, self.build_argv(), env, prompt=prompt, attempt=attempts, soft_timeout_s=next_soft,
- on_stderr=retries.feed, model=self.model, key_tail=key[-4:])
- ended = time.time()
- outcome = self._interpret(proc, retries, self._read_record(s, started, env), started, ended)
- usage_total = usage_total + outcome.usage
- usage_from.append(outcome.usage_source)
- wait_s += outcome.wait_s
- # the pool is shared with every API call: a hang, a substituted model or the
- # agent's own failure is not the key's fault ("skip" = counters untouched).
- # session_key took no in-flight slot, so there is nothing to release.
- pool.report(key, "429" if outcome.rate_limited else "ok" if outcome.ok
- else "5xx" if outcome.transient else "skip")
- # a per-minute 429 on the single key a CLI process holds clears within the
- # rotated retry's wait; ab_fewer_turns (2026-08-29) lost 4 of 10 cells to
- # two 429s in a row, so a rate-limited failure gets one more rotated attempt
- max_attempts = QUOTA_MAX_ATTEMPTS if outcome.rate_limited else 2
- if (outcome.ok or outcome.exit_reason in ("timeout", "model_substituted") or not outcome.transient
- or attempts >= max_attempts):
- 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
- retry_from = time.time()
- 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)
- # turns stays 0: gemini-cli's stats carry tools.totalCalls only, no turn count
- 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,
- transient=outcome.transient and not outcome.ok, quota=outcome.quota, provider_wait_s=wait_s,
- attempts=attempts, rc=proc.rc, killed_reason=proc.killed_reason, session_id=outcome.session_id,
- usage_from=usage_from, # per attempt: envelope | chat record | none
- )
- finally:
- release_session(s)
-
- def _read_record(self, s: Session, started: float, env: Mapping[str, str]) -> GeminiChatLog | None:
- """This attempt's chat record, its tool calls written as the transcript's trace — never fatal."""
- try:
- records = gemini_chat_records(s.ws.root, started, env)
- if not records:
- s.notes.append("no gemini-cli chat record found for this attempt: tool trace missing")
- return None
- chat = read_gemini_chats(records)
- record_tool_calls(s, chat.calls, source="gemini-cli chat record")
- return chat
- except Exception as e: # noqa: BLE001 — the trace is telemetry; a session must never fail on it
- log.debug("gemini-cli chat record unreadable: %s", e)
- return None
-
- def _interpret(self, proc: CompletedProc, retries: GeminiRetries, chat: GeminiChatLog | None,
- started: float, ended: float) -> _GeminiAttempt:
- parsed = parse_gemini_json(proc.stdout)
- stats = (parsed or {}).get("stats") or {}
- out = _GeminiAttempt(usage=Usage(backend=self.kind, model=self.model), text=str((parsed or {}).get("response") or ""),
- session_id=str((parsed or {}).get("session_id") or ""))
- if stats:
- out.usage, out.usage_source = usage_from_stats(stats, self.model), "envelope"
- elif chat is not None and chat.tokens:
- # no envelope — the CLI prints its JSON once, at the end: a session the watchdog killed
- # printed none, and one that gave up printed an error object on stderr with no stats.
- # Its chat record holds every reply's tokens; the envelope, when there is one, wins.
- out.usage, out.usage_source = usage_from_stats(chat.stats(), self.model), "chat record"
- out.usage.tool_calls = len(chat.calls)
- out.usage.latency_ms = int(proc.duration_s * 1000)
- # without the record's message times there is no telling a storm from the work around
- # it (every failure would run to the end): unknown, so 0.0
- out.wait_s = provider_wait([(t, b) for t, b, _ in retries.rows], ended, [started, *chat.times]) if chat else 0.0
- text = out.text.strip()
- served = list((stats.get("models") or {}).keys())
- if proc.timed_out:
- # the CLI retries 503s itself, with backoff, and never gives up before our wall:
- # measured 2026-09-07, 8-17 "Attempt N failed with status 503" per 12-minute
- # session, nothing produced. That is a storm, not the task.
- end = classify_end(proc, ok=False, text=text, provider_retried=bool(retries.rows))
- out.errors.append(watchdog_error(proc))
- if end.transient:
- out.errors.append(f"{retries.tally()} inside the CLI's own retry loop before the wall; nothing produced")
- elif served and self.model not in served:
- out.exit_reason = "model_substituted"
- out.errors.append(f"requested {self.model!r} but CLI served {served}")
- return out
- elif parsed is None or proc.rc != 0 or not text:
- # the CLI's own give-up object (stderr: {"session_id", "error": {"type", "message", "code"}}),
- # else whatever it printed before it died
- gave_up = find_json_object(proc.stderr, lambda d: isinstance(d.get("error"), dict))
- err = (gave_up or {}).get("error") or {}
- said = f"{err.get('code', '')} {err.get('type', '')}: {err.get('message', '')}" if err else proc.stderr + proc.stdout
- out.session_id = out.session_id or str((gave_up or {}).get("session_id") or "")
- end = classify_end(proc, ok=False, text=text, said=(said,), provider_failed=parsed is not None and not text,
- rate_limited=err.get("code") == 429 if err else None)
- out.errors.append(f"rc={proc.rc}; response={'<empty>' if not text else 'ok'}; stderr tail: {proc.stderr[-1500:]}")
- else:
- end = classify_end(proc, ok=True, text=text)
- out.ok = True
- out.exit_reason, out.transient, out.quota, out.rate_limited = end.exit_reason, end.transient, end.quota, end.rate_limited
- return out
-
-
-class _GeminiAttempt:
- """One gemini-cli invocation, read: its envelope when it printed one, else its chat record."""
-
- usage: Usage
- text: str = ""
- session_id: str = ""
- ok: bool = False
- exit_reason: str = "error"
- errors: list[str] = dataclasses.field(default_factory=list)
- transient: bool = False
- quota: bool = False
- rate_limited: bool = False # a 429: the key cools down in the pool, the retry rotates
- wait_s: float = 0.0
- usage_source: str = "none" # envelope | chat record | none
-
-
def _compose_prompt(job: AgentJob) -> str:
- """gemini-cli and codex have no system-prompt flag: prepend ``system_append``."""
+ """codex and agy 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}"
@@ -1029,6 +593,15 @@ def resolve_model(model: str, binary: str) -> str:
return model
+def api_model_effort(model: str) -> tuple[str, str]:
+ """``gemini-3.7-flash-low`` → ``('gemini-3.7-flash', 'low')``; a bare id runs at
+ ``AGY_API_EFFORT`` — the agy spelling of an effort is accepted so either id works."""
+ for effort in EFFORTS:
+ if model.endswith(f"-{effort}"):
+ return model[: -len(effort) - 1], effort
+ return model, AGY_API_EFFORT
+
+
def parse_agy_json(stdout: str) -> dict[str, Any] | None:
"""agy's envelope is the JSON line carrying ``response`` or ``status``."""
return find_json_object(stdout, lambda d: "response" in d or "status" in d)
@@ -1036,9 +609,25 @@ def parse_agy_json(stdout: str) -> dict[str, Any] | None:
#: the per-session CLI log agy writes into the trajectory dir (``--log-file``)
AGY_LOG = "agy.log"
-#: where agy 1.2.2 keeps each conversation: one SQLite file named by the envelope's
+#: where agy keeps each conversation under its HOME: one SQLite file named by the envelope's
#: ``conversation_id``, a ``steps`` table whose ``step_payload`` is protobuf
-AGY_CONVERSATIONS = Path.home() / ".gemini" / "antigravity-cli" / "conversations"
+AGY_CONVERSATIONS = Path(".gemini") / "antigravity-cli" / "conversations"
+#: agy's Gemini-API mode (1.2+, checked live on 1.3.4, 2026-10-13): ``modelProvider: "gemini"``
+#: in its settings plus ``GEMINI_API_KEY`` in the env — no sign-in, billed to the key, and the
+#: catalogue is the API's (gemini-3.7-flash, 3.6-flash, 3.1-pro, …). Without the setting the
+#: key alone is ignored and the CLI asks for a login.
+AGY_SETTINGS = Path(".gemini") / "antigravity-cli" / "settings.json"
+AGY_API_SETTINGS = {"modelProvider": "gemini"}
+#: in API mode ``--model gemini-api://<id>`` sends ``<id>`` to the API verbatim — any model the
+#: key serves, listed by ``agy models`` or not (gemini-4-argon) — and ``--effort`` sets its
+#: thinking level (low → 1, high → 3 in the CLI log, 2026-10-13)
+AGY_API_SCHEME = "gemini-api://"
+#: the effort an API-mode id without a ``-low/-medium/-high`` suffix runs at: the Gemini API's
+#: own default thinking level, which every gemini-cli session ran at before agy replaced it
+AGY_API_EFFORT = "high"
+#: agy's ONLY MCP config is per user (``~/.gemini/config/mcp_config.json``, the shape
+#: ``agy mcp add`` writes) — so an API-key session gets a HOME of its own, and this file in it
+AGY_MCP_CONFIG = Path(".gemini") / "config" / "mcp_config.json"
#: a tool call inside a step payload is three consecutive strings — its id, the tool name,
#: the JSON arguments (``call_4419682`` · ``view_file`` · ``{"AbsolutePath": ...}``), read out
#: of recorded conversations; no schema needed, and a tool result step that echoes the
@@ -1159,20 +748,55 @@ def agy_error(stderr: str) -> dict[str, Any]:
return {}
-def usage_from_agy(env: dict[str, Any], model: str) -> Usage:
+def usage_from_agy(env: dict[str, Any], model: str, *, priced: bool) -> Usage:
+ """The envelope's tokens; priced at the Gemini list rate when the session ran on an API
+ key (``priced``), ``$0`` on a subscription sign-in, which exposes no USD. agy 1.3.4 splits
+ neither way the pricing convention does: ``input_tokens`` EXCLUDES ``cache_read_tokens`` (a
+ live 18-minute session, 2026-10-13: 582 179 input against 10 980 664 cache reads), so the total
+ prompt is their sum; and ``output_tokens`` CONTAINS ``thinking_tokens`` (``total == input +
+ output`` on every envelope), so the thinking share moves to ``thoughts_tokens``, billed once."""
u = env.get("usage") or {}
- return Usage(
+ thinking = int(u.get("thinking_tokens") or 0)
+ cached = int(u.get("cache_read_tokens") or 0)
+ out = 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
+ input_tokens=int(u.get("input_tokens") or 0) + cached,
+ output_tokens=max(0, int(u.get("output_tokens") or 0) - thinking),
+ cached_tokens=cached,
+ thoughts_tokens=thinking,
latency_ms=int(float(env.get("duration_seconds") or 0.0) * 1000),
)
+ out.cost_usd = estimate_cost("gemini", model, out) if priced else 0.0
+ return out
+
+
+def _key_pool() -> KeyPool:
+ """THE process-wide Gemini pool — ``models.gemini.shared_pool``: the same cooldowns and
+ dead-key bench the API path uses; a session takes its key with ``session_key`` (no
+ in-flight slot: the CLI makes its own calls for minutes)."""
+ from codeverse3d.models.gemini import shared_pool
+
+ return shared_pool(list(get_settings().gemini_api_keys))
+
+
+def _pool_outcome(end: SessionEnd, ok: bool, died: dict[str, Any]) -> str:
+ """What one session tells the pool about its key. A hang, a bad answer or the agent's own
+ failure is not the key's fault (``skip``: counters untouched)."""
+ code = died.get("error_code")
+ if code in (401, 403) or "API_KEY_INVALID" in json.dumps(died):
+ return "dead"
+ if end.rate_limited:
+ return "429"
+ return "ok" if ok else "5xx" if end.transient else "skip"
class AntigravityAgent(_CliAgent):
+ """``agy:<model>``. A Gemini model with keys configured runs in Gemini-API mode: one pool key,
+ a HOME of its own under the cache dir holding the API-mode settings and the 3dcode MCP server
+ (deleted after the session; the tool trace is read out first), usage priced. Anything else —
+ a non-Gemini model agy serves (``claude-sonnet-4-6``), or no keys — runs on the machine's
+ subscription sign-in: real HOME, no MCP (the body documents the shell fallback), ``$0``."""
+
kind = "agy"
cli_label = "agy"
@@ -1180,29 +804,61 @@ class AntigravityAgent(_CliAgent):
self.model = model
self.binary = binary or get_settings().binaries.agy_cli
+ @property
+ def api_mode(self) -> bool:
+ return self.model.startswith("gemini") and bool(get_settings().gemini_api_keys)
+
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)
+ """The model id the session is booked under: the API model in API mode, else the id
+ sent to agy (a bare one gains its effort suffix)."""
+ return api_model_effort(self.model)[0] if self.api_mode else resolve_model(self.model, self.binary)
+
+ def model_args(self) -> list[str]:
+ if not self.model:
+ return []
+ if self.api_mode:
+ name, effort = api_model_effort(self.model)
+ return ["--model", f"{AGY_API_SCHEME}{name}", "--effort", effort]
+ return ["--model", self.served_model()]
def build_argv(self, s: Session) -> list[str]:
- """No ``--print``: agy 1.2.8 reads the prompt from a piped stdin, byte for byte, and
- still answers as print mode (``--print -`` would send the prompt "-"). ``--log-file``
- keeps its CLI log with the session — the record of the retries it made."""
+ """No ``--print``: agy reads the prompt from a piped stdin, byte for byte, and still
+ answers as print mode (``--print -`` would send the prompt "-"). ``--log-file`` keeps
+ its CLI log with the session — the record of the retries it made."""
minutes = max(1, int(s.job.timeout_s // 60) + 1)
- argv = [self.binary, "--dangerously-skip-permissions",
+ return [self.binary, "--dangerously-skip-permissions",
"--print-timeout", f"{minutes}m", "--output-format", "json",
- "--add-dir", str(s.ws.root), "--disable-slash-commands", "--log-file", str(s.traj.dir / AGY_LOG)]
- 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)
+ "--add-dir", str(s.ws.root), "--disable-slash-commands", "--log-file", str(s.traj.dir / AGY_LOG),
+ *self.model_args()]
+
+ def build_home(self, s: Session) -> Path:
+ """A fresh HOME for one API-mode session: the API-mode settings and, when the job has
+ spatial tools, the 3dcode MCP server — which keeps the REAL home (the harness reads its
+ settings, keys and caches from there)."""
+ home = get_settings().cache_dir / "agy_homes" / f"{s.traj.dir.name}-{os.getpid()}-{time.time_ns()}"
+ (home / AGY_SETTINGS).parent.mkdir(parents=True, exist_ok=True)
+ (home / AGY_SETTINGS).write_text(json.dumps(AGY_API_SETTINGS))
+ servers: dict[str, Any] = {}
+ if s.job.spatial_tools:
+ cmd = mcp_command_for(s.ws, s.job)
+ servers[MCP_SERVER_NAME] = {"command": cmd[0], "args": cmd[1:], "env": {"HOME": str(Path.home())}}
+ (home / AGY_MCP_CONFIG).parent.mkdir(parents=True, exist_ok=True)
+ (home / AGY_MCP_CONFIG).write_text(json.dumps({"mcpServers": servers}, indent=2))
+ return home
+
+ def build_env(self, s: Session, *, key: str = "", home: Path | None = None) -> dict[str, str]:
+ env = hardened_env(s.ws, s.job)
+ if key and home is not None:
+ env["GEMINI_API_KEY"] = key
+ env["HOME"] = str(home)
+ # the agent's own shell inherits the fake HOME: keep puppeteer on the real Chrome cache
+ env.setdefault("PUPPETEER_CACHE_DIR", str(Path.home() / ".cache" / "puppeteer"))
+ return env
- def _record_trace(self, s: Session, conversation_id: str) -> int:
+ def _record_trace(self, s: Session, home: Path, conversation_id: str) -> int:
"""The session's tool calls, from agy's own conversation database — never fatal.
Returns how many (agy's JSON envelope carries no tool count of its own)."""
- db = AGY_CONVERSATIONS / f"{conversation_id}.db" if conversation_id else None
+ db = home / AGY_CONVERSATIONS / f"{conversation_id}.db" if conversation_id else None
if db is None or not db.is_file():
s.notes.append("no agy conversation record found for this session: tool trace missing")
return 0
@@ -1214,25 +870,38 @@ class AntigravityAgent(_CliAgent):
def run(self, job: AgentJob) -> AgentResult:
"""``usage`` comes from agy's envelope only: a killed session books nothing (its
- conversation database is named by the envelope's id). ``provider_wait_s`` from its log."""
+ conversation database is named by the envelope's id). ``provider_wait_s`` from its log.
+ No retry loop: agy retries its own model calls (waits ≤ 30 s since 1.3.4, stops at once
+ on a spent daily quota), and a transient death goes back to the round loop's one retry —
+ which takes a fresh key, the 429'd one cooling in the pool."""
ok, why = self.available()
s = begin_session(job, self.kind)
+ key, home = "", None
try:
if not ok:
return failed(s, "error", why)
- proc = invoke(s, self.build_argv(s), self.build_env(s), prompt=_compose_prompt_agy(s))
+ if self.api_mode:
+ pool = _key_pool()
+ try:
+ key = pool.session_key()
+ except KeyPoolExhausted as e: # every key throttled for the whole wait budget
+ return failed(s, "budget", f"Gemini key pool exhausted: {e}")
+ home = self.build_home(s)
+ proc = invoke(s, self.build_argv(s), self.build_env(s, key=key, home=home), prompt=_compose_prompt_agy(s),
+ **({"model": self.model, "key_tail": key[-4:]} if key else {}))
ended = time.time()
env = parse_agy_json(proc.stdout)
- n_calls = self._record_trace(s, str((env or {}).get("conversation_id") or ""))
+ n_calls = self._record_trace(s, home or Path.home(), str((env or {}).get("conversation_id") or ""))
retries = agy_retries(s.traj.dir / AGY_LOG)
served = self.served_model()
- usage = usage_from_agy(env, served) if env else Usage(backend=self.kind, model=served)
+ usage = usage_from_agy(env, served, priced=bool(key)) 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 not key:
+ s.notes.append("agy ran on the subscription sign-in: cost_usd=0")
died = agy_error(proc.stderr)
said = (json.dumps(died), str((env or {}).get("error") or ""), proc.stderr)
ok = False
@@ -1247,6 +916,8 @@ class AntigravityAgent(_CliAgent):
ok = True
end = classify_end(proc, ok=ok, text=text, said=said, provider_retried=bool(retries) or bool(died.get("retryable")),
provider_failed=bool(died.get("retryable")))
+ if key:
+ _key_pool().report(key, _pool_outcome(end, ok, died))
usage.tool_calls = n_calls
return finish_session(
s, ok=ok, exit_reason=end.exit_reason, text=text, usage=usage, tool_calls=n_calls,
@@ -1256,6 +927,8 @@ class AntigravityAgent(_CliAgent):
conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
)
finally:
+ if home is not None:
+ shutil.rmtree(home, ignore_errors=True)
release_session(s)
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index d11bb363..239b89ae 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -98,7 +98,7 @@ class Trajectory:
# ===================================================================== watchdog
-_SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".gemini", ".gemini_home"}
+_SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".gemini"}
@dataclass
@@ -291,8 +291,8 @@ def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:
#: paths the harness owns; never attributed to an agent session even when git sees them change
#: (`.3dcv` = `.3dcode` in a workspace made before the 2026-09-21 rename, still resumable)
HARNESS_OWNED_DIRS = ("artifacts", "trajectories", "stages", "rounds", "_cand", "_assets", ".3dcode", ".3dcv", ".gemini", ".claude", ".agents", ".git")
-HARNESS_OWNED_FILES = frozenset({"events.jsonl", "run_state.json", "record.json", "AGENTS.md", "GEMINI.md", "CLAUDE.md",
- ".mcp.json", ".geminiignore", ".aiexclude", ".gitignore"})
+HARNESS_OWNED_FILES = frozenset({"events.jsonl", "run_state.json", "record.json", "AGENTS.md", "CLAUDE.md",
+ ".mcp.json", ".antigravityignore", ".gitignore"})
#: gitignored control files git cannot revert (downstream trusts both blindly):
#: byte-snapshotted by :func:`begin_session`, compared + restored by :func:`_enforce_scope`
UNTRACKED_CONTROL_FILES = ("run_state.json", "record.json")
@@ -350,7 +350,7 @@ class Session:
#: late-starting session's ``pre:`` commit absorbs a sibling's in-flight writes, which
#: makes concurrent provenance (and any per-path rollback) unfixable after the fact.
#: So agent sessions on one workspace are serialised.
-EXCLUSIVE_KINDS = frozenset({"claude-code", "codex", "gemini-cli", "agy"})
+EXCLUSIVE_KINDS = frozenset({"claude-code", "codex", "agy"})
_WS_SESSION_LOCKS: dict[str, threading.RLock] = {}
_WS_SESSION_LOCKS_GUARD = threading.Lock()
@@ -552,8 +552,6 @@ def invoke(
stdout_name: str = "stdout.json",
on_stdout: Callable[[str], None] | None = None,
on_stderr: Callable[[str], None] | None = None,
- attempt: int = 1,
- soft_timeout_s: float | None = None,
**invoke_extra: Any,
) -> CompletedProc:
"""Run one CLI agent process under the watchdog and record it in the trajectory.
@@ -561,9 +559,9 @@ def invoke(
The prompt goes to the CLI on STDIN, always, for every backend — never on argv and never
through a file the agent must read. argv caps one argument at 128 KiB (``MAX_ARG_STRLEN``),
and the file stub this replaced (``task_prompt.md`` above 100 kB) handed the prompt to the
- agent's own file tool: gemini-cli's ``read_file`` stops at 2 000 lines, so the last zones of a
- 5-zone scene prompt were silently dropped. Each CLI reads its whole stdin as the prompt,
- byte for byte (checked 2026-09-22 against gemini-cli 0.53, claude-code 2.1.280, codex
+ agent's own file tool, which (gemini-cli's ``read_file``, 2 000 lines) silently dropped the
+ last zones of a 5-zone scene prompt. Each CLI reads its whole stdin as the prompt,
+ byte for byte (checked 2026-09-22 against claude-code 2.1.280, codex
0.155.1 and agy 1.2.8 with a 185 000-character, 2 502-line prompt; agy alone truncates a
request past ~175 kB, whatever carries it).
@@ -572,19 +570,16 @@ def invoke(
transcript, ``src/`` + ``public/`` as activity dirs) and the stdout/stderr captures next to
the transcript. ``stdout_name`` sets the capture's name (codex streams JSONL →
``stdout.jsonl``); ``on_stdout`` / ``on_stderr`` also receive each line as it arrives (the
- backends fold their event streams and retry reports live); ``attempt`` > 1 writes
- ``stdout.<n>.json`` / ``stderr.<n>.log`` so a retry keeps attempt 1's captures. The
- ``invoke`` line records ``attempt`` and the prompt's size, plus ``invoke_extra`` (gemini-cli
- adds ``model`` and ``key_tail``).
+ backends fold their event streams live). The ``invoke`` line records the prompt's size,
+ plus ``invoke_extra`` (agy in API mode adds ``model`` and ``key_tail``).
"""
- soft = float(s.job.timeout_s if soft_timeout_s is None else soft_timeout_s)
+ soft = float(s.job.timeout_s)
hard = soft + 300.0
if s.job.hard_deadline_s is not None:
- # This runs AFTER begin_session's workspace lock and on every vendor retry.
- # A queued job must not regain the window it had before waiting for a peer.
+ # This runs AFTER begin_session's workspace lock. A queued job must not regain the window it had before waiting for a peer.
hard = min(hard, max(0.0, s.job.hard_deadline_s - time.monotonic()))
soft = min(soft, hard)
- s.traj.append("invoke", argv=list(argv), attempt=attempt, stdin_bytes=len(prompt.encode("utf-8")),
+ s.traj.append("invoke", argv=list(argv), stdin_bytes=len(prompt.encode("utf-8")),
soft_timeout_s=soft, hard_timeout_s=hard, started=hard > 0, **invoke_extra)
def on_line(stream: str, line: str) -> None:
@@ -602,10 +597,8 @@ def invoke(
idle_grace_s=IDLE_GRACE_S, poll_s=POLL_S,
on_line=on_line, stdin=prompt, activity_dirs=[s.ws.src, s.ws.public],
)
- suffix = "" if attempt == 1 else f".{attempt}"
- out = Path(stdout_name)
- s.traj.write_text(f"{out.stem}{suffix}{out.suffix}", proc.stdout)
- s.traj.write_text(f"stderr{suffix}.log", proc.stderr)
+ s.traj.write_text(stdout_name, proc.stdout)
+ s.traj.write_text("stderr.log", proc.stderr)
return proc
@@ -630,7 +623,7 @@ TRACE_ARG_CHARS = 400
@dataclass(frozen=True)
class ToolCall:
"""One tool call as the CLI reported it. ``skill`` names the bundle when the call was
- the CLI's own skill-activation tool (claude-code ``Skill``, gemini-cli ``activate_skill``),
+ the CLI's own skill-activation tool (claude-code ``Skill``),
so a reader of the trace never needs any vendor's tool vocabulary; ``failed`` is the
CLI's own verdict on the call (a ``sed`` of a mis-expanded skill path read nothing —
codex 0.155.1 did exactly that on its first try, 2026-09-22)."""
@@ -681,7 +674,7 @@ def record_tool_calls(s: Session, calls: Iterable[ToolCall], *, source: str,
#: lower-case "internal" is in every node stack trace (``node:internal/process/...``), which made
#: any crashed CLI look transient. A plain "timed out" is NOT here: the watchdog's own kill, a
#: slow MCP tool and a provider timeout all say it, and a retry of the first two buys another
-#: full window for the same outcome (provider timeouts arrive typed: gemini-cli's retry lines,
+#: full window for the same outcome (provider timeouts arrive typed: agy's ``AGY_ERROR``,
#: ``ModelError(status=408, retryable=True)``).
_TRANSIENT_RE = re.compile(
r"(?-i:\b(?:UNAVAILABLE|INTERNAL|RESOURCE_EXHAUSTED|DEADLINE_EXCEEDED)\b)|\b(?:429|50[0234]|529)\b|overloaded"
@@ -722,7 +715,7 @@ def is_rate_limited(*texts: str) -> bool:
class SessionEnd:
"""How a CLI session ended: ``exit_reason`` (completed | timeout | budget | error) and the
typed failure class ``AgentResult.transient`` / ``.quota`` carry. ``rate_limited`` is a
- 429 — gemini-cli cools its key and rotates."""
+ 429 — agy in API mode cools its key in the pool."""
exit_reason: str
transient: bool = False
@@ -735,9 +728,9 @@ def classify_end(proc: CompletedProc, *, ok: bool, text: str, said: Sequence[str
rate_limited: bool | None = None) -> SessionEnd:
"""THE end rule for every CLI backend (N71; D83) — each backend brings only its vendor's
evidence: ``said`` (what the CLI printed about the call that ended it), ``provider_retried``
- (the CLI's OWN record of retried provider calls: gemini-cli's retry lines, claude's
+ (the CLI's OWN record of retried provider calls: claude's
``api_retry`` events, codex's error events, agy's log) and ``provider_failed`` (a typed
- vendor verdict: agy's ``AGY_ERROR.retryable``, gemini-cli's empty envelope).
+ vendor verdict: agy's ``AGY_ERROR.retryable``).
A watchdog kill is ``timeout``, and transient only when nothing was produced AND the CLI
recorded provider retries: a kill with no provider evidence is the task's (a retry buys
@@ -761,14 +754,13 @@ def provider_wait(failures: Iterable[tuple[float, float]], end: float,
"""Seconds a session lost to provider errors, from the CLI's own record of them.
``failures`` are ``(t, backoff_s)``: when the CLI reported a failed API attempt, and the
- back-off it announced before the next one (0 when it does not say — gemini-cli's 5xx
- lines). ``progress`` are the times the session demonstrably moved on (a model message, a
+ back-off it announced before the next one (0 when it does not say). ``progress`` are the times the session demonstrably moved on (a model message, a
tool result); ``None`` when the CLI records none (agy's log). Failures with no progress
between them form one burst, which costs from the last progress before it — when the
request that failed went out; its first failure when nothing precedes it — until the
CLI tried again after the burst's last failure (``t + backoff``). A burst no progress
ever followed costs until ``end``: the CLI gave up, or the watchdog killed it mid-storm.
- A lower bound wherever the back-off is unannounced (≤ 30 s per burst for gemini-cli)."""
+ A lower bound wherever the back-off is unannounced."""
fails = sorted(failures)
prog = sorted(progress) if progress is not None else []
total, i = 0.0, 0
@@ -789,10 +781,8 @@ def find_json_object(stdout: str, accept: Callable[[dict[str, Any]], bool]) -> d
Tries the whole text; unwraps a top-level list (claude's stream-json array) to
its LAST accepted element; then ``{``-starting lines from the END (claude / agy
- print one envelope per line after their chatter); then ``json.loads(s[start:])``
- forward from every ``{`` — mandatory, not a fallback: ``gemini --output-format
- json`` prints an INDENTED multi-line object that no single-line scan can parse.
- ``accept`` says which dict is the envelope."""
+ print one envelope per line after their chatter). ``accept`` says which dict is the
+ envelope."""
s = stdout.strip()
if not s:
return None
@@ -815,14 +805,6 @@ def find_json_object(stdout: str, accept: Callable[[dict[str, Any]], bool]) -> d
continue
if isinstance(cand, dict) and accept(cand):
return cand
- start = s.find("{")
- while start != -1:
- try:
- obj = json.loads(s[start:])
- except json.JSONDecodeError:
- start = s.find("{", start + 1)
- continue
- return obj if isinstance(obj, dict) and accept(obj) else None
return None
diff --git a/harness/codeverse3d/agents/materialize.py b/harness/codeverse3d/agents/materialize.py
index ee15c915..db560d20 100644
--- a/harness/codeverse3d/agents/materialize.py
+++ b/harness/codeverse3d/agents/materialize.py
@@ -1,44 +1,37 @@
-"""Materialise per-workspace agent instructions + MCP configs.
+"""Materialise per-workspace agent instructions + ignore file.
-One shared body is written to ``AGENTS.md`` (codex / generic), ``GEMINI.md``
-(gemini-cli) and ``CLAUDE.md`` (claude-code): task-agnostic rules, how to call
-the ``3dcode`` spatial tools, where the cookbook is, and the language contract.
-MCP wiring:
+One shared body is written to ``AGENTS.md`` (codex / agy) and ``CLAUDE.md`` (claude-code):
+task-agnostic rules, how to call the ``3dcode`` spatial tools, where the cookbook is, and the
+language contract. (agy reads ``GEMINI.md`` as well as ``AGENTS.md``; a third copy would be
+loaded twice.) MCP wiring — never a file in the workspace, which is agent-writable:
-* gemini-cli → the per-session system settings (``agents/backends.write_system_settings``);
- ``ws/.gemini/settings.json`` is agent-writable, so it only carries the ``context`` block
* claude-code → per-session ``trajectories/<label>_rNN/mcp.json`` (``agents/backends.py``)
* codex → ``-c`` overrides (:func:`codex_mcp_overrides`, built per session by its backend)
-* agy (Antigravity) → no per-workspace MCP; the body documents the CLI fallback.
+* agy → in API mode, the ``mcp_config.json`` of the session's own HOME
+ (``AntigravityAgent.build_home``); on a subscription sign-in none — the body documents the
+ shell fallback.
Skills: the routed ``SKILL.md`` bundles are written per ROUND, not here — the set depends
on the round's kind and the previous round's gate findings (``codeverse3d/skills``,
``tracks/skills_hook.py``). ``skills.materialize.write_index`` then edits a marked section
-into the three body files this module writes, so there is exactly one shared head and no
+into the body files this module writes, so there is exactly one shared head and no
new one (docs/COST.md §13 measured and reverted a second head at +2,925 tokens/call).
Nothing here needs to change for the CLIs to see them: codex's per-tool approval override
-below is scoped to ``mcp_servers.3dcode.*`` and cannot reach its skills loader, and
-gemini-cli's ``activate_skill`` consent is already covered by ``--approval-mode yolo``.
-The per-backend wiring lives in ``agents/backends.py``: claude-code needs ``Skill`` in its
-``--allowedTools`` (``ALLOWED_TOOLS``), gemini-cli needs ``skills.enabled`` and folder trust
-off in its per-session system settings (``SYSTEM_SETTINGS``: 0.53 skips both workspace skill
-roots in an untrusted folder), and each backend records what its CLI activated
-(``cli_common.record_tool_calls``) — re-read against the installed CLIs 2026-09-22.
-
-Ignore files: ``.geminiignore`` / ``.aiexclude`` hide only noise (:data:`IGNORE_LINES`);
-``.gemini/settings.json`` gets ``context.fileFiltering.respectGitIgnore=false`` because the
-workspace ``.gitignore`` hides ``artifacts/`` from git and gemini-cli would otherwise refuse
-to read the build census there.
+below is scoped to ``mcp_servers.3dcode.*`` and cannot reach its skills loader.
+claude-code needs ``Skill`` in its ``--allowedTools`` (``backends.ALLOWED_TOOLS``), and each
+backend records what its CLI activated (``cli_common.record_tool_calls``).
+
+Ignore file: ``.antigravityignore`` hides only noise (:data:`IGNORE_LINES`).
"""
from __future__ import annotations
import json
import logging
-from pathlib import Path
from codeverse3d.agents.cli_common import default_mcp_command
from codeverse3d.proc import read_json_or_none
+from codeverse3d.skills.materialize import BODY_FILES
from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
@@ -46,20 +39,16 @@ log = logging.getLogger(__name__)
C3D_DIR = ".3dcode" # harness-owned read-only docs inside the workspace
MCP_SERVER_NAME = "3dcode"
MCP_TOOL_TIMEOUT_MS = 600_000
-#: ``.geminiignore`` / ``.aiexclude`` — gemini-cli's read_file/glob REFUSE ignored paths, so the
-#: agent-facing artefacts must stay readable: ``artifacts/*.json`` (the build tool advertises
-#: ``census.json`` etc.) and ``artifacts/tool_renders/``. Only noise / harness-private output is
-#: hidden — ``trajectories/`` whole since the prompt reaches every CLI on stdin (it was the
-#: long-prompt file's home until 2026-09-22).
+#: ``.antigravityignore`` — agy's own ignore file. The agent-facing artefacts must stay readable:
+#: ``artifacts/*.json`` (the build tool advertises ``census.json`` etc.) and
+#: ``artifacts/tool_renders/``. Only noise / harness-private output is hidden — ``trajectories/``
+#: whole since the prompt reaches every CLI on stdin.
+IGNORE_FILE = ".antigravityignore"
IGNORE_LINES = (
"artifacts/renders/", "artifacts/judge/", "trajectories/",
"stages/", "rounds/", "_cand/", "_assets/",
".git/", "node_modules/", "__pycache__/", ".gemini/tmp/",
)
-#: gemini-cli also honours the workspace ``.gitignore`` (``artifacts/``, ``trajectories/``, ``.3dcode/``
-#: are git-ignored run state) unless told otherwise — the per-workspace settings turn that off so
-#: ``IGNORE_LINES`` is the single source of truth for what the agent may read.
-GEMINI_CONTEXT_SETTINGS = {"fileFiltering": {"respectGitIgnore": False, "respectGeminiIgnore": True}}
# --------------------------------------------------------------------------- body
@@ -86,15 +75,11 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str],
f"`mcp__{MCP_SERVER_NAME}__<name>` (e.g. `mcp__{MCP_SERVER_NAME}__build`).")
elif agent_kind == "agy":
how = (
- "This session has no MCP server. Call a tool from the shell instead:\n"
+ f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}`; call them by name and prefer them "
+ "over shell commands. If your tool list has no such server, call a tool from the shell instead:\n"
"`python -m codeverse3d.cli.main tools <name> --json '{\"arg\": \"value\"}'` "
"(run from the workspace root; prints the observation as text + JSON)."
)
- elif agent_kind == "gemini-cli":
- how = (
- f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}`; they appear in your tool list as "
- f"`mcp_{MCP_SERVER_NAME}_<name>` (or plain `<name>`). Prefer them over shell commands."
- )
else:
how = f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}` (command: `{' '.join(mcp_command)}`); call them by name."
workflow = (
@@ -135,36 +120,6 @@ def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools:
# --------------------------------------------------------------------------- configs
-def _merge_json(path: Path, patch: dict) -> None:
- data: dict = {}
- if path.is_file():
- try:
- data = json.loads(path.read_text() or "{}")
- except json.JSONDecodeError as e:
- raise ValueError(f"{path} is not valid JSON; refusing to merge: {e}") from e
- for k, v in patch.items():
- if isinstance(v, dict) and isinstance(data.get(k), dict):
- data[k].update(v)
- else:
- data[k] = v
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(data, indent=2) + "\n")
-
-
-def _drop_server(path: Path) -> None:
- if not path.is_file():
- return
- try:
- data = json.loads(path.read_text() or "{}")
- except json.JSONDecodeError:
- return
- servers = data.get("mcpServers")
- if isinstance(servers, dict) and servers.keys() & {MCP_SERVER_NAME, "3dcv"}: # "3dcv": the name before 2026-09-21
- servers.pop(MCP_SERVER_NAME, None)
- servers.pop("3dcv", None)
- path.write_text(json.dumps(data, indent=2) + "\n")
-
-
def _toml_str_list(items: list[str]) -> str:
return "[" + ", ".join(json.dumps(x) for x in items) + "]"
@@ -199,7 +154,7 @@ def materialize_workspace(
spatial_tools: bool,
mcp_command: list[str] | None = None,
) -> None:
- """Write AGENTS.md / GEMINI.md / CLAUDE.md + MCP configs + ignore files into ``ws``.
+ """Write AGENTS.md / CLAUDE.md + the ignore file into ``ws``.
``mcp_command`` defaults to ``cli_common.default_mcp_command(ws)`` — the same
``sys.executable`` the backends launch; three callers used to spell a bare ``python``
@@ -234,15 +189,8 @@ def materialize_workspace(
cookbook_note = "No cookbook is available in this session; rely on the contract below."
body = _body(agent_kind, contract_md, cookbook_note, spatial_tools, mcp_command, ws)
- for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):
+ for name in BODY_FILES:
(ws.root / name).write_text(body)
-
# No MCP server is written into the workspace: every CLI gets 3dcode from a harness-owned
# per-session file, so an agent-planted server cannot reach the next round (audit 2026-08-27).
- gemini_settings = ws.root / ".gemini" / "settings.json"
- _merge_json(gemini_settings, {"context": dict(GEMINI_CONTEXT_SETTINGS)})
- _drop_server(gemini_settings)
-
- ignore_text = "\n".join(IGNORE_LINES) + "\n"
- for name in (".geminiignore", ".aiexclude"):
- (ws.root / name).write_text(ignore_text)
+ (ws.root / IGNORE_FILE).write_text("\n".join(IGNORE_LINES) + "\n")
diff --git a/harness/codeverse3d/agents/registry.py b/harness/codeverse3d/agents/registry.py
index abea23c2..a6d11d8b 100644
--- a/harness/codeverse3d/agents/registry.py
+++ b/harness/codeverse3d/agents/registry.py
@@ -14,7 +14,7 @@ class CodingAgent(Protocol):
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.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,
@@ -26,7 +26,7 @@ class CodingAgent(Protocol):
process group on timeout).
"""
- kind: str # gemini-cli | claude-code | codex | agy
+ kind: str # claude-code | codex | agy
model: str
@property
@@ -40,11 +40,11 @@ class CodingAgent(Protocol):
# ===================================================================== registry
-KINDS = ("gemini-cli", "claude-code", "codex", "agy")
+KINDS = ("claude-code", "codex", "agy")
def parse_agent_id(agent_id: str) -> tuple[str, str]:
- """``gemini-cli:gemini-3.6-flash`` → ('gemini-cli', 'gemini-3.6-flash')."""
+ """``agy:gemini-3.7-flash`` → ('agy', 'gemini-3.7-flash')."""
if ":" not in agent_id:
raise ValueError(f"agent id must be '<kind>:<model>', got {agent_id!r}")
kind, model = agent_id.split(":", 1)
@@ -66,5 +66,5 @@ def _build_agent(agent_id: str) -> CodingAgent:
kind, model = parse_agent_id(agent_id) # an unknown kind has raised already
from codeverse3d.agents import backends
- return {"gemini-cli": backends.GeminiCliAgent, "claude-code": backends.ClaudeCodeAgent,
- "codex": backends.CodexAgent, "agy": backends.AntigravityAgent}[kind](model)
+ return {"claude-code": backends.ClaudeCodeAgent, "codex": backends.CodexAgent,
+ "agy": backends.AntigravityAgent}[kind](model)
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 6f464b24..ca108b07 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -240,7 +240,7 @@ def make(
generator: Annotated[
str | None,
typer.Option(
- help="gemini-cli:gemini-3.6-flash | claude-code:... | codex:... | agy:... | single-shot:gemini:..."
+ help="agy:gemini-3.7-flash[-low|-medium|-high] | claude-code:... | codex:... | single-shot:gemini:..."
),
] = None,
planner: Annotated[str | None, typer.Option()] = None,
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index 548b9199..42e8f853 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -74,7 +74,6 @@ BLENDER_MIN: tuple[int, int] = (4, 2)
class Binaries(BaseModel):
blender: str = Field(default="", description="path to a Blender 4.2+/5.x binary (headless capable)")
node: str = "node"
- gemini_cli: str = "gemini"
claude_cli: str = "claude"
codex_cli: str = "codex"
agy_cli: str = "agy"
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
index 8ea1b39f..245fe1e6 100644
--- a/harness/codeverse3d/contracts/agent.py
+++ b/harness/codeverse3d/contracts/agent.py
@@ -35,7 +35,7 @@ class AgentJob(BaseModel):
"remaining hard clock before queuing. Shared by retries; recomputed on resume. "
"None preserves the standalone CLI's session grace",
)
- #: consumed only by claude-code (``--max-turns``); gemini-cli / codex / agy have no
+ #: consumed only by claude-code (``--max-turns``); codex / agy have no
#: turn flag and run unbounded except by ``timeout_s`` and the run's wall clock
max_turns: int = 60
spatial_tools: bool = Field(
@@ -93,9 +93,7 @@ class AgentResult(BaseModel):
"overloaded / token-limit retries and their back-off inside the CLI — read from the CLI's "
"own log; 0.0 when none were seen or the CLI does not expose them. A step's effective "
"time is ``duration_s - provider_wait_s`` (owner, 2026-09-22). Sources "
- "(cli_common.provider_wait): gemini-cli its stderr retry lines against its chat record — a "
- "lower bound, its 5xx back-off is unannounced — plus the key rotation between attempts; "
- "claude-code its stream-json ``api_retry`` events; agy the retry lines of its ``--log-file``; "
+ "(cli_common.provider_wait): claude-code its stream-json ``api_retry`` events; agy the retry lines of its ``--log-file``; "
"codex none (its HTTP client retries without an event)",
)
usage_estimated: bool = Field(
@@ -106,16 +104,14 @@ class AgentResult(BaseModel):
tool_calls: int = 0
turns: int = Field(
default=0, description="model turns as the backend counts them (claude-code num_turns, codex "
- "turn.completed events, agy num_turns); 0 for gemini-cli, which exposes no turn count",
+ "turn.completed events, agy num_turns)",
)
errors: list[str] = Field(default_factory=list)
transient: bool = Field(
default=False,
description="the session died of a provider failure a retry may get through — 5xx / UNAVAILABLE / "
"overloaded / a 429 rate limit / a dropped connection, as the CLI itself reported it — not of "
- "the task: the round loop re-runs such a round once, and a session that also wrote nothing falls "
- "back to the cheap single-shot path, hedged across keys (measured 2026-09-07: 23 of 24 gemini-cli "
- "sessions of one evening died in a 503 storm)",
+ "the task: the round loop re-runs such a round once",
)
quota: bool = Field(
default=False,
diff --git a/harness/codeverse3d/contracts/common.py b/harness/codeverse3d/contracts/common.py
index d11266c3..b022b194 100644
--- a/harness/codeverse3d/contracts/common.py
+++ b/harness/codeverse3d/contracts/common.py
@@ -179,8 +179,8 @@ class Backends(BaseModel):
* API chat models: ``gemini:gemini-3.7-flash`` · ``anthropic:claude-sonnet-5``
· ``openai:gpt-5.6-sol``
- * Coding agents: ``gemini-cli:gemini-3.7-flash`` · ``claude-code:sonnet``
- · ``codex:gpt-5.6-sol`` · ``agy:gemini-3.7-flash-high``
+ * Coding agents: ``agy:gemini-3.7-flash`` (``-low``/``-medium``/``-high``) · ``claude-code:sonnet``
+ · ``codex:gpt-5.6-sol``
The coding agent is always a VENDOR agent: the harness supplies the workspace, the
prompt and its 3D tools (over MCP) and reads the result. The in-process
@@ -189,7 +189,7 @@ class Backends(BaseModel):
"""
planner: str = "gemini:gemini-3.7-flash"
- generator: str = "gemini-cli:gemini-3.7-flash"
+ generator: str = "agy:gemini-3.7-flash"
# The judge drives the refine loop: the pro tier has ~3x lower sample noise than
# flash (calibration 2026-08-23: std 0.03 vs 0.08-0.12) for ~$0.07 per verdict.
judge: str = "gemini:gemini-3.1-pro-preview"
diff --git a/harness/codeverse3d/cost/profiles.py b/harness/codeverse3d/cost/profiles.py
index 43d4b0e9..6aaa8d62 100644
--- a/harness/codeverse3d/cost/profiles.py
+++ b/harness/codeverse3d/cost/profiles.py
@@ -23,10 +23,10 @@ Every number is taken from the measurements in ``docs/COST.md``:
$4.93, r02 for $6.80, r03 for $33.49). It does **not** shrink the judge
payload and does **not** carry its own turn cap — both were measured and
neither paid (see the note on :class:`Profile`).
-* **balanced** — exactly today's defaults (gemini-cli generator, pro judge at
+* **balanced** — exactly today's defaults (agy generator, pro judge at
n=1, 4 rounds, no best-of-N, no texture): the arm every number in the audit
was measured on.
-* **quality** — gemini-cli + the pro judge at ``n=3`` (σ 0.030/√3 ≈ 0.017),
+* **quality** — agy + the pro judge at ``n=3`` (σ 0.030/√3 ≈ 0.017),
best-of-2 baselines and the texture pass behind its before/after gate.
The expected $ per profile comes from the same 61 runs; see
@@ -115,10 +115,11 @@ PROFILES: dict[str, Profile] = {
expected_usd=1.47,
expected_score="0.835 mean on compare_v1, 36/61 runs passed ($2.50 per passing artifact) "
"— MEASURED ON gemini-cli:gemini-3.6-flash, not on this dial's generator",
- note="today's defaults. The generator moved to 3.7-flash on 2026-08-28 and these two "
- "expectations have NOT been re-measured on it: docs/COST.md §12 puts the 3.7 CLI arm "
- "at $0.73/call against 3.6's $0.52 and 0.827 against 0.835, so expect this run to "
- "cost more and score about the same until a battery says otherwise",
+ note="today's defaults. The generator moved to 3.7-flash on 2026-08-28 and from gemini-cli "
+ "to agy on 2026-10-13 (D103), and these two expectations have NOT been re-measured on "
+ "either: docs/COST.md §12 puts the 3.7 CLI arm at $0.73/call against 3.6's $0.52 and "
+ "0.827 against 0.835, so expect this run to cost more and score about the same until a "
+ "battery says otherwise",
),
"quality": Profile(
name="quality",
@@ -132,8 +133,8 @@ PROFILES: dict[str, Profile] = {
expected_score="best-of-2 lifted the stool baseline 0.563 → 0.612 and the texture pass "
"0.686 → 0.701; judge σ 0.017 at n=3 "
"— MEASURED ON gemini-cli:gemini-3.6-flash, not on this dial's generator",
- note="gemini-cli + pro judge n=3 + 4 rounds + best-of-2 + texture pass. The generator "
- "moved to 3.7-flash on 2026-08-28 and the $3.20 / score expectations above have NOT "
+ note="agy + pro judge n=3 + 4 rounds + best-of-2 + texture pass. The generator "
+ "moved to 3.7-flash on 2026-08-28 and to agy on 2026-10-13 (D103), and the $3.20 / score expectations above have NOT "
"been re-measured on it (same caveat as balanced: docs/COST.md §12 puts the 3.7 CLI "
"arm at $0.73/call vs 3.6's $0.52), so expect this dial to cost more and score about "
"the same until a battery says otherwise",
diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.py
index f673811b..452730e1 100644
--- a/harness/codeverse3d/cost/types.py
+++ b/harness/codeverse3d/cost/types.py
@@ -190,7 +190,7 @@ class CallCost(BaseModel):
backend: str = ""
provider: str = ""
model: str = "" # bare model name, canonical (no provider prefix)
- model_id: str = "" # as reported by the backend ("gemini-cli:gemini-3.6-flash")
+ model_id: str = "" # as reported by the backend ("agy:gemini-3.7-flash")
input_tokens: int = 0
cached_tokens: int = 0
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 518bacdb..104dfe75 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -270,12 +270,16 @@ def check_keys(live: bool) -> list[Row]:
def check_clis() -> list[Row]:
s = get_settings()
rows: list[Row] = []
- for name, binary in (("gemini-cli", s.binaries.gemini_cli), ("claude", s.binaries.claude_cli),
- ("codex", s.binaries.codex_cli), ("agy", s.binaries.agy_cli)):
+ for name, binary in (("agy", s.binaries.agy_cli), ("claude", s.binaries.claude_cli),
+ ("codex", s.binaries.codex_cli)):
okk, v = _ver([binary, "--version"])
rows.append((name, "OK" if okk else "WARN", v if okk else f"{v} (backend {name} unavailable)"))
okk, v = _ver(["git", "--version"])
rows.append(("git", "OK" if okk else "FAIL", v))
+ n = len(s.gemini_api_keys)
+ rows.append(("agy gemini mode", "OK" if n else "WARN",
+ f"API-key mode: {n}-key pool, 3dcode MCP, priced" if n
+ else "no Gemini keys: agy:gemini-* runs on the subscription sign-in, without the 3dcode MCP tools"))
return rows
@@ -297,7 +301,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 codeverse3d.agents.backends import ALLOWED_TOOLS, SYSTEM_SETTINGS
+ from codeverse3d.agents.backends import ALLOWED_TOOLS
from codeverse3d.skills import bundle_dirs, skills_dir, validate_bundle
from codeverse3d.skills.materialize import SKILL_ROOTS
from codeverse3d.skills.registry import ROUTED_SKILLS
@@ -320,10 +324,6 @@ def check_skills() -> list[Row]:
rows.append(("skills discovery", "OK", "materialised into " + " + ".join(SKILL_ROOTS)))
rows.append(("claude-code Skill tool", "OK" if "Skill" in ALLOWED_TOOLS else "FAIL",
"in --allowedTools" if "Skill" in ALLOWED_TOOLS else "missing: claude-code would deny skill activation"))
- pinned = (SYSTEM_SETTINGS.get("skills") or {}).get("enabled") is True
- rows.append(("gemini-cli skills setting", "OK" if pinned else "FAIL",
- "skills.enabled pinned in the per-session system settings" if pinned
- else "not pinned: a user's skills.enabled=false would hide every bundle from gemini-cli"))
return rows
diff --git a/harness/codeverse3d/models/pricing.py b/harness/codeverse3d/models/pricing.py
index 2eccf484..26c91d7e 100644
--- a/harness/codeverse3d/models/pricing.py
+++ b/harness/codeverse3d/models/pricing.py
@@ -79,6 +79,10 @@ class Price:
# fmt: off
PRICES: dict[tuple[str, str], Price] = {
# ---------------------------------------------------------------- gemini
+ # 4 argon: introductory rates valid through 2026-11-30; they double on 2026-12-01
+ # ($4.00 / $20.00 / $0.20). Update then. No >200k tier; output includes thinking.
+ ("gemini", "gemini-4-argon"): Price(2.00, 10.00, 0.10, checked="2026-10-13",
+ note="intro rate through 2026-11-30, then 4.00/20.00/0.20"),
# 3.6 / 3.7 / 3.8 flash: introductory rates valid through 2026-12-31; they double
# on 2027-01-01 ($1.50 / $7.50 / $0.15). Update then. No >200k surcharge.
("gemini", "gemini-3.8-flash"): Price(0.75, 3.75, 0.075, checked="2026-09-21",
diff --git a/harness/codeverse3d/skills/materialize.py b/harness/codeverse3d/skills/materialize.py
index 9071252d..af23b3c5 100644
--- a/harness/codeverse3d/skills/materialize.py
+++ b/harness/codeverse3d/skills/materialize.py
@@ -1,7 +1,7 @@
"""Write the routed bundles into a workspace, as real files, twice.
WHY twice: the discovery roots were read out of the shipped binaries, not assumed.
-gemini-cli, codex and agy all read ``<ws>/.agents/skills/<name>/SKILL.md``; claude-code
+codex and agy both read ``<ws>/.agents/skills/<name>/SKILL.md``; claude-code
2.1 reads ``<ws>/.claude/skills/<name>/SKILL.md`` and has **no** ``.agents`` skill root at
all (its ``.agents`` strings are plugin-migration paths). So the same bytes go to both.
@@ -19,7 +19,7 @@ nobody reading anything. Two independent causes, both verified:
* ``Workspace.changed_files`` runs ``git add -A -N`` then ``git diff --numstat`` after
every agent session, and git reads each untracked file to compute the diff. On a real
git workspace that alone flips all four files of a bundle to "read".
-* all four CLIs (codex 0.149.0, claude-code 2.1.245, agy 1.1.20, gemini-cli 0.53.0) open
+* every CLI (codex 0.149.0, claude-code 2.1.245, agy 1.1.20 — and gemini-cli 0.53.0, gone since D103) opens
``references/*.md`` while activating a skill, including on a task whose description does
not match and with the prompt telling them not to activate anything.
@@ -54,8 +54,8 @@ from codeverse3d.skills.registry import plan_signals, select
log = logging.getLogger(__name__)
SKILL_ROOTS = (AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT)
-#: the AGENTS.md/GEMINI.md/CLAUDE.md body files a workspace already has
-BODY_FILES = ("AGENTS.md", "GEMINI.md", "CLAUDE.md")
+#: the AGENTS.md/CLAUDE.md body files a workspace already has
+BODY_FILES = ("AGENTS.md", "CLAUDE.md")
MARK_BEGIN = "<!-- 3dcode:skills -->"
MARK_END = "<!-- /3dcode:skills -->"
diff --git a/harness/codeverse3d/skills/prompting.py b/harness/codeverse3d/skills/prompting.py
index c49f88f7..daef962e 100644
--- a/harness/codeverse3d/skills/prompting.py
+++ b/harness/codeverse3d/skills/prompting.py
@@ -5,13 +5,13 @@ The library itself is agent-agnostic: plain `agentskills.io` bundles under
in it knows what a backend is. What genuinely differs between backends is only
**delivery**, and only in one bit: which discovery root does it read?
-Read out of the shipped binaries, not assumed: gemini-cli, codex and agy read
+Read out of the shipped binaries, not assumed: codex and agy read
``<ws>/.agents/skills/<name>/SKILL.md``; claude-code 2.1 reads ``<ws>/.claude/skills/…``
-and has no ``.agents`` skill root at all. All four have a NATIVE skill loader (they find
+and has no ``.agents`` skill root at all. All three have a NATIVE skill loader (they find
and index the bundles themselves), so none is handed a second index — it would list the
same skills twice. Adding a backend is ONE row here — not a new module, not a branch in
three files. (The loaderless path — an explicit index plus a ``read_skill`` tool — served
-the in-process api-agent and went with it: ``agents/registry.KINDS`` accepts only these four.)
+the in-process api-agent and went with it: ``agents/registry.KINDS`` accepts only these three.)
"""
from __future__ import annotations
@@ -33,7 +33,6 @@ CLAUDE_SKILL_ROOT = ".claude/skills"
_BACKEND_ROOTS: dict[str, str] = {
"claude-code": CLAUDE_SKILL_ROOT,
"codex": AGENTS_SKILL_ROOT,
- "gemini-cli": AGENTS_SKILL_ROOT,
"agy": AGENTS_SKILL_ROOT,
}
diff --git a/harness/codeverse3d/skills/telemetry.py b/harness/codeverse3d/skills/telemetry.py
index 1b35f1c7..a4707c01 100644
--- a/harness/codeverse3d/skills/telemetry.py
+++ b/harness/codeverse3d/skills/telemetry.py
@@ -7,8 +7,8 @@ nicer file format without measuring reads would repeat that at a new price.
**Ground truth first (2026-09-22).** Every CLI backend now folds its session's tool
calls into ``trajectories/<label>/transcript.jsonl`` (``agents/cli_common.record_tool_calls``:
-claude-code's ``Skill``/``Read`` from stream-json, gemini-cli's ``activate_skill``/
-``read_file`` from its chat record, codex's shell commands from ``exec --json``). A
+claude-code's ``Skill``/``Read`` from stream-json, codex's shell commands from
+``exec --json``, agy's ``view_file`` from its conversation database). A
bundle is *surfaced* when a call activated it or named its ``SKILL.md``, *deep* when a
call named a file under its ``references/``, and the control is read when a call touched
it — ``SkillsUsage.evidence == "transcript"``. Only when a session after the attach left
diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.py
index 85ebfdcd..54650a67 100644
--- a/harness/codeverse3d/tracks/common.py
+++ b/harness/codeverse3d/tracks/common.py
@@ -170,7 +170,7 @@ class RunContext:
@property
def agent_kind(self) -> str:
- """``gemini-cli`` of ``gemini-cli:gemini-3.7-flash``."""
+ """``agy`` of ``agy:gemini-3.7-flash``."""
return self.agent_id.split(":", 1)[0]
def record_prompt(self, name: str, text: str) -> None:
@@ -216,26 +216,8 @@ def single_shot_ctx(ctx: RunContext) -> RunContext | None:
def generate_for(ctx: RunContext, task: GenerationTask) -> GenerationResult:
- """``generate()`` with everything ``ctx`` knows — the one call every stage makes — plus the
- storm fallback: a session that died on a transient-failure streak and wrote nothing
- (``GenerationResult.storm``) is retried through the single-shot path, one hedged,
- key-rotating API call. Measured 2026-09-07: 23 of 24 gemini-cli sessions of an evening
- ended ``timeout / 0 turns / $0`` after 8-17 consecutive 503s inside the CLI's own retry
- loop, while every single-shot in the same minutes got through; the stages that lost
- their session shipped the skeleton env and empty zones and judged 0.00-0.14."""
- res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
- budget=ctx.budget, events=ctx.events)
- if not res.storm or ctx.single_shot:
- return res
- sub = single_shot_ctx(ctx)
- if sub is None:
- return res
- ctx.events.emit("generate.storm_fallback", label=task.label, sessions=res.sessions, notes=res.notes[:300])
- again = generate(sub.ws, agent_id=sub.agent_id, task=task, agent=sub.agent, model=sub.model, settings=sub.settings,
- budget=sub.budget, events=sub.events)
- again.usage = res.usage + again.usage
- again.notes = f"agent session died in a 503 storm ({res.notes[:120]}) → single-shot: {again.notes}"
- # the cheap route did not get through either: the task still died of the storm (the round
- # loop's one retry keys on it — RoundFailed.transient)
- again.transient = again.transient or not again.ok
- return again
+ """``generate()`` with everything ``ctx`` knows — the one call every stage makes. A session
+ that died of a provider failure comes back ``transient``; the round loop's one retry is the
+ only retry above the CLI's own."""
+ return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index 4ca8882f..6ae83ad8 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -1,7 +1,7 @@
"""Code generation: one entry point, two strategies.
* **CodingAgent path** — ``agent_id`` is any id ``codeverse3d.agents`` knows
- (``gemini-cli:*``, ``claude-code:*``, ``codex:*``, ``agy:*``):
+ (``agy:*``, ``claude-code:*``, ``codex:*``):
the workspace is materialised once per run (AGENTS.md + MCP config), then
``agent.run(AgentJob)``. Truth is on disk: ``ok`` means files changed.
* **Single-shot path** — ``agent_id = "single-shot:<provider>:<model>"``: one
@@ -341,11 +341,6 @@ class GenerationResult(BaseModel):
description="the last session met the vendor's usage limit (AgentResult.quota): no retry gets "
"through until it resets",
)
- storm: bool = Field(
- default=False,
- description="transient AND nothing was written — the agent route is down, not the task; "
- "tracks fall back to the hedged single-shot path (tracks.common.generate_for)",
- )
@classmethod
def from_error(cls, label: str, e: BaseException) -> GenerationResult:
@@ -574,7 +569,7 @@ def run_agent_task(
and not acc.wrapped
and res.exit_reason not in ("timeout", "budget")
# a provider failure or a spent usage limit is not a bail: a second session meets the
- # same wall (the storm fallback and the round loop's one retry handle a transient)
+ # same wall (the round loop's one retry handles a transient)
and not (res.transient or res.quota)
):
events.emit("generate.silent_bail", label=task.label, exit_reason=res.exit_reason)
@@ -618,7 +613,6 @@ def run_agent_task(
turn_capped=acc.wrapped,
transient=bool(res.transient),
quota=bool(res.quota),
- storm=not changes and bool(res.transient),
)
@@ -663,7 +657,7 @@ class _SessionAcc:
self.errors.append(f"{label}: {type(e).__name__}: {e}")
return None
self.usage = self.usage + res.usage
- # the count as the BACKEND reports it (0 for gemini-cli, which exposes none): a size
+ # the count as the BACKEND reports it: a size
# signal for the generate.turn_cap event, not what the cap is enforced against
self.turns += res.turns
if self.budget is not None:
@@ -681,7 +675,7 @@ def _images_block(images: list[ImagePart], ws: Workspace) -> str:
Every image is copied into ``.3dcode/images/`` first, exactly as the cookbook is (D9),
and listed workspace-relative: a CLI reads only INSIDE its workspace (``--image
ref.png`` stores the host's absolute path), and the judged contact sheet sits under
- ``artifacts/renders/``, which ``.geminiignore`` hides from gemini-cli's read_file."""
+ ``artifacts/renders/``, which ``.antigravityignore`` hides from agy."""
paths: list[tuple[str, str]] = []
for i in images:
if not i.path:
diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.py
index 74324982..83895a4c 100644
--- a/harness/codeverse3d/tracks/scene_assets.py
+++ b/harness/codeverse3d/tracks/scene_assets.py
@@ -301,27 +301,7 @@ def _ladder(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language,
res = _generate_asset(ctx, asset, rel, language=language, attempt=0, files=files, timeout_s=timeout_s)
notes = res.notes
strategy = "escalated" if chk is not None else "agent"
- # a session that died in the storm mid-work (D68) left partial files: build and check
- # them, but with the CHEAP context — the check's own one build repair then goes
- # through the single-shot path, not another agent session at the wall
- chk = check(sub if res.transient and sub is not None else ctx) if res.ok else chk
- if res.transient and sub is not None and chk is not None and not chk.ok:
- # the session died in a 503 storm mid-work (D68): its partial files failed the
- # check, and another 12 minutes at the wall would too — the cheap rung answers.
- ctx.events.emit("asset.storm_repair", asset=asset.name, errors=chk.errors[:3])
- try:
- res2 = _generate_asset(sub, asset, rel, language=language, attempt=2, files=files,
- feedback=repair_feedback(chk, rel))
- except Exception as e: # noqa: BLE001 — same rule as the ladder's own single-shots
- if isinstance(e, BudgetExceeded):
- raise
- log.warning("storm repair of %s failed: %s", asset.name, e)
- return strategy, chk, notes
- if res2.ok:
- chk2 = check(sub)
- if chk2.ok:
- return "escalated+repair", chk2, res2.notes
- chk = chk2
+ chk = check(ctx) if res.ok else chk
return strategy, chk, notes
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index aae2d1ea..fd3da754 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -25,8 +25,9 @@ layered on top of the language — for four **tracks**:
* `ChatModel` (API): `gemini:*`, `anthropic:*`, `openai:*` — planner, judge,
captioner, single-shot generation.
* `CodingAgent` (agentic session on a workspace): always a vendor CLI —
- `gemini-cli:*`, `claude-code:*`, `codex:*`, `agy:*` (Antigravity); the in-process
- `api-agent` was deleted 2026-08-28. Plus `single-shot:<chat-model>` (one envelope
+ `agy:*` (Antigravity — Google's models, in Gemini-API mode with pool keys + MCP),
+ `claude-code:*`, `codex:*`; the in-process `api-agent` was deleted 2026-08-28 and
+ `gemini-cli:*` on 2026-10-13 (D103). Plus `single-shot:<chat-model>` (one envelope
of files, no tools) handled inside `tracks/generation.py`.
Every run is: **spec → plan → skeleton → [scene stages] → baseline round
@@ -114,10 +115,10 @@ codeverse3d/
probe: no retries, no backoff), schema_utils.py (strict schema), 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: argv, env, each CLI's own
- record read back — envelope, chat record / stream, retry reports), cli_common.py
- (sessions, the watchdog clocks, the prompt on stdin, the transcript, retry
- trajectory naming, files_changed attribution, THE failure vocabulary,
+ (claude-code / codex / antigravity: argv, env, each CLI's own record read
+ back — envelope, stream, conversation db, retry reports; agy's API-mode
+ HOME + pool key), cli_common.py (sessions, the watchdog clocks, the prompt
+ on stdin, the transcript, files_changed attribution, THE failure vocabulary,
provider_wait), materialize.py
languages/ LanguageRuntime + RuntimeLayout (base.py: every runtime states its file layout —
expected_files / files_for — and the tracks ask it); one merged module per language since 2026-08-28 —
@@ -378,7 +379,7 @@ says the tool **could not run** (exception, missing artefact, unusable arguments
tools set `failed` on an observation they compose themselves; the list of those places
lives with the field, in `spatial/registry.Observation.error`. MCP `is_error` is `failed` alone: a
negative verdict is a result whose text leads with FAIL, because a vendor CLI retries an
-errored call, and over 224 recorded gemini-cli sessions `is_error = not ok` made 62 % of
+errored call, and over 224 recorded gemini-cli sessions (removed in D103) `is_error = not ok` made 62 % of
1 445 `joint_sweep` calls, 23 % of 2 144 `build`s and ~15 % of the connectivity/contract
calls look broken (a mean 119 k prompt tokens ≈ $0.030 blended a retry — docs/COST.md §30
for the selector, and for what an errored result costs when it carries an image).
@@ -579,20 +580,22 @@ the since-deleted in-process `api-agent` and the since-removed pass / plateau st
camera-in-geometry can miss open-back enclosures.
* threejs: textures are stripped on GLB export (the texture pass re-adds them as a
derived pack); `userData.tick` cannot survive export.
-* agy exposes no per-workspace MCP, cost or served model; a killed agy session books no
- usage (its tokens are in the envelope only). A killed codex session books an ESTIMATE
+* agy has no per-workspace MCP: in Gemini-API mode each session gets a HOME of its own with
+ the 3dcode server in it; on the subscription sign-in it has no MCP (shell fallback) and books
+ $0. A killed agy session books no usage (its tokens are in the envelope only). A killed codex session books an ESTIMATE
(usage is per turn and `--ephemeral` leaves no rollout; `CodexEvents.estimated_usage` prices
the stream it left, ledger `source="estimate"`, $ within 0.62–1.34× of actual on 356 recorded
sessions); a killed claude-code session books its
- per-message usage, whose output side is a floor. A killed or given-up gemini-cli
- session books its chat record (exact).
+ per-message usage, whose output side is a floor.
* Vendor sessions see only the routed skill bundles, except agy (5 built-ins; no
- per-session switch) and any user-level skill root codex or gemini-cli might grow.
+ per-session switch) and any user-level skill root codex might grow.
* Anthropic / OpenAI backends are mock-tested only (no keys on this box).
* Budget checks run between steps: a round the clock cuts mid-way is rolled back (its
spend stays in `aborted_rounds`) — give scenes `--max-minutes 60`.
* Gemini flash 503 storms happen; dead keys and 429s rotate freely now, but a
- sustained outage can still fail a round (`3dcode resume` re-uses cached stages).
+ sustained outage can still fail a round (`3dcode resume` re-uses cached stages). A
+ storm-dead agent session gets the round loop's ONE transport retry (fresh key), no
+ single-shot fallback (D103).
## 11. Flywheel
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index d56753b7..78e37b73 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -134,7 +134,7 @@ openai.
| `urdf` | yourdfpy, scipy | the `articulated_object` track: URDF parse/validate + joint math |
| `graphics` | moderngl | the `graphics` track (`glsl_shader`, `opengl_python`) — headless GL rendering in `spatial/gl_render.py` |
| `mesh` | shapely, networkx, manifold3d, matplotlib | `cross_section` (filled area / hollow ratio from shapely, the image drawn by the judge-slice renderer in matplotlib), mesh split / connectivity (networkx), joint-sweep boolean intersections (`trimesh.boolean(engine="manifold")`), judge cross-section slices on gate-ERROR rounds (`judge_slices`, D48; without the extra the judge logs a warning and sends the pre-D48 payload) |
-| `mcp` | mcp | `3dcode mcp` / `codeverse3d.spatial.mcp_server`, i.e. spatial tools for the `gemini-cli`, `claude-code` and `codex` backends |
+| `mcp` | mcp | `3dcode mcp` / `codeverse3d.spatial.mcp_server`, i.e. spatial tools for the `agy` (Gemini-API mode), `claude-code` and `codex` backends |
| `flywheel` | pyarrow | `3dcode flywheel export --pack` (parquet shards). A plain `flywheel export` needs nothing: without pyarrow it writes `metadata.jsonl` and skips `metadata.parquet` with a warning. |
| `all` | all of the above | — |
| `dev` | pytest, pytest-timeout, ruff | the test suite and the linter |
@@ -358,24 +358,26 @@ export GEMINI_API_KEYS="key1,key2,key3" # e.g. in ~/.bashrc
3dcodeverse doctor --live # one ~$0.00001 "pong" call
```
-### 8.2 The coding-agent CLIs (`gemini` required, the rest optional)
+### 8.2 The coding-agent CLIs (`agy` required, the rest optional)
-The generator is always a vendor CLI: `--generator gemini-cli:… | claude-code:… | codex:… | agy:…`.
-Since 2026-08-28 the default is `gemini-cli:gemini-3.7-flash`, so **`gemini` is the one CLI a default
-run needs**; it authenticates with the same api key as the harness's own calls. The other three are
-needed only when you name them.
+The generator is always a vendor CLI: `--generator agy:… | claude-code:… | codex:…`.
+Since 2026-10-13 (D103; gemini-cli was removed) the default is `agy:gemini-3.7-flash`, so **`agy` is
+the one CLI a default run needs**. With Gemini keys configured (§8.1) an `agy:gemini-*` session runs
+in **Gemini-API mode**: one key from the harness's own pool, the 3dcode MCP tools, priced at Gemini
+list price — no sign-in. Without keys, or for a non-Gemini model (`agy:claude-sonnet-4-6`), it runs
+on agy's own subscription sign-in, without the MCP tools, booked $0 (doctor row `agy gemini mode`).
+The other two are needed only when you name them.
```bash
-npm i -g @google/gemini-cli # gemini (0.53.0 here)
+# agy (Antigravity CLI, 1.3.4 here): the Antigravity installer puts it in ~/.local/bin
npm i -g @anthropic-ai/claude-code # claude (2.1.241 here)
npm i -g @openai/codex # codex (0.149.0 here)
-# agy (Antigravity, 1.1.19 here) ships with the Antigravity IDE
```
-`claude`, `codex` and `agy` authenticate against your local subscription (their
-own `login` flows) — test lightly. The harness handles the per-CLI quirks for you (the
-gemini-cli system settings file, codex's MCP approval mode, agy's missing per-workspace
-MCP); what each one is and why it must not be undone: `docs/RUNBOOK.md` §3.
+`claude` and `codex` (and agy outside API mode) authenticate against your local subscription
+(their own `login` flows) — test lightly. The harness handles the per-CLI quirks for you
+(agy's per-session API-mode HOME, codex's MCP approval mode); what each one is and why it must
+not be undone: `docs/RUNBOOK.md` §3.
The spatial MCP server itself is the `mcp` extra (§4); check it with
`python -m codeverse3d.spatial.mcp_server --workspace <ws> --list`.
@@ -448,11 +450,11 @@ Real output on this box (exit code 0; any FAIL row makes it exit 1):
│ gemini keys │ OK │ 22 key(s) │
│ anthropic key │ WARN │ not set (anthropic:* backends unavailable) │
│ openai key │ WARN │ not set (openai:* backends unavailable) │
-│ gemini-cli │ OK │ 0.53.0 │
+│ agy │ OK │ 1.3.4 │
│ claude │ OK │ 2.1.241 (Claude Code) │
│ codex │ OK │ codex-cli 0.149.0 │
-│ agy │ OK │ 1.1.19 │
│ git │ OK │ git version 2.53.0 │
+│ agy gemini mode │ OK │ API-key mode: 15-key pool, 3dcode MCP, priced │
│ mcp │ OK │ mcp + codeverse3d.spatial.mcp_server importable │
└───────────────┴────────┴─────────────────────────────────────────────────────┘
```
@@ -486,8 +488,9 @@ that the keys work end to end):
| `chrome webgl` | SKIP | `runtime_js/gpu_launch.cjs` not present | you are not in a full checkout |
| `gemini keys` | FAIL | no keys resolved | `export GEMINI_API_KEYS="k1,k2"` (§8.1) — everything model-driven needs this |
| `anthropic key` / `openai key` | WARN | not set | expected unless you use `anthropic:*` / `openai:*`; export the key to clear it |
-| `gemini-cli` / `claude` / `codex` / `agy` | WARN | CLI not on `PATH` | optional (§8.2); only that `--generator` is unavailable |
+| `agy` / `claude` / `codex` | WARN | CLI not on `PATH` | only that `--generator` is unavailable — but `agy` serves the default generator (§8.2) |
| `git` | FAIL | git missing | install git — run workspaces are git repos |
+| `agy gemini mode` | WARN | no Gemini keys: `agy:gemini-*` runs on agy's subscription sign-in, without the 3dcode MCP tools, booked $0 | export `GEMINI_API_KEYS` (§8.1) for API-key mode (pool key, MCP, priced); the subscription sign-in no longer serves `gemini-3.7-flash` (2026-10-13) |
| `mcp` | WARN | `mcp` package or the server module missing | `pip install -e 'harness[mcp]'`; only affects the agentic CLI backends |
| `gemini live call` (`--live`) | FAIL | key rejected / no network | check the key value and outbound access; a `503 … high demand` is transient, not an install problem |
| `in-flight slots` | WARN | every machine-wide slot is held right now (`busy n/n`), or `max_in_flight=0` switched the cap off | busy: other harness processes are mid-call and new calls wait for a slot (docs/COST.md §23) — nothing to fix unless it stays full; a slot is held only while a call is out and a killed process frees its slots at once. Off: unset `C3D_MAX_IN_FLIGHT` |
@@ -497,7 +500,6 @@ that the keys work end to end):
| `skills routing` | WARN | a routed skill has no installed bundle | restore the missing bundle from the checkout or update the stale route |
| `skills discovery` | OK | always informational | shows the agent-native directories where bundles are materialised |
| `claude-code Skill tool` | FAIL | the Claude backend would deny native skill activation | update/reinstall the harness so `Skill` is present in Claude Code's allowed tools |
-| `gemini-cli skills setting` | FAIL | the per-session gemini-cli system settings do not pin `skills.enabled` | update/reinstall the harness; without the pin a user's `skills.enabled: false` hides every bundle from gemini-cli |
---
@@ -574,7 +576,7 @@ cleanup. On this machine `eval/bench/out/` is read-only reference material
Uninstalling does not touch `~/.config/3dcodeverse/config.yaml`,
`~/.config/astra3d/gemini_keys.env` or the globally installed CLIs — remove
-those by hand (`npm rm -g @google/gemini-cli @anthropic-ai/claude-code @openai/codex`).
+those by hand (`npm rm -g @anthropic-ai/claude-code @openai/codex`; agy: `rm ~/.local/bin/agy`).
---
@@ -589,5 +591,5 @@ those by hand (`npm rm -g @google/gemini-cli @anthropic-ai/claude-code @openai/c
| Chrome (puppeteer) | 148.0.7778.97 (+ headless-shell) | `~/.cache/puppeteer` |
| Blender | 5.0.1 (2025-12-16) | `~/.local/bin/blender-5.0` → `~/3dcodeverse_data/tools/blender-5.0.1-linux-x64` |
| git | 2.53.0 | `/usr/bin/git` |
-| gemini-cli / claude / codex / agy | 0.53.0 / 2.1.241 / 0.149.0 / 1.1.19 | npm global / `~/.local/bin` |
+| agy / claude / codex | 1.3.4 / 2.1.241 / 0.149.0 | `~/.local/bin` / npm global |
| GPU (Chrome WebGL) | ANGLE · D3D12 · NVIDIA GeForce RTX 5090 Laptop GPU · OpenGL ES 3.1 | via `--use-angle=gl-egl` + Mesa d3d12 |
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index bc9e8ab9..df838cfd 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -13,8 +13,8 @@ test-pinned (`tests/core/test_interfaces_names.py`).
* Chat models: `<provider>:<model>` — `gemini:*` · `anthropic:*` · `openai:*`
(`models.registry.parse_model_id`).
-* Coding agents: `<kind>:<model>` — `gemini-cli:*` · `claude-code:*` · `codex:*` ·
- `agy:*` (`agents.registry.parse_agent_id`).
+* Coding agents: `<kind>:<model>` — `agy:*` · `claude-code:*` · `codex:*`
+ (`agents.registry.parse_agent_id`; `KINDS`; `gemini-cli:*` deleted in D103).
* **Δ** Single-shot generation ids: `single-shot:<provider>:<model>` — handled only
inside `tracks/generation.py` (`is_single_shot`, `single_shot_model_id`); never
registered in `agents/`. `Spec.backends.generator` accepts any of the three.
@@ -180,29 +180,30 @@ materialize_workspace(ws, *, agent_kind, contract_md, cookbook_text, spatial_too
# so an agent-written <ws>/<lang>/cookbook.md shadowed the harness cookbook); "" → "No cookbook is available" + a warning
# mcp_command defaults to cli_common.default_mcp_command(ws) = [sys.executable, -m codeverse3d.spatial.mcp_server --workspace …]
# (None/[] = the default — no ValueError); tracks/common.Services.materialize takes no mcp_command
-# writes AGENTS.md + GEMINI.md + CLAUDE.md (same body), ws/.3dcode/cookbook.md (Δ written in: gemini-cli cannot read
-# outside the workspace), .geminiignore/.aiexclude, and MCP wiring:
-# gemini-cli → ws/.gemini/settings.json only gets context.fileFiltering.respectGitIgnore=false; the 3dcode server
-# and mcp.allowed live in the per-session system settings (Δ that file is agent-writable — audit 2026-08-27)
+# writes AGENTS.md + CLAUDE.md (same body; Δ D103 no GEMINI.md — agy reads it AND AGENTS.md, so the body loaded
+# twice), ws/.3dcode/cookbook.md (Δ written in: an agent may not read outside the workspace), .antigravityignore,
+# and NO MCP file in the workspace (it is agent-writable — audit 2026-08-27); MCP wiring is per session:
# claude-code → trajectories/<label>_rNN/mcp.json codex → codex_mcp_overrides(mcp_command) built PER SESSION:
# -c mcp_servers.3dcode.command=… -c mcp_servers.3dcode.args=[…] -c mcp_servers.3dcode.default_tools_approval_mode="approve"
# (Δ without the approval mode every MCP tool call is elicited and auto-cancelled)
-# agy → no per-workspace MCP; body documents `3dcode tools <name> --json … --workspace .` as the fallback
+# agy → API mode (Gemini model + keys): <cache_dir>/agy_homes/<session>/.gemini/config/mcp_config.json in the
+# session's own HOME (its env.HOME = the real home); subscription mode: none. The body documents the shell
+# fallback `python -m codeverse3d.cli.main tools <name> --json …` either way
res = agent.run(AgentJob(workspace=..., prompt=..., label="baseline", timeout_s=1800, max_turns=60,
spatial_tools=True, write_roots=["src","public"])) # typed kwargs only: no extra=, no model=
-res.ok, res.exit_reason # completed | timeout | error | budget | model_substituted
-res.turns # claude-code num_turns · codex turn.completed count · agy num_turns · gemini-cli 0 (not on the wire)
+res.ok, res.exit_reason # completed | timeout | error | budget (model_substituted: gemini-cli's, no backend sets it since D103)
+res.turns # claude-code num_turns · codex turn.completed count · agy num_turns
res.files_changed (git-derived, attributed per session), res.usage, res.transcript_path, res.tool_calls, res.errors
res.transient # a provider failure a retry may get through (5xx / overloaded / 429 / dropped connection)
res.quota # Δ 2026-09-22 the vendor's usage limit is spent — never also transient
res.provider_wait_s # Δ seconds of duration_s lost to provider errors (cli_common.provider_wait; codex: 0.0)
# Δ 2026-09-22 the prompt reaches EVERY CLI on stdin (cli_common.invoke; no -p / --print / positional text,
# codex "-"), byte for byte; the >100 kB task_prompt.md stub is gone. The transcript's invoke row keeps
-# argv + stdin_bytes. res.usage is the CLI's envelope; with none (killed / given up) gemini-cli's comes
-# from its chat record (read_gemini_chats) and claude-code's from its stream's per-message usage
-# (output a floor); result.json "usage_from" says which. A session sees only the routed skill bundles:
+# argv + stdin_bytes. res.usage is the CLI's envelope; with none (killed / given up) claude-code's comes
+# from its stream's per-message usage (output a floor), codex's is an estimate, agy books none;
+# result.json "usage_from" says which. A session sees only the routed skill bundles:
# claude --setting-sources project + CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1 + --settings skillOverrides;
-# codex -c skills.bundled.enabled=false; gemini-cli skills.disabled (its two built-ins); agy: no switch.
+# codex -c skills.bundled.enabled=false; agy: no switch.
from codeverse3d.agents.cli_common import is_transient_failure, is_quota_failure, is_rate_limited, provider_wait
# THE failure vocabulary (one place; the backends apply it to what the CLI said about the call that ended
# its session) and provider_wait(failures=[(t, backoff_s)], end, progress=[t] | None) -> seconds
@@ -227,14 +228,18 @@ it is what names the effect library without listing every module).
Each session writes `trajectories/<label>_rNN/` (files: docs/RUN_LAYOUT.md); **Δ** a re-run of the
same label+round lands in `<label>.a2_rNN` (then `.a3` …) — the first attempt is never overwritten;
`result.json` records `attempt` + `job_label`. Each session makes two git commits (`pre:`/`agent:<label>`).
-gemini-cli specifics: system settings file via `GEMINI_CLI_SYSTEM_SETTINGS_PATH`
-(written per session into the trajectory dir: api-key auth, `dynamicModelConfiguration=true`
-else silent model substitution → `exit_reason="model_substituted"`, `folderTrust.enabled=false`
-else workspace MCP silently dropped, plus `mcpServers.3dcode` + `mcp.allowed=["3dcode"]` — **Δ** it is
-applied LAST and `mcp.allowed` replaces, so an agent-planted server in ws/.gemini/settings.json is Blocked). **Δ** `Usage.input_tokens` = `tokens.prompt` (TOTAL prompt incl.
-cached; `tokens.input` is the uncached count) and each served model is priced at its
-own rate. KeyPoolExhausted never escapes `run()` (→ `exit_reason=budget`); retries
-prefer a different key (10 s wait) before re-using the same one.
+agy specifics (**Δ D103**, which deleted the gemini-cli backend): `AntigravityAgent.api_mode` = model starts
+with `gemini` AND Gemini keys are configured. API mode: one key per session from THE shared pool
+(`models.gemini.shared_pool`, `pool.session_key()`, no in-flight slot), outcome reported back
+(`_pool_outcome`: 401/403/API_KEY_INVALID → dead, 429 → cooldown, 5xx, ok, skip); a fresh HOME under
+`<cache_dir>/agy_homes/` holds `.gemini/antigravity-cli/settings.json` = `{"modelProvider": "gemini"}` (without
+it agy ignores `GEMINI_API_KEY` and asks for a login) + the MCP config, and is deleted after the session (the
+tool trace is read from its conversation db first); argv `--model gemini-api://<bare id> --effort <e>`, effort
+from a `-low/-medium/-high` suffix, default `high`; usage priced at Gemini list price with
+output = output − thinking, thoughts = thinking (agy's output already includes thinking). Subscription mode:
+real HOME, no MCP, `cost_usd=0` (the ledger re-prices $0 rows at list price). KeyPoolExhausted never escapes
+`run()` (→ `exit_reason=budget`). No retry loop in the backend: agy retries its own calls; a transient
+death goes to the round loop's one retry, which takes a fresh key.
## languages/
```python
from codeverse3d.languages import get_runtime # (Language | str) -> LanguageRuntime
@@ -562,14 +567,13 @@ from codeverse3d.judges.prompt_builder import gates_section, contact_ledger #
from codeverse3d.tracks.generation import write_files # (ws, files, *, allowed_roots, only=None, frozen=(), on_skip=None):
# frozen = harness-owned paths a single-shot envelope may not rewrite (skipped with a reason, never an error)
from codeverse3d.agents.cli_common import find_json_object, default_mcp_command # THE one JSON-envelope finder behind
- # parse_gemini_json / parse_claude_json / parse_agy_json; default_mcp_command(ws, *, language, track, round_index)
+ # parse_claude_json / parse_agy_json; default_mcp_command(ws, *, language, track, round_index)
from codeverse3d.tracks.generation import generate, run_agent_task, parse_multifile, is_single_shot
GenerationTask.phase: int = 0 # tasks run in parallel WITHIN a phase, phases in ascending order
# (tracks.steps.run_generation_tasks). Only user: the scoped baseline — phase 0 = one session per
# part group (`baseline_<parts>`, own files only), phase 1 = ONE `assemble` session that owns the
# entry file and the placement gates. Every other caller is phase 0, i.e. unchanged.
generate(ws, *, agent_id, task, ..., budget=BudgetGuard) -> GenerationResult
- # GenerationResult.storm: every session died on a transient streak (AgentResult.transient) and wrote nothing
# Δ 2026-09-22 GenerationResult.transient / .quota carry the backend's typed class; a call that RAISED is
# GenerationResult.from_error(label, e) — transient = tracks.generation.is_model_outage(e) (ModelError
# retryable or 429/5xx; moved from scene_assets, the one exception classifier)
@@ -578,7 +582,8 @@ from codeverse3d.tracks.steps import RoundFailed # RoundFailed(message, *, tra
# the round once), never the message (looks_transport / looks_quota deleted)
tracks.common.generate_for(ctx: RunContext, task: GenerationTask) -> GenerationResult
# THE call every stage makes (env, zones, rounds, repairs, asset ladder, judged fix): generate()
- # with everything ctx knows, and a storm-dead task retried through single_shot_ctx(ctx) (D68)
+ # with everything ctx knows; Δ D103 no storm fallback (D68's single-shot retry, GenerationResult.storm and
+ # the asset ladder's storm-repair rung are gone): a transient death reaches the round loop's one retry
tracks.common.single_shot_agent_id(agent_id, chat_model_id='') -> str · single_shot_ctx(ctx) -> RunContext | None
# moved from tracks.scene_assets 2026-09-07 (never scene-specific)
# GenerationResult adds turns / sessions / turn_capped. A turn cap is applied ONLY if the machine
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index 550ce109..ad7973fa 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -1,7 +1,8 @@
# Runbook — operating the harness
Everything here was exercised on this machine (WSL2, RTX 5090, Blender 5.0.1,
-node 24, gemini-cli 0.53, claude 2.1, codex 0.147+, agy 1.1) on 2026-08-23. Paths
+node 24, gemini-cli 0.53 (removed in D103), claude 2.1, codex 0.147+, agy 1.1) on 2026-08-23;
+the agy rows re-checked on agy 1.3.4, 2026-10-13. Paths
are relative to `/home/yipeng/3dcodeverse/harness` unless absolute. The CLI is
`3dcodeverse` with short alias `3dcode` (used below).
@@ -29,7 +30,7 @@ one home); each setting's default and description is its `Settings` field in
# static object — Blender (default language, multi-file src/model.py + src/parts/*.py)
3dcode make "a mid-century wooden dining chair" --track static_object --language blender
3dcode make "a brass desk lamp" --track static_object --language cadquery
-3dcode make "a classic park bench" --track static_object --language threejs --generator gemini-cli:gemini-3.7-flash
+3dcode make "a classic park bench" --track static_object --language threejs --generator agy:gemini-3.7-flash
# articulated object — bpy links + URDF
3dcode make "a bedside cabinet with one hinged door and one drawer" --track articulated_object --language urdf_blender
# scene — multi-file three.js + GLSL (+ optional bpy GLB assets chosen by the planner)
@@ -64,39 +65,40 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60`).
| id | what runs | notes |
|---|---|---|
-| `gemini-cli:gemini-3.7-flash` (default) | `gemini -m … --approval-mode yolo --skip-trust --output-format json`, prompt on stdin; every spatial tool over MCP | cheapest agentic path; see gotchas below |
+| `agy:gemini-3.7-flash` (default) | `agy --dangerously-skip-permissions --print-timeout … --output-format json --add-dir ws --log-file trajectories/<label>_rNN/agy.log --model gemini-api://gemini-3.7-flash --effort high`, prompt on stdin (no `--print`: `--print -` sends "-") | Gemini-API mode with keys: pool key, every spatial tool over MCP, priced; see gotchas below. Truncates a prompt past ~175 kB itself |
| `single-shot:gemini:gemini-3.7-flash` | one structured-output call → multi-file envelope, no tools | fastest/cheapest; baseline for "raw model" deltas |
| `claude-code:<model>` | `claude -p --dangerously-skip-permissions --setting-sources project --settings '{"skillOverrides":…}' --mcp-config trajectories/<label>_rNN/mcp.json --strict-mcp-config …`, prompt on stdin, `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1` | local subscription — test lightly; no user setting source, so `~/.claude/settings.json` (effortLevel, hooks, env) does not reach a session |
| `codex:<model>[@<effort>]` | `codex exec --json -C ws --sandbox workspace-write -c model_reasoning_effort=high -c skills.bundled.enabled=false -c mcp_servers.3dcode.… -`, prompt on stdin | subscription; MCP tools need `default_tools_approval_mode="approve"` (harness passes it); reasoning effort is always stated (`Settings.agents.codex_reasoning_effort`, default `high`; `codex:gpt-5.6-sol@medium` per id, `""` to defer to `~/.codex/config.toml`) |
-| `agy:<model>` | `agy --add-dir ws --log-file trajectories/<label>_rNN/agy.log …`, prompt on stdin (no `--print`: `--print -` sends "-") | no per-workspace MCP: tools via `3dcode tools <name> --json … --workspace .`; no served-model or cost reporting; truncates a prompt past ~175 kB itself |
+| `agy:<model>` (non-Gemini, e.g. `claude-sonnet-4-6`, or no keys) | same argv, `--model <id>` (a bare id gains agy's effort suffix) | subscription sign-in: no MCP (tools via `python -m codeverse3d.cli.main tools <name> --json …`), booked $0; the sign-in no longer serves `gemini-3.7-flash` (2026-10-13) |
| `gemini:* / anthropic:* / openai:*` | ChatModel for planner / judge / captioner / single-shot | Anthropic/OpenAI untested live here |
-### gemini-cli gotchas (handled by `agents/backends.py`; do not undo)
-* A system settings file, written per session into `trajectories/<label>_rNN/` and passed via
- `GEMINI_CLI_SYSTEM_SETTINGS_PATH`: api-key auth (`security.auth.selectedType="gemini-api-key"`;
- a pre-existing OAuth login of your own is overridden, not consumed),
- `experimental.dynamicModelConfiguration=true` (else unknown models are silently
- substituted → checked, `exit_reason=model_substituted`), `security.folderTrust.enabled=false`
- (else workspace MCP servers are silently ignored even with `--skip-trust`), and the `3dcode`
- MCP server itself with `mcp.allowed=["3dcode"]` — the file is merged LAST and `mcp.allowed`
- replaces, so a server the agent plants in the workspace's `.gemini/settings.json` is Blocked.
-* Workspace `.gemini/settings.json` sets `context.fileFiltering.respectGitIgnore=false`
- so the fine-grained `.geminiignore` (not the git ignore) decides what the agent can
- read: build/census/measurement JSON stay readable, renders/judge output and the whole
- `trajectories/` stay hidden (the prompt comes on stdin; there is no prompt file).
-* The system settings also disable gemini-cli's two built-in skills (`skills.disabled`),
- so a session lists only the routed bundles.
-* Usage when the CLI printed no envelope (watchdog kill; a give-up after its own 503
- retries, which writes an error object to STDERR and exits 247): the attempt's chat
- record under `~/.gemini/tmp/<project>/chats/` — `result.json` `usage_from` says which.
-* One pool key injected as `GEMINI_API_KEY`; other credential env stripped; retries
- prefer a different key (never raise KeyPoolExhausted out of a session).
-* Cost accounting: `tokens.prompt` (total, incl. cached) is the input count; each
- served model priced at its own rate.
-* Cookbook copied to `ws/.3dcode/cookbook.md` (gemini-cli cannot read outside the ws).
+### agy gotchas (handled by `agents/backends.py`; do not undo — D103)
+* API mode (`AntigravityAgent.api_mode`: a `gemini*` model AND Gemini keys configured): one key
+ per session from THE shared pool (`KeyPool.session_key`, no in-flight slot) as `GEMINI_API_KEY`,
+ its outcome reported back (429 → cooldown, 401/403/`API_KEY_INVALID` → dead, 5xx, ok, skip);
+ other credential env stripped; KeyPoolExhausted → `exit_reason=budget`, never raised.
+* Each API-mode session gets a fresh HOME under `<cache_dir>/agy_homes/…` holding
+ `.gemini/antigravity-cli/settings.json` = `{"modelProvider": "gemini"}` (without it agy ignores
+ the key and asks for a login) and `.gemini/config/mcp_config.json` with the `3dcode` server
+ (agy has no per-workspace MCP; the server's `env.HOME` is the real home). The HOME is deleted
+ after the session; the tool trace is read from its conversation db first. `PUPPETEER_CACHE_DIR`
+ points the agent's shell at the real Chrome cache.
+* argv `--model gemini-api://<bare id> --effort <low|medium|high>`: the id goes to the API
+ verbatim (any model the key serves); effort from an agy-style `-low/-medium/-high` suffix,
+ default `high` (the Gemini API's own default).
+* Cost: priced at Gemini list price; agy's `output_tokens` already include `thinking_tokens`, so
+ output = output − thinking, thoughts = thinking (billed once).
+* Subscription mode (non-Gemini model, or no keys): real HOME and sign-in, no MCP (AGENTS.md
+ documents the shell fallback), booked $0 by the backend (the ledger re-prices $0 rows).
+* No retry loop in the backend: agy retries its own model calls (≤ 30 s waits since 1.3.4, stops
+ at once on a spent daily quota); a transient death goes to the round loop's ONE transport retry,
+ which takes a fresh key. There is no single-shot storm fallback (deleted in D103).
+* Workspace files: `AGENTS.md` + `CLAUDE.md` (no `GEMINI.md`: agy reads both it and AGENTS.md)
+ and `.antigravityignore`, which hides only noise (renders/judge output, the whole
+ `trajectories/`); build/census/measurement JSON stay readable.
+* Cookbook copied to `ws/.3dcode/cookbook.md` (an agent may not read outside the ws).
* MCP server argv is `[sys.executable, -m, codeverse3d.spatial.mcp_server, --workspace, ws]`;
- server name `3dcode` → tools appear as `mcp_3dcode_<name>` (gemini) / `mcp__3dcode__<name>`
- (claude). `3dcode mcp --workspace runs/<slug>` execs the same server;
+ server name `3dcode` → tools appear as `mcp__3dcode__<name>` (claude). `3dcode mcp --workspace runs/<slug>` execs the same server;
`python -m codeverse3d.spatial.mcp_server --workspace ws --list` prints the tools.
## 4. Where outputs land
@@ -296,7 +298,7 @@ python -m bench.run_bench bench/prompts/static_objects_v1.yaml --generator singl
python -m bench.report bench/out/static_objects_v1 # report.md + self-contained report.html (gallery)
cd ../harness
python ../eval/bench/compare_backends.py --prompts ../eval/bench/prompts/compare_v1.yaml \
- --arms harness:gemini-cli:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out ../eval/bench/out/compare_v1
+ --arms harness:agy:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out ../eval/bench/out/compare_v1
```
Results stream to `results.jsonl` (resumable). The batteries, the protocol and judge
calibration: `eval/docs/EVAL.md` (§2 lists the batteries).
diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.md
index 51c2689d..973e8281 100644
--- a/harness/docs/SKILLS.md
+++ b/harness/docs/SKILLS.md
@@ -9,8 +9,8 @@ stays the reference manual with the copyable code; a skill states rules and numb
names the cookbook section to fetch. Two libraries of truth would be worse than one.
`SKILL.md` is an open standard (agentskills.io, Dec 2025), which is why the format below is
-not ours to bend: **claude-code, codex, gemini-cli and agy discover these bundles
-themselves** — proven live, see §7. (The in-process `api-agent`, the one backend that
+not ours to bend: **claude-code, codex and agy discover these bundles
+themselves** — proven live, see §7 (gemini-cli did too, until its backend was deleted in D103). (The in-process `api-agent`, the one backend that
needed harness-side injection, was deleted 2026-08-28; bundles now reach a session only
through its vendor's native skill loader.)
@@ -36,7 +36,7 @@ one file, `skills/prompting.py`:
| backend | discovery root |
|---|---|
| `claude-code` | `.claude/skills` |
-| `codex`, `gemini-cli`, `agy` | `.agents/skills` |
+| `codex`, `agy` | `.agents/skills` |
It was read out of the shipped binaries, not assumed — and re-read 2026-09-22 against the
installed versions, with what each CLI needs to see the bundles and what its own record of
@@ -45,7 +45,7 @@ a session says it did with them:
| CLI (2026-09-22) | workspace roots · user roots | what must hold | what the model is shown | activation, as its own record logs it |
|---|---|---|---|---|
| `claude-code` 2.1.280 | `.claude/skills` · `~/.claude/skills` (+ claude.ai-synced skills, plugins) | `Skill` in `--allowedTools`; never `--disable-slash-commands` ("Disable all skills") | name + description list; stream-json `init` event's `skills` | `Skill` tool `{"skill": name}`, then `Read` of `references/` |
-| `gemini-cli` 0.53.0 | `.gemini/skills`, `.agents/skills` — **only in a trusted folder** · `~/.gemini/skills`, `~/.agents/skills` | `skills.enabled` (default true; the harness pins it in the per-session system settings, merged last) and folder trust (`folderTrust.enabled=false` ⇒ trusted) | `<available_skills>` XML (name, description, location) in the system prompt + `activate_skill` with an enum of names | `activate_skill` `{"name": name}` returns the body; `read_file` for `references/` |
+| `gemini-cli` 0.53.0 (backend deleted in D103) | `.gemini/skills`, `.agents/skills` — **only in a trusted folder** · `~/.gemini/skills`, `~/.agents/skills` | `skills.enabled` (default true; the harness pins it in the per-session system settings, merged last) and folder trust (`folderTrust.enabled=false` ⇒ trusted) | `<available_skills>` XML (name, description, location) in the system prompt + `activate_skill` with an enum of names | `activate_skill` `{"name": name}` returns the body; `read_file` for `references/` |
| `codex` 0.155.1 | `.agents/skills` of the working root (`-C <ws>`, also the repo root) · `$CODEX_HOME/skills` (+ `.system`) | nothing — listed from an untrusted `/tmp` workspace too (`codex debug prompt-input`) | `## Skills` section: name, description and an aliased path `r1/<name>/SKILL.md` with a `### Skill roots` table | a shell `sed`/`cat` of `SKILL.md` (an `exec --json` `command_execution` item) |
| `agy` 1.2.2 | `.agents/skills` under the repo root · a global customization root under `~/.gemini/` | nothing; `--disable-slash-commands` only stops `/name` expansion of the prompt (1.1.9 changelog) | a skills section of its system prompt (paths included: its first calls were the four absolute `SKILL.md` paths, with no listing before them) | `view_file` of `SKILL.md` (a step in its conversation database) |
@@ -62,7 +62,7 @@ skills of its own; each is switched off with the CLI's documented knob where it
|---|---|---|---|
| `claude-code` 2.1.280 | 26: bundled (`update-config`, `code-review`, `loop`, …), account-synced (`deep-research`, `anthropic-skills:*`, …) | `--setting-sources project` (synced skills and plugins come with the "user" source) + `CLAUDE_CODE_DISABLE_BUNDLED_SKILLS=1` + `--settings {"skillOverrides": {"design": "off", "doctor": "off"}}` (the two that survive the bundled switch by design) | nothing — and the owner's `~/.claude/settings.json` (effortLevel, hooks, env) no longer reaches a session |
| `codex` 0.155.1 | 5 `.system` (imagegen, openai-docs, plugin-creator, skill-creator, skill-installer) | `-c skills.bundled.enabled=false` | any user root (`~/.codex/skills`, `~/.agents/skills`): no stable switch; none here |
-| `gemini-cli` 0.53.0 | 2 built-ins (skill-creator, antigravity-support) — `gemini skills list` hides them, the model does not | `skills.disabled` in the per-session system settings (by name) | the user roots (`~/.gemini/skills`, `~/.agents/skills`): no switch; none here |
+| `gemini-cli` 0.53.0 (deleted in D103) | 2 built-ins (skill-creator, antigravity-support) — `gemini skills list` hides them, the model does not | `skills.disabled` in the per-session system settings (by name) | the user roots (`~/.gemini/skills`, `~/.agents/skills`): no switch; none here |
| `agy` 1.2.8 | 5 built-ins (agy-customizations, antigravity-guide, generative_ui, migrate-workflows, permissioned-github; `agy -p /skills` lists them without a turn) | none per session: built-ins survive even an agent's `inherit_user: false` | all 5 |
**Adding a backend is one row in that table** (`_BACKEND_ROOTS`, read by `skill_path`). A test
@@ -249,9 +249,9 @@ failure verdict as `failed`), then one `tool_trace` row that closes the session
| backend | source | skill activation looks like |
|---|---|---|
| claude-code | `--output-format stream-json --verbose` (was `json`, which carried no tool stream); the `init` event's `skills` list is kept as `skills_index` | `Skill {"skill": name}` |
-| gemini-cli | its chat record, `~/.gemini/tmp/<project>/chats/session-*.jsonl`, found by the project's `.project_root` + mtime — so a session the watchdog killed before it printed JSON still has one (and, since 2026-09-22, its usage: `read_gemini_chats` reads calls, tokens and times in one pass). `--output-format json` stays: it has per-tool COUNTS only, and `stream-json` drops the `thoughts` tokens pricing needs | `activate_skill {"name": name}` |
+| gemini-cli (deleted in D103) | its chat record, `~/.gemini/tmp/<project>/chats/session-*.jsonl`, found by the project's `.project_root` + mtime — so a session the watchdog killed before it printed JSON still has one (and, since 2026-09-22, its usage: `read_gemini_chats` reads calls, tokens and times in one pass). `--output-format json` stays: it has per-tool COUNTS only, and `stream-json` drops the `thoughts` tokens pricing needs | `activate_skill {"name": name}` |
| codex | the `exec --json` events it already streamed (`command_execution`, `mcp_tool_call`, `file_change`) | a `sed`/`cat` of `…/<name>/SKILL.md` |
-| agy | its conversation database, `~/.gemini/antigravity-cli/conversations/<conversation_id>.db` — a schema-free walk of each step's protobuf for (call id, tool, JSON args) | `view_file` of `…/<name>/SKILL.md` |
+| agy | its conversation database, `<HOME>/.gemini/antigravity-cli/conversations/<conversation_id>.db` (HOME = the API-mode session's own, read before it is deleted; else `~`) — a schema-free walk of each step's protobuf for (call id, tool, JSON args) | `view_file` of `…/<name>/SKILL.md` |
`skills/telemetry.probe_reads` credits only sessions logged after the attach
(`SkillsMaterialized.attached_at`), and uses the transcript only when **every** such session
diff --git a/harness/docs/SKILLS_LEDGER.md b/harness/docs/SKILLS_LEDGER.md
index ea7d27e8..880f06c5 100644
--- a/harness/docs/SKILLS_LEDGER.md
+++ b/harness/docs/SKILLS_LEDGER.md
@@ -116,13 +116,15 @@ system settings listed the four + the control, all `[Enabled]`, from
their tool trace (found by `.project_root` + mtime, not `session_id`, for exactly this
case). They also expose a cost gap outside this lane: a killed gemini-cli session is
recorded at $0 although its chat record holds ~$0.34 of tokens (closed the same day:
- the chat record is such a session's usage — `agents/backends.read_gemini_chats`).
+ the chat record is such a session's usage — `agents/backends.read_gemini_chats`; deleted with the
+ gemini-cli backend in D103).
* codex's MCP server did not start in this rig (codex hands MCP servers a scrubbed env; the
lane worktree is on `PYTHONPATH`, not installed), so it spent its session probing the
server by hand — a rig artefact, not a skills result.
**Gaps closed** (code, 2026-09-22): gemini-cli `skills.enabled` pinned in the per-session
-system settings (merged last; a user's `false` would have hidden every bundle); claude-code
+system settings (merged last; a user's `false` would have hidden every bundle — moot since D103
+deleted that backend); claude-code
switched to `--output-format stream-json --verbose` (its `json` output carried no tool
calls); every backend writes its CLI's tool calls into `transcript.jsonl` and the read probe
reads them first; agy's `AgentResult.tool_calls` is the trace count (was always 0).
diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.py
index df0766ee..befd8b97 100644
--- a/harness/tests/agents/test_antigravity.py
+++ b/harness/tests/agents/test_antigravity.py
@@ -1,4 +1,4 @@
-"""AntigravityAgent: envelope parsing, argv, fake binary, live smoke."""
+"""AntigravityAgent: envelope parsing, argv, fake binary, Gemini-API mode, live smoke."""
from __future__ import annotations
@@ -14,9 +14,17 @@ from codeverse3d.agents.backends import (
resolve_model,
)
from codeverse3d.agents.cli_common import begin_session
+from codeverse3d.config import get_settings
from codeverse3d.contracts.agent import AgentJob
from codeverse3d.workspace import Workspace
+
[email protected](autouse=True)
+def _subscription(monkeypatch, tmp_path):
+ """Every test here runs on the subscription sign-in unless it hands out keys itself."""
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", [])
+ monkeypatch.setattr(get_settings(), "cache_dir", tmp_path / "cache")
+
ENVELOPE = {"conversation_id": "c1", "status": "SUCCESS", "response": "DONE\n", "duration_seconds": 3.0, "num_turns": 1,
"usage": {"input_tokens": 18589, "output_tokens": 494, "thinking_tokens": 413, "cache_read_tokens": 12199, "total_tokens": 19083}}
@@ -89,7 +97,9 @@ def test_fake_run_json_and_text(tmp_ws: Workspace, fake_bin, monkeypatch):
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="a", timeout_s=30))
assert res.ok and res.text.strip() == "DONE", res.errors
u = res.usage
- assert (u.input_tokens, u.output_tokens, u.thoughts_tokens, u.cached_tokens) == (18589, 494, 413, 12199)
+ # agy's input_tokens EXCLUDE the cache reads and its output_tokens CONTAIN the thinking
+ # (total == input + output): the pricing convention is total prompt, thinking billed once
+ assert (u.input_tokens, u.output_tokens, u.thoughts_tokens, u.cached_tokens) == (18589 + 12199, 81, 413, 12199)
assert [f.path for f in res.files_changed] == ["src/hello.txt", "src/prompt.txt"]
assert (tmp_ws.src / "prompt.txt").read_text().endswith("\n\nhello") # on stdin, after the workspace header
monkeypatch.setenv("FAKE_MODE", "text")
@@ -157,3 +167,55 @@ def test_the_run_uses_and_records_the_resolved_id(tmp_ws: Workspace, fake_bin):
assert res.ok and res.text.strip() == "DONE", res.errors
assert res.usage.model == "gemini-3.7-flash-medium"
+
+
+#: agy in Gemini-API mode, as the harness drives it: everything it needs is in its own HOME
+FAKE_AGY_API = r'''
+args = sys.argv[1:]
+prompt = sys.stdin.read()
+home = os.environ["HOME"]
+settings = json.load(open(os.path.join(home, ".gemini/antigravity-cli/settings.json")))
+mcp = json.load(open(os.path.join(home, ".gemini/config/mcp_config.json")))
+os.makedirs("src", exist_ok=True)
+open("src/seen.json", "w").write(json.dumps({
+ "key": os.environ.get("GEMINI_API_KEY"), "home": home, "settings": settings, "mcp": mcp,
+ "model": args[args.index("--model") + 1], "effort": args[args.index("--effort") + 1]}))
+if os.environ.get("FAKE_MODE") == "429":
+ print(json.dumps({"conversation_id": "c9", "status": "ERROR", "response": "", "error": "Error 429"}))
+ print('AGY_ERROR: {"status":"RESOURCE_EXHAUSTED","error_code":429,"retryable":true}', file=sys.stderr)
+ sys.exit(3)
+print(''' + repr(json.dumps(ENVELOPE)) + r''')
+'''
+
+
+def test_api_mode_runs_on_a_pool_key_in_a_home_of_its_own(tmp_ws: Workspace, fake_bin, monkeypatch):
+ """A Gemini model with keys configured: one pool key, agy's API-mode setting and the 3dcode MCP
+ server in a fresh HOME (gone afterwards), the model sent verbatim with its effort, usage priced."""
+ from codeverse3d.agents import backends
+
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", ["key-one"])
+ a = AntigravityAgent("gemini-3.7-flash-low", binary=fake_bin("agy", FAKE_AGY_API))
+ assert a.api_mode and a.served_model() == "gemini-3.7-flash"
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="api", timeout_s=30, language="blender"))
+ assert res.ok, res.errors
+ seen = json.loads((tmp_ws.src / "seen.json").read_text())
+ assert seen["key"] == "key-one" and seen["settings"] == {"modelProvider": "gemini"}
+ assert (seen["model"], seen["effort"]) == ("gemini-api://gemini-3.7-flash", "low")
+ server = seen["mcp"]["mcpServers"]["3dcode"]
+ assert server["args"][:2] == ["-m", "codeverse3d.spatial.mcp_server"] and server["env"] == {"HOME": str(Path.home())}
+ assert seen["home"] != str(Path.home()) and not Path(seen["home"]).exists() # deleted after the session
+ assert res.usage.model == "gemini-3.7-flash" and res.usage.cost_usd > 0
+ # a bare id runs at the API's own default effort
+ assert AntigravityAgent("gemini-4-argon").model_args() == ["--model", "gemini-api://gemini-4-argon", "--effort", "high"]
+ # a 429 cools the key in the shared pool
+ monkeypatch.setenv("FAKE_MODE", "429")
+ res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="api429", timeout_s=30, spatial_tools=False))
+ assert not res2.ok and res2.exit_reason == "budget" and res2.transient
+ assert backends._key_pool().stats()["keys"][0]["429"] >= 1
+ assert json.loads((tmp_ws.src / "seen.json").read_text())["mcp"] == {"mcpServers": {}}
+
+
+def test_a_model_agy_only_serves_on_the_subscription_never_takes_a_key(monkeypatch):
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", ["key-one"])
+ assert not AntigravityAgent("claude-sonnet-4-6").api_mode
+ assert AntigravityAgent("gemini-3.7-flash").api_mode
diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.py
index 79bd42a1..24bf9a63 100644
--- a/harness/tests/agents/test_cli_common.py
+++ b/harness/tests/agents/test_cli_common.py
@@ -94,7 +94,7 @@ def test_one_failure_vocabulary():
assert is_rate_limited("status 429") and is_rate_limited("RESOURCE_EXHAUSTED") and not is_rate_limited("503")
-def test_queued_invocation_and_retry_share_the_run_deadline(tmp_ws: Workspace, monkeypatch):
+def test_queued_invocations_share_the_run_deadline(tmp_ws: Workspace, monkeypatch):
clock = [100.0]
windows = []
@@ -109,12 +109,12 @@ def test_queued_invocation_and_retry_share_the_run_deadline(tmp_ws: Workspace, m
clock[0] = 104.0 # waiting for a workspace lock consumed four seconds
invoke(s, ["unused"], {}, prompt="p")
clock[0] = 109.0
- invoke(s, ["unused"], {}, prompt="p", attempt=2, soft_timeout_s=90)
+ invoke(s, ["unused"], {}, prompt="p")
assert windows == [(6.0, 6.0), (1.0, 1.0)]
clock[0] = 111.0
- expired = invoke(s, ["unused"], {}, prompt="p", attempt=3)
+ expired = invoke(s, ["unused"], {}, prompt="p")
assert len(windows) == 2 and expired.timed_out and expired.duration_s == 0
- assert "before CLI launch" in (s.traj.dir / "stderr.3.log").read_text()
+ assert "before CLI launch" in (s.traj.dir / "stderr.log").read_text()
assert [r["started"] for r in s.traj.read_transcript() if r["kind"] == "invoke"] == [True, True, False]
@@ -199,7 +199,7 @@ _ENDINGS = {
@pytest.mark.parametrize("ending", sorted(_ENDINGS))
[email protected]("vendor", ["gemini-cli", "claude-code", "codex", "agy"])
[email protected]("vendor", ["claude-code", "codex", "agy", "agy-api"])
def test_every_cli_backend_ends_by_one_rule(tmp_ws: Workspace, fake_bin, monkeypatch, vendor, ending):
"""N71: one ``classify_end`` — a kill with no provider evidence is not transient, and a spent
usage limit or a 429 is ``budget``, whichever vendor's CLI said it."""
@@ -207,18 +207,18 @@ def test_every_cli_backend_ends_by_one_rule(tmp_ws: Workspace, fake_bin, monkeyp
AntigravityAgent,
ClaudeCodeAgent,
CodexAgent,
- GeminiCliAgent,
)
from codeverse3d.config import get_settings
monkeypatch.setattr(cli_common, "IDLE_GRACE_S", 0.3)
- monkeypatch.setattr("codeverse3d.agents.backends.RETRY_KEY_WAIT_S", 0.05)
monkeypatch.setattr(get_settings(), "gemini_api_keys", ["n71-key"])
body, want = _ENDINGS[ending]
+ monkeypatch.setattr(get_settings(), "cache_dir", tmp_ws.root.parent / "cache")
binary = fake_bin(vendor, "sys.stdin.read()\n" + body)
- agent = {"gemini-cli": lambda: GeminiCliAgent("m", binary=binary), "claude-code": lambda: ClaudeCodeAgent("m", binary=binary),
+ agent = {"claude-code": lambda: ClaudeCodeAgent("m", binary=binary),
"codex": lambda: CodexAgent("m", binary=binary, reasoning_effort=""),
- "agy": lambda: AntigravityAgent("m", binary=binary)}[vendor]()
+ "agy": lambda: AntigravityAgent("m", binary=binary), # subscription sign-in
+ "agy-api": lambda: AntigravityAgent("gemini-m", binary=binary)}[vendor]() # a pool key
if vendor == "agy":
monkeypatch.setattr(agent, "served_model", lambda: "m")
res = agent.run(AgentJob(workspace=str(tmp_ws.root), prompt="p", label=ending, spatial_tools=False,
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
deleted file mode 100644
index e2d2668e..00000000
--- a/harness/tests/agents/test_gemini_cli.py
+++ /dev/null
@@ -1,354 +0,0 @@
-"""GeminiCliAgent with a fake `gemini` binary + one live smoke test."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-
-import pytest
-
-from codeverse3d.agents.backends import GeminiCliAgent, parse_gemini_json, usage_from_stats
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.agent import AgentJob
-from codeverse3d.workspace import Workspace
-
-FAKE_GEMINI = r'''
-from datetime import datetime, timezone
-args = sys.argv[1:]
-model = args[args.index("-m") + 1]
-assert "-p" not in args and "--prompt" not in args, "the prompt goes on stdin"
-prompt = sys.stdin.read()
-open("artifacts/stdin.txt", "w").write(prompt)
-mode = os.environ.get("FAKE_MODE", "ok")
-
-def chat_record():
- """What gemini-cli 0.53 appends to ~/.gemini/tmp/<project>/chats/ as the session runs."""
- proj = os.path.join(os.environ["GEMINI_CLI_HOME"], ".gemini", "tmp", "fake-project")
- os.makedirs(os.path.join(proj, "chats"), exist_ok=True)
- open(os.path.join(proj, ".project_root"), "w").write(os.getcwd())
- now = lambda: datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
- rows = [{"sessionId": "fake", "kind": "main"},
- {"id": "u1", "type": "user", "timestamp": now(), "content": [{"text": prompt[:20]}]},
- {"id": "g1", "type": "gemini", "timestamp": now(), "model": model, "content": "",
- "toolCalls": [{"id": "write_file__1", "name": "write_file", "args": {"file_path": "src/a.js"}, "status": "success"}],
- "tokens": {"input": 1000, "output": 20, "cached": 400, "thoughts": 7, "tool": 0, "total": 1027}},
- {"id": "g1", "type": "gemini", "timestamp": now(), "model": model, "content": "", # re-written: once
- "toolCalls": [{"id": "write_file__1", "name": "write_file", "args": {"file_path": "src/a.js"}, "status": "success"}],
- "tokens": {"input": 1000, "output": 20, "cached": 400, "thoughts": 7, "tool": 0, "total": 1027}},
- {"id": "u2", "type": "user", "timestamp": now(), "content": [{"functionResponse": {"id": "write_file__1"}}]},
- {"id": "g2", "type": "gemini", "timestamp": now(), "model": model, "content": "",
- "tokens": {"input": 3000, "output": 50, "cached": 2000, "thoughts": 13, "tool": 0, "total": 3063}}]
- with open(os.path.join(proj, "chats", "session-2026-09-22T21-00-fake0001.jsonl"), "a") as f:
- f.write("".join(json.dumps(r) + "\n" for r in rows))
-assert os.environ.get("GEMINI_API_KEY"), "no key in env"
-assert "GEMINI_API_KEYS" not in os.environ
-assert "FAKE_SERVICE_API_KEY" not in os.environ, "secret leaked"
-assert os.path.isfile(os.environ["GEMINI_CLI_SYSTEM_SETTINGS_PATH"])
-if mode in ("fail_once", "fail_once_503", "fail_always", "fail_twice_429"):
- marker = "artifacts/attempts.txt"
- n = int(open(marker).read()) if os.path.exists(marker) else 0
- open(marker, "w").write(str(n + 1))
- if n == 0 or mode == "fail_always" or (mode == "fail_twice_429" and n < 2):
- if mode == "fail_once_503":
- print("Error when talking to Gemini API: got status: UNAVAILABLE 503", file=sys.stderr)
- sys.exit(247)
- print("Error: 429 RESOURCE_EXHAUSTED quota", file=sys.stderr)
- sys.exit(1)
-if mode == "hang":
- time.sleep(60)
-if mode == "crash": # the agent's own failure: nothing transient about it
- print("TypeError: Cannot read properties of undefined (reading 'parts')", file=sys.stderr)
- sys.exit(2)
-if mode == "storm": # what gemini-cli 0.53 prints, 8-17 times per session, in a 503 storm
- chat_record()
- for i in range(4):
- print(f"Attempt {i + 1} failed with status 503. Retrying with backoff... _ApiError: UNAVAILABLE", file=sys.stderr)
- sys.stderr.flush()
- time.sleep(0.05)
- time.sleep(60)
-if mode == "gave_up": # 0.53 after its own retries: an error object on STDERR, no stats, exit(503) = 247
- chat_record()
- print("Attempt 1 failed with status 503. Retrying with backoff... _ApiError: UNAVAILABLE", file=sys.stderr)
- print("Error when talking to Gemini API Full report available at: /tmp/x.json", file=sys.stderr)
- print(json.dumps({"session_id": "s9", "error": {"type": "Error", "message": "got status: UNAVAILABLE.", "code": 503}},
- indent=2), file=sys.stderr)
- sys.exit(247)
-if mode == "ok_with_record": # every real session writes both: the envelope must win, never add
- chat_record()
-served = "gemini-9-pro" if mode == "substitute" else model
-os.makedirs("src", exist_ok=True)
-open("src/hello.txt", "w").write(prompt[:20])
-out = {"session_id": "s1", "response": "DONE: " + prompt[:10],
- "stats": {"models": {served: {"tokens": {"input": 95, "prompt": 100, "candidates": 20, "cached": 5, "thoughts": 7}}},
- "tools": {"totalCalls": 1}}}
-print(json.dumps(out, indent=2))
-'''
-
-
-def agent(fake_bin, monkeypatch, tmp_path):
- binary = fake_bin("gemini", FAKE_GEMINI)
- monkeypatch.setenv("GEMINI_CLI_HOME", str(tmp_path / "gemini_home")) # the fake writes its chat record here
- s = get_settings()
- monkeypatch.setattr(s, "gemini_api_keys", ["k1", "k2"])
- monkeypatch.setattr(s, "cache_dir", Path(binary).parent / "cache")
- monkeypatch.delenv("GEMINI_API_KEYS", raising=False)
- # shared_pool caches per (keys, quota) for the life of the PROCESS, so an earlier
- # test in this worker can leave k1 spent or cooling and the next invoke starts on
- # k2 — which broke `keys == ["k1", "k2"]` once the suite went parallel and test
- # grouping changed. Every test here starts from a fresh pool.
- from codeverse3d.models import gemini as gm
- for sig in [x for x in list(gm._pools) if x and x[0] in ("k1", "only")]: # noqa: SLF001
- gm._pools.pop(sig, None) # noqa: SLF001
- return GeminiCliAgent("gemini-3.7-flash", binary=binary)
-
-
-def test_retry_window_never_restarts():
- """What is LEFT of the window, or None when < min(120, T/4)."""
- from codeverse3d.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
- assert retry_window_left(20, 2) == 18 # small test jobs keep retrying
- assert retry_window_left(20, 16) is None # 4s left < 5s (T/4)
-
-
-def _job(ws: Workspace, **kw) -> AgentJob:
- base = dict(workspace=str(ws.root), prompt="write hello", model="gemini-3.7-flash", timeout_s=20, label="t")
- base.update(kw)
- return AgentJob(**base)
-
-
-def test_the_metered_proxy_books_a_killed_sessions_record_once(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch,
- tmp_path):
- """A watchdog-killed session is booked from its chat record (it was booked at $0 until 2026-09-22)."""
- from codeverse3d.cost import load_ledger
- from codeverse3d.cost.instrument import MeteredAgent, run_ledger
-
- monkeypatch.setenv("FAKE_MODE", "storm")
- monkeypatch.setattr("codeverse3d.agents.cli_common.IDLE_GRACE_S", 1.0)
- with run_ledger(tmp_path / "run", run="r1"):
- res = MeteredAgent(agent).run(_job(tmp_ws, timeout_s=1, kind="baseline"))
- (row,) = load_ledger(tmp_path / "run")
- assert row.source == "session" and row.outcome == "timeout" and row.input_tokens == res.usage.input_tokens == 4000
- assert row.cost_usd == pytest.approx(res.usage.cost_usd, abs=1e-6) and row.cost_usd > 0
-
-
-def test_a_session_that_gave_up_is_booked_from_its_record_and_is_typed_transient(tmp_ws: Workspace,
- agent: GeminiCliAgent, monkeypatch):
- """0.53's give-up: an error object on STDERR, no stats, exit 503 & 255 = 247."""
- monkeypatch.setattr(get_settings(), "gemini_api_keys", ["only"])
- from codeverse3d.models import gemini as gm
- for sig in [x for x in list(gm._pools) if x and x[0] == "only"]: # noqa: SLF001
- gm._pools.pop(sig, None) # noqa: SLF001
- monkeypatch.setenv("FAKE_MODE", "gave_up")
- res = agent.run(_job(tmp_ws))
- assert not res.ok and res.exit_reason == "error" and res.transient and not res.quota
- assert res.usage.input_tokens == 2 * 4000 # both attempts, each from its own record
- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
- assert rec["attempts"] == 2 and rec["usage_from"] == ["chat record", "chat record"] and rec["session_id"] == "s9"
-
-
-def test_the_envelope_wins_over_the_record_and_nothing_is_booked_twice(tmp_ws: Workspace, agent: GeminiCliAgent,
- monkeypatch):
- """The chat record's tokens count only when the envelope has none — adding them doubles the bill."""
- monkeypatch.setenv("FAKE_MODE", "ok_with_record")
- res = agent.run(_job(tmp_ws))
- assert res.ok and res.usage.input_tokens == 100 and res.usage.output_tokens == 20 # the envelope's, alone
- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
- assert rec["usage_from"] == ["envelope"]
- rows = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
- assert [r["tool"] for r in rows if r["kind"] == "tool_call"] == ["write_file"] # the record still traced
-
-
-def test_agent_planted_mcp_server_never_reaches_the_cli(tmp_ws: Workspace, agent: GeminiCliAgent):
- """3dcode + mcp.allowed live in the per-session system settings, applied last (audit 2026-08-27)."""
- from codeverse3d.agents.cli_common import begin_session, default_mcp_command, release_session
- from codeverse3d.agents.materialize import materialize_workspace
-
- materialize_workspace(tmp_ws, agent_kind="gemini-cli", contract_md="c", cookbook_text="",
- spatial_tools=True, mcp_command=default_mcp_command(tmp_ws))
- planted = tmp_ws.root / ".gemini" / "settings.json"
- data = json.loads(planted.read_text())
- data["mcpServers"] = {"evil": {"command": "/tmp/evil"}}
- data["mcp"] = {"allowed": ["evil"]}
- planted.write_text(json.dumps(data))
-
- s = begin_session(_job(tmp_ws), "gemini-cli")
- try:
- env = agent.build_env(s, "k1")
- finally:
- release_session(s)
- path = Path(env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"])
- settings = json.loads(path.read_text())
- assert path.parent == s.traj.dir, "per session, in the harness-owned trajectory dir"
- assert list(settings["mcpServers"]) == ["3dcode"] and settings["mcp"]["allowed"] == ["3dcode"]
- assert "evil" not in json.dumps(settings)
- assert settings["security"]["folderTrust"]["enabled"] is False
-
-
-def test_single_key_transient_failure_retries_same_key_and_never_raises(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- """Settings with ONE key: the retry must reuse it (no KeyPoolExhausted out of run())."""
-
- monkeypatch.setattr(get_settings(), "gemini_api_keys", ["only"])
- from codeverse3d.models import gemini as gm
- for sig in [s for s in list(gm._pools) if s and s[0] == "only"]:
- gm._pools.pop(sig, None)
- monkeypatch.setenv("FAKE_MODE", "fail_once_503")
- res = agent.run(_job(tmp_ws))
- assert res.ok, res.errors
- assert (tmp_ws.artifacts / "attempts.txt").read_text() == "2"
- lines = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
- assert [ln["key_tail"] for ln in lines if ln["kind"] == "invoke"] == ["only", "only"]
-
-
-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 codeverse3d.agents import backends as gc
-
- monkeypatch.setattr(get_settings(), "gemini_api_keys", ["solo"])
- monkeypatch.setattr(gc, "RETRY_KEY_WAIT_S", 0.2)
- from codeverse3d.models import gemini as gm
- for sig in [s for s in list(gm._pools) if s and s[0] == "solo"]:
- gm._pools.pop(sig, None)
- monkeypatch.setenv("FAKE_MODE", "fail_always")
- res = agent.run(_job(tmp_ws))
- assert not res.ok and res.exit_reason == "budget"
- assert (tmp_ws.artifacts / "attempts.txt").read_text() == "1"
- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
- assert rec["attempts"] == 1 and any("no usable key" in n for n in rec["notes"])
-
-
-def test_pool_exhausted_before_first_attempt_is_a_budget_result(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- from codeverse3d.agents import backends as gc
- from codeverse3d.models.retry import KeyPoolExhausted
-
- class Dead:
- def session_key(self, **kw):
- raise KeyPoolExhausted("all 2 keys throttled; waited 120s")
-
- def report(self, *a, **k):
- return None
-
- monkeypatch.setattr(gc, "_key_pool", lambda keys: Dead())
- res = agent.run(_job(tmp_ws))
- assert not res.ok and res.exit_reason == "budget" and "exhausted" in res.errors[0]
-
-
-def test_a_timeout_after_a_503_streak_is_marked_transient(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- """A 503 storm inside the CLI's own retry loop ends on the wall: the result says why (2026-09-07)."""
- monkeypatch.setenv("FAKE_MODE", "storm")
- monkeypatch.setattr("codeverse3d.agents.cli_common.IDLE_GRACE_S", 1.0)
- res = agent.run(_job(tmp_ws, timeout_s=1))
- assert not res.ok and res.exit_reason == "timeout" and res.transient is True
- assert any("4 x 503" in e for e in res.errors), res.errors
- assert res.provider_wait_s > 0.0
-
-
-def test_the_key_pool_hears_a_5xx_only_when_the_failure_was_transient(tmp_ws: Workspace, agent: GeminiCliAgent,
- monkeypatch):
- """A hang, a substituted model or the agent's own crash is not transient and not the key's fault."""
- from codeverse3d.agents import backends as gc
-
- monkeypatch.setattr("codeverse3d.agents.cli_common.IDLE_GRACE_S", 1.0)
- pool = gc._key_pool(get_settings().gemini_api_keys) # noqa: SLF001
- for mode, timeout_s in (("substitute", 20), ("crash", 20), ("hang", 1)):
- monkeypatch.setenv("FAKE_MODE", mode)
- res = agent.run(_job(tmp_ws, timeout_s=timeout_s, label=mode))
- assert not res.ok and res.transient is False, mode
- if mode == "substitute": # the served model is checked against the requested one
- assert res.exit_reason == "model_substituted" and "gemini-9-pro" in res.errors[0]
- st = pool.stats()
- assert (st["5xx"], st["ok"], st["error"]) == (0, 0, 0), st
- monkeypatch.setenv("FAKE_MODE", "fail_once_503") # a real 503, then a rotated success
- assert agent.run(_job(tmp_ws, label="storm")).ok
- st = pool.stats()
- assert (st["5xx"], st["ok"]) == (1, 1), st
-
-
-def test_unavailable_when_no_keys(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- monkeypatch.setattr(get_settings(), "gemini_api_keys", [])
- ok, why = agent.available()
- assert not ok and "key" in why
- res = agent.run(_job(tmp_ws))
- assert not res.ok and res.exit_reason == "error"
-
-
-def test_parse_helpers():
- assert parse_gemini_json("noise\n{\"response\": \"x\"}") == {"response": "x"}
- assert parse_gemini_json("") is None
- # the CLI prints the envelope INDENTED over many lines (a single-line scan finds nothing)
- assert parse_gemini_json('log line\n{\n "response": "x",\n "stats": {\n "models": {}\n }\n}\n')["response"] == "x"
- # no `prompt` key: total prompt = uncached input + cached
- u = usage_from_stats({"models": {"m": {"tokens": {"input": 1, "candidates": 2, "cached": 3, "thoughts": 4}}},
- "tools": {"totalCalls": 9}}, "m")
- assert (u.input_tokens, u.output_tokens, u.cached_tokens, u.thoughts_tokens, u.tool_calls) == (4, 2, 3, 4, 9)
-
-
-def test_usage_input_is_total_prompt_and_cost_reprices_cache():
- """tokens.input is prompt - cached; pricing wants the TOTAL prompt (was ~4x under-billing)."""
- from codeverse3d.models.pricing import estimate_cost, lookup_price
-
- tok = {"input": 720_753, "prompt": 14_190_170, "cached": 13_469_417, "candidates": 62_012, "thoughts": 66_809}
- u = usage_from_stats({"models": {"gemini-3.7-flash": {"tokens": tok}}}, "gemini-3.7-flash")
- assert u.input_tokens == tok["prompt"] and u.cached_tokens == tok["cached"]
- price = lookup_price("gemini", "gemini-3.7-flash")
- assert price is not None
- m = 1_000_000
- want = ((tok["prompt"] - tok["cached"]) * price.input + tok["cached"] * price.cached
- + (tok["candidates"] + tok["thoughts"]) * price.output) / m
- assert u.cost_usd == pytest.approx(want, rel=1e-9)
- assert u.cost_usd == pytest.approx(estimate_cost("gemini", "gemini-3.7-flash", u), rel=1e-9)
- assert u.cost_usd > 3 * estimate_cost("gemini", "gemini-3.7-flash", u.model_copy(update={"input_tokens": tok["input"]}))
-
-
-def test_usage_prices_each_served_model_at_its_own_rate():
- from codeverse3d.contracts.common import Usage
- from codeverse3d.models.pricing import estimate_cost
-
- stats = {"models": {"gemini-3.7-flash": {"tokens": {"prompt": 1_000_000, "cached": 0, "candidates": 1000}},
- "gemini-3-flash-preview": {"tokens": {"prompt": 1_000_000, "cached": 0, "candidates": 1000}},
- "unknown-utility-model-x": {"tokens": {"prompt": 1_000_000, "cached": 0, "candidates": 1000}}}}
- u = usage_from_stats(stats, "gemini-3.7-flash")
- assert u.input_tokens == 3_000_000 and u.output_tokens == 3000
- one = Usage(input_tokens=1_000_000, output_tokens=1000)
- want = (estimate_cost("gemini", "gemini-3.7-flash", one) + estimate_cost("gemini", "gemini-3-flash-preview", one)
- + estimate_cost("gemini", "gemini-3.7-flash", one)) # unknown model falls back to the requested rate
- assert u.cost_usd == pytest.approx(want, rel=1e-9)
-
-
-def test_system_append_is_prepended(tmp_ws: Workspace, agent: GeminiCliAgent):
- res = agent.run(_job(tmp_ws, system_append="BE BRIEF"))
- assert res.ok
- assert (tmp_ws.src / "hello.txt").read_text().startswith("<harness_instr")
-
-
-def test_live_gemini_cli_creates_file(tmp_ws: Workspace):
- if not get_settings().gemini_api_keys:
- pytest.skip("no gemini keys")
- agent = GeminiCliAgent("gemini-3.7-flash")
- job = AgentJob(workspace=str(tmp_ws.root), prompt="Create the file src/hello.txt containing exactly the word 'hi'. "
- "Then reply with the single word DONE.", timeout_s=240, label="live", spatial_tools=False)
- res = agent.run(job)
- assert res.ok, res.errors
- assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"
- assert res.usage.input_tokens > 0 and res.usage.model == "gemini-3.7-flash"
- assert any(f.path == "src/hello.txt" for f in res.files_changed)
-
-
-def test_quota_failure_gets_a_third_rotated_attempt(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
- """Two 429s in a row on two keys, the third key answers: the cell is not lost."""
- monkeypatch.setattr(get_settings(), "gemini_api_keys", ["k1", "k2", "k3"])
- from codeverse3d.models import gemini as gm
- for sig in [s for s in list(gm._pools) if s and s[0] in ("k1", "only")]:
- gm._pools.pop(sig, None)
- monkeypatch.setenv("FAKE_MODE", "fail_twice_429")
- res = agent.run(_job(tmp_ws))
- assert res.ok, res.errors
- assert (tmp_ws.artifacts / "attempts.txt").read_text() == "3"
- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
- assert rec["attempts"] == 3
- lines = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
- keys = [ln["key_tail"] for ln in lines if ln["kind"] == "invoke"]
- assert len(keys) == 3 and len(set(keys)) == 3 # a fresh key each time
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
index 48b6fc8f..690d8560 100644
--- a/harness/tests/agents/test_materialize.py
+++ b/harness/tests/agents/test_materialize.py
@@ -1,4 +1,4 @@
-"""materialize_workspace: bodies, MCP configs, ignore files, cookbook, codex overrides."""
+"""materialize_workspace: bodies, ignore file, cookbook, codex overrides."""
from __future__ import annotations
@@ -15,7 +15,7 @@ from codeverse3d.workspace import Workspace
CONTRACT = "## blender contract\nWrite pure bpy into src/model.py."
-def _mat(ws: Workspace, kind: str = "gemini-cli", spatial: bool = True, cookbook: str = ""):
+def _mat(ws: Workspace, kind: str = "agy", spatial: bool = True, cookbook: str = ""):
return materialize_workspace(ws, agent_kind=kind, contract_md=CONTRACT, cookbook_text=cookbook,
spatial_tools=spatial, mcp_command=default_mcp_command(ws))
@@ -40,22 +40,18 @@ def test_bodies_document_only_this_tracks_tools(tmp_ws: Workspace):
assert "`joint_sweep`" in (tmp_ws.root / "AGENTS.md").read_text()
-def test_no_mcp_server_is_written_into_the_workspace(tmp_ws: Workspace):
- """Only the ``context`` block goes into the agent-writable ws/.gemini/settings.json;
- 3dcode reaches each CLI through a harness-owned per-session file (audit 2026-08-27)."""
- gs = tmp_ws.root / ".gemini" / "settings.json"
- gs.parent.mkdir(parents=True)
- gs.write_text(json.dumps({"mcpServers": {"3dcode": {"command": "/tmp/evil"}}, "ui": {"theme": "dark"}}))
- _mat(tmp_ws)
- data = json.loads(gs.read_text())
- assert data["ui"]["theme"] == "dark"
- assert "3dcode" not in data["mcpServers"], "an agent-planted 3dcode impostor must be dropped"
+def test_no_mcp_config_and_no_gemini_body_is_written_into_the_workspace(tmp_ws: Workspace):
+ """3dcode reaches each CLI through a harness-owned per-session file (audit 2026-08-27), and
+ agy reads GEMINI.md as well as AGENTS.md — a third copy of the body would be loaded twice."""
+ for kind in ("agy", "claude-code", "codex"):
+ _mat(tmp_ws, kind=kind)
assert not (tmp_ws.root / ".mcp.json").exists(), "claude-code writes its own per-session mcp.json"
- assert data["context"]["fileFiltering"]["respectGitIgnore"] is False # .gitignore hides artifacts/ + trajectories/
+ assert not (tmp_ws.root / ".gemini").exists() and not (tmp_ws.root / "GEMINI.md").exists()
+ assert {p.name for p in tmp_ws.root.glob("*.md")} >= {"AGENTS.md", "CLAUDE.md"}
def test_ignore_files_keep_agent_facing_paths_readable_and_a_missing_cookbook_is_said(tmp_ws: Workspace):
- """gemini-cli refuses read_file on ignored paths: census and tool renders stay readable."""
+ """Ignored paths are hidden from the agent: census and tool renders stay readable."""
import fnmatch
from codeverse3d.agents.materialize import IGNORE_LINES
@@ -71,7 +67,7 @@ def test_ignore_files_keep_agent_facing_paths_readable_and_a_missing_cookbook_is
return True
return False
- for f in (".geminiignore", ".aiexclude"):
+ for f in (".antigravityignore",):
lines = tuple(ln for ln in (tmp_ws.root / f).read_text().splitlines() if ln.strip())
assert lines == IGNORE_LINES
assert "artifacts/" not in lines and "trajectories/" in lines
@@ -80,7 +76,7 @@ def test_ignore_files_keep_agent_facing_paths_readable_and_a_missing_cookbook_is
"src/model.py", ".3dcode/cookbook.md"):
assert not ignored(readable, lines), readable
for hidden in ("artifacts/renders/r00/sheet.png", "trajectories/baseline_r00/stdout.json",
- "trajectories/baseline_r00/prompt.md", "trajectories/baseline_r00/gemini_settings.json",
+ "trajectories/baseline_r00/prompt.md", "trajectories/baseline_r00/agy.log",
"trajectories/baseline_r00/stderr.log", "node_modules/three/x.js", ".git/HEAD"):
assert ignored(hidden, lines), hidden
# no cookbook resolved (the default here): the body says so rather than naming a missing file
@@ -91,7 +87,8 @@ def test_kind_specific_tool_hint_and_spatial_disabled_documents_absence(tmp_ws:
_mat(tmp_ws, kind="claude-code")
assert "mcp__3dcode__" in (tmp_ws.root / "CLAUDE.md").read_text()
_mat(tmp_ws, kind="agy")
- assert "codeverse3d.cli.main tools" in (tmp_ws.root / "AGENTS.md").read_text()
+ body = (tmp_ws.root / "AGENTS.md").read_text()
+ assert "MCP server `3dcode`" in body and "codeverse3d.cli.main tools" in body # API mode / sign-in fallback
_mat(tmp_ws, spatial=False)
assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()
diff --git a/harness/tests/agents/test_tool_trace.py b/harness/tests/agents/test_tool_trace.py
index e75243f0..8d260481 100644
--- a/harness/tests/agents/test_tool_trace.py
+++ b/harness/tests/agents/test_tool_trace.py
@@ -4,17 +4,11 @@ from __future__ import annotations
import json
import sqlite3
-import time
-from pathlib import Path
from codeverse3d.agents.backends import (
- SYSTEM_SETTINGS,
ClaudeCodeAgent,
ClaudeStream,
agy_tool_calls,
- gemini_chat_records,
- read_gemini_chats,
- write_system_settings,
)
from codeverse3d.agents.cli_common import (
TOOL_CALL_ROW,
@@ -84,69 +78,6 @@ def test_claude_is_launched_streaming(tmp_ws: Workspace):
assert argv[argv.index("--output-format") + 1] == "stream-json" and "--verbose" in argv
-# --------------------------------------------------------------------------- gemini-cli
-GEMINI_RECORD = [
- {"sessionId": "da5c91db-7d90-4dd9-a360-56b03e1fd339", "projectHash": "4b58", "startTime": "2026-09-22T19:31:33.522Z",
- "lastUpdated": "2026-09-22T19:31:33.522Z", "kind": "main"},
- {"$set": {"messages": [{"id": "d049", "type": "user", "content": [{"text": "<session_context>..."}]}]}},
- {"id": "fb86", "type": "gemini", "content": "I will activate the relevant skills for Blender modeling",
- "toolCalls": [
- {"id": "activate_skill__call_48964", "name": "activate_skill", "args": {"name": "c3d-blender-forms"},
- "status": "success"},
- {"id": "activate_skill__call_48965", "name": "activate_skill", "args": {"name": "c3d-part-contact"},
- "status": "success"}]},
- {"$set": {"lastUpdated": "2026-09-22T19:31:48.148Z"}},
- {"id": "fb87", "type": "gemini", "content": "",
- "toolCalls": [{"id": "read_file__call_5", "name": "read_file", "status": "success",
- "args": {"file_path": ".agents/skills/c3d-part-contact/references/worked_example.md"}},
- {"id": "read_file__call_6", "name": "read_file", "status": "error",
- "args": {"file_path": ".agents/skills/zz-c3d-read-control/SKILL.md"}}]},
- # the append-only record re-writes a message as it progresses: one call, not two
- {"id": "fb86", "type": "gemini", "content": "", "toolCalls": [
- {"id": "activate_skill__call_48964", "name": "activate_skill", "args": {"name": "c3d-blender-forms"},
- "status": "success"}]},
-]
-
-
-def _gemini_home(tmp_path: Path, ws: Path) -> Path:
- home = tmp_path / "home"
- proj = home / ".gemini" / "tmp" / ws.name
- (proj / "chats").mkdir(parents=True)
- (proj / ".project_root").write_text(str(ws))
- other = home / ".gemini" / "tmp" / "someone-else"
- (other / "chats").mkdir(parents=True)
- (other / ".project_root").write_text("/elsewhere/run")
- (other / "chats" / "session-2026-09-22T19-31-aaaaaaaa.jsonl").write_text(json.dumps(GEMINI_RECORD[2]) + "\n")
- rec = proj / "chats" / "session-2026-09-22T19-31-da5c91db.jsonl"
- rec.write_text("".join(json.dumps(r) + "\n" for r in GEMINI_RECORD))
- return home
-
-
-def test_gemini_chat_record_is_found_by_workspace_and_time_and_folded_by_call_id(tmp_path):
- ws = tmp_path / "gemini1"
- ws.mkdir()
- home = _gemini_home(tmp_path, ws)
- recs = gemini_chat_records(ws, time.time() - 60, {"GEMINI_CLI_HOME": str(home)})
- assert [p.name for p in recs] == ["session-2026-09-22T19-31-da5c91db.jsonl"]
- calls = read_gemini_chats(recs).calls
- assert [(c.tool, c.skill, c.failed) for c in calls] == [
- ("activate_skill", "c3d-blender-forms", False), ("activate_skill", "c3d-part-contact", False),
- ("read_file", "", False), ("read_file", "", True)]
- # an earlier session's record in the same workspace belongs to that session
- assert gemini_chat_records(ws, time.time() + 60, {"GEMINI_CLI_HOME": str(home)}) == []
- assert gemini_chat_records(tmp_path / "unknown", 0.0, {"GEMINI_CLI_HOME": str(home)}) == []
-
-
-def test_gemini_system_settings_pin_skills_on_and_keep_the_workspace_trusted(tmp_path):
- """0.53 merges the system file last; folderTrust off makes discoverSkills read the workspace roots."""
- data = json.loads(write_system_settings(tmp_path / "s.json").read_text())
- assert data["skills"]["enabled"] is True and data["skills"] == SYSTEM_SETTINGS["skills"]
- assert data["security"]["folderTrust"] == {"enabled": False}
- assert data["security"]["auth"]["selectedType"] == "gemini-api-key"
- assert data["experimental"]["dynamicModelConfiguration"] is True # else 0.53 substitutes models
- assert data["skills"]["disabled"] == ["skill-creator", "antigravity-support"] # the CLI's own bundles
-
-
# --------------------------------------------------------------------------- agy
def _pb(field: int, payload: bytes) -> bytes:
"""One length-delimited protobuf field (the only wire type the fixture needs)."""
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index 6e50192c..b4a98bb8 100644
--- a/harness/tests/cost/test_profiles.py
+++ b/harness/tests/cost/test_profiles.py
@@ -76,11 +76,11 @@ def test_an_explicit_flag_beats_the_profile(tmp_path: Path):
runs = tmp_path / "runs"
r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--slug", "pot",
"--profile", "economy", "--rounds", "4",
- "--generator", "gemini-cli:gemini-3.6-flash"])
+ "--generator", "agy:gemini-3.6-flash"])
assert r.exit_code == 0, r.output
spec = json.loads((runs / "pot" / "spec.json").read_text())
assert spec["budget"]["max_rounds"] == 4 and spec["budget"]["max_minutes"] > 0
- assert spec["backends"]["generator"] == "gemini-cli:gemini-3.6-flash"
+ assert spec["backends"]["generator"] == "agy:gemini-3.6-flash"
assert spec["backends"]["judge"] == "gemini:gemini-3.7-flash" # unstated → still the profile's
@@ -133,12 +133,12 @@ def _dial_from_env(name: str, monkeypatch):
"rounds": 2, "candidates": 1, "texture": False,
"judge_max_px": 1024, "judge_montages": 5, "judge_detail_crops": 2,
"agent_max_turns": 0, "max_minutes": 30.0}),
- ("balanced", {"generator": "gemini-cli:gemini-3.7-flash",
+ ("balanced", {"generator": "agy:gemini-3.7-flash",
"judge": "gemini:gemini-3.1-pro-preview", "judge_samples": 1,
"rounds": 4, "candidates": 1, "texture": False,
"judge_max_px": 1024, "judge_montages": 5, "judge_detail_crops": 2,
"agent_max_turns": 0, "max_minutes": 60.0}),
- ("quality", {"generator": "gemini-cli:gemini-3.7-flash",
+ ("quality", {"generator": "agy:gemini-3.7-flash",
"judge": "gemini:gemini-3.1-pro-preview", "judge_samples": 3,
"rounds": 4, "candidates": 2, "texture": True,
"judge_max_px": 1024, "judge_montages": 5, "judge_detail_crops": 2,
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index 49a4d664..6b76b911 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -58,7 +58,7 @@ def test_make_no_run_creates_valid_workspace(tmp_path: Path):
runs = tmp_path / "runs"
r = runner.invoke(app, ["make", "a wooden dining chair", "--track", "static_object", "--language", "blender",
"--runs-dir", str(runs), "--no-run", "--dim", "width=0.5", "--must", "four legs",
- "--rounds", "2", "--generator", "gemini-cli:gemini-3.7-flash"])
+ "--rounds", "2", "--generator", "agy:gemini-3.7-flash"])
assert r.exit_code == 0, r.output
# `.locks/` (runlock.exclusive) lives beside the run dirs on purpose — a lock inside
# the directory a --force wipe deletes is no lock
@@ -69,7 +69,7 @@ def test_make_no_run_creates_valid_workspace(tmp_path: Path):
spec = Spec.model_validate_json((ws / "spec.json").read_text())
assert spec.constraints.dimensions_m == {"width": 0.5} and spec.constraints.must_have == ["four legs"]
assert spec.budget.max_rounds == 2 and spec.budget.max_minutes == 60.0
- assert spec.backends.generator == "gemini-cli:gemini-3.7-flash"
+ assert spec.backends.generator == "agy:gemini-3.7-flash"
assert (ws / "src").is_dir() and (ws / "artifacts" / "renders").is_dir()
# same prompt again → same slug → refuse without --force
r2 = runner.invoke(app, ["make", "a wooden dining chair", "--runs-dir", str(runs), "--no-run"])
@@ -437,7 +437,7 @@ def test_render_only_labels_the_working_tree_round(tmp_path: Path):
@pytest.mark.parametrize("flag,value", [
- ("--generator", "antigravity:gemini-3.7-flash"), ("--generator", "nocolon"), ("--generator", "single-shot:nope"),
+ ("--generator", "antigravity:gemini-3.7-flash"), ("--generator", "gemini-cli:gemini-3.7-flash"), ("--generator", "nocolon"), ("--generator", "single-shot:nope"),
("--generator", "single-shot:gemini:"), ("--planner", "gemini"), ("--judge", "bogus:model"),
("--captioner", "gemini:"),
], ids=lambda v: v.strip("-"))
diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.py
index ebc54883..d0a7dc06 100644
--- a/harness/tests/orchestrator_tracks/test_cost_latency.py
+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py
@@ -158,21 +158,15 @@ STORM_DEATH = AgentResult(ok=False, exit_reason="timeout", transient=True,
errors=["killed by watchdog (hard_timeout) after 720s", "11 x 503 inside the CLI's own retry loop before the wall; nothing produced"])
-def test_a_storm_dead_session_falls_back_to_single_shot(tmp_path, settings):
- """A session that died in a 503 storm goes once more through the single-shot path."""
- def respond(req):
- return _envelope("src/env.js", "export function buildEnv() { return {}; }\n")
-
- services = _ChatServices(FakeChatModel(respond))
+def test_a_storm_dead_session_comes_back_transient_and_is_not_retried_here(tmp_path, settings):
+ """No hidden single-shot fallback under ``generate_for`` (D103): the session's death is typed
+ ``transient`` and the round loop's one transport retry is the only retry above the CLI's own."""
+ services = _ChatServices(FakeChatModel(lambda req: pytest.fail("no single-shot call")))
agent = FakeAgent(lambda j, w: STORM_DEATH)
ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, agent_id="fake-agent:gemini:x")
task = GenerationTask(label="env", prompt="write `src/env.js`", files_hint=["src/env.js"], round=0, kind="env")
res = generate_for(ctx, task)
- assert res.ok and [c.path for c in res.files_changed] == ["src/env.js"]
- assert len(agent.jobs) == 1 and services.chat_ids == [ctx.spec.backends.planner] # the planner backend, always an API model
- assert "503 storm" in res.notes and "single-shot" in res.notes
- kinds = [e["event"] for e in _events(ctx)]
- assert "generate.storm_fallback" in kinds
+ assert not res.ok and res.transient and len(agent.jobs) == 1 and services.chat_ids == []
def test_a_zones_session_the_clock_stopped_is_kept_for_the_resume(tmp_path, settings):
diff --git a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py
index 8aa5645c..033a8752 100644
--- a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py
+++ b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py
@@ -76,50 +76,6 @@ def _crate_plan(asset):
acceptance=[])
-class _StormAgent(FakeAgent):
- """A CLI session that wrote partial files and died at the wall in a 503 streak (D68)."""
-
- def run(self, job):
- from codeverse3d.contracts.agent import AgentResult
- from codeverse3d.workspace import Workspace
-
- self.jobs.append(job)
- ws = Workspace(job.workspace)
- before = ws.head()
- for rel, content in (self.writer(job, ws) or {}).items():
- (ws.root / rel).parent.mkdir(parents=True, exist_ok=True)
- (ws.root / rel).write_text(content)
- return AgentResult(ok=False, exit_reason="timeout", transient=True, files_changed=ws.changed_files(before),
- errors=["killed by watchdog (hard_timeout) after 720s", "7 x 503 inside the CLI's own retry loop before the wall; nothing produced"])
-
-
-def test_a_hero_session_that_died_in_the_storm_gets_one_more_cheap_repair(tmp_ws, settings, monkeypatch):
- """A storm-dead hero session gets ONE more single-shot repair with the check's feedback."""
- calls = {"n": 0}
-
- class FailTwiceThenGood(SingleShotServices):
- def _answer(self, req):
- if req.response_schema is not None:
- return plan_example(Track.STATIC_OBJECT)
- calls["n"] += 1
- body = GOOD_MODEL if calls["n"] >= 3 else f"import bpy\n{FAIL_MARK}\n" # two shots fail, the rung answers
- return f"=== FILE: src/model.py ===\n{body}=== END FILE ==="
-
- services = FailTwiceThenGood()
- agent = _StormAgent(_writer(f"import bpy\n{FAIL_MARK}\n")) # partial, broken parts
- monkeypatch.setattr(SA, "hero_plan", lambda sub, asset: _crate_plan(asset))
- ctx, hero = _scene(tmp_ws, settings, services=services, agent=agent)
- res = SA.build_blender_asset(ctx, hero, judge=False)
- assert res.ok and res.strategy == "escalated+repair", (res.strategy, res.notes)
- # ONE agent session: the partial files were checked on the cheap context (no agent repair) and the rung went single-shot
- assert calls["n"] == 3 and [j.label for j in agent.jobs] == [f"asset_{SA.to_snake(hero.name)}"]
- texts = [" ".join(p.text for m in r.messages for p in m.parts if getattr(p, "text", "")) for r in services.chat.requests
- if r.response_schema is None]
- assert "did NOT pass the deterministic asset check" in texts[2]
- events = [json.loads(line) for line in tmp_ws.events_path.read_text().splitlines()]
- assert [e["event"] for e in events if e["event"] in ("asset.escalated", "asset.storm_repair")] == ["asset.escalated", "asset.storm_repair"]
-
-
def test_hero_repair_sessions_are_clipped_to_the_asset_window_and_capped_at_one(tmp_ws, settings):
agent = FakeAgent(_writer(f"import bpy\n# {FAIL_MARK}\n")) # every session leaves a build that fails
ctx, hero = _scene(tmp_ws, settings, services=CardedServices(), agent=agent)
diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.py
index d2dbdb03..ef2a35da 100644
--- a/harness/tests/prompts/manifest.py
+++ b/harness/tests/prompts/manifest.py
@@ -13,7 +13,7 @@ are dropped) and stored in ``manifest.json`` as ``kind → {sha256, bytes}``:
``JudgeInput`` the in-run judge reads (``FakeJudge.calls``) and the request the real
``VlmJudge`` builds from it;
* ``context:<workspace>/files`` — what a session reads in its workspace, as materialised
- (AGENTS/GEMINI/CLAUDE.md, the cookbook copy, the gemini settings, the ignore files);
+ (AGENTS/CLAUDE.md, the cookbook copy, the ignore file);
* ``skills:<workspace>:<kind>@rNN/routed`` — the skill bundles routed to a round;
* ``mcp_tools:<track>/<language>`` — the MCP tool list a session is offered;
@@ -29,7 +29,7 @@ Not covered (the fakes cannot drive it): reference-image runs (reference and lik
silhouette gate), the texture pack's own planner (``texturing/scene_pack.md``: the scene is handed
a canned pack) and the texture pass (``texturing/material_plan.md``), replays (``3dcode judge``),
the budget-stop salvage (the clock is frozen), the node asset checker (a python stand-in answers)
-and each vendor CLI's own framing of a session (only gemini-cli's workspace files are built).
+and each vendor CLI's own framing of a session (only agy's workspace files are built).
"""
from __future__ import annotations
@@ -90,7 +90,7 @@ from tests.orchestrator_tracks.fakes import (
)
MANIFEST = Path(__file__).with_name("manifest.json")
-AGENT = "gemini-cli:gemini-3.7-flash" # the default generator (a vendor CLI; FakeAgent answers)
+AGENT = "agy:gemini-3.7-flash" # the default generator (a vendor CLI; FakeAgent answers)
SINGLE_SHOT = "single-shot:gemini:gemini-3.7-flash"
#: what each track is asked for
REQUESTS = {Track.STATIC_OBJECT: ("a mid-century wooden dining chair", Constraints(dimensions_m={"height": 0.82}, must_have=["armrests"])),
@@ -103,7 +103,7 @@ BRIEF = {"object_name": "DiningChair", "reference": "a Danish oak dining chair",
"sub_assemblies": [{"name": "frame", "purpose": "carries the load", "parts": ["legs", "rails"], "material": "oak"}],
"mechanism": "the legs carry the seat", "visible_from_outside": ["seat", "legs", "backrest"],
"signature_features": ["tapered legs", "curved backrest"], "materials": ["seat: oiled oak"]}
-CONTEXT_FILES = ("AGENTS.md", "GEMINI.md", "CLAUDE.md", ".3dcode/cookbook.md", ".gemini/settings.json", ".geminiignore", ".aiexclude")
+CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".3dcode/cookbook.md", ".antigravityignore")
VOLATILE = frozenset({"duration_ms", "duration_s", "latency_ms", "max_wait_s", "timeout_s", "hard_deadline_s", "workspace", "data_b64"})
SHADER = ("void mainImage(out vec4 fragColor, in vec2 fragCoord) {{\n vec2 uv = fragCoord / u_resolution.xy;\n"
" // {tag}\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}}\n")
diff --git a/harness/tests/skills/test_config.py b/harness/tests/skills/test_config.py
index aa186166..ca6ff1cc 100644
--- a/harness/tests/skills/test_config.py
+++ b/harness/tests/skills/test_config.py
@@ -25,13 +25,13 @@ def test_on_by_default_and_garbage_keeps_the_default(monkeypatch, name, raw, wan
assert (s.skills, s.skills_unverified, s.skills_max) == want
-def test_doctor_reports_the_default_and_the_gemini_pin(monkeypatch):
- """ON is healthy, and gemini-cli's skills.enabled must be pinned per session."""
+def test_doctor_reports_the_default_and_the_skill_tool(monkeypatch):
+ """ON is healthy, and claude-code's Skill tool must be allowed."""
from codeverse3d.doctor import check_skills
monkeypatch.delenv("C3D_SKILLS", raising=False)
rows = {name: status for name, status, _ in check_skills()}
- assert rows["skills switch"] == "OK" and rows["gemini-cli skills setting"] == "OK"
+ assert rows["skills switch"] == "OK"
assert rows["claude-code Skill tool"] == "OK"
monkeypatch.setenv("C3D_SKILLS", "0")
get_settings.cache_clear()