From 3f29301271a8dd175639618e9c4f76ed36d88e6a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 27 Nov 2026 14:53:04 -0800 Subject: [PATCH 1/4] refactor(agents): one follower feeds every agent's atif/1 adapter, and Codex's and Gemini's tails get modules of their own The three bridges each followed their CLI's files their own way, Codex's and Gemini's with copies of one loop. utils/tail_follow is the one follower now, taken by each image through shared_sources.toml; Claude Code's tail gains take(), its read committed. Codex's rollout tail moves to codex_rollout.py and Gemini's transcript tail to gemini_transcript.py, each given how to find its files rather than reaching back into the bridge. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/claude-code/Dockerfile | 5 +- .../agents/claude-code/claude_bridge.py | 49 +--- .../agents/agents/claude-code/install.sh | 2 +- .../agents/claude-code/shared_sources.toml | 1 + src/agent_env/agents/agents/codex/Dockerfile | 8 +- .../agents/agents/codex/codex_bridge.py | 262 +----------------- .../agents/agents/codex/codex_rollout.py | 233 ++++++++++++++++ src/agent_env/agents/agents/codex/install.sh | 2 +- .../agents/agents/codex/shared_sources.toml | 1 + src/agent_env/agents/agents/gemini/Dockerfile | 4 +- .../agents/agents/gemini/gemini_bridge.py | 197 +++---------- .../agents/agents/gemini/gemini_transcript.py | 124 +++++++++ src/agent_env/agents/agents/gemini/install.sh | 4 +- .../agents/agents/gemini/shared_sources.toml | 3 + .../utils/tail_follow/tail_follow.py | 47 ++++ tst/unit/agents/claude_code/agent.py | 5 +- tst/unit/agents/codex/agent.py | 7 +- tst/unit/agents/codex/test_codex_atif.py | 4 +- tst/unit/agents/codex/test_image_contract.py | 2 +- tst/unit/agents/codex/test_rollout_tail.py | 68 ++--- tst/unit/agents/gemini/agent.py | 11 +- tst/unit/agents/gemini/test_card_contract.py | 4 +- tst/unit/agents/gemini/test_gemini_atif.py | 4 +- tst/unit/agents/gemini/test_image_contract.py | 37 ++- tst/unit/agents/gemini/test_session_tail.py | 63 ++--- tst/unit/agents/test_tail_follow.py | 86 ++++++ 26 files changed, 649 insertions(+), 584 deletions(-) create mode 100644 src/agent_env/agents/agents/codex/codex_rollout.py create mode 100644 src/agent_env/agents/agents/gemini/gemini_transcript.py create mode 100644 src/agent_env/agents/agents/gemini/shared_sources.toml create mode 100644 src/agent_env/utils/tail_follow/tail_follow.py create mode 100644 tst/unit/agents/test_tail_follow.py diff --git a/src/agent_env/agents/agents/claude-code/Dockerfile b/src/agent_env/agents/agents/claude-code/Dockerfile index 45f647bad..5897131b8 100644 --- a/src/agent_env/agents/agents/claude-code/Dockerfile +++ b/src/agent_env/agents/agents/claude-code/Dockerfile @@ -41,8 +41,9 @@ COPY requirements.txt model-requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt -r model-requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. COPY a2a_server.py claude_bridge.py claude_code_atif.py kit.py tar_changelog.py entrypoint.sh install.sh run.sh ./ -# Every clocked agent's egress rule, which the bridge imports, and the clock page's format it reads (shared_sources.toml). -COPY agent_clock/agent_egress.py clock/clockpage.py ./ +# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the follower that +# feeds the atif/1 adapter the transcript (shared_sources.toml). +COPY agent_clock/agent_egress.py clock/clockpage.py tail_follow/tail_follow.py ./ # The CLI's cwd, /app, and its state, fixed so neither follows the uid. RUN useradd --create-home --uid 10001 agent && mkdir -p /app /home/agent/.claude \ && chown agent:agent /app /home/agent/.claude && chmod 0755 entrypoint.sh diff --git a/src/agent_env/agents/agents/claude-code/claude_bridge.py b/src/agent_env/agents/agents/claude-code/claude_bridge.py index d3d2df304..ab17b4d96 100644 --- a/src/agent_env/agents/agents/claude-code/claude_bridge.py +++ b/src/agent_env/agents/agents/claude-code/claude_bridge.py @@ -22,6 +22,7 @@ from pydantic import BaseModel, ConfigDict, model_validator from agent_egress import clock_armed, egress_env +from tail_follow import following from kit import in_thread_to_its_end logger = logging.getLogger(__name__) @@ -568,6 +569,13 @@ def advance(self, files: Mapping[Path, _TailedFile], shapes: set[tuple[str | Non self._shapes.update(shapes) self._earlier_shape = None + def take(self, final: bool = False) -> list[tuple[str, dict]]: + """What ``read`` gives, committed: the follower feeds every read it makes (``tail_follow``). The transcript has + no end of its own to read to, so a final read is like any other.""" + records, files, shapes = self.read() + self.advance(files, shapes) + return records + @staticmethod def _new_lines(path: Path, tailed: _TailedFile | None) -> tuple[_TailedFile, list[bytes]]: status = path.stat() @@ -656,35 +664,6 @@ def _ends_in(file, tailed: _TailedFile) -> bool: return file.read(len(tailed.last)) == tailed.last -async def _stop_following(following: asyncio.Task, tail: SessionTail, feed: Callable[[str, Any], None]) -> None: - """Stop following once the CLI has exited, then feed what its transcripts gained since the last read. A follower - that failed is logged; the turn goes on without its records.""" - following.cancel() - try: - await following - except asyncio.CancelledError: - if (current := asyncio.current_task()) is not None and current.cancelling(): - raise - except Exception: - logger.warning("following the session transcript failed; the ATIF copy lacks its later records", exc_info=True) - return - await _feed_tail(tail, feed) - - -async def _follow(tail: SessionTail, feed: Callable[[str, Any], None]) -> None: - """Feed ``tail``'s records while the CLI runs.""" - while True: - await _feed_tail(tail, feed) - await asyncio.sleep(SESSION_POLL_S) - - -async def _feed_tail(tail: SessionTail, feed: Callable[[str, Any], None]) -> None: - records, files, shapes = await asyncio.to_thread(tail.read) - tail.advance(files, shapes) - for name, record in records: - feed(name, record) - - def _one_line(text: str) -> str: return _LINE_BREAK_PATTERN.sub(" ", text).strip() @@ -782,15 +761,13 @@ async def run_claude( else max(int(deadline - time.monotonic()) - _DEADLINE_HEADROOM_S, 1)) # Each scrub ends before the turn does, cancelled or not: a later turn on the context mustn't start while it # can still replace the transcript that turn appends to. - following = asyncio.create_task(_follow(tail, aux_callback)) if tail is not None else None + follow = following(tail.take, aux_callback, SESSION_POLL_S, "session transcript") if tail is not None \ + else contextlib.nullcontext() try: - result = await spawn(prompt=attempt_prompt, session_id=attempt_session, resume=attempt_resume, - timeout_s=attempt_timeout_s) - if following is not None: - await _stop_following(following, tail, aux_callback) + async with follow: + result = await spawn(prompt=attempt_prompt, session_id=attempt_session, resume=attempt_resume, + timeout_s=attempt_timeout_s) finally: - if following is not None: - following.cancel() await in_thread_to_its_end(scrub_session_transcript, attempt_session) if result.session_id != attempt_session: await in_thread_to_its_end(scrub_session_transcript, result.session_id) diff --git a/src/agent_env/agents/agents/claude-code/install.sh b/src/agent_env/agents/agents/claude-code/install.sh index 6407175b6..f3d836ebe 100755 --- a/src/agent_env/agents/agents/claude-code/install.sh +++ b/src/agent_env/agents/agents/claude-code/install.sh @@ -22,7 +22,7 @@ PYTHON_VERSION=3.12 START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 CLAUDE_CODE_VERSION=$(sed -n 's/^ARG CLAUDE_CODE_VERSION=//p' "$here/Dockerfile") -AGENT_FILES="a2a_server.py claude_bridge.py claude_code_atif.py kit.py requirements.txt run.sh tar_changelog.py agent_clock/agent_egress.py clock/clockpage.py" +AGENT_FILES="a2a_server.py claude_bridge.py claude_code_atif.py kit.py requirements.txt run.sh tar_changelog.py agent_clock/agent_egress.py clock/clockpage.py tail_follow/tail_follow.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced. case $mode in diff --git a/src/agent_env/agents/agents/claude-code/shared_sources.toml b/src/agent_env/agents/agents/claude-code/shared_sources.toml index 6076f3540..1aa135aaa 100644 --- a/src/agent_env/agents/agents/claude-code/shared_sources.toml +++ b/src/agent_env/agents/agents/claude-code/shared_sources.toml @@ -3,3 +3,4 @@ clock = "utils/faketime_clock" egress = "utils/egress_proxy" agent_clock = "utils/agent_clock" +tail_follow = "utils/tail_follow" diff --git a/src/agent_env/agents/agents/codex/Dockerfile b/src/agent_env/agents/agents/codex/Dockerfile index 8cd999fd2..f8239dd81 100644 --- a/src/agent_env/agents/agents/codex/Dockerfile +++ b/src/agent_env/agents/agents/codex/Dockerfile @@ -35,10 +35,10 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error && COPY requirements.txt model-requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt -r model-requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. -COPY a2a_server.py codex_atif.py codex_bridge.py codex_config.py codex_date.py codex_kit.py entrypoint.sh install.sh run.sh ./ -# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, and the model relay -# each CLI run calls the endpoint through (shared_sources.toml). -COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py ./ +COPY a2a_server.py codex_atif.py codex_bridge.py codex_config.py codex_date.py codex_kit.py codex_rollout.py entrypoint.sh install.sh run.sh ./ +# Every clocked agent's egress rule, which the bridge imports, the clock page's format it reads, the model relay each +# CLI run calls the endpoint through, and the follower that feeds the atif/1 adapter the rollouts (shared_sources.toml). +COPY agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py tail_follow/tail_follow.py ./ # The CLI's cwd, /app, and its state, fixed so neither follows the uid. RUN useradd --create-home --uid 10001 agent && mkdir -p /app /home/agent/.codex \ && chown agent:agent /app /home/agent/.codex && chmod 0755 entrypoint.sh diff --git a/src/agent_env/agents/agents/codex/codex_bridge.py b/src/agent_env/agents/agents/codex/codex_bridge.py index 151f6f4de..88ff7a8e6 100644 --- a/src/agent_env/agents/agents/codex/codex_bridge.py +++ b/src/agent_env/agents/agents/codex/codex_bridge.py @@ -26,7 +26,9 @@ from agent_egress import clock_armed, egress_env from codex_config import MODEL_HEADERS_ENV, endpoint_root, model_headers, relayed_provider from codex_date import env_date_rewrite +from codex_rollout import ROLLOUT_POLL_S, RolloutTail from model_relay import Calls, model_relay +from tail_follow import following logger = logging.getLogger(__name__) WORKSPACE_DIR = os.environ.get("CODEX_WORKSPACE_DIR", "/app") @@ -64,255 +66,6 @@ def find_rollout_path(thread_id: str) -> Path | None: return matches[0] -ROLLOUT_POLL_S = 0.05 -# How often the follower looks for a sub-agent's new rollout, in polls. -_SUBAGENT_SCAN_POLLS = 10 -_ROLLOUT_EVENTS = frozenset({"task_started", "task_complete"}) -_ROLLOUT_ITEMS = frozenset({"reasoning", "message", "function_call", "custom_tool_call", "tool_search_call", - "web_search_call", "function_call_output", "custom_tool_call_output", - "tool_search_output"}) - - -def rollout_aux(record: dict, thread_id: str, parent: str | None = None) -> dict | None: - """A rollout record as the atif/1 adapter's ``rollout`` aux record, naming its thread and, for a sub-agent's, the - thread that spawned it: what the adapter reads of it, or None for a record it doesn't read (the instructions and - context the CLI sends, its own bookkeeping).""" - kind, payload = record.get("type"), record.get("payload") - if not isinstance(payload, dict): - return None - if kind == "session_meta": - source = payload.get("source") - spawn = source.get("subagent", {}).get("thread_spawn", {}) if isinstance(source, dict) else {} - kept = {"id": payload.get("id"), "parent_thread_id": payload.get("parent_thread_id"), - "agent_path": spawn.get("agent_path") if isinstance(spawn, dict) else None, - "agent_nickname": payload.get("agent_nickname"), "cli_version": payload.get("cli_version")} - elif kind == "turn_context": - kept = {"model": payload.get("model"), "effort": payload.get("effort")} - elif kind == "event_msg" and payload.get("type") in _ROLLOUT_EVENTS: - kept = {key: payload.get(key) for key in ("type", "error")} - elif kind == "token_usage_record": - kept = {key: payload.get(key) for key in ("response_id", "usage")} - elif kind == "response_item" and payload.get("type") in _ROLLOUT_ITEMS: - if payload.get("type") == "message" and payload.get("role") != "assistant": - return None - kept = {key: value for key, value in payload.items() if key != "internal_chat_message_metadata_passthrough"} - else: - return None - fed = {"type": kind, "timestamp": record.get("timestamp"), "thread": thread_id, - "payload": {key: value for key, value in kept.items() if value is not None}} - if parent is not None: - fed["parent"] = parent - return fed - - -@dataclass -class _Followed: - thread: str - parent: str | None - inode: int - offset: int - lines: int - # A forked sub-agent's rollout begins with the turns of the thread it was forked from, which aren't its own. - forked_from: str | None = None - copied_turns: set[str] = field(default_factory=set) - own_turns: set[str] = field(default_factory=set) - - -def _turn_of(record: dict) -> str | None: - """The turn a rollout record belongs to, as the CLI names it.""" - payload = record.get("payload") - if not isinstance(payload, dict): - return None - passthrough = payload.get("internal_chat_message_metadata_passthrough") - turn = payload.get("turn_id") or (passthrough.get("turn_id") if isinstance(passthrough, dict) else None) - return turn if isinstance(turn, str) else None - - -def _thread_turns(thread: str) -> frozenset[str]: - """Every turn a thread's rollout holds, the ones it copied from a thread it was forked from included.""" - path = find_rollout_path(thread) - if path is None: - return frozenset() - turns = set() - try: - with path.open("rb") as file: - for raw in file: - if b'"task_started"' not in raw: - continue - try: - record = json.loads(raw) - except (json.JSONDecodeError, UnicodeDecodeError): - continue - if isinstance(record, dict) and (turn := _turn_of(record)) is not None: - turns.add(turn) - except OSError: - pass - return frozenset(turns) - - -class RolloutTail: - """One turn's new rollout records, as ``rollout_aux`` gives them: its thread's, and each sub-agent's it spawns at - any depth, as the CLI appends them. Each file is read from where it ended when the turn began, so an earlier turn's - records aren't fed again; a file replaced since is read on from its line count. ``bind`` names the thread once the - CLI has started a new one.""" - - def __init__(self, thread_id: str | None) -> None: - self._lock = threading.Lock() - self._threads: set[str] = set() - self._unfound: set[str] = set() - self._files: dict[Path, _Followed] = {} - self._metas: dict[Path, dict] = {} - self._polls = 0 - if thread_id: - self.bind(thread_id, from_end=True) - self._scan(from_end=True) - - def bind(self, thread_id: str, *, from_end: bool = False) -> None: - with self._lock: - if thread_id in self._threads: - return - self._threads.add(thread_id) - path = find_rollout_path(thread_id) - if path is None: - self._unfound.add(thread_id) - else: - self._start(path, thread_id, None, from_end) - - def read(self, *, final: bool = False) -> list[dict]: - """The records the files gained since the last read, in the order they were written.""" - with self._lock: - for thread in list(self._unfound): - if (path := find_rollout_path(thread)) is not None: - self._unfound.discard(thread) - self._start(path, thread, None, from_end=False) - self._polls += 1 - if final or self._polls % _SUBAGENT_SCAN_POLLS == 0: - self._scan(from_end=False) - records = [record for path in list(self._files) for record in self._new_records(path)] - return sorted(records, key=lambda record: str(record.get("timestamp") or "")) - - def _start(self, path: Path, thread: str, parent: str | None, from_end: bool, forked_from: str | None = None - ) -> None: - try: - status, lines = path.stat(), _count_lines(path) if from_end else 0 - except OSError: - return - self._files[path] = _Followed(thread, parent, status.st_ino, status.st_size if from_end else 0, lines, - forked_from, set(_thread_turns(forked_from)) if forked_from else set()) - - def _scan(self, *, from_end: bool) -> None: - """Follow each sub-agent rollout not yet followed whose parent is a thread followed, until none is new. Each - file's first record is read once, as it may name a parent followed only later.""" - if SESSIONS_DIR.exists(): - for path in SESSIONS_DIR.rglob("rollout-*.jsonl"): - if path not in self._metas and (meta := _session_meta(path)) is not None: - self._metas[path] = meta - found = True - while found: - found = False - for path, meta in self._metas.items(): - thread, parent = meta.get("id"), meta.get("parent_thread_id") - if parent in self._threads and isinstance(thread, str) and thread not in self._threads: - self._threads.add(thread) - forked = meta.get("forked_from_id") - self._start(path, thread, parent, from_end, forked if isinstance(forked, str) else None) - found = True - - def _new_records(self, path: Path) -> list[dict]: - followed = self._files[path] - try: - status = path.stat() - with path.open("rb") as file: - if status.st_ino != followed.inode or status.st_size < followed.offset: - for _ in range(followed.lines): - if not file.readline(): - break - followed.inode, followed.offset = status.st_ino, file.tell() - file.seek(followed.offset) - data = file.read() - except OSError: - return [] - complete = data[:data.rfind(b"\n") + 1] - followed.offset += len(complete) - records = [] - for raw in complete.splitlines(): - followed.lines += 1 - try: - record = json.loads(raw) - except (json.JSONDecodeError, UnicodeDecodeError): - continue - if not isinstance(record, dict) or self._copied(record, followed): - continue - if (fed := rollout_aux(record, followed.thread, followed.parent)) is not None: - records.append(fed) - return records - - - @staticmethod - def _copied(record: dict, followed: _Followed) -> bool: - """A record a forked sub-agent's rollout copied from the thread it was forked from: that thread's meta, or - one of its turns', which that thread's rollout is read again for when a turn is new here.""" - payload = record.get("payload") - if record.get("type") == "session_meta": - return isinstance(payload, dict) and payload.get("id") != followed.thread - turn = _turn_of(record) - if followed.forked_from is None or turn is None or turn in followed.own_turns: - return False - if turn not in followed.copied_turns: - followed.copied_turns |= _thread_turns(followed.forked_from) - if turn not in followed.copied_turns: - followed.own_turns.add(turn) - return False - return True - - -def _count_lines(path: Path) -> int: - with path.open("rb") as file: - return sum(1 for _ in file) - - -def _session_meta(path: Path) -> dict | None: - """A rollout's first record's payload when it is the session's meta, None while the CLI hasn't written it.""" - try: - with path.open("rb") as file: - first = file.readline() - except OSError: - return None - if not first.endswith(b"\n"): - return None - try: - record = json.loads(first) - except (json.JSONDecodeError, UnicodeDecodeError): - return {} - payload = record.get("payload") if isinstance(record, dict) and record.get("type") == "session_meta" else None - return payload if isinstance(payload, dict) else {} - - -async def follow_rollout(tail: RolloutTail, feed: Callable[[str, dict], None], stopped: asyncio.Event) -> None: - """Feed ``tail``'s records while the CLI runs, then, once ``stopped`` is set, what the rollouts gained since. A read - in progress when it's set is fed first, since the read has already moved past what it returns.""" - while not stopped.is_set(): - for record in await asyncio.to_thread(tail.read): - feed("rollout", record) - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(stopped.wait(), ROLLOUT_POLL_S) - for record in await asyncio.to_thread(tail.read, final=True): - feed("rollout", record) - - -async def stop_following_rollout(following: asyncio.Task, stopped: asyncio.Event) -> None: - """Have the follower feed what's left once the CLI has exited, and wait for it. A follower that failed is logged; - the turn goes on without its later records.""" - stopped.set() - try: - await following - except asyncio.CancelledError: - following.cancel() - raise - except Exception: - logger.warning("following the rollouts failed; the ATIF copy lacks its later records", exc_info=True) - - # LiteLLM attribution-probe state. The codex CLI's config.toml maps # LITELLM_CUSTOMER_ID/LITELLM_TAGS env vars onto x-litellm-customer-id / # x-litellm-tags headers at request time (via env_http_headers). We @@ -1229,7 +982,7 @@ async def run_codex( config_overrides=config_overrides, max_turns=max_turns, mcp_urls=mcp_urls) if aux_callback is None: return await attempts(event_callback=event_callback) - tail = await asyncio.to_thread(RolloutTail, thread_id) + tail = await asyncio.to_thread(RolloutTail, thread_id, SESSIONS_DIR, find_rollout_path) def on_event(event: dict) -> None: if event.get("type") == "thread.started" and isinstance(event.get("thread_id"), str): @@ -1237,12 +990,11 @@ def on_event(event: dict) -> None: if event_callback is not None: event_callback(event) - stopped = asyncio.Event() - following = asyncio.create_task(follow_rollout(tail, aux_callback, stopped)) - try: + def read(final: bool) -> list[tuple[str, dict]]: + return [("rollout", record) for record in tail.read(final=final)] + + async with following(read, aux_callback, ROLLOUT_POLL_S, "rollout"): return await attempts(event_callback=on_event) - finally: - await stop_following_rollout(following, stopped) async def _run_codex_attempts( diff --git a/src/agent_env/agents/agents/codex/codex_rollout.py b/src/agent_env/agents/agents/codex/codex_rollout.py new file mode 100644 index 000000000..6cda02360 --- /dev/null +++ b/src/agent_env/agents/agents/codex/codex_rollout.py @@ -0,0 +1,233 @@ +"""The Codex CLI's rollouts as its atif/1 adapter reads them: each record it reads as the ``rollout`` aux record +(``rollout_aux``), and the tail that finds them as a turn writes them (``RolloutTail``), its sub-agents' included.""" + +from __future__ import annotations + +import json +import threading +from collections.abc import Callable +from dataclasses import dataclass, field +from pathlib import Path + +ROLLOUT_POLL_S = 0.05 +# How often the follower looks for a sub-agent's new rollout, in polls. +_SUBAGENT_SCAN_POLLS = 10 +_ROLLOUT_EVENTS = frozenset({"task_started", "task_complete"}) +_ROLLOUT_ITEMS = frozenset({"reasoning", "message", "function_call", "custom_tool_call", "tool_search_call", + "web_search_call", "function_call_output", "custom_tool_call_output", + "tool_search_output"}) + + +def rollout_aux(record: dict, thread_id: str, parent: str | None = None) -> dict | None: + """A rollout record as the atif/1 adapter's ``rollout`` aux record, naming its thread and, for a sub-agent's, the + thread that spawned it: what the adapter reads of it, or None for a record it doesn't read (the instructions and + context the CLI sends, its own bookkeeping).""" + kind, payload = record.get("type"), record.get("payload") + if not isinstance(payload, dict): + return None + if kind == "session_meta": + source = payload.get("source") + spawn = source.get("subagent", {}).get("thread_spawn", {}) if isinstance(source, dict) else {} + kept = {"id": payload.get("id"), "parent_thread_id": payload.get("parent_thread_id"), + "agent_path": spawn.get("agent_path") if isinstance(spawn, dict) else None, + "agent_nickname": payload.get("agent_nickname"), "cli_version": payload.get("cli_version")} + elif kind == "turn_context": + kept = {"model": payload.get("model"), "effort": payload.get("effort")} + elif kind == "event_msg" and payload.get("type") in _ROLLOUT_EVENTS: + kept = {key: payload.get(key) for key in ("type", "error")} + elif kind == "token_usage_record": + kept = {key: payload.get(key) for key in ("response_id", "usage")} + elif kind == "response_item" and payload.get("type") in _ROLLOUT_ITEMS: + if payload.get("type") == "message" and payload.get("role") != "assistant": + return None + kept = {key: value for key, value in payload.items() if key != "internal_chat_message_metadata_passthrough"} + else: + return None + fed = {"type": kind, "timestamp": record.get("timestamp"), "thread": thread_id, + "payload": {key: value for key, value in kept.items() if value is not None}} + if parent is not None: + fed["parent"] = parent + return fed + + +@dataclass +class _Followed: + thread: str + parent: str | None + inode: int + offset: int + lines: int + # A forked sub-agent's rollout begins with the turns of the thread it was forked from, which aren't its own. + forked_from: str | None = None + copied_turns: set[str] = field(default_factory=set) + own_turns: set[str] = field(default_factory=set) + + +def _turn_of(record: dict) -> str | None: + """The turn a rollout record belongs to, as the CLI names it.""" + payload = record.get("payload") + if not isinstance(payload, dict): + return None + passthrough = payload.get("internal_chat_message_metadata_passthrough") + turn = payload.get("turn_id") or (passthrough.get("turn_id") if isinstance(passthrough, dict) else None) + return turn if isinstance(turn, str) else None + + +def _thread_turns(find: Callable[[str], Path | None], thread: str) -> frozenset[str]: + """Every turn a thread's rollout holds, the ones it copied from a thread it was forked from included.""" + path = find(thread) + if path is None: + return frozenset() + turns = set() + try: + with path.open("rb") as file: + for raw in file: + if b'"task_started"' not in raw: + continue + try: + record = json.loads(raw) + except (json.JSONDecodeError, UnicodeDecodeError): + continue + if isinstance(record, dict) and (turn := _turn_of(record)) is not None: + turns.add(turn) + except OSError: + pass + return frozenset(turns) + + +class RolloutTail: + """One turn's new rollout records, as ``rollout_aux`` gives them: its thread's, and each sub-agent's it spawns at + any depth, as the CLI appends them, from the rollouts under ``sessions``, ``find`` naming a thread's. Each file is + read from where it ended when the turn began, so an earlier turn's records aren't fed again; a file replaced since + is read on from its line count. ``bind`` names the thread once the CLI has started a new one.""" + + def __init__(self, thread_id: str | None, sessions: Path, find: Callable[[str], Path | None]) -> None: + self._lock = threading.Lock() + self._sessions, self._find = sessions, find + self._threads: set[str] = set() + self._unfound: set[str] = set() + self._files: dict[Path, _Followed] = {} + self._metas: dict[Path, dict] = {} + self._polls = 0 + if thread_id: + self.bind(thread_id, from_end=True) + self._scan(from_end=True) + + def bind(self, thread_id: str, *, from_end: bool = False) -> None: + with self._lock: + if thread_id in self._threads: + return + self._threads.add(thread_id) + path = self._find(thread_id) + if path is None: + self._unfound.add(thread_id) + else: + self._start(path, thread_id, None, from_end) + + def read(self, *, final: bool = False) -> list[dict]: + """The records the files gained since the last read, in the order they were written.""" + with self._lock: + for thread in list(self._unfound): + if (path := self._find(thread)) is not None: + self._unfound.discard(thread) + self._start(path, thread, None, from_end=False) + self._polls += 1 + if final or self._polls % _SUBAGENT_SCAN_POLLS == 0: + self._scan(from_end=False) + records = [record for path in list(self._files) for record in self._new_records(path)] + return sorted(records, key=lambda record: str(record.get("timestamp") or "")) + + def _start(self, path: Path, thread: str, parent: str | None, from_end: bool, forked_from: str | None = None + ) -> None: + try: + status, lines = path.stat(), _count_lines(path) if from_end else 0 + except OSError: + return + self._files[path] = _Followed(thread, parent, status.st_ino, status.st_size if from_end else 0, lines, + forked_from, set(_thread_turns(self._find, forked_from)) if forked_from else set()) + + def _scan(self, *, from_end: bool) -> None: + """Follow each sub-agent rollout not yet followed whose parent is a thread followed, until none is new. Each + file's first record is read once, as it may name a parent followed only later.""" + if self._sessions.exists(): + for path in self._sessions.rglob("rollout-*.jsonl"): + if path not in self._metas and (meta := _session_meta(path)) is not None: + self._metas[path] = meta + found = True + while found: + found = False + for path, meta in self._metas.items(): + thread, parent = meta.get("id"), meta.get("parent_thread_id") + if parent in self._threads and isinstance(thread, str) and thread not in self._threads: + self._threads.add(thread) + forked = meta.get("forked_from_id") + self._start(path, thread, parent, from_end, forked if isinstance(forked, str) else None) + found = True + + def _new_records(self, path: Path) -> list[dict]: + followed = self._files[path] + try: + status = path.stat() + with path.open("rb") as file: + if status.st_ino != followed.inode or status.st_size < followed.offset: + for _ in range(followed.lines): + if not file.readline(): + break + followed.inode, followed.offset = status.st_ino, file.tell() + file.seek(followed.offset) + data = file.read() + except OSError: + return [] + complete = data[:data.rfind(b"\n") + 1] + followed.offset += len(complete) + records = [] + for raw in complete.splitlines(): + followed.lines += 1 + try: + record = json.loads(raw) + except (json.JSONDecodeError, UnicodeDecodeError): + continue + if not isinstance(record, dict) or self._copied(record, followed): + continue + if (fed := rollout_aux(record, followed.thread, followed.parent)) is not None: + records.append(fed) + return records + + + def _copied(self, record: dict, followed: _Followed) -> bool: + """A record a forked sub-agent's rollout copied from the thread it was forked from: that thread's meta, or + one of its turns', which that thread's rollout is read again for when a turn is new here.""" + payload = record.get("payload") + if record.get("type") == "session_meta": + return isinstance(payload, dict) and payload.get("id") != followed.thread + turn = _turn_of(record) + if followed.forked_from is None or turn is None or turn in followed.own_turns: + return False + if turn not in followed.copied_turns: + followed.copied_turns |= _thread_turns(self._find, followed.forked_from) + if turn not in followed.copied_turns: + followed.own_turns.add(turn) + return False + return True + + +def _count_lines(path: Path) -> int: + with path.open("rb") as file: + return sum(1 for _ in file) + + +def _session_meta(path: Path) -> dict | None: + """A rollout's first record's payload when it is the session's meta, None while the CLI hasn't written it.""" + try: + with path.open("rb") as file: + first = file.readline() + except OSError: + return None + if not first.endswith(b"\n"): + return None + try: + record = json.loads(first) + except (json.JSONDecodeError, UnicodeDecodeError): + return {} + payload = record.get("payload") if isinstance(record, dict) and record.get("type") == "session_meta" else None + return payload if isinstance(payload, dict) else {} diff --git a/src/agent_env/agents/agents/codex/install.sh b/src/agent_env/agents/agents/codex/install.sh index 9ed78b1ed..504ace512 100755 --- a/src/agent_env/agents/agents/codex/install.sh +++ b/src/agent_env/agents/agents/codex/install.sh @@ -24,7 +24,7 @@ START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 dockerfile_arg() { sed -n "s/^ARG $1=//p" "$here/Dockerfile"; } NODE_VERSION=$(dockerfile_arg NODE_VERSION) -AGENT_FILES="a2a_server.py codex_atif.py codex_bridge.py codex_config.py codex_date.py codex_kit.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py" +AGENT_FILES="a2a_server.py codex_atif.py codex_bridge.py codex_config.py codex_date.py codex_kit.py codex_rollout.py requirements.txt run.sh agent_clock/agent_egress.py clock/clockpage.py model_relay/model_relay.py tail_follow/tail_follow.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC # DEST copies a folder to DEST, which isn't there. diff --git a/src/agent_env/agents/agents/codex/shared_sources.toml b/src/agent_env/agents/agents/codex/shared_sources.toml index ba8b8a852..72e0e187a 100644 --- a/src/agent_env/agents/agents/codex/shared_sources.toml +++ b/src/agent_env/agents/agents/codex/shared_sources.toml @@ -4,3 +4,4 @@ clock = "utils/faketime_clock" egress = "utils/egress_proxy" agent_clock = "utils/agent_clock" model_relay = "utils/model_relay" +tail_follow = "utils/tail_follow" diff --git a/src/agent_env/agents/agents/gemini/Dockerfile b/src/agent_env/agents/agents/gemini/Dockerfile index fa9045a93..774022ed1 100644 --- a/src/agent_env/agents/agents/gemini/Dockerfile +++ b/src/agent_env/agents/agents/gemini/Dockerfile @@ -20,7 +20,9 @@ RUN npm ci --ignore-scripts --omit=dev --no-audit --no-fund --loglevel=error && COPY requirements.txt model-requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt -r model-requirements.txt # install.sh and run.sh are install/v1's: in the image, so they stay in its build context. -COPY a2a_server.py gemini_atif.py gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py entrypoint.sh install.sh run.sh ./ +COPY a2a_server.py gemini_atif.py gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py gemini_transcript.py entrypoint.sh install.sh run.sh ./ +# The follower that feeds the atif/1 adapter the transcript, one copy every following agent takes (shared_sources.toml). +COPY tail_follow/tail_follow.py ./ # The CLI's cwd and file-tool boundary, /workspace, and its state, fixed so neither follows the uid: Modal runs the # image as root. /app is kept, empty and writable, for tasks that name it. RUN useradd --create-home --uid 10001 agent && mkdir -p /workspace/inputs /app /home/agent/.gemini \ diff --git a/src/agent_env/agents/agents/gemini/gemini_bridge.py b/src/agent_env/agents/agents/gemini/gemini_bridge.py index feb6a2b64..eccc74d18 100644 --- a/src/agent_env/agents/agents/gemini/gemini_bridge.py +++ b/src/agent_env/agents/agents/gemini/gemini_bridge.py @@ -10,6 +10,7 @@ import asyncio import contextlib +import functools import json import logging import os @@ -23,6 +24,8 @@ from pathlib import Path from gemini_config import SYSTEM_SETTINGS_ENV, gemini_home +from gemini_transcript import SESSION_POLL_S, SessionTail +from tail_follow import following logger = logging.getLogger(__name__) @@ -162,145 +165,6 @@ def _unclaimed_session_id(since: float, claimed: Collection[str], cwd: str) -> s return next(iter(found), None) -SESSION_POLL_S = 0.25 - - -def session_aux(message: dict) -> dict | None: - """A session transcript's model message as the atif/1 adapter's ``session`` aux record: what the adapter reads of - it, or None for a message it doesn't read (the user's, the CLI's notices). Each call keeps its result, without how - the CLI displays it.""" - if message.get("type") != "gemini": - return None - record = {key: message[key] for key in ("type", "id", "timestamp", "model", "content", "thoughts", "tokens") - if message.get(key) is not None} - calls = [{key: call[key] for key in ("id", "name", "args", "status", "timestamp", "result") - if call.get(key) is not None} for call in message.get("toolCalls") or () if isinstance(call, dict)] - if calls: - record["toolCalls"] = calls - return record - - -def transcript_messages(text: str, jsonl: bool) -> list[dict] | None: - """A transcript's messages in order: a ``.json`` file's ``messages``, which the CLI rewrites whole, or a ``.jsonl`` - file's lines after its first, the session's metadata, a message written again replacing its earlier copy in its - place. None for a ``.json`` file that doesn't parse whole, as one the CLI is writing; a ``.jsonl`` line not yet - whole is left out.""" - if not jsonl: - try: - transcript = json.loads(text) - except ValueError: - return None - messages = transcript.get("messages") if isinstance(transcript, dict) else None - return [message for message in messages if isinstance(message, dict)] if isinstance(messages, list) else None - by_id: dict[str, dict] = {} - for line in text.splitlines(keepends=True)[1:]: - try: - message = json.loads(line) if line.endswith("\n") else None - except ValueError: - continue - if isinstance(message, dict) and isinstance(message.get("id"), str): - by_id[message["id"]] = message - return list(by_id.values()) - - -class SessionTail: - """One turn's new model messages from the session's transcript, ``.json`` or ``.jsonl``, as ``session_aux`` gives - them: each once a later message follows it, since the CLI adds a message's tool calls and their results after - writing it, and the last at the turn's end. A resumed session's messages from before the turn aren't fed again, - one restored from a snapshot's included. ``bind`` names the session once the CLI has started a new one.""" - - def __init__(self, session_id: str | None, cwd: str) -> None: - self._lock = threading.Lock() - self._cwd = cwd - self._session: str | None = None - self._path: Path | None = None - self._stamp: tuple[int, int] | None = None - self._messages: list[dict] = [] - self._fed: set[str] = set() - self._resumed = False - if session_id: - self.bind(session_id, resumed=True) - - def bind(self, session_id: str, *, resumed: bool = False) -> None: - with self._lock: - if self._session is not None: - return - self._session, self._resumed = session_id, resumed - if resumed: - self._load() - - def read(self, *, final: bool = False) -> list[dict]: - """The messages settled since the last read, in order; with ``final``, the last one too.""" - with self._lock: - self._load() - settled = self._messages if final else self._messages[:-1] - fed = [] - for message in settled: - if not isinstance(message.get("id"), str) or message["id"] in self._fed: - continue - self._fed.add(message["id"]) - if (record := session_aux(message)) is not None: - fed.append(record) - return fed - - def _load(self) -> None: - """The transcript's messages, read again when the file changed: one the CLI is still writing is read at the - next poll, and one it moved, as from ``.json`` to ``.jsonl``, is found and read in this one.""" - if self._session is None: - return - for _ in range(2): - if self._path is None: - self._path = find_session_file(self._session, self._cwd) - if self._path is None: - return - try: - status = self._path.stat() - stamp = (status.st_mtime_ns, status.st_size) - if stamp == self._stamp: - return - text = self._path.read_text() - break - except FileNotFoundError: - self._path = self._stamp = None - except OSError: - return - else: - return - messages = transcript_messages(text, jsonl=self._path.suffix == ".jsonl") - if messages is not None: - self._stamp = stamp - self._messages = messages - if self._resumed: - # The transcript as the turn found it: what's in it already is earlier turns'. - self._fed.update(message.get("id") for message in self._messages) - self._resumed = False - - -async def follow_session(tail: SessionTail, feed: Callable[[str, dict], None], stopped: asyncio.Event) -> None: - """Feed ``tail``'s messages while the CLI runs, then, once ``stopped`` is set, what the transcript gained since. A read - in progress when it's set is fed first, since the read has already moved past what it returns.""" - while not stopped.is_set(): - for record in await asyncio.to_thread(tail.read): - feed("session", record) - with contextlib.suppress(TimeoutError): - await asyncio.wait_for(stopped.wait(), SESSION_POLL_S) - for record in await asyncio.to_thread(tail.read, final=True): - feed("session", record) - - -async def stop_following_session(following: asyncio.Task, stopped: asyncio.Event) -> None: - """Have the follower feed what's left once the CLI has exited, and wait for it. A follower that failed is logged; - the turn goes on without its later messages.""" - stopped.set() - try: - await following - except asyncio.CancelledError: - following.cancel() - raise - except Exception: - logger.warning("following the transcript failed; the ATIF copy lacks its later messages", exc_info=True) - - def detect_format(raw: bytes) -> str: """Classify a transcript blob as 'json' (legacy single-object) or 'jsonl'. Used by snapshot save/load to preserve the source format byte-for-byte @@ -675,7 +539,8 @@ async def run_gemini( ) started = time.time() # Read before the CLI starts, so a resumed session's messages from earlier turns are the ones it skips. - tail = await asyncio.to_thread(SessionTail, session_id, cwd or os.getcwd()) if aux_callback is not None else None + tail = await asyncio.to_thread(SessionTail, session_id, functools.partial(find_session_file, cwd=cwd or os.getcwd())) \ + if aux_callback is not None else None proc = await _started(asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, @@ -689,8 +554,6 @@ async def run_gemini( response_parts: list[str] = [] tool_count = 0 captured_session_id: str | None = session_id - stopped = asyncio.Event() - following = asyncio.create_task(follow_session(tail, aux_callback, stopped)) if tail is not None else None def on_line(line: str) -> None: nonlocal tool_count, captured_session_id @@ -730,29 +593,33 @@ def on_line(line: str) -> None: if event_callback is not None: event_callback(event) - try: - stderr = await asyncio.wait_for(_stream_cli(proc, on_line), timeout=timeout_s) - except asyncio.CancelledError: - _kill_cli(proc) - await _reap(proc) - raise - except asyncio.TimeoutError: - _kill_cli(proc) - await _reap(proc) - return GeminiResult( - response="", tool_call_count=0, session_id=captured_session_id, - error=f"gemini CLI timed out after {timeout_s}s", - ) - except Exception: - # A failure while reading, such as an event_callback that raises, must - # not leave the CLI running. - _kill_cli(proc) - await _reap(proc) - raise - finally: - _RUNNING.discard(proc) - if following is not None: - await stop_following_session(following, stopped) + def read(final: bool) -> list[tuple[str, dict]]: + return [("session", record) for record in tail.read(final=final)] + + follow = following(read, aux_callback, SESSION_POLL_S, "transcript") if tail is not None \ + else contextlib.nullcontext() + async with follow: + try: + stderr = await asyncio.wait_for(_stream_cli(proc, on_line), timeout=timeout_s) + except asyncio.CancelledError: + _kill_cli(proc) + await _reap(proc) + raise + except asyncio.TimeoutError: + _kill_cli(proc) + await _reap(proc) + return GeminiResult( + response="", tool_call_count=0, session_id=captured_session_id, + error=f"gemini CLI timed out after {timeout_s}s", + ) + except Exception: + # A failure while reading, such as an event_callback that raises, must + # not leave the CLI running. + _kill_cli(proc) + await _reap(proc) + raise + finally: + _RUNNING.discard(proc) response = "".join(response_parts) err: str | None = None diff --git a/src/agent_env/agents/agents/gemini/gemini_transcript.py b/src/agent_env/agents/agents/gemini/gemini_transcript.py new file mode 100644 index 000000000..e15bf2b9a --- /dev/null +++ b/src/agent_env/agents/agents/gemini/gemini_transcript.py @@ -0,0 +1,124 @@ +"""The Gemini CLI's session transcripts as its atif/1 adapter reads them: each model message it reads as the +``session`` aux record (``session_aux``), and the tail that finds them as a turn writes them (``SessionTail``), from a +``.json`` transcript the CLI rewrites whole or a ``.jsonl`` one it appends to.""" + +from __future__ import annotations + +import json +import threading +from collections.abc import Callable +from pathlib import Path + +SESSION_POLL_S = 0.25 + + +def session_aux(message: dict) -> dict | None: + """A session transcript's model message as the atif/1 adapter's ``session`` aux record: what the adapter reads of + it, or None for a message it doesn't read (the user's, the CLI's notices). Each call keeps its result, without how + the CLI displays it.""" + if message.get("type") != "gemini": + return None + record = {key: message[key] for key in ("type", "id", "timestamp", "model", "content", "thoughts", "tokens") + if message.get(key) is not None} + calls = [{key: call[key] for key in ("id", "name", "args", "status", "timestamp", "result") + if call.get(key) is not None} for call in message.get("toolCalls") or () if isinstance(call, dict)] + if calls: + record["toolCalls"] = calls + return record + + +def transcript_messages(text: str, jsonl: bool) -> list[dict] | None: + """A transcript's messages in order: a ``.json`` file's ``messages``, which the CLI rewrites whole, or a ``.jsonl`` + file's lines after its first, the session's metadata, a message written again replacing its earlier copy in its + place. None for a ``.json`` file that doesn't parse whole, as one the CLI is writing; a ``.jsonl`` line not yet + whole is left out.""" + if not jsonl: + try: + transcript = json.loads(text) + except ValueError: + return None + messages = transcript.get("messages") if isinstance(transcript, dict) else None + return [message for message in messages if isinstance(message, dict)] if isinstance(messages, list) else None + by_id: dict[str, dict] = {} + for line in text.splitlines(keepends=True)[1:]: + try: + message = json.loads(line) if line.endswith("\n") else None + except ValueError: + continue + if isinstance(message, dict) and isinstance(message.get("id"), str): + by_id[message["id"]] = message + return list(by_id.values()) + + +class SessionTail: + """One turn's new model messages from the session's transcript, ``.json`` or ``.jsonl``, as ``session_aux`` gives + them: each once a later message follows it, since the CLI adds a message's tool calls and their results after + writing it, and the last at the turn's end. A resumed session's messages from before the turn aren't fed again, + one restored from a snapshot's included, ``find`` naming a session's transcript. ``bind`` names the session once the + CLI has started a new one.""" + + def __init__(self, session_id: str | None, find: Callable[[str], Path | None]) -> None: + self._lock = threading.Lock() + self._find = find + self._session: str | None = None + self._path: Path | None = None + self._stamp: tuple[int, int] | None = None + self._messages: list[dict] = [] + self._fed: set[str] = set() + self._resumed = False + if session_id: + self.bind(session_id, resumed=True) + + def bind(self, session_id: str, *, resumed: bool = False) -> None: + with self._lock: + if self._session is not None: + return + self._session, self._resumed = session_id, resumed + if resumed: + self._load() + + def read(self, *, final: bool = False) -> list[dict]: + """The messages settled since the last read, in order; with ``final``, the last one too.""" + with self._lock: + self._load() + settled = self._messages if final else self._messages[:-1] + fed = [] + for message in settled: + if not isinstance(message.get("id"), str) or message["id"] in self._fed: + continue + self._fed.add(message["id"]) + if (record := session_aux(message)) is not None: + fed.append(record) + return fed + + def _load(self) -> None: + """The transcript's messages, read again when the file changed: one the CLI is still writing is read at the + next poll, and one it moved, as from ``.json`` to ``.jsonl``, is found and read in this one.""" + if self._session is None: + return + for _ in range(2): + if self._path is None: + self._path = self._find(self._session) + if self._path is None: + return + try: + status = self._path.stat() + stamp = (status.st_mtime_ns, status.st_size) + if stamp == self._stamp: + return + text = self._path.read_text() + break + except FileNotFoundError: + self._path = self._stamp = None + except OSError: + return + else: + return + messages = transcript_messages(text, jsonl=self._path.suffix == ".jsonl") + if messages is not None: + self._stamp = stamp + self._messages = messages + if self._resumed: + # The transcript as the turn found it: what's in it already is earlier turns'. + self._fed.update(message.get("id") for message in self._messages) + self._resumed = False diff --git a/src/agent_env/agents/agents/gemini/install.sh b/src/agent_env/agents/agents/gemini/install.sh index 377c1a3f8..0d571388f 100755 --- a/src/agent_env/agents/agents/gemini/install.sh +++ b/src/agent_env/agents/agents/gemini/install.sh @@ -24,7 +24,7 @@ START_TIMEOUT_S=120 STOP_TIMEOUT_S=10 dockerfile_arg() { sed -n "s/^ARG $1=//p" "$here/Dockerfile"; } NODE_VERSION=$(dockerfile_arg NODE_VERSION) -AGENT_FILES="a2a_server.py gemini_atif.py gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py requirements.txt run.sh" +AGENT_FILES="a2a_server.py gemini_atif.py gemini_bridge.py gemini_changelog.py gemini_config.py gemini_kit.py gemini_transcript.py requirements.txt run.sh tail_follow/tail_follow.py" # put SRC DEST replaces DEST by a rename, so a binary an earlier install's agent still runs can be replaced; put_dir SRC # DEST copies a folder to DEST, which isn't there. @@ -132,7 +132,7 @@ put "$stage/agent.env" "$root/agent.env" put "$here/package.json" "$root/npm/package.json" put "$here/package-lock.json" "$root/npm/package-lock.json" for file in $AGENT_FILES; do - put "$here/$file" "$root/app/$file" + put "$here/$file" "$root/app/${file##*/}" done on "chmod 0600 $r/agent.env && chmod 0755 $r/bin/uv $r/bin/gemini $r/app/run.sh" diff --git a/src/agent_env/agents/agents/gemini/shared_sources.toml b/src/agent_env/agents/agents/gemini/shared_sources.toml new file mode 100644 index 000000000..2bb6e5f94 --- /dev/null +++ b/src/agent_env/agents/agents/gemini/shared_sources.toml @@ -0,0 +1,3 @@ +# What this image's build context takes from agent-env's own sources, at the name its Dockerfile copies it from: one +# copy of each, shared with the other images that take it (utils/docker/context.py). Paths are under src/agent_env. +tail_follow = "utils/tail_follow" diff --git a/src/agent_env/utils/tail_follow/tail_follow.py b/src/agent_env/utils/tail_follow/tail_follow.py new file mode 100644 index 000000000..cc75e8756 --- /dev/null +++ b/src/agent_env/utils/tail_follow/tail_follow.py @@ -0,0 +1,47 @@ +"""How an agent's bridge feeds its atif/1 adapter the records the CLI writes to its own files, imported by every bridge +that follows them, whose image copies it beside the bridge (``shared_sources.toml``): a tail of those files, read while +the CLI runs and once more after it exits, each record fed as an aux record as it's read.""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +from collections.abc import AsyncIterator, Callable, Iterable +from typing import Any + +logger = logging.getLogger(__name__) + +#: A tail's read: the (aux file, record) pairs it gained since the last read, everything that's left when ``final``. +Read = Callable[[bool], Iterable[tuple[str, Any]]] + + +async def follow(read: Read, feed: Callable[[str, Any], None], stopped: asyncio.Event, poll_s: float) -> None: + """Feed what ``read`` gives every ``poll_s`` until ``stopped`` is set, then what it gives read final. A read in + progress when it's set is fed first: it has already moved past what it returns, so dropping it would lose it.""" + while not stopped.is_set(): + for name, record in await asyncio.to_thread(read, False): + feed(name, record) + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(stopped.wait(), poll_s) + for name, record in await asyncio.to_thread(read, True): + feed(name, record) + + +@contextlib.asynccontextmanager +async def following(read: Read, feed: Callable[[str, Any], None], poll_s: float, what: str) -> AsyncIterator[None]: + """Follow ``read`` (``follow``) while the block runs, the CLI's run, and have it feed what's left once the block + ends, however it ends. A follower that failed is logged; the turn goes on without the later records of ``what``.""" + stopped = asyncio.Event() + task = asyncio.create_task(follow(read, feed, stopped, poll_s)) + try: + yield + finally: + stopped.set() + try: + await task + except asyncio.CancelledError: + task.cancel() + raise + except Exception: + logger.warning("following the %s failed; the ATIF copy lacks its later records", what, exc_info=True) diff --git a/tst/unit/agents/claude_code/agent.py b/tst/unit/agents/claude_code/agent.py index e2f0dc352..242cff6e6 100644 --- a/tst/unit/agents/claude_code/agent.py +++ b/tst/unit/agents/claude_code/agent.py @@ -1,5 +1,6 @@ """The Claude Code agent's modules, imported as its image runs them: by their own names, from its folder and from the -folders its build context takes as agent_clock/ and clock/, whose modules the image copies beside the bridge.""" +folders its build context takes as agent_clock/, clock/ and tail_follow/, whose modules the image copies beside the +bridge.""" import importlib import os @@ -11,7 +12,7 @@ AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "claude-code" IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "agent_clock/agent_egress.py").parent), - str(sent(AGENT_DIR, "clock/clockpage.py").parent)] + str(sent(AGENT_DIR, "clock/clockpage.py").parent), str(sent(AGENT_DIR, "tail_follow/tail_follow.py").parent)] PYTHONPATH = os.pathsep.join(IMPORTED) sys.path[:0] = IMPORTED a2a_server = importlib.import_module("a2a_server") diff --git a/tst/unit/agents/codex/agent.py b/tst/unit/agents/codex/agent.py index ed141e9fd..58878485e 100644 --- a/tst/unit/agents/codex/agent.py +++ b/tst/unit/agents/codex/agent.py @@ -1,5 +1,6 @@ """The Codex agent's modules, imported as its image runs them: by their own names, from its folder and from the folders -its build context takes as agent_clock/, clock/ and model_relay/, whose modules the image copies beside the bridge.""" +its build context takes as agent_clock/, clock/, model_relay/ and tail_follow/, whose modules the image copies beside the +bridge.""" import importlib import importlib.util @@ -12,11 +13,13 @@ AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "codex" IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "agent_clock/agent_egress.py").parent), - str(sent(AGENT_DIR, "clock/clockpage.py").parent), str(sent(AGENT_DIR, "model_relay/model_relay.py").parent)] + str(sent(AGENT_DIR, "clock/clockpage.py").parent), str(sent(AGENT_DIR, "model_relay/model_relay.py").parent), + str(sent(AGENT_DIR, "tail_follow/tail_follow.py").parent)] PYTHONPATH = os.pathsep.join(IMPORTED) sys.path[:0] = IMPORTED codex_atif = importlib.import_module("codex_atif") codex_bridge = importlib.import_module("codex_bridge") +codex_rollout = importlib.import_module("codex_rollout") codex_config = importlib.import_module("codex_config") codex_date = importlib.import_module("codex_date") codex_kit = importlib.import_module("codex_kit") diff --git a/tst/unit/agents/codex/test_codex_atif.py b/tst/unit/agents/codex/test_codex_atif.py index a0613f1b5..c212d1876 100644 --- a/tst/unit/agents/codex/test_codex_atif.py +++ b/tst/unit/agents/codex/test_codex_atif.py @@ -12,7 +12,7 @@ import pytest from agentenv_protocol.atif import Fed, RecordedTask, TurnContext, check_adapter, profile_of -from tst.unit.agents.codex.agent import AGENT_DIR, codex_atif, codex_bridge +from tst.unit.agents.codex.agent import AGENT_DIR, codex_atif, codex_rollout CodexAtif = codex_atif.CodexAtif MAIN, SUB = "01a2-main", "01a2-sub" @@ -40,7 +40,7 @@ def raw(self, kind, payload, thread=MAIN, parent=None): Feed.clock += 1 record = {"timestamp": f"2026-11-25T16:15:{Feed.clock // 1000:02d}.{Feed.clock % 1000:03d}Z", "type": kind, "payload": payload} - fed = codex_bridge.rollout_aux(record, thread, parent) + fed = codex_rollout.rollout_aux(record, thread, parent) if fed is not None: self.records.append(Fed(fed, aux="rollout")) return self diff --git a/tst/unit/agents/codex/test_image_contract.py b/tst/unit/agents/codex/test_image_contract.py index 175a41601..496ea061a 100644 --- a/tst/unit/agents/codex/test_image_contract.py +++ b/tst/unit/agents/codex/test_image_contract.py @@ -45,7 +45,7 @@ def test_every_file_the_image_copies_is_in_the_folder(): assert copied and all(_in_context(name) for name in copied), copied # install.sh and run.sh are install/v1's; a build context pruned to what the Dockerfile reads keeps them so. assert {"a2a_server.py", "codex_atif.py", "codex_bridge.py", "codex_config.py", "codex_date.py", "codex_kit.py", - "entrypoint.sh", "install.sh", "run.sh", "package.json", "package-lock.json"} <= set(copied) + "codex_rollout.py", "entrypoint.sh", "install.sh", "run.sh", "package.json", "package-lock.json"} <= set(copied) def _imported(path) -> set[str]: diff --git a/tst/unit/agents/codex/test_rollout_tail.py b/tst/unit/agents/codex/test_rollout_tail.py index ed18e182d..9a78b745e 100644 --- a/tst/unit/agents/codex/test_rollout_tail.py +++ b/tst/unit/agents/codex/test_rollout_tail.py @@ -1,14 +1,13 @@ -"""The bridge's rollout tail, which feeds Codex's atif/1 adapter: each turn's new rollout records, its thread's and -its sub-agents', as the CLI appends them, and ``run_codex`` feeding them while the CLI runs and the rest once it has -exited.""" +"""The rollout tail that feeds Codex's atif/1 adapter (``codex_rollout``): each turn's new rollout records, its +thread's and its sub-agents', as the CLI appends them, and ``run_codex`` feeding them while the CLI runs and the rest +once it has exited.""" import asyncio import json import os -import threading import pytest -from tst.unit.agents.codex.agent import codex_bridge +from tst.unit.agents.codex.agent import codex_bridge, codex_rollout MAIN = "01a21385-2388-7b60-adb8-331c882b4e9a" SUB = "01a21385-2cea-7b83-9a89-8cd36b7ffe19" @@ -23,6 +22,11 @@ def sessions(monkeypatch, tmp_path): return folder +def tail_for(thread): + """The tail a turn on ``thread`` (None for a new one) follows, over the rollouts the fixture puts in place.""" + return codex_rollout.RolloutTail(thread, codex_bridge.SESSIONS_DIR, codex_bridge.find_rollout_path) + + def meta(thread, parent=None): return {"timestamp": "2026-11-25T16:23:42.479Z", "type": "session_meta", "payload": {"id": thread, "parent_thread_id": parent, "agent_nickname": "Mendel" if parent else None, @@ -53,14 +57,14 @@ def rollout(folder, thread): def test_a_new_threads_rollout_is_read_from_its_start_and_a_resumed_ones_from_where_it_ended(sessions): path = rollout(sessions, MAIN) write(path, meta(MAIN), item("one")) - tail = codex_bridge.RolloutTail(None) + tail = tail_for(None) tail.bind(MAIN) first = tail.read() assert [record["type"] for record in first] == ["session_meta", "response_item"] assert all(record["thread"] == MAIN and "parent" not in record for record in first) - resumed = codex_bridge.RolloutTail(MAIN) + resumed = tail_for(MAIN) assert resumed.read() == [] write(path, item("two")) assert texts(resumed.read()) == ["two"] @@ -69,7 +73,7 @@ def test_a_new_threads_rollout_is_read_from_its_start_and_a_resumed_ones_from_wh def test_a_line_the_cli_is_still_writing_waits_for_its_end(sessions): path = rollout(sessions, MAIN) write(path, meta(MAIN), partial=json.dumps(item("half"))[:30]) - tail = codex_bridge.RolloutTail(None) + tail = tail_for(None) tail.bind(MAIN) assert texts(tail.read()) == [] @@ -79,7 +83,7 @@ def test_a_line_the_cli_is_still_writing_waits_for_its_end(sessions): def test_sub_agents_rollouts_are_found_at_any_depth_and_marked_with_their_parent(sessions): write(rollout(sessions, MAIN), meta(MAIN)) - tail = codex_bridge.RolloutTail(None) + tail = tail_for(None) tail.bind(MAIN) tail.read() write(rollout(sessions, SUB), meta(SUB, MAIN), item("sub")) @@ -96,7 +100,7 @@ def test_sub_agents_rollouts_are_found_at_any_depth_and_marked_with_their_parent def test_a_sub_agents_rollout_seen_before_its_parents_is_followed_once_its_parent_is(sessions): write(rollout(sessions, MAIN), meta(MAIN)) - tail = codex_bridge.RolloutTail(None) + tail = tail_for(None) tail.bind(MAIN) write(rollout(sessions, DEEPER), meta(DEEPER, SUB), item("deeper")) assert texts(tail.read(final=True)) == [] @@ -118,7 +122,7 @@ def call(call_id, turn): reply = {**item("one"), "payload": {**item("one")["payload"], "internal_chat_message_metadata_passthrough": {"turn_id": "turn-1"}}} write(rollout(sessions, MAIN), meta(MAIN), started("turn-1"), call("call_1", "turn-1"), reply, started("turn-2")) - tail = codex_bridge.RolloutTail(None) + tail = tail_for(None) tail.bind(MAIN) tail.read() forked = {**meta(SUB, MAIN), "payload": {**meta(SUB, MAIN)["payload"], "forked_from_id": MAIN}} @@ -134,7 +138,7 @@ def call(call_id, turn): def test_a_replaced_rollout_is_read_on_from_its_line_count(sessions): path = rollout(sessions, MAIN) write(path, meta(MAIN), item("one")) - tail = codex_bridge.RolloutTail(MAIN) + tail = tail_for(MAIN) replacement = path.with_suffix(".tmp") write(replacement, meta(MAIN), item("one"), item("two")) os.replace(replacement, path) @@ -150,12 +154,12 @@ def test_a_replaced_rollout_is_read_on_from_its_line_count(sessions): {"type": "event_msg", "payload": {"type": "item_completed"}}, ]) def test_records_the_adapter_doesnt_read_are_left_out(record): - assert codex_bridge.rollout_aux({"timestamp": "2026-11-25T16:23:43.000Z", **record}, MAIN) is None + assert codex_rollout.rollout_aux({"timestamp": "2026-11-25T16:23:43.000Z", **record}, MAIN) is None def test_a_usage_record_keeps_its_response_and_its_counts_alone(): usage = {"input_tokens": 13350, "cached_input_tokens": 13184, "output_tokens": 90} - fed = codex_bridge.rollout_aux({"timestamp": "2026-11-25T16:23:44.676Z", "type": "token_usage_record", + fed = codex_rollout.rollout_aux({"timestamp": "2026-11-25T16:23:44.676Z", "type": "token_usage_record", "payload": {"thread_id": MAIN, "response_id": "resp_1", "usage": usage, "turn_token_usage": usage, "thread_token_usage": usage}}, MAIN) @@ -199,7 +203,7 @@ async def written(line): if event["type"] == "thread.started": write(path, meta(MAIN), item("one")) elif event["type"] == "turn.completed": - await asyncio.sleep(codex_bridge.ROLLOUT_POLL_S * 4) + await asyncio.sleep(codex_rollout.ROLLOUT_POLL_S * 4) seen_before_exit.append(len(fed)) write(path, item("two")) @@ -219,37 +223,3 @@ async def exec_(*cmd, **kwargs): assert {name for name, _ in fed} == {"rollout"} assert texts([record for _, record in fed]) == ["one", "two"] assert seen_before_exit == [2] - - -class _SlowTail: - """A tail whose second read is still running when the follower is told to stop.""" - - def __init__(self): - self.reads, self.release, self.reading = 0, threading.Event(), threading.Event() - - def read(self, *, final=False): - if final: - return [{"type": "final"}] - self.reads += 1 - if self.reads == 2: - self.reading.set() - self.release.wait(5) - return [{"type": "in flight"}] - return [{"type": "first"}] if self.reads == 1 else [] - - -def test_a_read_in_flight_when_following_stops_is_fed_before_the_final_one(): - tail, fed = _SlowTail(), [] - - async def follow(): - stopped = asyncio.Event() - following = asyncio.create_task(codex_bridge.follow_rollout(tail, lambda name, r: fed.append(r), stopped)) - await asyncio.to_thread(tail.reading.wait, 5) - stopping = asyncio.create_task(codex_bridge.stop_following_rollout(following, stopped)) - await asyncio.sleep(0.05) - tail.release.set() - await stopping - - asyncio.run(follow()) - - assert [record["type"] for record in fed] == ["first", "in flight", "final"] diff --git a/tst/unit/agents/gemini/agent.py b/tst/unit/agents/gemini/agent.py index 95510464e..32c23b1b5 100644 --- a/tst/unit/agents/gemini/agent.py +++ b/tst/unit/agents/gemini/agent.py @@ -1,19 +1,24 @@ -"""The Gemini agent's modules, imported from its folder as its image runs them: by their own names, from the folder on -the path.""" +"""The Gemini agent's modules, imported as its image runs them: by their own names, from its folder and from the folder +its build context takes as tail_follow/, whose module the image copies beside the bridge.""" import importlib import importlib.util +import os import sys from pathlib import Path import agent_env +from tst.util.build_context import sent AGENT_DIR = Path(agent_env.__file__).parent / "agents" / "agents" / "gemini" -sys.path.insert(0, str(AGENT_DIR)) +IMPORTED = [str(AGENT_DIR), str(sent(AGENT_DIR, "tail_follow/tail_follow.py").parent)] +PYTHONPATH = os.pathsep.join(IMPORTED) +sys.path[:0] = IMPORTED gemini_config = importlib.import_module("gemini_config") gemini_kit = importlib.import_module("gemini_kit") gemini_changelog = importlib.import_module("gemini_changelog") gemini_bridge = importlib.import_module("gemini_bridge") +gemini_transcript = importlib.import_module("gemini_transcript") gemini_atif = importlib.import_module("gemini_atif") # By its path: another agent's a2a_server, imported by the same name, may be loaded already. _spec = importlib.util.spec_from_file_location("gemini_a2a_server", AGENT_DIR / "a2a_server.py") diff --git a/tst/unit/agents/gemini/test_card_contract.py b/tst/unit/agents/gemini/test_card_contract.py index 65057dab5..81b666805 100644 --- a/tst/unit/agents/gemini/test_card_contract.py +++ b/tst/unit/agents/gemini/test_card_contract.py @@ -8,7 +8,7 @@ import subprocess import sys -from tst.unit.agents.gemini.agent import AGENT_DIR, a2a_server +from tst.unit.agents.gemini.agent import AGENT_DIR, PYTHONPATH, a2a_server from tst.unit.agents.gemini.support import card _GEMINI_SKILL = { @@ -236,7 +236,7 @@ def test_install_mode_reads_the_card_by_importing_agent_card(): "from a2a_server import AGENT_CARD; " "print(json.dumps(AGENT_CARD.model_dump()))" ) - env = {k: v for k, v in os.environ.items() if not k.startswith("LITELLM_")} + env = {**{k: v for k, v in os.environ.items() if not k.startswith("LITELLM_")}, "PYTHONPATH": PYTHONPATH} out = subprocess.run([sys.executable, "-c", script], cwd=AGENT_DIR, env=env, capture_output=True, text=True, check=True) exported = json.loads(out.stdout) diff --git a/tst/unit/agents/gemini/test_gemini_atif.py b/tst/unit/agents/gemini/test_gemini_atif.py index 3101ccf68..2ecf26ccd 100644 --- a/tst/unit/agents/gemini/test_gemini_atif.py +++ b/tst/unit/agents/gemini/test_gemini_atif.py @@ -13,7 +13,7 @@ import pytest from agentenv_protocol.atif import Fed, RecordedTask, TurnContext, check_adapter, profile_of -from tst.unit.agents.gemini.agent import AGENT_DIR, gemini_atif, gemini_bridge +from tst.unit.agents.gemini.agent import AGENT_DIR, gemini_atif, gemini_transcript GeminiAtif = gemini_atif.GeminiAtif MODEL = "gemini-2.5-flash" @@ -63,7 +63,7 @@ def message(self, message_id, content="", *, tokens=None, thoughts=(), calls=(), "tokens": tokens or {"input": 7338, "output": 77, "cached": 0, "thoughts": 105, "tool": 0, "total": 7520}, "model": model, "toolCalls": list(calls)} - self.records.append(Fed(gemini_bridge.session_aux(message), aux="session")) + self.records.append(Fed(gemini_transcript.session_aux(message), aux="session")) return self def result(self, error=None): diff --git a/tst/unit/agents/gemini/test_image_contract.py b/tst/unit/agents/gemini/test_image_contract.py index bcec9a418..83ba3adb8 100644 --- a/tst/unit/agents/gemini/test_image_contract.py +++ b/tst/unit/agents/gemini/test_image_contract.py @@ -1,17 +1,21 @@ -"""The agent's folder is its build context: the Dockerfile copies only its own files, pins Node by its checksum and the -CLI by package-lock.json, keeps TLS checks on, and installs the protocol at or above its floor, which a release doesn't -pin; install.sh brings the same Node and the same CLI.""" +"""The agent's folder is its build context: the Dockerfile copies only its own files and those its +``shared_sources.toml`` takes from agent-env's sources, pins Node by its checksum and the CLI by package-lock.json, keeps +TLS checks on, and installs the protocol at or above its floor, which a release doesn't pin; install.sh brings the same +Node and the same CLI.""" from __future__ import annotations import ast import json import re +import tomllib from tst.unit.agents.gemini.agent import AGENT_DIR DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() INSTALL_SH = (AGENT_DIR / "install.sh").read_text() +SOURCES = AGENT_DIR.parents[2] +SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text()) # Harbor bundles pin the same versions (agentenvhub-sdk's _DOC_TOOL_PACKAGES), so a task's documents read alike in both. @@ -23,13 +27,21 @@ def _copied() -> list[str]: for name in line.split()] +def _source(name: str): + """Where the build context's ``name`` comes from: the folder, or a folder shared_sources.toml takes from agent-env's + own sources at that name.""" + first, _, rest = name.partition("/") + return SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name + + def test_every_file_the_image_copies_is_in_the_folder(): copied = _copied() - assert copied and all((AGENT_DIR / name).is_file() for name in copied), copied + assert copied and all(_source(name).is_file() for name in copied), copied # install.sh and run.sh are install/v1's; a build context pruned to what the Dockerfile reads keeps them so. - assert {"a2a_server.py", "gemini_bridge.py", "gemini_changelog.py", "gemini_config.py", "gemini_kit.py", - "entrypoint.sh", "install.sh", "run.sh", "package.json", "package-lock.json"} <= set(copied) + assert {"a2a_server.py", "gemini_atif.py", "gemini_bridge.py", "gemini_changelog.py", "gemini_config.py", + "gemini_kit.py", "gemini_transcript.py", "entrypoint.sh", "install.sh", "run.sh", "package.json", + "package-lock.json"} <= set(copied) def _imported(path) -> set[str]: @@ -43,10 +55,19 @@ def _imported(path) -> set[str]: def test_the_image_and_an_install_carry_every_module_the_server_imports(): - modules = {path.stem: path for path in AGENT_DIR.glob("*.py")} - needed = {"a2a_server.py"} | {f"{name}.py" for path in modules.values() for name in _imported(path) & set(modules)} + """The folder's own modules and those the build context takes from agent-env's sources, the follower among them, + each by its name in the context.""" + shared = {path.stem: f"{name}/{path.name}" for name, source in SHARED.items() + for path in (SOURCES / source).glob("*.py")} + modules = {**shared, **{path.stem: path.name for path in AGENT_DIR.glob("*.py")}} + needed, pending = set(), ["a2a_server"] + while pending: + if (name := modules[pending.pop()]) not in needed: + needed.add(name) + pending += _imported(_source(name)) & set(modules) installed = set(re.search(r'^AGENT_FILES="([^"]+)"$', INSTALL_SH, re.MULTILINE).group(1).split()) + assert {"tail_follow/tail_follow.py", "gemini_transcript.py"} <= needed assert needed <= set(_copied()) and needed <= installed, (needed, installed) diff --git a/tst/unit/agents/gemini/test_session_tail.py b/tst/unit/agents/gemini/test_session_tail.py index b8f731084..7879ca034 100644 --- a/tst/unit/agents/gemini/test_session_tail.py +++ b/tst/unit/agents/gemini/test_session_tail.py @@ -1,20 +1,26 @@ -"""The bridge's session tail, which feeds Gemini's atif/1 adapter: each turn's new model messages from the transcript +"""The session tail that feeds Gemini's atif/1 adapter (``gemini_transcript``): each turn's new model messages from the transcript the CLI rewrites whole, each once a later one follows it and the last at the turn's end, and ``run_gemini`` feeding them while the CLI runs and the rest once it has exited.""" import asyncio +import functools import json import os -import threading import pytest -from tst.unit.agents.gemini.agent import gemini_bridge +from tst.unit.agents.gemini.agent import gemini_bridge, gemini_transcript from tst.unit.agents.gemini.fake_cli import FakeCLI from tst.unit.agents.gemini.support import chats SESSION = "97b4a411-6d52-4c55-9e61-1b2c3d4e5f60" +def tail_for(session): + """The tail a turn on ``session`` (None for a new one) follows, over the transcripts the home fixture puts in place.""" + return gemini_transcript.SessionTail(session, functools.partial(gemini_bridge.find_session_file, + cwd=os.environ["GEMINI_CWD"])) + + def user(message_id): return {"id": message_id, "timestamp": "2026-11-25T16:24:25.449Z", "type": "user", "content": [{"text": "go"}]} @@ -40,7 +46,7 @@ def ids(records): def test_a_message_is_fed_once_a_later_one_follows_it_and_the_last_at_the_turns_end(home): - tail = gemini_bridge.SessionTail(None, os.environ["GEMINI_CWD"]) + tail = tail_for(None) tail.bind(SESSION) write(home, user("u-1"), model("g-1")) assert tail.read() == [] @@ -53,14 +59,14 @@ def test_a_message_is_fed_once_a_later_one_follows_it_and_the_last_at_the_turns_ def test_a_resumed_sessions_earlier_messages_are_not_fed_again(home): write(home, user("u-1"), model("g-1"), model("g-2")) - tail = gemini_bridge.SessionTail(SESSION, os.environ["GEMINI_CWD"]) + tail = tail_for(SESSION) write(home, user("u-1"), model("g-1"), model("g-2"), user("u-2"), model("g-3")) assert ids(tail.read(final=True)) == ["g-3"] def test_a_transcript_the_cli_is_still_writing_is_read_at_the_next_poll(home): - tail = gemini_bridge.SessionTail(None, os.environ["GEMINI_CWD"]) + tail = tail_for(None) tail.bind(SESSION) whole = json.dumps({"sessionId": SESSION, "messages": [user("u-1"), model("g-1")]}) write(home, raw=whole[:len(whole) // 2]) @@ -71,7 +77,7 @@ def test_a_transcript_the_cli_is_still_writing_is_read_at_the_next_poll(home): def test_a_model_message_keeps_what_the_adapter_reads_and_drops_how_the_cli_displays_it(): - record = gemini_bridge.session_aux(model("g-1", "done")) + record = gemini_transcript.session_aux(model("g-1", "done")) assert record == {"type": "gemini", "id": "g-1", "timestamp": "2026-11-25T16:24:27.358Z", "content": "done", "tokens": {"input": 7338, "output": 77}, "model": "gemini-2.5-flash", @@ -79,7 +85,7 @@ def test_a_model_message_keeps_what_the_adapter_reads_and_drops_how_the_cli_disp "status": "success", "timestamp": "2026-11-25T16:24:27.367Z", "result": [{"functionResponse": {"id": "write_1", "response": {"output": "ok"}}}]}]} - assert gemini_bridge.session_aux(user("u-1")) is None + assert gemini_transcript.session_aux(user("u-1")) is None @pytest.fixture @@ -121,41 +127,6 @@ async def turn(): assert ids(record for _, record in fed) == ["g-1", "g-2"] -class _SlowTail: - """A tail whose second read is still running when the follower is told to stop.""" - - def __init__(self): - self.reads, self.release, self.reading = 0, threading.Event(), threading.Event() - - def read(self, *, final=False): - if final: - return [{"id": "final"}] - self.reads += 1 - if self.reads == 2: - self.reading.set() - self.release.wait(5) - return [{"id": "in flight"}] - return [{"id": "first"}] if self.reads == 1 else [] - - -def test_a_read_in_flight_when_following_stops_is_fed_before_the_final_one(monkeypatch): - monkeypatch.setattr(gemini_bridge, "SESSION_POLL_S", 0.01) - tail, fed = _SlowTail(), [] - - async def follow(): - stopped = asyncio.Event() - following = asyncio.create_task(gemini_bridge.follow_session(tail, lambda name, r: fed.append(r), stopped)) - await asyncio.to_thread(tail.reading.wait, 5) - stopping = asyncio.create_task(gemini_bridge.stop_following_session(following, stopped)) - await asyncio.sleep(0.05) - tail.release.set() - await stopping - - asyncio.run(follow()) - - assert ids(fed) == ["first", "in flight", "final"] - - def write_jsonl(home, *messages): path = chats(home) / f"session-2026-11-25T16-24-{SESSION[:8]}.jsonl" path.write_text("".join(json.dumps(line) + "\n" for line in ({"sessionId": SESSION, "projectHash": "p"}, @@ -165,7 +136,7 @@ def write_jsonl(home, *messages): def test_a_restored_jsonl_sessions_new_messages_are_fed_as_their_latest_copy_and_its_earlier_ones_not_again(home): path = write_jsonl(home, user("u-1"), model("g-1")) - tail = gemini_bridge.SessionTail(SESSION, os.environ["GEMINI_CWD"]) + tail = tail_for(SESSION) first = {**model("g-2"), "toolCalls": []} write_jsonl(home, user("u-1"), model("g-1"), user("u-2"), first) assert tail.read() == [] @@ -177,7 +148,7 @@ def test_a_restored_jsonl_sessions_new_messages_are_fed_as_their_latest_copy_and def test_a_settled_message_written_again_in_a_jsonl_transcript_is_fed_as_its_latest_copy(home): - tail = gemini_bridge.SessionTail(None, os.environ["GEMINI_CWD"]) + tail = tail_for(None) tail.bind(SESSION) write_jsonl(home, user("u-1"), {**model("g-1"), "toolCalls": []}, model("g-1"), model("g-2", "5050")) @@ -186,7 +157,7 @@ def test_a_settled_message_written_again_in_a_jsonl_transcript_is_fed_as_its_lat def test_a_transcript_moved_from_json_to_jsonl_is_found_again_and_nothing_is_fed_twice(home): - tail = gemini_bridge.SessionTail(None, os.environ["GEMINI_CWD"]) + tail = tail_for(None) tail.bind(SESSION) legacy = write(home, user("u-1"), model("g-1"), model("g-2")) assert ids(tail.read()) == ["g-1"] diff --git a/tst/unit/agents/test_tail_follow.py b/tst/unit/agents/test_tail_follow.py new file mode 100644 index 000000000..1eb3f25c3 --- /dev/null +++ b/tst/unit/agents/test_tail_follow.py @@ -0,0 +1,86 @@ +"""The follower every agent's bridge feeds its atif/1 adapter with (``utils/tail_follow``), which each image copies +beside its bridge: a tail's records fed while the CLI runs and once more after it exits, none of them lost however the +run ends.""" + +from __future__ import annotations + +import asyncio +import importlib.util +import logging +import sys +import threading +from pathlib import Path + +import pytest + +import agent_env + +_PATH = Path(agent_env.__file__).parent / "utils" / "tail_follow" / "tail_follow.py" +_spec = importlib.util.spec_from_file_location("shared_tail_follow", _PATH) +tail_follow = importlib.util.module_from_spec(_spec) +sys.modules[_spec.name] = tail_follow +_spec.loader.exec_module(tail_follow) + + +class _Tail: + """A tail that gives one record a read, ``final`` on the last, the second read held until ``release`` is set.""" + + def __init__(self, hold_second=False): + self.reads, self.release, self.reading = 0, threading.Event(), threading.Event() + self.hold_second = hold_second + + def read(self, final): + if final: + return [("aux", "final")] + self.reads += 1 + if self.hold_second and self.reads == 2: + self.reading.set() + self.release.wait(5) + return [("aux", "in flight")] + return [("aux", f"read {self.reads}")] if self.reads == 1 else [] + + +def test_a_read_in_flight_when_the_run_ends_is_fed_before_the_final_one(): + tail, fed = _Tail(hold_second=True), [] + + async def run(): + async def release_once_stopping(): + await asyncio.to_thread(tail.reading.wait, 5) + await asyncio.sleep(0.05) + tail.release.set() + + async with tail_follow.following(tail.read, lambda name, record: fed.append(record), 0.001, "test"): + await asyncio.to_thread(tail.reading.wait, 5) + asyncio.get_running_loop().create_task(release_once_stopping()) + + asyncio.run(run()) + + assert fed == ["read 1", "in flight", "final"] + + +def test_a_run_that_raises_still_has_what_its_files_gained_fed(): + tail, fed = _Tail(), [] + + async def run(): + async with tail_follow.following(tail.read, lambda name, record: fed.append((name, record)), 0.001, "test"): + raise RuntimeError("the CLI failed") + + with pytest.raises(RuntimeError, match="the CLI failed"): + asyncio.run(run()) + + assert fed[-1] == ("aux", "final") + + +def test_a_follower_that_fails_is_logged_and_the_run_goes_on(caplog): + def read(final): + raise OSError("the file went away") + + async def run(): + async with tail_follow.following(read, lambda name, record: None, 0.001, "transcript"): + await asyncio.sleep(0.01) + return "answered" + + with caplog.at_level(logging.WARNING): + assert asyncio.run(run()) == "answered" + + assert "following the transcript failed" in caplog.text From 20d3eedc143a7bfa4780ebc2bfe58381b3bdc2ce Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 27 Nov 2026 15:00:13 -0800 Subject: [PATCH 2/4] refactor(agents): the atif/1 recorders and recorded tests share their helpers, and Codex's sub-agent says where its records go tst/manual/atif_recording.py holds what both recorders did alike (the image built as a release builds it, a turn sent and read back with its live pages, the key kept out), and tst/util/atif_recorded.py the loading, replaying and checks the three agents' recorded tests repeated. Codex's adapter keeps a sub-agent's place as one state, held, embedded or an earlier task's, rather than two flags. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/AGENTS.md | 7 +- .../agents/agents/codex/codex_atif.py | 29 +++-- tst/manual/atif_recording.py | 85 ++++++++++++++ tst/manual/claude_code_atif/record.py | 82 +------------- tst/manual/codex_gemini_atif/record.py | 80 +------------ .../test_claude_code_atif_recorded.py | 107 +++++++----------- .../agents/codex/test_codex_atif_recorded.py | 89 +++++---------- .../gemini/test_gemini_atif_recorded.py | 81 ++++--------- tst/util/atif_recorded.py | 100 ++++++++++++++++ 9 files changed, 311 insertions(+), 349 deletions(-) create mode 100644 tst/manual/atif_recording.py create mode 100644 tst/util/atif_recorded.py diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 7d7fd1c93..d6fccc711 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -163,8 +163,11 @@ Reference: `enable(TRAJECTORY_V1, live=True, ...)`, `ClaudeCodeAgent.run` passin `event_callback=request.trajectory.append`, and `get_context_trajectory` / `upload_context_trajectory`. Its adapter, `claude_code_atif.py`, builds steps from stream-json with each message's time, usage and tools from the CLI's session transcript, which `claude_bridge.SessionTail` feeds as aux records only while `request.trajectory.builds_atif`. Codex's, -`codex_atif.py`, builds them from the CLI's rollout alone, which `codex_bridge.RolloutTail` feeds; Gemini's, -`gemini_atif.py`, from its session transcript (`gemini_bridge.SessionTail`) and the proxy's call records. A runtime +`codex_atif.py`, builds them from the CLI's rollout alone, which `codex_rollout.RolloutTail` feeds; Gemini's, +`gemini_atif.py`, from its session transcript (`gemini_transcript.SessionTail`) and the proxy's call records. Each +bridge follows its tail with `tail_follow.following` (`utils/tail_follow`, which its image takes in `shared_sources.toml` +and copies beside the bridge): read while the CLI runs and once more after it exits, a read in flight when the run ends +fed rather than dropped. A runtime that only has a record at the end returns it with `native_trajectory(...)`: `agents/pi/pi_agent.py` `_result`. ### `skill-config/v1`, `/ext/skill-config` diff --git a/src/agent_env/agents/agents/codex/codex_atif.py b/src/agent_env/agents/agents/codex/codex_atif.py index 05c3c6db5..0d063818b 100644 --- a/src/agent_env/agents/agents/codex/codex_atif.py +++ b/src/agent_env/agents/agents/codex/codex_atif.py @@ -18,6 +18,7 @@ import json import re from dataclasses import dataclass, field +from enum import Enum from typing import Any from agentenv_protocol.atif import Adapter, Native, atif_adapter, aux, finish, is_token_count, native @@ -51,16 +52,25 @@ def _string(value: Any) -> str | None: return value if isinstance(value, str) and value else None +class _Placed(Enum): + """Where a sub-agent's records go: held until it's declared under its spawn in this task, then into its embedded + trajectory; one an earlier task saw has its records left to the native log, and no spawn now takes it, even one + that reuses its path.""" + + HELD = "held" + EMBEDDED = "embedded" + EARLIER = "earlier" + + @dataclass class _Sub: - """A sub-agent's thread: its path and name once its first record gives them, its records while it isn't declared - in this task, and whether an earlier task saw it, so a spawn now that reuses its path names another thread.""" + """A sub-agent's thread: its path and name once its first record gives them, where its records go (``placed``), + and its records while they're held.""" path: str | None = None name: str | None = None held: list[dict[str, Any]] = field(default_factory=list) - declared: bool = False - earlier: bool = False + placed: _Placed = _Placed.HELD @atif_adapter(native_format=NATIVE_FORMAT, version="0.1.0", input_includes_cache=True, tested_with=TESTED_WITH) @@ -93,7 +103,7 @@ def rollout(self, record: dict[str, Any], turn: Any) -> None: if record.get("type") == "session_meta": self._meta(thread, sub, record["payload"], turn) return - if not sub.declared: + if sub.placed is not _Placed.EMBEDDED: sub.held.append(record) return self._apply(record, thread, turn) @@ -106,13 +116,13 @@ def end(self, turn: Any) -> None: for record in sub.held: turn.unmatched(record) sub.held.clear() - sub.declared, sub.earlier = False, True + sub.placed = _Placed.EARLIER self._new_task() def _meta(self, thread: str, sub: _Sub, payload: dict[str, Any], turn: Any) -> None: sub.path = _string(payload.get("agent_path")) sub.name = _string(payload.get("agent_nickname")) or sub.path - if not sub.earlier and sub.path in self._held_results: + if sub.placed is _Placed.HELD and sub.path in self._held_results: self._declare(thread, *self._held_results.pop(sub.path), turn) def _apply(self, record: dict[str, Any], thread: str, turn: Any) -> None: @@ -177,8 +187,7 @@ def _output(self, payload: dict[str, Any], record: dict[str, Any], turn: Any) -> if path is None: self._result(record, turn) return - thread = next((t for t, sub in self._subs.items() if sub.path == path and not sub.declared and not sub.earlier), - None) + thread = next((t for t, sub in self._subs.items() if sub.path == path and sub.placed is _Placed.HELD), None) if thread is None: self._held_results[path] = (call_id, record) else: @@ -217,7 +226,7 @@ def _declare(self, thread: str, call_id: str, result: dict[str, Any], turn: Any) the sub-agent's held records.""" sub = self._subs[thread] turn.subagent(thread, spawned_by=call_id, name=sub.name) - sub.declared = True + sub.placed = _Placed.EMBEDDED self._result(result, turn) held, sub.held = sub.held, [] for record in held: diff --git a/tst/manual/atif_recording.py b/tst/manual/atif_recording.py new file mode 100644 index 000000000..35e2c8344 --- /dev/null +++ b/tst/manual/atif_recording.py @@ -0,0 +1,85 @@ +"""What the atif/1 recorders share (``claude_code_atif/record.py``, ``codex_gemini_atif/record.py``): an agent's image +built from this checkout as a release builds it, its A2A turns sent and read back with their live atif/1 pages, and the +model key kept out of everything they write.""" +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path + +REPO = Path(__file__).resolve().parents[2] +SECRET = os.environ.get("LITELLM_API_KEY", "") +TERMINAL = {"completed", "failed", "canceled", "rejected", "input-required", "auth-required"} + + +def mask(text: str) -> str: + return text.replace(SECRET, "***") if SECRET else text + + +def run(command: list[str], **kw) -> subprocess.CompletedProcess: + done = subprocess.run(command, capture_output=True, text=True, **kw) + done.stdout, done.stderr = mask(done.stdout), mask(done.stderr) + return done + + +def http(method: str, url: str, body=None, timeout: float = 60): + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.status, json.loads(response.read() or b"null") + except urllib.error.HTTPError as exc: + raw = exc.read() + try: + return exc.code, json.loads(raw or b"null") + except ValueError: + return exc.code, mask(raw.decode(errors="replace"))[:300] + except (urllib.error.URLError, OSError) as exc: + return 0, str(exc) + + +def save(path: Path, value) -> None: + path.write_text(mask(json.dumps(value, indent=1, ensure_ascii=False))) + + +def build(image_name: str) -> str: + """The agent's image, built from this checkout for this machine's architecture.""" + planned = run([sys.executable, ".github/scripts/infra_images.py", "plan", "--only", "agents"], cwd=REPO) + entry = next(e for e in json.loads(planned.stdout) if e["name"] == image_name) + arch = "arm64" if platform.machine() in ("arm64", "aarch64") else "amd64" + env = {**os.environ, "GITHUB_REPOSITORY": "scaleapi/agentenv-framework", "GITHUB_SHA": "recording"} + built = run([sys.executable, ".github/scripts/infra_build.py", "build", json.dumps(entry), arch], cwd=REPO, env=env) + if built.returncode != 0: + raise SystemExit(f"the image didn't build:\n{built.stdout[-3000:]}\n{built.stderr[-3000:]}") + return f"{entry['repository']}:{entry['tag']}-{arch}" + + +def start(command: list[str]) -> None: + started = run(command) + if started.returncode != 0: + raise RuntimeError(started.stderr[-500:]) + + +def turn(base: str, context_id: str, prompt: str) -> tuple[str, dict, list]: + message = {"messageId": uuid.uuid4().hex, "role": "user", "contextId": context_id, + "parts": [{"kind": "text", "text": prompt}]} + status, sent = http("POST", f"{base}/a2a", {"jsonrpc": "2.0", "id": "1", "method": "message/send", + "params": {"message": message, "configuration": {"blocking": False}}}) + if status != 200 or "error" in (sent or {}): + raise RuntimeError(f"message/send {status} {sent}") + task_id, pages, deadline = sent["result"]["id"], [], time.time() + 900 + while time.time() < deadline: + status, page = http("POST", f"{base}/ext/trajectory", {"task_id": task_id, "format": "atif/1", "after": 0}) + if status == 200: + pages.append(page) + status, polled = http("POST", f"{base}/a2a", {"jsonrpc": "2.0", "id": "p", "method": "tasks/get", + "params": {"id": task_id}}) + if status == 200 and "result" in polled and polled["result"]["status"]["state"] in TERMINAL: + return task_id, polled["result"], pages + time.sleep(1.0) + raise RuntimeError("the turn didn't end in 15 minutes") diff --git a/tst/manual/claude_code_atif/record.py b/tst/manual/claude_code_atif/record.py index 6e5f70d0a..0c0fdb3aa 100644 --- a/tst/manual/claude_code_atif/record.py +++ b/tst/manual/claude_code_atif/record.py @@ -19,21 +19,18 @@ ``make_fixtures.py`` writes the fixtures, keeping each request shape's tools once under ``tools/``, and running the recorded test as a script writes the expected documents. Note the CLI version in ``claude_code_atif.TESTED_WITH``.""" import argparse -import json import os -import platform import shutil -import subprocess import sys import time -import urllib.error -import urllib.request -import uuid from pathlib import Path REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO)) + +from tst.manual.atif_recording import SECRET, build, http, mask, run, save, start, turn # noqa: E402 + HERE = Path(__file__).resolve().parent -SECRET = os.environ.get("LITELLM_API_KEY", "") NETWORK = "claude-atif-recording" BROWSER = "claude-atif-playwright" FAULTS = "claude-atif-faults" @@ -44,7 +41,6 @@ # Sonnet 5.5 and 4.5 return omitted thinking for it instead, so the scenario records a thinking model's turn. REDACTED_THINKING = ("ANTHROPIC_MAGIC_STRING_TRIGGER_REDACTED_THINKING_" "46C9A13E193C177646C7398A98432ECCCE4C1253D5E2D82641AC0E52CC2876CB") -TERMINAL = {"completed", "failed", "canceled", "rejected", "input-required", "auth-required"} def scenarios(thinking_model: str) -> dict[str, dict]: @@ -75,54 +71,6 @@ def scenarios(thinking_model: str) -> dict[str, dict]: } -def mask(text: str) -> str: - return text.replace(SECRET, "***") if SECRET else text - - -def run(command: list[str], **kw) -> subprocess.CompletedProcess: - done = subprocess.run(command, capture_output=True, text=True, **kw) - done.stdout, done.stderr = mask(done.stdout), mask(done.stderr) - return done - - -def http(method: str, url: str, body=None, timeout: float = 60): - data = json.dumps(body).encode() if body is not None else None - request = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) - try: - with urllib.request.urlopen(request, timeout=timeout) as response: - return response.status, json.loads(response.read() or b"null") - except urllib.error.HTTPError as exc: - raw = exc.read() - try: - return exc.code, json.loads(raw or b"null") - except ValueError: - return exc.code, mask(raw.decode(errors="replace"))[:300] - except (urllib.error.URLError, OSError) as exc: - return 0, str(exc) - - -def save(path: Path, value) -> None: - path.write_text(mask(json.dumps(value, indent=1, ensure_ascii=False))) - - -def build() -> str: - """The agent's image, built from this checkout for this machine's architecture.""" - planned = run([sys.executable, ".github/scripts/infra_images.py", "plan", "--only", "agents"], cwd=REPO) - entry = next(e for e in json.loads(planned.stdout) if e["name"] == "agentenv-claude-code") - arch = "arm64" if platform.machine() in ("arm64", "aarch64") else "amd64" - env = {**os.environ, "GITHUB_REPOSITORY": "scaleapi/agentenv-framework", "GITHUB_SHA": "recording"} - built = run([sys.executable, ".github/scripts/infra_build.py", "build", json.dumps(entry), arch], cwd=REPO, env=env) - if built.returncode != 0: - raise SystemExit(f"the image didn't build:\n{built.stdout[-3000:]}\n{built.stderr[-3000:]}") - return f"{entry['repository']}:{entry['tag']}-{arch}" - - -def start(command: list[str]) -> None: - started = run(command) - if started.returncode != 0: - raise RuntimeError(started.stderr[-500:]) - - def start_agent(image: str, name: str, scenario: dict) -> tuple[str, dict]: endpoint = (f"http://{FAULTS}:{FAULT_PORTS[scenario['faults']]}" if "faults" in scenario else os.environ["LITELLM_BASE_URL"]) @@ -140,26 +88,6 @@ def start_agent(image: str, name: str, scenario: dict) -> tuple[str, dict]: raise RuntimeError(f"no card: {run(['docker', 'logs', '--tail', '40', name]).stdout[-2000:]}") -def turn(base: str, context_id: str, prompt: str) -> tuple[str, dict, list]: - message = {"messageId": uuid.uuid4().hex, "role": "user", "contextId": context_id, - "parts": [{"kind": "text", "text": prompt}]} - status, sent = http("POST", f"{base}/a2a", {"jsonrpc": "2.0", "id": "1", "method": "message/send", - "params": {"message": message, "configuration": {"blocking": False}}}) - if status != 200 or "error" in (sent or {}): - raise RuntimeError(f"message/send {status} {sent}") - task_id, pages, deadline = sent["result"]["id"], [], time.time() + 900 - while time.time() < deadline: - status, page = http("POST", f"{base}/ext/trajectory", {"task_id": task_id, "format": "atif/1", "after": 0}) - if status == 200: - pages.append(page) - status, polled = http("POST", f"{base}/a2a", {"jsonrpc": "2.0", "id": "p", "method": "tasks/get", - "params": {"id": task_id}}) - if status == 200 and "result" in polled and polled["result"]["status"]["state"] in TERMINAL: - return task_id, polled["result"], pages - time.sleep(1.0) - raise RuntimeError("the turn didn't end in 15 minutes") - - def record(image: str, name: str, scenario: dict, model: str, out: Path) -> None: folder = out / name shutil.rmtree(folder, ignore_errors=True) @@ -208,7 +136,7 @@ def main() -> None: all_scenarios = scenarios(args.thinking_model) only = args.only.split(",") if args.only else list(all_scenarios) args.out.mkdir(parents=True, exist_ok=True) - image = build() + image = build("agentenv-claude-code") print("built", image, run(["docker", "run", "--rm", "--entrypoint", "claude", image, "--version"]).stdout.strip()) run(["docker", "network", "create", NETWORK]) try: diff --git a/tst/manual/codex_gemini_atif/record.py b/tst/manual/codex_gemini_atif/record.py index 9c57dd55c..8bd755534 100644 --- a/tst/manual/codex_gemini_atif/record.py +++ b/tst/manual/codex_gemini_atif/record.py @@ -19,28 +19,24 @@ writes the fixtures, and running the recorded test as a script writes the expected documents. Note the CLI version in the adapter's ``TESTED_WITH``.""" import argparse -import json import os -import platform import shutil -import subprocess import sys import time -import urllib.error -import urllib.request -import uuid from pathlib import Path REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO)) + +from tst.manual.atif_recording import SECRET, build, http, mask, run, save, start, turn # noqa: E402 + HERE = Path(__file__).resolve().parent -SECRET = os.environ.get("LITELLM_API_KEY", "") NETWORK = "atif-recording" BROWSER = "atif-recording-playwright" FAULTS = "atif-recording-faults" PLAYWRIGHT_MCP = ("mcr.microsoft.com/playwright/mcp:v0.0.86" "@sha256:2dfc17e08e8db54678ec965ce9ffb4100be0aa68135774d761bac9035ceb6668") FAULT_PORTS = {"refuse": 18601, "resume": 18602, "retry": 18603} -TERMINAL = {"completed", "failed", "canceled", "rejected", "input-required", "auth-required"} AGENTS = { "codex": {"image": "agentenv-codex", "model": "gpt-5.5", "files": "/home/agent/.codex/sessions", "version": ["codex", "--version"]}, @@ -72,54 +68,6 @@ } -def mask(text: str) -> str: - return text.replace(SECRET, "***") if SECRET else text - - -def run(command: list[str], **kw) -> subprocess.CompletedProcess: - done = subprocess.run(command, capture_output=True, text=True, **kw) - done.stdout, done.stderr = mask(done.stdout), mask(done.stderr) - return done - - -def http(method: str, url: str, body=None, timeout: float = 60): - data = json.dumps(body).encode() if body is not None else None - request = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) - try: - with urllib.request.urlopen(request, timeout=timeout) as response: - return response.status, json.loads(response.read() or b"null") - except urllib.error.HTTPError as exc: - raw = exc.read() - try: - return exc.code, json.loads(raw or b"null") - except ValueError: - return exc.code, mask(raw.decode(errors="replace"))[:300] - except (urllib.error.URLError, OSError) as exc: - return 0, str(exc) - - -def save(path: Path, value) -> None: - path.write_text(mask(json.dumps(value, indent=1, ensure_ascii=False))) - - -def build(image_name: str) -> str: - """The agent's image, built from this checkout for this machine's architecture.""" - planned = run([sys.executable, ".github/scripts/infra_images.py", "plan", "--only", "agents"], cwd=REPO) - entry = next(e for e in json.loads(planned.stdout) if e["name"] == image_name) - arch = "arm64" if platform.machine() in ("arm64", "aarch64") else "amd64" - env = {**os.environ, "GITHUB_REPOSITORY": "scaleapi/agentenv-framework", "GITHUB_SHA": "recording"} - built = run([sys.executable, ".github/scripts/infra_build.py", "build", json.dumps(entry), arch], cwd=REPO, env=env) - if built.returncode != 0: - raise SystemExit(f"the image didn't build:\n{built.stdout[-3000:]}\n{built.stderr[-3000:]}") - return f"{entry['repository']}:{entry['tag']}-{arch}" - - -def start(command: list[str]) -> None: - started = run(command) - if started.returncode != 0: - raise RuntimeError(started.stderr[-500:]) - - def fault(agent: str, scenario: dict) -> str | None: faults = scenario.get("faults") return faults.get(agent) if isinstance(faults, dict) else faults @@ -139,26 +87,6 @@ def start_agent(agent: str, image: str, name: str, scenario: dict) -> str: raise RuntimeError(f"no card: {run(['docker', 'logs', '--tail', '40', name]).stdout[-2000:]}") -def turn(base: str, context_id: str, prompt: str) -> tuple[str, dict, list]: - message = {"messageId": uuid.uuid4().hex, "role": "user", "contextId": context_id, - "parts": [{"kind": "text", "text": prompt}]} - status, sent = http("POST", f"{base}/a2a", {"jsonrpc": "2.0", "id": "1", "method": "message/send", - "params": {"message": message, "configuration": {"blocking": False}}}) - if status != 200 or "error" in (sent or {}): - raise RuntimeError(f"message/send {status} {sent}") - task_id, pages, deadline = sent["result"]["id"], [], time.time() + 900 - while time.time() < deadline: - status, page = http("POST", f"{base}/ext/trajectory", {"task_id": task_id, "format": "atif/1", "after": 0}) - if status == 200: - pages.append(page) - status, polled = http("POST", f"{base}/a2a", {"jsonrpc": "2.0", "id": "p", "method": "tasks/get", - "params": {"id": task_id}}) - if status == 200 and "result" in polled and polled["result"]["status"]["state"] in TERMINAL: - return task_id, polled["result"], pages - time.sleep(1.0) - raise RuntimeError("the turn didn't end in 15 minutes") - - def record(agent: str, image: str, name: str, scenario: dict, out: Path) -> None: spec = AGENTS[agent] folder = out / agent / name diff --git a/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py b/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py index 33f098f7e..8ff9d671c 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py @@ -12,7 +12,6 @@ from __future__ import annotations import json -import math import sys from pathlib import Path @@ -22,7 +21,7 @@ if __name__ == "__main__": sys.path.insert(0, str(REPO)) -from agentenv_protocol.atif import RecordedTask, check_adapter, check_media, task_document, tasks # noqa: E402 +from agentenv_protocol.atif import check_adapter, check_media, task_document, tasks # noqa: E402 from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( # noqa: E402 compact_atif_trajectory, @@ -36,87 +35,77 @@ turn_events, ) from tst.unit.agents.claude_code.agent import claude_code_atif # noqa: E402 +from tst.util.atif_recorded import ( # noqa: E402 + Recordings, + assert_every_model_call_has_its_time_and_usage, + assert_steps_sum_to_reported_usage, + trajectories, +) FIXTURES = REPO / "tst" / "data" / "claude_code_atif" -SCENARIOS = sorted(path.stem for path in FIXTURES.glob("*.json") if not path.name.endswith(".expected.json")) ClaudeCodeAtif = claude_code_atif.ClaudeCodeAtif -def _shared(marker: dict) -> list: - return json.loads((FIXTURES / marker["shared"]).read_text()) - - -def recorded(scenario: str) -> tuple[list[RecordedTask], list[dict | None]]: - data = json.loads((FIXTURES / f"{scenario}.json").read_text()) - tasks, usage = [], [] - for turn in data["turns"]: - aux = [{**entry, "record": {**entry["record"], "tools": _shared(entry["record"]["tools"])}} - if entry["name"] == "tools" else entry for entry in turn["aux"]] - tasks.append(RecordedTask.from_served(turn["turn"], turn["native"], aux)) - usage.append(turn["usage"]) - return tasks, usage - - -def compacted_turns(scenario: str) -> set[int]: - """The turns whose native stdout compacts the conversation (a ``compact_boundary``).""" - data = json.loads((FIXTURES / f"{scenario}.json").read_text()) - return {index for index, turn in enumerate(data["turns"]) - if any(item.get("subtype") == "compact_boundary" for item in turn["native"] if isinstance(item, dict))} - - -def _trajectories(document: dict) -> list[dict]: - return [document, *(document.get("subagent_trajectories") or [])] - - def _tool_files() -> dict[str, list]: return {f"tools/{path.name}": [claude_code_atif._function(tool) for tool in json.loads(path.read_text())] for path in sorted((FIXTURES / "tools").glob("*.json"))} -def expected(scenario: str) -> dict: +def _fed(entry: dict) -> dict: + """An aux entry as the agent fed it, a request shape's tools read back from the shared file it names.""" + if entry["name"] != "tools": + return entry + tools = json.loads((FIXTURES / entry["record"]["tools"]["shared"]).read_text()) + return {**entry, "record": {**entry["record"], "tools": tools}} + + +def _read_back(document: dict) -> dict: """The checked-in document, each agent block's tool definitions read back from the shared file it names.""" - document = json.loads((FIXTURES / f"{scenario}.expected.json").read_text()) files = _tool_files() - for trajectory in _trajectories(document): + for trajectory in trajectories(document): named = trajectory["agent"].get("tool_definitions") if isinstance(named, dict): trajectory["agent"]["tool_definitions"] = files[named["shared"]] return document -def replay(scenario: str): - tasks, _ = recorded(scenario) - return check_adapter(ClaudeCodeAtif, tasks) +def _named(document: dict) -> dict: + """A replay's document as it's checked in, each agent block's tool definitions named by their shared file.""" + files = _tool_files() + for trajectory in trajectories(document): + definitions = trajectory["agent"].get("tool_definitions") + named = next((name for name, converted in files.items() if converted == definitions), None) + if named is not None: + trajectory["agent"]["tool_definitions"] = {"shared": named} + return document + + +RECORDINGS = Recordings(FIXTURES, ClaudeCodeAtif, aux=_fed, expected=_read_back, saved=_named) +SCENARIOS = RECORDINGS.scenarios +recorded, replay = RECORDINGS.recorded, RECORDINGS.replay + + +def compacted_turns(scenario: str) -> set[int]: + """The turns whose native stdout compacts the conversation (a ``compact_boundary``).""" + return {index for index, turn in enumerate(RECORDINGS.data(scenario)["turns"]) + if any(item.get("subtype") == "compact_boundary" for item in turn["native"] if isinstance(item, dict))} @pytest.mark.parametrize("scenario", SCENARIOS) def test_a_recorded_run_replays_to_its_document_under_the_live_rule(scenario): - tasks, _ = recorded(scenario) - kit = check_adapter(ClaudeCodeAtif, tasks, expected=expected(scenario)) - kit.raise_for_errors() + RECORDINGS.check(scenario) @pytest.mark.parametrize("scenario", SCENARIOS) def test_a_recorded_runs_steps_sum_to_the_usage_each_turn_reported(scenario): """The copy's totals are the turns' reported usage, a turn that compacts the conversation's included: the step of the call that wrote its summary carries what the turn reported beyond its other steps.""" - _, usage = recorded(scenario) - final = replay(scenario).document["final_metrics"] - reported = [turn or {} for turn in usage] - for metric, field in (("total_prompt_tokens", "input_tokens"), ("total_completion_tokens", "output_tokens"), - ("total_cached_tokens", "cache_read_tokens")): - total = sum(turn.get(field) or 0 for turn in reported) - assert final.get(metric, 0) == total, (metric, final.get(metric), total) - if all(turn.get("cost_usd") is not None for turn in reported): - assert math.isclose(final["total_cost_usd"], sum(turn["cost_usd"] for turn in reported)) + assert_steps_sum_to_reported_usage(replay(scenario).document, recorded(scenario)[1]) @pytest.mark.parametrize("scenario", SCENARIOS) def test_every_model_call_of_a_recorded_run_is_a_step_with_its_transcripts_time_and_usage(scenario): - for trajectory in _trajectories(replay(scenario).document): - for step in trajectory["steps"]: - if step["source"] == "agent" and step.get("llm_call_count") != 0: - assert step.get("timestamp") and "completion_tokens" in step.get("metrics", {}), step["step_id"] + assert_every_model_call_has_its_time_and_usage(replay(scenario).document) def test_the_recordings_cover_what_the_adapter_maps(): @@ -141,7 +130,7 @@ def test_a_judge_reads_each_recorded_turn_with_its_calls_results_answer_and_scre kit = replay(scenario) for task in tasks(kit.document): view = task_document(kit.document, [task.task_id]) - steps = [step for trajectory in _trajectories(view) for step in trajectory["steps"] if step["source"] == "agent"] + steps = [step for trajectory in trajectories(view) for step in trajectory["steps"] if step["source"] == "agent"] results = [result for step in steps for result in (step.get("observation") or {}).get("results") or ()] images = [part for result in results for part in result.get("content") or () if isinstance(part, dict) and part.get("type") == "image"] @@ -216,17 +205,5 @@ def test_from_atif_reads_harbors_own_conversion_of_a_recorded_session(): assert ClaudeCodeAtif.from_atif(harbor).log -def _regenerate() -> None: - files = _tool_files() - for scenario in SCENARIOS: - document = replay(scenario).document - for trajectory in _trajectories(document): - definitions = trajectory["agent"].get("tool_definitions") - named = next((name for name, converted in files.items() if converted == definitions), None) - if named is not None: - trajectory["agent"]["tool_definitions"] = {"shared": named} - (FIXTURES / f"{scenario}.expected.json").write_text(json.dumps(document, indent=1, ensure_ascii=False) + "\n") - - if __name__ == "__main__": - _regenerate() + RECORDINGS.regenerate() diff --git a/tst/unit/agents/codex/test_codex_atif_recorded.py b/tst/unit/agents/codex/test_codex_atif_recorded.py index d5cda6591..474df46d2 100644 --- a/tst/unit/agents/codex/test_codex_atif_recorded.py +++ b/tst/unit/agents/codex/test_codex_atif_recorded.py @@ -11,7 +11,6 @@ ``tst/manual/codex_gemini_atif/record.py``, whose docstring has the steps.""" from __future__ import annotations -import json import sys from pathlib import Path @@ -21,97 +20,61 @@ if __name__ == "__main__": sys.path.insert(0, str(REPO)) -from agentenv_protocol.atif import RecordedTask, check_adapter, check_media, profile_of # noqa: E402 +from agentenv_protocol.atif import check_media, profile_of # noqa: E402 from tst.unit.agents.codex.agent import codex_atif # noqa: E402 +from tst.util.atif_recorded import ( # noqa: E402 + Recordings, + agent_steps, + assert_every_call_has_its_result, + assert_every_model_call_has_its_time_and_usage, + assert_steps_sum_to_reported_usage, + images, +) -FIXTURES = REPO / "tst" / "data" / "codex_atif" -SCENARIOS = sorted(path.stem for path in FIXTURES.glob("*.json") if not path.name.endswith(".expected.json")) -CodexAtif = codex_atif.CodexAtif +RECORDINGS = Recordings(REPO / "tst" / "data" / "codex_atif", codex_atif.CodexAtif) -def recorded(scenario: str) -> tuple[list[RecordedTask], list[dict | None]]: - data = json.loads((FIXTURES / f"{scenario}.json").read_text()) - return ([RecordedTask.from_served(turn["turn"], turn["native"], turn["aux"]) for turn in data["turns"]], - [turn["usage"] for turn in data["turns"]]) - - -def expected(scenario: str) -> dict: - return json.loads((FIXTURES / f"{scenario}.expected.json").read_text()) - - -def replay(scenario: str): - return check_adapter(CodexAtif, recorded(scenario)[0]) - - -def _trajectories(document: dict) -> list[dict]: - return [document, *(document.get("subagent_trajectories") or [])] - - -def _agent_steps(trajectory: dict) -> list[dict]: - return [step for step in trajectory["steps"] if step["source"] == "agent"] - - -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_a_recorded_run_replays_to_its_document_under_the_live_rule(scenario): - kit = check_adapter(CodexAtif, recorded(scenario)[0], expected=expected(scenario)) - kit.raise_for_errors() + RECORDINGS.check(scenario) -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_a_recorded_runs_steps_sum_to_the_usage_each_turn_reported(scenario): """Each response's own usage, sub-agents' included, adds up to what the CLI reported for the turn.""" - _, usage = recorded(scenario) - final = replay(scenario).document["final_metrics"] - reported = [turn or {} for turn in usage] - for metric, field in (("total_prompt_tokens", "input_tokens"), ("total_completion_tokens", "output_tokens"), - ("total_cached_tokens", "cache_read_tokens")): - assert final.get(metric, 0) == sum(turn.get(field) or 0 for turn in reported), metric + assert_steps_sum_to_reported_usage(RECORDINGS.replay(scenario).document, RECORDINGS.recorded(scenario)[1]) -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_every_model_call_of_a_recorded_run_is_a_step_with_its_rollouts_time_model_and_usage(scenario): - for trajectory in _trajectories(replay(scenario).document): - for step in _agent_steps(trajectory): - if step.get("llm_call_count") != 0: - assert step.get("timestamp") and step.get("model_name"), step["step_id"] - assert "completion_tokens" in step.get("metrics", {}), step["step_id"] + assert_every_model_call_has_its_time_and_usage(RECORDINGS.replay(scenario).document) -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_every_call_of_a_recorded_run_has_its_result(scenario): - for trajectory in _trajectories(replay(scenario).document): - for step in _agent_steps(trajectory): - answered = {result["source_call_id"] for result in (step.get("observation") or {}).get("results") or ()} - assert {call["tool_call_id"] for call in step.get("tool_calls") or ()} <= answered, step["step_id"] + assert_every_call_has_its_result(RECORDINGS.replay(scenario).document) def test_the_recordings_cover_what_the_adapter_maps(): - documents = {scenario: replay(scenario) for scenario in SCENARIOS} + documents = {scenario: RECORDINGS.replay(scenario) for scenario in RECORDINGS.scenarios} browser = documents["browser"] - images = [part for step in _agent_steps(browser.document) - for result in (step.get("observation") or {}).get("results") or () - for part in result["content"] if isinstance(result["content"], list) and part.get("type") == "image"] - assert images - for image in images: + assert images(browser.document) + for image in images(browser.document): check_media(image["source"]["path"], browser.media[image["source"]["path"]]) - assert any(call["function_name"].startswith("mcp__browser__") for step in _agent_steps(browser.document) + assert any(call["function_name"].startswith("mcp__browser__") for step in agent_steps(browser.document) for call in step.get("tool_calls") or ()) assert [len(documents[name].document.get("subagent_trajectories") or ()) for name in ("subagent", "forked")] \ == [1, 1] - retried = _agent_steps(documents["retried"].document) + retried = agent_steps(documents["retried"].document) assert any(profile_of(step).get("attempt") == 2 for step in retried) assert any("error" in profile_of(step) for step in retried) - refused, closing = _agent_steps(documents["refused"].document) + refused, closing = agent_steps(documents["refused"].document) assert refused["llm_call_count"] == 0 and profile_of(refused)["error"]["kind"] == "infra_error" assert profile_of(closing)["state"] == "failed" - reasoning = _agent_steps(documents["reasoning"].document) + reasoning = agent_steps(documents["reasoning"].document) assert reasoning[0]["reasoning_effort"] == "high" and profile_of(reasoning[0])["reasoning"] if __name__ == "__main__": - for name in SCENARIOS: - run = replay(name) - run.raise_for_errors() - (FIXTURES / f"{name}.expected.json").write_text(json.dumps(run.document, indent=1, ensure_ascii=False) + "\n") - print("wrote", name) + RECORDINGS.regenerate() diff --git a/tst/unit/agents/gemini/test_gemini_atif_recorded.py b/tst/unit/agents/gemini/test_gemini_atif_recorded.py index 9684f4c8a..2359aba73 100644 --- a/tst/unit/agents/gemini/test_gemini_atif_recorded.py +++ b/tst/unit/agents/gemini/test_gemini_atif_recorded.py @@ -9,7 +9,6 @@ ``tst/manual/codex_gemini_atif/record.py``, whose docstring has the steps.""" from __future__ import annotations -import json import sys from pathlib import Path @@ -19,86 +18,56 @@ if __name__ == "__main__": sys.path.insert(0, str(REPO)) -from agentenv_protocol.atif import RecordedTask, check_adapter, check_media, profile_of # noqa: E402 +from agentenv_protocol.atif import check_media, profile_of # noqa: E402 from tst.unit.agents.gemini.agent import gemini_atif # noqa: E402 +from tst.util.atif_recorded import ( # noqa: E402 + Recordings, + agent_steps, + assert_every_call_has_its_result, + assert_every_model_call_has_its_time_and_usage, + assert_steps_sum_to_reported_usage, + images, +) -FIXTURES = REPO / "tst" / "data" / "gemini_atif" -SCENARIOS = sorted(path.stem for path in FIXTURES.glob("*.json") if not path.name.endswith(".expected.json")) -GeminiAtif = gemini_atif.GeminiAtif +RECORDINGS = Recordings(REPO / "tst" / "data" / "gemini_atif", gemini_atif.GeminiAtif) -def recorded(scenario: str) -> tuple[list[RecordedTask], list[dict | None]]: - data = json.loads((FIXTURES / f"{scenario}.json").read_text()) - return ([RecordedTask.from_served(turn["turn"], turn["native"], turn["aux"]) for turn in data["turns"]], - [turn["usage"] for turn in data["turns"]]) - - -def expected(scenario: str) -> dict: - return json.loads((FIXTURES / f"{scenario}.expected.json").read_text()) - - -def replay(scenario: str): - return check_adapter(GeminiAtif, recorded(scenario)[0]) - - -def _agent_steps(document: dict) -> list[dict]: - return [step for step in document["steps"] if step["source"] == "agent"] - - -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_a_recorded_run_replays_to_its_document_under_the_live_rule(scenario): - kit = check_adapter(GeminiAtif, recorded(scenario)[0], expected=expected(scenario)) - kit.raise_for_errors() + RECORDINGS.check(scenario) -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_a_recorded_runs_steps_sum_to_the_usage_each_turn_reported(scenario): """Each call the proxy forwarded, a message's or not, adds up to the turn's usage, which is the proxy's sum.""" - _, usage = recorded(scenario) - final = replay(scenario).document["final_metrics"] - reported = [turn or {} for turn in usage] - for metric, field in (("total_prompt_tokens", "input_tokens"), ("total_completion_tokens", "output_tokens"), - ("total_cached_tokens", "cache_read_tokens")): - assert final.get(metric, 0) == sum(turn.get(field) or 0 for turn in reported), metric + assert_steps_sum_to_reported_usage(RECORDINGS.replay(scenario).document, RECORDINGS.recorded(scenario)[1]) -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_every_response_of_a_recorded_run_is_a_step_with_its_time_model_and_usage(scenario): - for step in _agent_steps(replay(scenario).document): - if step.get("llm_call_count") != 0: - assert step.get("timestamp") and step.get("model_name"), step["step_id"] - assert "completion_tokens" in step.get("metrics", {}), step["step_id"] + assert_every_model_call_has_its_time_and_usage(RECORDINGS.replay(scenario).document) -@pytest.mark.parametrize("scenario", SCENARIOS) +@pytest.mark.parametrize("scenario", RECORDINGS.scenarios) def test_every_call_of_a_recorded_run_has_its_result(scenario): - for step in _agent_steps(replay(scenario).document): - answered = {result["source_call_id"] for result in (step.get("observation") or {}).get("results") or ()} - assert {call["tool_call_id"] for call in step.get("tool_calls") or ()} <= answered, step["step_id"] + assert_every_call_has_its_result(RECORDINGS.replay(scenario).document) def test_the_recordings_cover_what_the_adapter_maps(): - documents = {scenario: replay(scenario) for scenario in SCENARIOS} + documents = {scenario: RECORDINGS.replay(scenario) for scenario in RECORDINGS.scenarios} browser = documents["browser"] - images = [part for step in _agent_steps(browser.document) - for result in (step.get("observation") or {}).get("results") or () - for part in result["content"] if isinstance(result["content"], list) and part.get("type") == "image"] - assert images - for image in images: + assert images(browser.document) + for image in images(browser.document): check_media(image["source"]["path"], browser.media[image["source"]["path"]]) - assert any(step.get("reasoning_content") for step in _agent_steps(documents["coding"].document)) - retried = _agent_steps(documents["retried"].document) + assert any(step.get("reasoning_content") for step in agent_steps(documents["coding"].document)) + retried = agent_steps(documents["retried"].document) assert any(step["llm_call_count"] == 0 and "error" in profile_of(step) for step in retried) assert retried[-1]["message"] - refused, closing = _agent_steps(documents["refused"].document) + refused, closing = agent_steps(documents["refused"].document) assert refused["llm_call_count"] == 0 and profile_of(refused)["error"]["message"].startswith("[API Error") assert profile_of(closing)["state"] == "failed" if __name__ == "__main__": - for name in SCENARIOS: - run = replay(name) - run.raise_for_errors() - (FIXTURES / f"{name}.expected.json").write_text(json.dumps(run.document, indent=1, ensure_ascii=False) + "\n") - print("wrote", name) + RECORDINGS.regenerate() diff --git a/tst/util/atif_recorded.py b/tst/util/atif_recorded.py new file mode 100644 index 000000000..00563bbc8 --- /dev/null +++ b/tst/util/atif_recorded.py @@ -0,0 +1,100 @@ +"""An agent's recorded atif/1 runs (``tst/data/_atif``), recorded through its image on the pinned CLI with +atif/1 prescribed: each scenario's turns as the agent served them, its native events, its aux log and its turn +context, replayed through its adapter as the SDK ran it live; and the checks every agent's recorded runs share.""" + +from __future__ import annotations + +import json +import math +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from agentenv_protocol.atif import KitResult, RecordedTask, check_adapter + + +class Recordings: + """The recordings in ``folder``, replayed through ``adapter``. ``aux`` turns a fixture's aux entry into the one the + agent fed, ``expected`` a checked-in document into the one a replay writes, and ``saved`` the other way, for an + agent whose fixtures keep what every run shares, its tools say, in files of their own.""" + + def __init__(self, folder: Path, adapter: type, *, aux: Callable[[dict], dict] = lambda entry: entry, + expected: Callable[[dict], dict] = lambda document: document, + saved: Callable[[dict], dict] = lambda document: document) -> None: + self.folder, self.adapter = folder, adapter + self._aux, self._expected, self._saved = aux, expected, saved + self.scenarios = sorted(path.stem for path in folder.glob("*.json") if not path.name.endswith(".expected.json")) + + def data(self, scenario: str) -> dict: + return json.loads((self.folder / f"{scenario}.json").read_text()) + + def recorded(self, scenario: str) -> tuple[list[RecordedTask], list[dict | None]]: + """The scenario's turns as recorded tasks, and the usage each turn reported.""" + turns = self.data(scenario)["turns"] + return ([RecordedTask.from_served(turn["turn"], turn["native"], [self._aux(entry) for entry in turn["aux"]]) + for turn in turns], [turn["usage"] for turn in turns]) + + def expected(self, scenario: str) -> dict: + return self._expected(json.loads((self.folder / f"{scenario}.expected.json").read_text())) + + def replay(self, scenario: str) -> KitResult: + return check_adapter(self.adapter, self.recorded(scenario)[0]) + + def check(self, scenario: str) -> None: + """The scenario replays to its checked-in document under the live rule.""" + check_adapter(self.adapter, self.recorded(scenario)[0], expected=self.expected(scenario)).raise_for_errors() + + def regenerate(self) -> None: + """Write each scenario's expected document again, after an intended change.""" + for scenario in self.scenarios: + run = self.replay(scenario) + run.raise_for_errors() + document = self._saved(run.document) + (self.folder / f"{scenario}.expected.json").write_text(json.dumps(document, indent=1, ensure_ascii=False) + + "\n") + print("wrote", scenario) + + +def trajectories(document: dict) -> list[dict]: + """The document's own trajectory and each embedded sub-agent's.""" + return [document, *(document.get("subagent_trajectories") or [])] + + +def agent_steps(trajectory: dict) -> list[dict]: + return [step for step in trajectory["steps"] if step["source"] == "agent"] + + +def assert_steps_sum_to_reported_usage(document: dict, usage: list[dict | None]) -> None: + """The copy's totals are the turns' reported usage, and its cost theirs when every turn reported one.""" + final, reported = document["final_metrics"], [turn or {} for turn in usage] + for metric, field in (("total_prompt_tokens", "input_tokens"), ("total_completion_tokens", "output_tokens"), + ("total_cached_tokens", "cache_read_tokens")): + total = sum(turn.get(field) or 0 for turn in reported) + assert final.get(metric, 0) == total, (metric, final.get(metric), total) + if all(turn.get("cost_usd") is not None for turn in reported): + assert math.isclose(final["total_cost_usd"], sum(turn["cost_usd"] for turn in reported)) + + +def assert_every_model_call_has_its_time_and_usage(document: dict, *, model: bool = True) -> None: + """Each step that made a model call, a sub-agent's included, has its time, its completion tokens and, with + ``model``, the model it called.""" + for trajectory in trajectories(document): + for step in agent_steps(trajectory): + if step.get("llm_call_count") != 0: + assert step.get("timestamp") and "completion_tokens" in step.get("metrics", {}), step["step_id"] + assert not model or step.get("model_name"), step["step_id"] + + +def assert_every_call_has_its_result(document: dict) -> None: + for trajectory in trajectories(document): + for step in agent_steps(trajectory): + answered = {result["source_call_id"] for result in (step.get("observation") or {}).get("results") or ()} + assert {call["tool_call_id"] for call in step.get("tool_calls") or ()} <= answered, step["step_id"] + + +def images(document: dict) -> list[dict[str, Any]]: + """Every image the document's results hold, a sub-agent's included.""" + return [part for trajectory in trajectories(document) for step in agent_steps(trajectory) + for result in (step.get("observation") or {}).get("results") or () + for part in (result.get("content") if isinstance(result.get("content"), list) else ()) + if isinstance(part, dict) and part.get("type") == "image"] From 07bddbcac1aa865f1ab49b82ca1445c328f78cb8 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 27 Nov 2026 16:53:46 -0800 Subject: [PATCH 3/4] fix(agents): Gemini's host install works in /app, which a local sandbox maps to its own folder A host install on a local sandbox runs on this machine as this user, who can't make /workspace at the root, so Gemini's install failed there before it copied anything. Every other shipped agent works in /app, which the local sandbox maps to a folder of its own. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/agents/agents/gemini/README.md | 2 +- src/agent_env/agents/agents/gemini/a2a_server.py | 4 +++- tst/unit/agents/gemini/test_card_contract.py | 11 ++++++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/agent_env/agents/agents/gemini/README.md b/src/agent_env/agents/agents/gemini/README.md index d7fd75c3c..57480d94c 100644 --- a/src/agent_env/agents/agents/gemini/README.md +++ b/src/agent_env/agents/agents/gemini/README.md @@ -44,7 +44,7 @@ bound. Through a LiteLLM proxy, a provider-prefixed model's chat completions don | `snapshot/v1` changelog | where the host has GNU tar: an AfterTool hook captures each tool call's writes as an incremental tar uploaded through the namespace grant; `apply` replays them in order and, with `resume_conversation`, binds the last applied tool call's session | | `peer-agents/v1` | SDK default: the CLI reaches the task's other agents through the SDK's `peer_agents` MCP tools | | `attribution-probe/v1` | the `project_id` and `task_id` the proxy last sent | -| `install/v1` | `install.sh`, into a task container (as root, the CLI working in `/workspace`) or onto a `vm` sandbox's Linux host: Node and uv checked against their checksums, the CLI from `package-lock.json` and the agent's requirements in a Python of its own, which the target's own Node and Python are never replaced by; the model's commands get the agent's where the target has none. Node's builds need glibc | +| `install/v1` | `install.sh`, into a task container (as root, the CLI working in `/workspace`) or onto a `vm` sandbox's Linux host (the CLI working in `/app`): Node and uv checked against their checksums, the CLI from `package-lock.json` and the agent's requirements in a Python of its own, which the target's own Node and Python are never replaced by; the model's commands get the agent's where the target has none. Node's builds need glibc | | `triggers/v1` | SDK default | The image is `python:3.11-slim` with Node, the CLI, the agent and the Python packages `model-requirements.txt` pins for diff --git a/src/agent_env/agents/agents/gemini/a2a_server.py b/src/agent_env/agents/agents/gemini/a2a_server.py index 315490bd9..21d5ada7d 100644 --- a/src/agent_env/agents/agents/gemini/a2a_server.py +++ b/src/agent_env/agents/agents/gemini/a2a_server.py @@ -309,7 +309,9 @@ def total(name: str) -> int | None: "LITELLM_EXTRA_HEADERS={litellm_extra_headers} AGENT_TRUST_ENV={trust_env} ") _ENDPOINT_PARAMS = ["litellm_api_key", "litellm_base_url", "litellm_extra_headers", "trust_env"] _INSTALL_COMMANDS = [_UNPACK, _ENDPOINT + "bash {work_dir}/agent/install.sh container {container} {a2a_port}"] -_HOST_WORKDIR = "/workspace" +# /app, as every shipped agent: a local sandbox maps it to a folder of its own, since its host install runs as this +# machine's user, who can't make a folder at the root. +_HOST_WORKDIR = "/app" _INSTALL_COMMANDS_HOST = [_UNPACK, _ENDPOINT + f"bash {{work_dir}}/agent/install.sh host {{agent_name}} {{a2a_port}} {_HOST_WORKDIR}"] diff --git a/tst/unit/agents/gemini/test_card_contract.py b/tst/unit/agents/gemini/test_card_contract.py index 81b666805..4def49659 100644 --- a/tst/unit/agents/gemini/test_card_contract.py +++ b/tst/unit/agents/gemini/test_card_contract.py @@ -8,6 +8,7 @@ import subprocess import sys +from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox from tst.unit.agents.gemini.agent import AGENT_DIR, PYTHONPATH, a2a_server from tst.unit.agents.gemini.support import card @@ -216,7 +217,15 @@ def test_install_params(app): assert params["required_params_host"] == ["work_dir", "agent_ctx_tar", "a2a_port", "agent_name", *endpoint] assert params["install_commands"] == a2a_server._INSTALL_COMMANDS assert params["install_commands_host"] == a2a_server._INSTALL_COMMANDS_HOST - assert (params["workdir_host"], params["user_host"]) == ("/workspace", "root") + assert (params["workdir_host"], params["user_host"]) == ("/app", "root") + + +def test_a_host_install_on_a_local_sandbox_works_in_the_sandboxs_own_folder(tmp_path): + """A local sandbox runs a host install on this machine as this user, who can't make a folder at the root: the + workspace the install names is the one it maps to a folder of its own.""" + command = a2a_server._INSTALL_COMMANDS_HOST[-1] + assert command.endswith(f" {a2a_server._HOST_WORKDIR}") + assert LocalSandbox(work_dir=tmp_path)._rewrite_app_script(command).endswith(f" {tmp_path}") def test_the_card_and_health_are_served(client): From 330ad633145a750acae037ecdeee5024d9c89c53 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 27 Nov 2026 18:54:15 -0800 Subject: [PATCH 4/4] refactor(agents): Claude Code's transcript tail reads and commits in one call, and its image and install carry every module the server imports The tail's read and advance were split so a read the follower cancelled midway was read again. The shared follower never cancels a read, so read now moves past what it gives, as Codex's and Gemini's tails do, and the follower calls it directly. Claude Code's image-contract test now checks, as Codex's and Gemini's do, that the Dockerfile and install.sh carry every module the server imports, the shared ones included. Co-Authored-By: Claude Opus 5.5 --- .../agents/claude-code/claude_bridge.py | 38 +++++--------- .../agents/claude_code/test_image_contract.py | 52 ++++++++++++++++--- .../agents/claude_code/test_session_tail.py | 24 ++++----- 3 files changed, 67 insertions(+), 47 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/claude_bridge.py b/src/agent_env/agents/agents/claude-code/claude_bridge.py index ab17b4d96..478922137 100644 --- a/src/agent_env/agents/agents/claude-code/claude_bridge.py +++ b/src/agent_env/agents/agents/claude-code/claude_bridge.py @@ -514,10 +514,10 @@ class SessionTail: """One turn's new transcript records, its sub-agents' transcripts' too, as the CLI appends them, each as the ATIF adapter's aux record (``session_aux``). It starts where each file ends, so an earlier turn isn't fed again, and finds its place in a file the scrub replaced between attempts by its line count, which a redaction keeps; a file is - taken as replaced when its inode or the line before the place it was read to changed. - ``read`` only reads; ``advance`` commits what it read, so a read abandoned midway is read again. For a new - document, ``new_document``, the first read also gives the latest request shape the transcript already held, which - the CLI writes once per session. Where it reads a whole file it reads it in pieces, since a long computer-use + taken as replaced when its inode or the line before the place it was read to changed. Each read moves past what + it gives, since the follower feeds every read it makes (``tail_follow``). For a new document, ``new_document``, the + first read also gives the latest request shape the transcript already held, which the CLI writes once per + session. Where it reads a whole file it reads it in pieces, since a long computer-use session's transcript holds each screenshot twice.""" def __init__(self, session_id: str, on_stdout: Collection[str], shapes: set[tuple[str | None, str]], *, @@ -540,40 +540,26 @@ def _paths(self) -> list[Path]: subagents = sorted(self._subagents.glob(f"{_SUBAGENT_PREFIX}*.jsonl")) if self._subagents.is_dir() else [] return ([self._main] if self._main.exists() else []) + subagents - def read(self) -> tuple[list[tuple[str, dict]], dict[Path, _TailedFile], set[tuple[str | None, str]]]: - """The aux records the files gained since the last ``advance``, where each file is read to, and the request - shapes fed then.""" + def read(self, final: bool = False) -> list[tuple[str, dict]]: + """The aux records the files gained since the last read. The transcript has no end of its own to read to, so a + final read is like any other.""" records: list[tuple[str, dict]] = [] - files: dict[Path, _TailedFile] = {} - shapes = set(self._shapes) - if self._earlier_shape is not None and (fed := session_aux(self._earlier_shape, None, (), shapes)): + if self._earlier_shape is not None and (fed := session_aux(self._earlier_shape, None, (), self._shapes)): records.append(fed) + self._earlier_shape = None for path in self._paths(): try: - tailed, lines = self._new_lines(path, self._files.get(path)) + self._files[path], lines = self._new_lines(path, self._files.get(path)) except OSError: continue - files[path] = tailed agent_id = path.stem.removeprefix(_SUBAGENT_PREFIX) if path.parent == self._subagents else None for raw in lines: try: record = json.loads(raw) except (json.JSONDecodeError, UnicodeDecodeError): continue - if isinstance(record, dict) and (fed := session_aux(record, agent_id, self._on_stdout, shapes)): + if isinstance(record, dict) and (fed := session_aux(record, agent_id, self._on_stdout, self._shapes)): records.append(fed) - return records, files, shapes - - def advance(self, files: Mapping[Path, _TailedFile], shapes: set[tuple[str | None, str]]) -> None: - self._files.update(files) - self._shapes.update(shapes) - self._earlier_shape = None - - def take(self, final: bool = False) -> list[tuple[str, dict]]: - """What ``read`` gives, committed: the follower feeds every read it makes (``tail_follow``). The transcript has - no end of its own to read to, so a final read is like any other.""" - records, files, shapes = self.read() - self.advance(files, shapes) return records @staticmethod @@ -761,7 +747,7 @@ async def run_claude( else max(int(deadline - time.monotonic()) - _DEADLINE_HEADROOM_S, 1)) # Each scrub ends before the turn does, cancelled or not: a later turn on the context mustn't start while it # can still replace the transcript that turn appends to. - follow = following(tail.take, aux_callback, SESSION_POLL_S, "session transcript") if tail is not None \ + follow = following(tail.read, aux_callback, SESSION_POLL_S, "session transcript") if tail is not None \ else contextlib.nullcontext() try: async with follow: diff --git a/tst/unit/agents/claude_code/test_image_contract.py b/tst/unit/agents/claude_code/test_image_contract.py index 88273104f..c6e82bc7e 100644 --- a/tst/unit/agents/claude_code/test_image_contract.py +++ b/tst/unit/agents/claude_code/test_image_contract.py @@ -1,15 +1,17 @@ """The agent's folder is its build context: the Dockerfile copies only its own files and the folders its shared_sources.toml takes from agent-env's sources, keeps TLS checks on, and installs the protocol at or above its -floor, which a release doesn't pin.""" +floor, which a release doesn't pin; the image and install.sh carry every module the server imports.""" from __future__ import annotations +import ast import re import tomllib from tst.unit.agents.claude_code.agent import AGENT_DIR DOCKERFILE = (AGENT_DIR / "Dockerfile").read_text() +INSTALL_SH = (AGENT_DIR / "install.sh").read_text() SOURCES = AGENT_DIR.parents[2] SHARED = tomllib.loads((AGENT_DIR / "shared_sources.toml").read_text()) @@ -17,23 +19,59 @@ DOC_LIBS = ["openpyxl==3.1.5", "pypdf==6.21.3", "python-docx==1.2.0", "python-pptx==1.0.2"] -def _in_context(name: str) -> bool: - """Whether the build context has ``name``: from the folder, or under a folder shared_sources.toml takes from - agent-env's own sources at that name.""" +def _copied() -> list[str]: + return [name for line in re.findall(r"^COPY (?!--from=)(.+) \S+$", DOCKERFILE, re.MULTILINE) + for name in line.split()] + + +def _source(name: str): + """Where the build context's ``name`` comes from: the folder, or a folder shared_sources.toml takes from agent-env's + own sources at that name.""" first, _, rest = name.partition("/") - path = SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name + return SOURCES / SHARED[first] / rest if first in SHARED else AGENT_DIR / name + + +def _in_context(name: str) -> bool: + path = _source(name) return path.is_dir() if name.endswith("/") else path.is_file() def test_every_file_the_image_copies_is_in_the_folder(): - copied = [name for line in re.findall(r"^COPY (?!--from=)(.+) \S+$", DOCKERFILE, re.MULTILINE) - for name in line.split()] + copied = _copied() assert copied and all(_in_context(name) for name in copied), copied # install.sh and run.sh are install/v1's; a build context pruned to what the Dockerfile reads keeps them so. assert {"a2a_server.py", "claude_bridge.py", "claude_code_atif.py", "kit.py", "tar_changelog.py", "entrypoint.sh", "install.sh", "run.sh"} <= set(copied) + +def _imported(path) -> set[str]: + names = set() + for node in ast.walk(ast.parse(path.read_text())): + if isinstance(node, ast.Import): + names |= {alias.name.split(".")[0] for alias in node.names} + elif isinstance(node, ast.ImportFrom) and node.module: + names.add(node.module.split(".")[0]) + return names + + +def test_the_image_and_an_install_carry_every_module_the_server_imports(): + """The folder's own modules and those the build context takes from agent-env's sources, the egress rule, the clock + page's format and the follower among them, each by its name in the context.""" + shared = {path.stem: f"{name}/{path.name}" for name, source in SHARED.items() + for path in (SOURCES / source).glob("*.py")} + modules = {**shared, **{path.stem: path.name for path in AGENT_DIR.glob("*.py")}} + needed, pending = set(), ["a2a_server"] + while pending: + if (name := modules[pending.pop()]) not in needed: + needed.add(name) + pending += _imported(_source(name)) & set(modules) + installed = set(re.search(r'^AGENT_FILES="([^"]+)"$', INSTALL_SH, re.MULTILINE).group(1).split()) + + assert {"agent_clock/agent_egress.py", "clock/clockpage.py", "tail_follow/tail_follow.py"} <= needed + assert needed <= set(_copied()) and needed <= installed, (needed, installed) + + def test_the_image_installs_the_protocol_alone_from_its_requirements(): requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] diff --git a/tst/unit/agents/claude_code/test_session_tail.py b/tst/unit/agents/claude_code/test_session_tail.py index d815c7dc4..883ac8d72 100644 --- a/tst/unit/agents/claude_code/test_session_tail.py +++ b/tst/unit/agents/claude_code/test_session_tail.py @@ -87,13 +87,11 @@ def test_the_tail_starts_where_the_files_end_and_waits_for_a_whole_line(tmp_path tail = claude_bridge.SessionTail("sess-1", set(), set()) with transcript.open("ab") as file: file.write(_lines(_assistant("new")) + b'{"type": "assist') - records, files, shapes = tail.read() - assert [record["uuid"] for _, record in records] == ["new"] - assert tail.read()[0] == records - tail.advance(files, shapes) + assert [record["uuid"] for _, record in tail.read()] == ["new"] + assert tail.read() == [] with transcript.open("ab") as file: file.write(b'ant", "uuid": "torn"}\n') - assert [record["uuid"] for _, record in tail.read()[0]] == ["torn"] + assert [record["uuid"] for _, record in tail.read(final=True)] == ["torn"] def test_the_tail_takes_sub_agent_transcripts_new_or_old_by_their_agent(tmp_path, monkeypatch): @@ -107,7 +105,7 @@ def test_the_tail_takes_sub_agent_transcripts_new_or_old_by_their_agent(tmp_path with (subagents / "agent-old.jsonl").open("ab") as file: file.write(_lines(_assistant("later"))) (subagents / "agent-new.jsonl").write_bytes(_lines(_shape("h2"), _assistant("first"))) - fed = tail.read()[0] + fed = tail.read() assert [(name, record.get("uuid"), record.get("agentId")) for name, record in fed] == [ ("tools", None, "new"), ("session", "first", "new"), ("session", "later", "old")] @@ -121,7 +119,7 @@ def test_a_transcript_the_scrub_replaced_is_followed_by_its_line_count(tmp_path, claude_bridge.scrub_session_transcript("sess-1") with transcript.open("ab") as file: file.write(_lines(_assistant("after"))) - assert [record["uuid"] for _, record in tail.read()[0]] == ["after"] + assert [record["uuid"] for _, record in tail.read()] == ["after"] def _transcript_writing(scripted, per_spawn): # noqa: F811 @@ -209,7 +207,7 @@ def test_a_transcript_rewritten_under_the_same_inode_is_followed_by_its_line_cou _assistant("seen"), _assistant("after"))) file.truncate() assert transcript.stat().st_ino == inode - assert [record["uuid"] for _, record in tail.read()[0]] == ["after"] + assert [record["uuid"] for _, record in tail.read()] == ["after"] def test_a_new_document_is_fed_the_latest_shape_its_transcript_already_held(tmp_path, monkeypatch): @@ -218,11 +216,9 @@ def test_a_new_document_is_fed_the_latest_shape_its_transcript_already_held(tmp_ shapes = {(None, "h2")} plain = claude_bridge.SessionTail("sess-1", set(), set(shapes)) fresh = claude_bridge.SessionTail("sess-1", set(), set(), new_document=True) - records, files, seen = fresh.read() - assert plain.read()[0] == [] - assert [(name, record["shapeHash"]) for name, record in records] == [("tools", "h2")] - fresh.advance(files, seen) - assert fresh.read()[0] == [] + assert plain.read() == [] + assert [(name, record["shapeHash"]) for name, record in fresh.read()] == [("tools", "h2")] + assert fresh.read() == [] def test_a_task_that_opens_a_new_document_feeds_its_tools_again(turns, client, monkeypatch): @@ -252,7 +248,7 @@ def test_the_tail_never_holds_a_whole_transcript(tmp_path, monkeypatch): transcript.write_bytes(rewritten) del rewritten tracemalloc.start() - records, _, _ = tail.read() + records = tail.read() read = tracemalloc.get_traced_memory()[1] finally: tracemalloc.stop()