Files
ai-agent/backend/test_codemode.py
gabrielvidalandClaude Opus 5.5 87c95d4262 feat(conversations): Code Mode — a script's calls are tagged with it
In Claude Code's Code Mode the model's REPL call comes back at once
("(dispatched #N)", evalId N); the calls its code made are written later,
after the delivery that settles eval N, as virtual records (repl_… ids,
zero usage). The parser (conversations/codemode.py) now links them: each
virtual call gets `script` (its REPL call's toolUseId) — when one delivery
settles several scripts, the one whose code holds the call's command —
and the REPL card gets what its code returned (`codeResult`) and how long
it ran (`codeMs`). Virtual records are no API call: they no longer count
as turns or put a $0 chip on their card.

The probe's call records pass `script`, `scriptGuess` and `command`
through (perf/calls.py view): a call that outlived its script never makes
it into the transcript, but agent-probe 0.1.2 has it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:34:05 +01:00

126 lines
6.2 KiB
Python

"""Claude Code's Code Mode (conversations/codemode.py): a REPL script's calls,
written later as virtual records, are tagged with the script that made them;
the script's card gets what its code returned; the virtual records' zero
usage counts as no model turn.
Records are trimmed copies of real Claude Code 2.1.327 transcript lines."""
import json
import conversations as c
from conversations import codemode
ZERO = {"input_tokens": 0, "output_tokens": 0, "cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0}
USAGE = {"input_tokens": 10, "output_tokens": 50, "cache_creation_input_tokens": 0,
"cache_read_input_tokens": 28000}
def _asst(tid, name, inp, ts, virtual=False):
rec = {"type": "assistant", "timestamp": ts, "sessionId": "s1",
"message": {"id": f"m-{tid}", "role": "assistant",
"model": "<synthetic>" if virtual else "claude-sonnet-5-5",
"usage": ZERO if virtual else USAGE,
"content": [{"type": "tool_use", "id": tid, "name": name, "input": inp}]}}
if virtual:
rec["isVirtual"] = True
else:
rec["requestId"] = f"req-{tid}"
return rec
def _result(tid, content, ts, virtual=False, tur=None):
rec = {"type": "user", "timestamp": ts, "sessionId": "s1",
"message": {"role": "user", "content": [
{"type": "tool_result", "tool_use_id": tid, "content": content}]}}
if virtual:
rec["isVirtual"] = rec["turnCompanion"] = True
if tur is not None:
rec["toolUseResult"] = tur
return rec
def _event(ev, status, result, ms=None):
m = f' ms="{ms}"' if ms is not None else ""
return (f'<event nonce="X" kind="repl-eval" at="2026-11-18T19:14:17Z" eval="{ev}"{m} '
f'status="{status}">\n<result>{result}</result>\n</event>')
def _virtual(tid, name, inp, out, ts):
return [_asst(tid, name, inp, ts, virtual=True), _result(tid, out, ts, virtual=True)]
A = "$`python3 -c 'x=1'`; $`ls /usr/lib | wc -l`"
B = "await $`sleep 12 && echo A-done`"
C = "await $`sleep 2 && echo B-done`; await edit('note.txt', 'hello', 'bye')"
RECORDS = [
{"type": "user", "timestamp": "2026-11-18T19:13:20Z", "sessionId": "s1",
"message": {"role": "user", "content": "run things"}},
_asst("toolu_A", "REPL", {"code": A}, "2026-11-18T19:13:25Z"),
_result("toolu_A", "(dispatched #1)", "2026-11-18T19:13:25Z",
tur={"evalId": 1, "asyncDispatched": True, "result": "(dispatched #1)"}),
# its delivery, then its two calls as virtual records
{"type": "attachment", "timestamp": "2026-11-18T19:13:28Z", "sessionId": "s1",
"attachment": {"type": "poll_events", "envelopes": [_event(1, "settled", "a: 67", 2924)]}},
*_virtual("repl_1", "Bash", {"command": "python3 -c 'x=1'"}, "", "2026-11-18T19:13:28Z"),
*_virtual("repl_2", "Bash", {"command": "ls /usr/lib | wc -l"}, "67", "2026-11-18T19:13:28Z"),
# two scripts dispatched together, settled in one Poll's delivery
_asst("toolu_B", "REPL", {"code": B}, "2026-11-18T19:14:05Z"),
_result("toolu_B", "(dispatched #2)", "2026-11-18T19:14:05Z", tur={"evalId": 2, "asyncDispatched": True}),
_asst("toolu_C", "REPL", {"code": C}, "2026-11-18T19:14:05Z"),
_result("toolu_C", "(dispatched #3)", "2026-11-18T19:14:05Z", tur={"evalId": 3, "asyncDispatched": True}),
_asst("toolu_P", "Poll", {}, "2026-11-18T19:14:06Z"),
_result("toolu_P", "<system>nonces</system>\n" + _event(2, "settled", "A-done", 12278)
+ "\n" + _event(3, "settled", "{ b: 'B-done' }", 2705), "2026-11-18T19:14:19Z"),
*_virtual("repl_3", "Bash", {"command": "sleep 12 && echo A-done"}, "A-done", "2026-11-18T19:14:19Z"),
*_virtual("repl_4", "Bash", {"command": "sleep 2 && echo B-done"}, "B-done", "2026-11-18T19:14:19Z"),
*_virtual("repl_5", "Edit", {"file_path": "/w/note.txt", "old_string": "hello", "new_string": "bye"},
"ok", "2026-11-18T19:14:19Z"),
# the model's own call afterwards: no script
_asst("toolu_D", "Bash", {"command": "cat note.txt"}, "2026-11-18T19:14:25Z"),
_result("toolu_D", "bye world", "2026-11-18T19:14:25Z"),
]
def _parse(tmp_path, recs):
p = tmp_path / "s1.jsonl"
p.write_text("\n".join(json.dumps(r) for r in recs) + "\n")
return c.parse_conversation(p, full=True)
def test_virtual_calls_are_tagged_with_their_script(tmp_path):
s = _parse(tmp_path, RECORDS)
by_id = {it.get("toolUseId"): it for it in s["thread"] if it.get("kind") == "tool_use"}
assert {k: by_id[k].get("script") for k in ("repl_1", "repl_2", "repl_3", "repl_4", "repl_5", "toolu_D")} == {
"repl_1": "toolu_A", "repl_2": "toolu_A", "repl_3": "toolu_B",
"repl_4": "toolu_C", "repl_5": "toolu_C", "toolu_D": None}
a = by_id["toolu_A"]
assert (a["evalId"], a["codeResult"], a["codeMs"]) == (1, "a: 67", 2924)
assert by_id["toolu_B"]["codeResult"] == "A-done" and by_id["toolu_C"]["codeMs"] == 2705
# the virtual records are no API call: no turn, no $0 chip on their card
assert s["assistantTurns"] == 5 # A, B, C, Poll, D — the five virtual calls aren't turns
assert all(by_id[k].get("turnTokens") is None for k in ("repl_1", "repl_3", "repl_5"))
def test_settled_reads_results_and_logs():
ev = codemode.settled(_event(4, "settled", "ok", 12) + '<event kind="repl-eval" eval="1" status="late">'
"<log>[late output]</log><log>A result: A-done</log></event>"
+ '<event kind="repl-status" pending="1">x</event>')
assert ev == [{"eval": 4, "status": "settled", "ms": 12, "result": "ok"},
{"eval": 1, "status": "late", "ms": None, "result": "[late output]\nA result: A-done"}]
def test_one_delivery_two_scripts_picks_by_code():
cm = codemode.CodeMode()
cm.started("t1", {"code": "await $`make build`"})
cm.started("t2", {"code": "await edit('a/b/notes.md', 'x', 'y')"})
cm.dispatched("t1", {"evalId": 1})
cm.dispatched("t2", {"evalId": 2})
cm.delivered(_event(1, "settled", "") + _event(2, "settled", ""))
assert cm.script_of({"file_path": "/w/a/b/notes.md"}) == "t2"
assert cm.script_of({"command": "make build"}) == "t1"
assert cm.script_of({"command": "something else"}) == "t1"
cm.model_turn()
assert cm.script_of({"command": "make build"}) is None