From ab0f79bd44dc8e3de7748e9aeb59563c64919252 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Sun, 22 Nov 2026 22:43:35 -0800 Subject: [PATCH 01/10] feat(task-steps): always_on keeps each wake's atif/1 copy as its trajectory when the run prescribes it, and its judge stages it always_on prescribes the run's formats and reads each wake's and nudge's trajectory through AtifCopies, inline within its one fetch cap: the atif/1 copy when prescribed and offered, else, or when the copy can't be had or lacks media, native. Every turn records what its url holds (target_agent_per_turn_trajectories), and in a prescribed run each turn's end names its index and format in the timeline, since its turns share one url. always_on_agent_verifier stages an atif/1 wake from its own task's events (turn_events.atif_turn_events, the shapes a native Claude Code turn gives), keyed by document and task, and reads no harness settings from a copy. A run that prescribes nothing is unchanged, and the judge-input pin gains an always_on atif/1 case. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +- .../task_step/snapshot_utils/atif_copies.py | 19 +++ .../task_step/task_steps/always_on.py | 71 ++++++----- .../verifiers/always_on_agent_verifier.py | 47 +++++++- .../verifiers/judge_utils/turn_events.py | 48 +++++++- tst/data/verifier_golden/judge_inputs.json | 33 +++++ .../test_claude_code_atif_recorded.py | 18 +++ .../test_always_on_agent_verifier.py | 41 ++++++- .../test_always_on_trajectory_formats.py | 113 +++++++++++++++++- .../task_step/verifiers/test_judge_inputs.py | 14 +++ 10 files changed, 368 insertions(+), 46 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9da4ced94..51ca19f7d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -122,8 +122,9 @@ or one of them only where it is used. agent whose trajectory it reads (prompt_agent and always_on call the trajectory extension's `prescribe` on the agent they prompt before its conversation starts); a run's `user_overrides.trajectory_formats` beats it. None by default, so an agent builds native only, and an `atif/1` read of a conversation not prescribed it is refused - (`format_not_prescribed`). A prompt step of a run that prescribes `atif/1` reads each turn's copy inline once the - turn ends, off the turn's path, and stores it as `.json` under `{prefix}atif/instance_id=//` + (`format_not_prescribed`). A prompt step or always_on step of a run that prescribes `atif/1` reads each turn's copy + inline once the turn ends (a prompt step off the turn's path, always_on within its one trajectory fetch cap), and + stores it as `.json` under `{prefix}atif/instance_id=//` (`metadata["atif_copies"]`, `task_step/snapshot_utils/atif_copies.py`), overwritten each turn, with the turn's aux log and turn context under `turns/` and the media it names pulled into `media/`; after a restart the session's earlier document names the next in `continued_trajectory_ref`. Each turn's record says how its copy checked @@ -132,8 +133,9 @@ or one of them only where it is used. had, or whose copy's media didn't all arrive, has its native trajectory read in its place. Judges read each turn's trajectory by its label (`verifiers/judge_utils/atif_turns.py`): an `atif/1` turn as its own A2A task cut out of the document (`agentenv_protocol.atif.task_document`), its media read from the document's `media/` and checked against their - names, any other turn as native. So prescribing atif/1 changes what a run's judges read and can move its scores. Only - prompt steps switch for now: always_on prescribes native only until it reads atif/1 copies. + names, any other turn as native; always_on's judge stages an `atif/1` wake from that task's events + (`turn_events.atif_turn_events`), each such wake's end naming its turn in the step's timeline, since the turns share + one url. So prescribing atif/1 changes what a run's judges read and can move its scores. - Secrets never live in the file: use `secret:KEY` or `env:NAME` references, resolved through `[stores.secret]`. - agent-env has no stage concept: "dev" versus "prod" is which file `AGENT_ENV_CONFIG` names. A diff --git a/src/agent_env/task_step/snapshot_utils/atif_copies.py b/src/agent_env/task_step/snapshot_utils/atif_copies.py index bd2dc3d16..869bfa2a1 100644 --- a/src/agent_env/task_step/snapshot_utils/atif_copies.py +++ b/src/agent_env/task_step/snapshot_utils/atif_copies.py @@ -135,6 +135,25 @@ def turn(self, index: int, task_id: str, name: str, record: TurnTrajectory, *, n previous = self._pending[-1][1] if self._pending else None self._pending.append((index, asyncio.create_task(self._turn(task_id, name, record, native, previous)))) + async def read(self, index: int, task_id: str, name: str, record: TurnTrajectory, *, native: NativeRead, + timeout: float) -> Optional[str]: + """``turn`` on the caller's path, for a step that reads each turn's trajectory before it goes on (always_on): + the turn's url once ``record`` is filled, all within ``timeout``. A copy that takes longer is recorded + ``unavailable``, ``timeout``, with no time left to read native in its place; without a copy, native is read as + ever, its error raised.""" + self.turn(index, task_id, name, record, native=native) + if not self.replaces_native: + url, record["format"] = await asyncio.wait_for(native(), timeout) + return url + try: + return await asyncio.wait_for(self._pending[-1][1], timeout) + except TimeoutError: + if record.get("atif") is None: + record["atif"] = _unavailable("timeout", task_id) + logger.warning(f"agent '{self._agent.agent_name}': task {task_id}'s trajectory wasn't read within " + f"{timeout:.0f}s (continuing)") + return None + async def join(self) -> dict[int, str | None]: """Each copied turn's url, by its index, once every copy has been stored and its record filled; cancelled while waiting, it cancels the copies left.""" diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 52ad8b3f0..adc60a4a1 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -79,6 +79,7 @@ from __future__ import annotations import asyncio +import functools import importlib.util import json import logging @@ -94,6 +95,7 @@ from zoneinfo import ZoneInfo from a2a.types import TaskState +from agentenv_protocol.atif import FORMAT as ATIF_FORMAT from agent_env.a2a_agent import A2AAgent, conversation_store, protocol from agent_env.a2a_agent.object_transfer import AgentTurn, send_and_wait @@ -112,7 +114,8 @@ ) from agent_env.config.model import ModelRole from agent_env.store import DuplicateKeyError, get_config -from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext +from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext, TurnTrajectory +from agent_env.task_step.snapshot_utils.atif_copies import AtifCopies from agent_env.task_step.usage import StepUsage from agent_env.task_step.task_step import TaskStep from agent_env.task_step.task_steps.agent import user_sim_versions @@ -122,6 +125,7 @@ PromptAgentTaskStep, fetch_native_trajectory, prescribe_formats, + prescribed_formats, ) from agent_env.task_step.task_steps.agent.user_sim_common import iso as _iso, person_of, task_zone, utc as _utc from agent_env.task_step.task_steps.agent.user_sim_common import attached, file_name, for_agent, recorded_opening @@ -381,6 +385,8 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.final_sent = False self.last_reply_at: Optional[datetime] = None self.per_turn_trajectory_urls: list[Optional[str]] = [] + self.per_turn_trajectories: list[TurnTrajectory] = [] # each turn's record, beside its url + self.copies: Optional[AtifCopies] = None self.per_turn_parts: list[Optional[list[dict]]] = [] self.tool_calls: Optional[int] = None # Each role's turns' usage, recorded as each turn ends. @@ -601,7 +607,10 @@ async def _configure_agents(self) -> None: if negotiated: await protocol.post_agent_config(self.target_url + negotiated.endpoint, negotiated.fields, headers=self.agent.control_headers) - await prescribe_formats(ctx, step.id, self.agent, self.target_url, formats=()) # native until it reads atif/1 + await prescribe_formats(ctx, step.id, self.agent, self.target_url) + self.copies = AtifCopies(ctx, self.agent, self.target_url, + A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY), + prescribed=ATIF_FORMAT in prescribed_formats(ctx)) solver_model = negotiated.fields.get("model") if negotiated else None ctx.record_model(ModelRole.SOLVER.record_key, step.id, solver_model) self.usage.start(ModelRole.SOLVER, solver_model, self.agent) @@ -1290,18 +1299,7 @@ def record() -> None: self.tool_calls = (self.tool_calls or 0) + term.tool_call_count messages, quiet = await self._take_messages() await self._read_changes("turn") - traj = None - card = self.agent.a2a_card or {} - traj_ext = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) - if traj_ext: - try: - traj = (await asyncio.wait_for( - fetch_native_trajectory(self.target_url, traj_ext, task_id, step._trajectory_prefix(), msg_id, - card=card, sandbox_type=self.agent.sandbox_type, - headers=self.agent.control_headers), TRAJECTORY_FETCH_SECONDS)).url - except Exception as e: - logger.warning(f"wake {self.wakes}: trajectory fetch failed (continuing): {e}") - self.per_turn_trajectory_urls.append(traj) + traj, which = await self._trajectory(task_id, msg_id, f"wake {self.wakes}") self.final_task_id = task_id ended = await self.now() plain = term.response_text or "" @@ -1309,7 +1307,7 @@ def record() -> None: self.log("agent_turn_end", n=self.wakes, state=str(state), virtual_time=_iso(ended), virtual_seconds=round((ended - sent_at).total_seconds()), real_seconds=round(time.time() - t, 1), tool_calls=term.tool_call_count, plain_reply=plain, messages_to_user=len(messages), - trajectory_url=traj, **extra) + trajectory_url=traj, **which, **extra) self._sent(messages) if not _completed(state): # failed, canceled or rejected: the turn didn't run to its end self._failed(term.error_type or f"agent_turn_{_state_name(state)}", @@ -1324,6 +1322,28 @@ def record() -> None: await self._read_changes("after_turn") await self._schedule_read() + async def _trajectory(self, task_id: str, msg_id: str, turn: str) -> tuple[Optional[str], dict]: + """The agent turn's trajectory, read within one fetch cap (TRAJECTORY_FETCH_SECONDS): its atif/1 copy when the + run prescribes atif/1 and the agent offers it, else, or when the copy can't be had, its native one. Its url and + record join the run's per-turn lists. Returns the url and, in a run that prescribes atif/1, whose turns share + one url, the timeline fields that say which turn it is and what its url holds.""" + step, card = self.step, self.agent.a2a_card or {} + extension = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) + record = TurnTrajectory(format=None, atif=None) + native = functools.partial(fetch_native_trajectory, self.target_url, extension, task_id, + step._trajectory_prefix(), msg_id, card=card, sandbox_type=self.agent.sandbox_type, + headers=self.agent.control_headers) if extension else _no_trajectory + index = len(self.per_turn_trajectory_urls) + url = None + try: + url = await self.copies.read(index, task_id, msg_id, record, native=native, + timeout=TRAJECTORY_FETCH_SECONDS) + except Exception as e: + logger.warning(f"{turn}: trajectory fetch failed (continuing): {e}") + self.per_turn_trajectory_urls.append(url) + self.per_turn_trajectories.append(record) + return url, ({"turn": index, "trajectory_format": record["format"]} if record["atif"] is not None else {}) + def _kept_parts(self, parts: list[dict]) -> list[dict]: """What the prompt response keeps of one wake's parts: TURN_TEXT_CHARS of each text, until TURN_TEXT_TOTAL_CHARS in all; then a note. Other parts (files, data) as they are.""" @@ -1368,25 +1388,14 @@ def record() -> None: self.tool_calls = (self.tool_calls or 0) + term.tool_call_count messages, quiet = await self._take_messages() await self._read_changes("nudge") - traj = None - card = self.agent.a2a_card or {} - traj_ext = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) - if traj_ext: - try: - traj = (await asyncio.wait_for( - fetch_native_trajectory(self.target_url, traj_ext, task_id, step._trajectory_prefix(), msg_id, - card=card, sandbox_type=self.agent.sandbox_type, - headers=self.agent.control_headers), TRAJECTORY_FETCH_SECONDS)).url - except Exception as e: - logger.warning(f"nudge after wake {self.wakes}: trajectory fetch failed (continuing): {e}") - self.per_turn_trajectory_urls.append(traj) + traj, which = await self._trajectory(task_id, msg_id, f"nudge after wake {self.wakes}") self.final_task_id = task_id plain = term.response_text or "" outcome = "message_user" if messages else "stay_quiet" if quiet else "neither" self.log("nudge", n=self.nudges, wake=self.wakes, virtual_time=_iso(sent_at), closing_text=closing, state=str(state), outcome=outcome, messages_to_user=len(messages), stay_quiet_calls=len(quiet), plain_reply_after=plain, tool_calls=term.tool_call_count, real_seconds=round(time.time() - t, 1), - trajectory_url=traj) + trajectory_url=traj, **which) self._sent(messages, after_nudge=True) if not _completed(state): self._failed(term.error_type or f"agent_turn_{_state_name(state)}", @@ -1751,6 +1760,7 @@ def _append_prompt_response(self, final_text: str) -> None: prompt_id=step.prompt_id, response=final_text, prompt_text=self._effective_prompt(), agent_trajectory_object_url=traj, agent_trajectory_object_prefix=step._trajectory_prefix(), target_agent_per_turn_trajectory_object_urls=self.per_turn_trajectory_urls or None, + target_agent_per_turn_trajectories=self.per_turn_trajectories or None, source_agent_per_turn_prompt_parts=self.per_turn_parts or None, tool_call_count=self.tool_calls, model=self.model, error_type=self.error_type, error_code=self.error_code, error_message=self.error, agent_session_id=self.final_task_id, @@ -1883,6 +1893,11 @@ def _task_zone(us: dict, clocks: list[dict]) -> str: return task_zone(us, clocks, "always_on") +async def _no_trajectory() -> tuple[None, None]: + """The native read of an agent whose card has no trajectory extension: nothing to read.""" + return None, None + + def _step_part(text: str, source: str) -> dict: """A line the step adds to a wake, marked so a reader can tell it from what the user or the world sent.""" return {"kind": "text", "text": text, "metadata": {"agentenv": {"source": source}}} diff --git a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py index 1b29396f3..255cb03d2 100644 --- a/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/always_on_agent_verifier.py @@ -63,9 +63,12 @@ JudgeOutputFormatSpec, get_judge_output_format_spec, ) +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import AtifDocuments, TurnSource +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import turns as turn_sources from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import ( TrajectoryFormatError, TurnEvents, + atif_turn_events, turn_events, ) from agent_env.task_step.task_steps.verifiers.rubrics_verifier import ( @@ -335,6 +338,9 @@ async def _assistant_harness(self, context: TaskStepContext, *, staged: bool) -> out["agent_card"] = card urls = [u for u in (response.target_agent_per_turn_trajectory_object_urls or []) if u] url = urls[-1] if urls else response.agent_trajectory_object_url + stored = [source for source in turn_sources(response) if source is not None] + if stored and stored[-1].atif: # an atif/1 copy carries no harness trace, so there are no settings to read + url = None if staged and url: try: reported = harness_usage(await asyncio.to_thread(self._read_trajectory_text, url)) @@ -392,9 +398,10 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom by_position = timeline is None if timeline is None: timeline = turns_by_position(prompt_response) + timeline, atif = _keyed_by_turn(timeline, prompt_response, by_position=by_position) urls = list(dict.fromkeys(e["trajectory_url"] for e in timeline if e.get("event") in ("agent_turn_end", "nudge") and e.get("trajectory_url"))) - turns = await self._read_turns(urls, _turn_names(timeline, by_position=by_position)) + turns = await self._read_turns(urls, _turn_names(timeline, by_position=by_position), atif) run = run_context or await load_run_context(context, prompt_response) # A run staged by position has no app changes to fill in. values = await self._change_values(context) if self.full_app_changes and not by_position else None @@ -408,15 +415,23 @@ async def stage_trajectory(self, context: TaskStepContext, prompt_response: Prom return StagedTrajectory(path=path, prompt_note=_files_note(path, staged, context_loss=_CONTEXT_LOSS_RUN.get()), record=staged.record) - async def _read_turns(self, urls: list[str], names: dict[str, str]) -> dict[str, Optional[TurnEvents]]: - """Each trajectory's events, by url; None for one that couldn't be read. One that breaks the harness labels it - carries raises ``UngradableRunError`` naming its wake (``names``).""" + async def _read_turns(self, urls: list[str], names: dict[str, str], + atif: dict[str, TurnSource]) -> dict[str, Optional[TurnEvents]]: + """Each trajectory's events, by url, an atif/1 turn's (``atif``, by its key) from its view; None for one that + couldn't be read. One that breaks the harness labels it carries raises ``UngradableRunError`` naming its wake + (``names``).""" gate = asyncio.Semaphore(STAGING_CONCURRENCY) + documents = AtifDocuments() + + def events(url: str) -> TurnEvents: + if url in atif: + return atif_turn_events(documents.view(atif[url])) + return turn_events(self._read_trajectory_text(url)) async def read(url: str) -> Optional[TurnEvents]: async with gate: try: - return await asyncio.to_thread(lambda: turn_events(self._read_trajectory_text(url))) + return await asyncio.to_thread(events, url) except TrajectoryFormatError as e: raise UngradableRunError( f"Verifier '{self.verifier_id}': {names.get(url, 'a turn')}'s trajectory ({url}) can't be " @@ -559,6 +574,28 @@ def turns_by_position(prompt_response: PromptResponse) -> list[dict]: return timeline +def _keyed_by_turn(timeline: list[dict], prompt_response: PromptResponse, *, + by_position: bool) -> tuple[list[dict], dict[str, TurnSource]]: + """The timeline with each atif/1 turn's ``trajectory_url`` made a key of its own, ``#`` + (a conversation's turns share one document), and the source of each such key. A turn is found by its index among + the per-turn trajectories: the ``turn`` the always_on step logged, or, by position, its place. A run with no atif/1 + turn is returned as it is.""" + sources = turn_sources(prompt_response) + if not any(source is not None and source.atif for source in sources): + return timeline, {} + keyed: list[dict] = [] + found: dict[str, TurnSource] = {} + for event in timeline: + index = (event.get("n") - 1 if isinstance(event.get("n"), int) else None) if by_position else event.get("turn") + source = sources[index] if isinstance(index, int) and 0 <= index < len(sources) else None + if event.get("event") in ("agent_turn_end", "nudge") and source is not None and source.atif: + key = f"{source.url}#{source.task_id}" + found[key] = source + event = {**event, "trajectory_url": key} + keyed.append(event) + return keyed, found + + def _turn_names(timeline: list[dict], *, by_position: bool) -> dict[str, str]: """Each trajectory's turn in words, by its url: "wake 4", "the nudge after wake 2", or by position "turn 3".""" names: dict[str, str] = {} diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py index 96f509ce9..713e05fea 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py @@ -1,6 +1,6 @@ """One agent turn's trajectory as what happened in it: the agent's text and each tool call with its input and result, from whichever format the agent stored it in (OTel spans, OpenInference's included; Claude Code's or Gemini's -stream-json). What each format repeats on every turn or call (the tool list, the conversation so far, signatures, token +stream-json), or from the turn's atif/1 view. What each format repeats on every turn or call (the tool list, the conversation so far, signatures, token counts) is dropped, and results are made readable: JSON envelopes unwrapped, email bodies decoded, images left out.""" from __future__ import annotations @@ -9,9 +9,14 @@ import binascii import json import re +from collections.abc import Mapping from dataclasses import dataclass from typing import Any, Optional +from agentenv_protocol.atif import FORMAT as ATIF, profile_of + +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import _by_call, _SubAgents, _text +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import _steps as _atif_steps from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( extract_final_response, is_tool_span, @@ -437,6 +442,47 @@ def _claude_code_events(items: list[dict]) -> list[dict]: return events +# ---- atif/1 ----------------------------------------------------------------------------------------------------------- +def atif_turn_events(view: Mapping[str, Any]) -> TurnEvents: + """One atif/1 turn's events, from its view (its A2A task cut out of the conversation's document, as + ``atif_turns.AtifDocuments.view`` gives it), in the shapes a native Claude Code turn's take: each agent step's + thinking and text, then its tool calls with their results; a sub-agent's events after the result that started it, + each naming it as ``subagent`` (the call that started it, as its ``parent_tool_use_id`` is natively); and the final, + the closing message, an error when the turn's task didn't complete.""" + events: list[dict] = [] + subagents = _SubAgents(view) + + def walk(trajectory: Mapping[str, Any], tag: dict) -> None: + for step in _atif_steps(trajectory): + if step.get("source") != "agent": + continue + if isinstance(step.get("reasoning_content"), str) and step["reasoning_content"].strip(): + events.append({"type": "thinking", "text": step["reasoning_content"], **tag}) + text = _text(step.get("message")) + if text.strip(): + events.append({"type": "text", "text": text, **tag}) + for call, results in _by_call(step): + event = None + if call is not None: + event = {**_call(str(call.get("function_name") or ""), call.get("tool_call_id"), + call.get("arguments")), **tag} + events.append(event) + for result in results: + if event is not None: + _settle(event, result.get("content"), profile_of(result).get("status") not in (None, "ok")) + for sub in subagents.started(trajectory, result): + walk(sub, {"subagent": sub.get("trajectory_id")}) + + walk(view, {}) + steps = _atif_steps(view) + closing = next((step for step in reversed(steps) + if step.get("source") == "agent" and _text(step.get("message")).strip()), None) + state = profile_of(steps[-1]).get("state") if steps else None + events.append({"type": "final", "text": _text(closing.get("message")) if closing else None, + "error": state not in (None, "completed")}) + return TurnEvents(ATIF, events, len(json.dumps(view))) + + # ---- Gemini stream-json ---------------------------------------------------------------------------------------------- def _gemini_events(items: list[dict]) -> list[dict]: """The prompt, assistant text (its ``delta`` chunks joined) and tool calls paired with their results by diff --git a/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index c309397d2..d94789bf5 100644 --- a/tst/data/verifier_golden/judge_inputs.json +++ b/tst/data/verifier_golden/judge_inputs.json @@ -2544,5 +2544,38 @@ ] } ] + }, + "always_on_atif_staged": { + "prompt": { + "sha256": "01b234920c6523077035db1f203b512a546e605e4b0b52f8e842c63d32d761fe", + "chars": 11549 + }, + "files": { + "/tmp/always_on_run//events.jsonl": { + "sha256": "be8a4ac97567a6f7b1d58d3964bbd402b43fd0c45ba0da8eb9f92756ff4c83e9", + "chars": 26443 + }, + "/tmp/always_on_run//index.md": { + "sha256": "e298b71fca2c39c8bb0a2b6664e3797ee47059d822001ea8c025fc3e5347195e", + "chars": 4947 + }, + "/tmp/always_on_run//triggers.jsonl": "", + "/tmp/always_on_run//wakes/wake_001.jsonl": { + "sha256": "4e945af581d31bd58c2ed2dd0933e2586f0ff334c3424de3aa8a061e27ed0f16", + "chars": 8124 + }, + "/tmp/always_on_run//wakes/wake_002.jsonl": { + "sha256": "a3ebf15e5662533572cfe8cd26a2c1b4c6bf8da844cafc3613c4a3b33e0c013d", + "chars": 8078 + }, + "/tmp/always_on_run//wakes/wake_003.jsonl": { + "sha256": "25f3022c96a010b21d2e50f9ce15341e5fc0f4fb88a5e10ec8f42a33e8e76141", + "chars": 4890 + }, + "/tmp/always_on_run//wakes/wake_004.jsonl": { + "sha256": "19afb8bc30fb6b487712fa44601a0471571e4eb0b48f1bfe4ac79a439ebf0f84", + "chars": 4831 + } + } } } 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 e7880ee07..9fc736cae 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 @@ -28,6 +28,7 @@ transcript_from_atif, ) from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter # noqa: E402 +from agent_env.task_step.task_steps.verifiers.judge_utils.turn_events import atif_turn_events, turn_events # noqa: E402 from tst.unit.agents.claude_code.agent import claude_code_atif # noqa: E402 FIXTURES = REPO / "tst" / "data" / "claude_code_atif" @@ -141,6 +142,23 @@ def test_a_judge_reads_each_recorded_turn_with_its_calls_results_answer_and_scre assert [event["tool"] for event in events if event["type"] == "tool_call" and event.get("subagent")] == ["Bash"] +@pytest.mark.parametrize("scenario", SCENARIOS) +def test_a_recorded_turns_copy_gives_a_judge_the_events_its_native_trajectory_does(scenario): + """always_on's judge stages each wake from its events. A copy gives the native turn's, but for a sub-agent's prompt, + which only native stdout carries (as a note), and its closing text, which only its transcript, so the copy, has.""" + data = json.loads((FIXTURES / f"{scenario}.json").read_text()) + document = replay(scenario).document + for turn in data["turns"]: + native = turn_events(json.dumps(turn["native"])).events + copied = atif_turn_events(task_document(document, [turn["turn"]["task_id"]])).events + if scenario == "subagent": + assert [e["type"] for e in native if e.get("subagent")] == ["note", "tool_call"] + assert [e["type"] for e in copied if e.get("subagent")] == ["tool_call", "text"] + native = [e for e in native if not (e["type"] == "note" and e.get("subagent"))] + copied = [e for e in copied if not (e["type"] == "text" and e.get("subagent"))] + assert copied == native + + def test_from_atif_reads_harbors_own_conversion_of_a_recorded_session(): harbor = json.loads((FIXTURES / "harbor" / "subagent.harbor.json").read_text()) tasks, _ = recorded("subagent") diff --git a/tst/unit/task_step/test_always_on_agent_verifier.py b/tst/unit/task_step/test_always_on_agent_verifier.py index 25edf9a2a..d5d5b7f0c 100644 --- a/tst/unit/task_step/test_always_on_agent_verifier.py +++ b/tst/unit/task_step/test_always_on_agent_verifier.py @@ -26,6 +26,7 @@ ) from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RUN_CONTEXT_PARTS, RubricsVerifierTaskStep from tst.unit.task_step.always_on_harness import Rig +from tst.util import atif_runs pytestmark = pytest.mark.usefixtures("local_stores") @@ -260,11 +261,27 @@ async def write_file_from_text(self, content, destination_path, **kwargs): self.files[destination_path] = content -def _staged_run(monkeypatch, *, object_url: bool = True) -> tuple[TaskStepContext, _Sandbox, dict[str, str]]: +def _staged_run(monkeypatch, *, object_url: bool = True, + atif_wakes: int = 0) -> tuple[TaskStepContext, _Sandbox, dict[str, str]]: """A recorded always_on run's context with a deployed judge; ``sources`` serves each stored trajectory: wake 2's - a Claude Code turn, wake 4's a PSI neutral harness v7 wake (Claude's: a save turn, a compaction, its own turn).""" + a Claude Code turn, wake 4's a PSI neutral harness v7 wake (Claude's: a save turn, a compaction, its own turn). + ``atif_wakes``: the run prescribed atif/1, its first wakes' copies (the ``two_turns`` fixture's tasks, one a wake) + are their trajectories, at the one url they share, and every wake's end names its turn, as the step logs it then.""" stored = json.loads((RECORDED / "always_on_timeline.json").read_text()) - urls = [e["trajectory_url"] for e in stored["timeline"] if e["event"] == "agent_turn_end"] + ends = [e for e in stored["timeline"] if e["event"] == "agent_turn_end"] + urls = [e["trajectory_url"] for e in ends] + records = None + if atif_wakes: + document, through = atif_runs.stored("two_turns", run="week"), atif_runs.through_steps("two_turns") + copied = ("task-91c2", "task-91c3")[:atif_wakes] + records = [] + for n, end in enumerate(ends): + if n < len(copied): + urls[n] = end["trajectory_url"] = document + records.append(atif_runs.record(document, copied[n], through[copied[n]])) + else: + records.append(atif_runs.native(f"task-{n}")) + end["turn"], end["trajectory_format"] = n, records[-1]["format"] record = {k: v for k, v in stored.items() if k != "timeline"} if object_url: record["object_url"] = get_config().get_object_store().put( @@ -274,6 +291,7 @@ def _staged_run(monkeypatch, *, object_url: bool = True) -> tuple[TaskStepContex ctx.prompt_responses.append(PromptResponse(prompt_id="ask", response="[Fri Nov 6] Dinner is booked", prompt_text="dinner for 7", step_id="week", target_agent_per_turn_trajectory_object_urls=urls, + target_agent_per_turn_trajectories=records, agent_trajectory_object_url=urls[-1])) ctx.deployed_agents.append(DeployedAgent(agent_name="judge", api_url="http://judge.test", a2a_url="http://judge.test", sandbox_id="sb-judge")) @@ -308,6 +326,23 @@ def read(url): return captured +@pytest.mark.asyncio +async def test_a_prescribed_runs_wakes_are_each_staged_from_their_own_task_of_the_copy(monkeypatch): + """Its wakes' copies share one document; each wake is staged from its own A2A task cut out of it, and the wakes + whose copies couldn't be had from their native trajectories.""" + ctx, sandbox, sources = _staged_run(monkeypatch, atif_wakes=2) + verifier = _verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge") + _agent_judge(monkeypatch, verifier, sources) + + await verifier.execute(ctx) + + [root] = {path.split("/")[3] for path in sandbox.files} + wake = {n: sandbox.files[f"/tmp/always_on_run/{root}/wakes/wake_00{n}.jsonl"] for n in range(1, 5)} + assert '"command": "pytest tests/test_parse.py -q"' in wake[1] and "test_offset" not in wake[1] + assert "def test_offset(): ..." in wake[2] and "pytest tests/test_parse.py" not in wake[2] + assert '"tool": "slow_search"' in wake[4] + + @pytest.mark.asyncio async def test_with_use_trajectory_the_agent_judge_searches_every_wake_staged_as_files(monkeypatch): ctx, sandbox, sources = _staged_run(monkeypatch) diff --git a/tst/unit/task_step/test_always_on_trajectory_formats.py b/tst/unit/task_step/test_always_on_trajectory_formats.py index f1bb0de3e..ec1f5e3a7 100644 --- a/tst/unit/task_step/test_always_on_trajectory_formats.py +++ b/tst/unit/task_step/test_always_on_trajectory_formats.py @@ -1,18 +1,72 @@ -"""always_on prescribes no format beside native to the agent it prompts, once, before its first wake, whatever the run -prescribes: until always_on reads atif/1 copies, its conversations build native only, even on an agent an earlier step -prescribed atif/1.""" +"""always_on prescribes the run's formats to the agent it prompts, once, before its first wake, and reads each turn's +trajectory as prompt_agent does: a run that prescribes atif/1 to an agent that offers it has each wake's and nudge's +atif/1 copy as its trajectory, read within the one fetch cap, and every turn records what its url holds.""" + +import asyncio import pytest +from agentenv_protocol.a2a_agent import TRAJECTORY_V1 +from agent_env.task_step.context import AtifRecord +from agent_env.task_step.snapshot_utils import atif_copies from agent_env.task_step.task_steps import always_on as ao +from agent_env.task_step.task_steps.prompt_agent import StoredTrajectory from tst.unit.task_step.always_on_harness import SOLVER, Rig pytestmark = pytest.mark.usefixtures("local_stores") +DOCUMENT = "file:///store/atif/instance_id=ti-1/solver/conversation.json" +TRAJECTORY = {"uri": TRAJECTORY_V1.uri, "params": { + "formats": ["shots/1", "atif/1"], "native": "shots/1", "default": "shots/1", + "methods": {"get": {"endpoint": "/ext/trajectory"}}}} + + +def _quiet(n, texts, rig): + rig.quiet() + return "" + + +def _nudged(n, texts, rig): + """The wake closes with text and neither messages nor stays quiet, so a nudge turn follows, in which it is quiet.""" + if n == 1: + return "All set." + rig.quiet() + return "" + + +def _offering(rig: Rig, prescribed: bool): + """A run whose solver's card offers atif/1 beside its native format, prescribing atif/1 or not.""" + context = rig.context() + solver = next(agent for agent in context.deployed_agents if agent.agent_name == "solver") + solver.a2a_card = {"capabilities": {"extensions": [TRAJECTORY]}} + if prescribed: + context.metadata["user_overrides"] = {"trajectory_formats": ["atif/1"]} + return context + + +def _reads(monkeypatch, *, copy_seconds: float = 0.0) -> dict[str, list]: + """Native reads and atif/1 copies, by task: each native read stored under its task, each copy a valid record of + the one conversation document, taking ``copy_seconds``.""" + seen: dict[str, list] = {"native": [], "copies": []} + + async def native(a2a_url, extension, task_id, prefix, name, **kwargs): + seen["native"].append(task_id) + return StoredTrajectory(f"file:///store/native-{task_id}.json", "shots/1") + + async def stored(self, task_id, name): + await asyncio.sleep(copy_seconds) + seen["copies"].append(task_id) + return AtifRecord(url=DOCUMENT, task_id=task_id, through_step=len(seen["copies"]) * 3, status="valid", rules=[], + reason=None, validator_version="v", adapter_version="a", aux_url=None, turn_context_url=None) + + monkeypatch.setattr(ao, "fetch_native_trajectory", native) + monkeypatch.setattr(atif_copies.AtifCopies, "_stored", stored) + return seen + @pytest.mark.asyncio @pytest.mark.parametrize("formats", [["atif/1"], None]) -async def test_always_on_prescribes_native_only_to_its_agent_before_its_first_wake(monkeypatch, tmp_path, formats): +async def test_always_on_prescribes_the_runs_formats_to_its_agent_before_its_first_wake(monkeypatch, tmp_path, formats): happened: list[tuple] = [] async def prescribe(context, step_id, agent, a2a_url, *, formats=None): @@ -32,6 +86,55 @@ def agent(n, texts, rig): await rig.run(rig.step(), context) - assert happened[0] == ("prescribe", "week", "solver", SOLVER, ()) + assert happened[0] == ("prescribe", "week", "solver", SOLVER, None) assert [event for event in happened if event[0] == "prescribe"] == [happened[0]] assert happened[1][0] == "wake" + + +@pytest.mark.asyncio +async def test_a_prescribed_runs_turns_are_their_atif_copies_each_named_in_the_timeline(monkeypatch, tmp_path): + seen = _reads(monkeypatch) + rig = Rig(monkeypatch, tmp_path, agent=_nudged) + await rig.arm() + context = await rig.run(rig.step(max_wakes=2), _offering(rig, prescribed=True)) + + [response] = context.prompt_responses + records = response.target_agent_per_turn_trajectories + assert seen["native"] == [] and len(seen["copies"]) == len(records) >= 2 + assert response.target_agent_per_turn_trajectory_object_urls == [DOCUMENT] * len(records) + assert [(r["format"], r["atif"]["status"], r["atif"]["task_id"]) for r in records] == [ + ("atif/1", "valid", task_id) for task_id in seen["copies"]] + ends = [e for e in rig.stored(context)["timeline"] if e["event"] in ("agent_turn_end", "nudge") and "state" in e] + assert [e["event"] for e in ends] == ["agent_turn_end", "nudge"] + assert [(e["turn"], e["trajectory_format"], e["trajectory_url"]) for e in ends] == [ + (n, "atif/1", DOCUMENT) for n in range(len(records))] + + +@pytest.mark.asyncio +async def test_a_copy_that_outlasts_the_fetch_cap_is_unavailable_and_the_wake_goes_on(monkeypatch, tmp_path): + _reads(monkeypatch, copy_seconds=5) + monkeypatch.setattr(ao, "TRAJECTORY_FETCH_SECONDS", 0.05) + rig = Rig(monkeypatch, tmp_path, agent=_quiet) + await rig.arm() + context = await rig.run(rig.step(max_wakes=1), _offering(rig, prescribed=True)) + + [response] = context.prompt_responses + assert response.target_agent_per_turn_trajectory_object_urls == [None] + [record] = response.target_agent_per_turn_trajectories + assert (record["format"], record["atif"]["status"], record["atif"]["reason"]) == (None, "unavailable", "timeout") + + +@pytest.mark.asyncio +async def test_a_run_that_prescribes_nothing_reads_native_and_names_no_turn_in_the_timeline(monkeypatch, tmp_path): + seen = _reads(monkeypatch) + rig = Rig(monkeypatch, tmp_path, agent=_nudged) + await rig.arm() + context = await rig.run(rig.step(max_wakes=2), _offering(rig, prescribed=False)) + + [response] = context.prompt_responses + assert seen["copies"] == [] and seen["native"] + assert response.target_agent_per_turn_trajectory_object_urls == [ + f"file:///store/native-{task_id}.json" for task_id in seen["native"]] + assert response.target_agent_per_turn_trajectories == [{"format": "shots/1", "atif": None}] * len(seen["native"]) + ends = [e for e in rig.stored(context)["timeline"] if e["event"] in ("agent_turn_end", "nudge")] + assert ends and all("turn" not in e and "trajectory_format" not in e for e in ends) diff --git a/tst/unit/task_step/verifiers/test_judge_inputs.py b/tst/unit/task_step/verifiers/test_judge_inputs.py index 7784c0489..03ff80196 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs.py @@ -400,6 +400,20 @@ async def judged(form): await _pinned("always_on_staged", judged) +@pytest.mark.asyncio +async def test_a_staged_always_on_judges_prompt_and_files_on_atif_wakes_are_pinned(monkeypatch): + run, sandbox, sources = A._staged_run(monkeypatch, atif_wakes=2) + + async def judged(form): + sandbox.files.clear() + verifier = A._verifier(use_agent_judge=True, use_trajectory=True, agent_name="judge") + captured = A._agent_judge(monkeypatch, verifier, sources) + await verifier.execute(form(copy.deepcopy(run))) + return {**captured, "files": dict(sorted(sandbox.files.items()))} + + await _pinned_atif("always_on_atif_staged", judged) + + def _user_sim_calls(fake: T.FakeModel) -> list[dict]: """What each of the user-sim judge's checks was sent, in an order its concurrency can't change.""" return sorted(({k: v for k, v in call.items() if k != "alongside"} for call in fake.calls), From 51f46bb810c0d97a54cb49fb0f27a118fcea95ca Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:11:22 -0800 Subject: [PATCH 02/10] feat(task-steps): a prescribed run follows each turn's atif/1 copy live, its media pulled as the pages come The live follow of a prompt step whose copy replaces native reads atif/1: each poll's new closed root steps are a page, the document's header is stored beside the page where it changed (versioned, so the greatest is the latest), each sub-agent's new steps and header go under sub//, and meta.json names the versions, the document's ids and the folder its media resolve in. Each page's media are pulled between polls into the run's atif folder through the copies' own record of what it holds, so the turn's copy asks for none of them again; nothing is pulled once the turn's drain starts. A turn the agent refuses atif/1 before any page was stored is followed natively; one refused after ends with end.json naming why, so a turn's pages never mix formats. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 6 +- .../a2a_agent/trajectory_follower.py | 45 ++++- .../task_step/snapshot_utils/atif_copies.py | 17 ++ .../snapshot_utils/live_trajectory.py | 123 +++++++++++-- .../task_step/task_steps/prompt_agent.py | 7 +- .../test_prompt_agent_atif_copies.py | 24 ++- .../task_step/test_prompt_agent_live_atif.py | 172 ++++++++++++++++++ 7 files changed, 369 insertions(+), 25 deletions(-) create mode 100644 tst/unit/task_step/test_prompt_agent_live_atif.py diff --git a/AGENTS.md b/AGENTS.md index 51ca19f7d..5a69a155d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -135,7 +135,11 @@ or one of them only where it is used. (`agentenv_protocol.atif.task_document`), its media read from the document's `media/` and checked against their names, any other turn as native; always_on's judge stages an `atif/1` wake from that task's events (`turn_events.atif_turn_events`), each such wake's end naming its turn in the step's timeline, since the turns share - one url. So prescribing atif/1 changes what a run's judges read and can move its scores. + one url. A prompt step that follows its turns live (`live_trajectory`) follows the copy too + (`snapshot_utils/live_trajectory.py`): each poll's new closed steps a page under `/live/`, the header beside the + page where it changed, each sub-agent's under `sub//`, and the media its steps name pulled between polls; a turn + the agent won't serve atif/1 is followed natively, and one it stops serving partway ends naming why (`end.json` + `stopped`). So prescribing atif/1 changes what a run's judges read and can move its scores. - Secrets never live in the file: use `secret:KEY` or `env:NAME` references, resolved through `[stores.secret]`. - agent-env has no stage concept: "dev" versus "prod" is which file `AGENT_ENV_CONFIG` names. A diff --git a/src/agent_env/a2a_agent/trajectory_follower.py b/src/agent_env/a2a_agent/trajectory_follower.py index daf20e0df..b8d31fedb 100644 --- a/src/agent_env/a2a_agent/trajectory_follower.py +++ b/src/agent_env/a2a_agent/trajectory_follower.py @@ -6,21 +6,23 @@ import logging from collections.abc import Awaitable, Callable, Mapping from contextlib import nullcontext -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any import httpx from agentenv_protocol.a2a_agent import ( + AtifEventsResponse, TaskEventsTrajectoryRequest, TrajectoryEventsResponse, TrajectoryState, card_request_accepts, request_fields, ) +from agentenv_protocol.atif import FORMAT as ATIF from agent_env.a2a_agent.a2a_agent import A2AAgent from agent_env.a2a_agent.object_transfer import parse_response -from agent_env.a2a_agent.protocol import raise_for_extension_status +from agent_env.a2a_agent.protocol import extension_error_code, raise_for_extension_status logger = logging.getLogger(__name__) @@ -30,12 +32,17 @@ _MAX_BACKOFF_SECONDS = 60 # Once stopped, the task has ended and its log is sealed, so the next read is normally the last. _STOPPED_INTERVAL_SECONDS = 0.2 +# What an agent answers for an atif/1 read it won't serve: the run didn't prescribe it, its adapter failed, or it builds +# no atif/1. +_ATIF_REFUSALS = frozenset({"format_not_prescribed", "atif_unavailable", "format_not_offered"}) @dataclass(frozen=True) class TrajectoryBatch: """Events ``after`` to ``next`` of a task's trajectory, as one read returned them; ``last`` - when the task has ended and no event remains unread.""" + when the task has ended and no event remains unread. An atif/1 read's also carry the document's ``header``, its + ``subagents`` as far as served and its versions; ``stopped`` names why an atif/1 follow ended before the task did + (the agent's refusal), with no events.""" after: int next: int @@ -43,6 +50,11 @@ class TrajectoryBatch: format: str | None state: TrajectoryState last: bool + header: dict[str, Any] | None = None + subagents: list[dict[str, Any]] = field(default_factory=list) + schema_version: str | None = None + profile_version: str | None = None + stopped: str | None = None TrajectorySink = Callable[[TrajectoryBatch], Awaitable[None]] @@ -69,17 +81,24 @@ async def follow_trajectory( client: httpx.AsyncClient | None = None, headers: Mapping[str, str] | None = None, format: str | None = None, + fallback_format: str | None = None, ) -> None: """Read task ``task_id``'s trajectory from its first event, handing ``sink`` each page that has events and the last one, until the task has ended and every event is read. Each read names ``format`` when given: only to a card that offers formats. + An atif/1 follow the agent refuses before any of its pages was stored goes on in ``fallback_format`` from the + task's first event; one refused after that hands ``sink`` a batch naming why it ``stopped`` and ends, so a turn's + pages never mix formats. + Between reads it waits ``poll_interval_seconds``, or less once ``stop`` is set. Transport errors and 5xx answers are retried with backoff until ``stop`` is set, and end following after it; a task the agent no longer knows (404) ends following.""" after = 0 failures = 0 + reading = format named = {"format": format} if format is not None else {} + stored_atif = False async with nullcontext(client) if client is not None else httpx.AsyncClient() as http: while True: try: @@ -92,6 +111,18 @@ async def follow_trajectory( return raise_for_extension_status(response, operation="trajectory get", include_body=True) except httpx.HTTPStatusError as exc: + refused = extension_error_code(exc.response) if reading == ATIF else None + if refused in _ATIF_REFUSALS: + if not stored_atif and fallback_format is not None: + logger.warning("Agent refused task %s's atif/1 trajectory (%s); following it as %s", + task_id, refused, fallback_format) + reading, named, after = fallback_format, {"format": fallback_format}, 0 + continue + logger.warning("Agent refused task %s's atif/1 trajectory (%s); stopped following it", + task_id, refused) + await sink(TrajectoryBatch(after=after, next=after, events=[], format=ATIF, + state=TrajectoryState.RUNNING, last=False, stopped=refused)) + return if exc.response.status_code < 500: raise failures += 1 @@ -101,9 +132,13 @@ async def follow_trajectory( logger.warning("Live trajectory read failed (consec=%d, will retry): %r", failures, exc) else: failures = 0 - page = parse_response(TrajectoryEventsResponse, response.json(), operation="trajectory get") + atif = reading == ATIF + page = parse_response(AtifEventsResponse if atif else TrajectoryEventsResponse, response.json(), + operation="trajectory get") last = page.state not in _OPEN_STATES and not page.has_more if page.events or last: + extra = ({"header": page.header, "subagents": page.subagents, "schema_version": page.schema_version, + "profile_version": page.profile_version} if atif else {}) await sink( TrajectoryBatch( after=after, @@ -112,9 +147,11 @@ async def follow_trajectory( format=page.format, state=page.state, last=last, + **extra, ) ) after = page.next + stored_atif = stored_atif or (atif and bool(page.events)) if last: return if page.has_more: diff --git a/src/agent_env/task_step/snapshot_utils/atif_copies.py b/src/agent_env/task_step/snapshot_utils/atif_copies.py index 869bfa2a1..33fbf0e17 100644 --- a/src/agent_env/task_step/snapshot_utils/atif_copies.py +++ b/src/agent_env/task_step/snapshot_utils/atif_copies.py @@ -154,6 +154,23 @@ async def read(self, index: int, task_id: str, name: str, record: TurnTrajectory f"{timeout:.0f}s (continuing)") return None + @property + def folder(self) -> str: + """The run's folder for this agent's copies, where their ``media/`` paths resolve.""" + return atif_folder(self._context, self._agent.agent_name) + + async def pull_live_media(self, document: Mapping[str, Any], session_id: Any) -> None: + """Pull into the run's folder the media a live page's steps (``document``) name that it lacks, as the turn's + copy does once the turn ends, so a reader of the live pages sees them as they come. The record of what the + folder holds is the copies', so nothing is asked for twice; a failure is logged and left to the copy's pull.""" + try: + store = get_config().get_object_store() + refs = _first_refs(document) + if refs: + await self._pull_media(refs, session_id, store, trajectory_prefix_key(store, self.folder)) + except Exception as exc: + logger.warning(f"agent '{self._agent.agent_name}': a live page's media pull failed (continuing): {exc}") + async def join(self) -> dict[int, str | None]: """Each copied turn's url, by its index, once every copy has been stored and its record filled; cancelled while waiting, it cancels the copies left.""" diff --git a/src/agent_env/task_step/snapshot_utils/live_trajectory.py b/src/agent_env/task_step/snapshot_utils/live_trajectory.py index 33176777e..6654d9cbe 100644 --- a/src/agent_env/task_step/snapshot_utils/live_trajectory.py +++ b/src/agent_env/task_step/snapshot_utils/live_trajectory.py @@ -4,6 +4,13 @@ ``canceled`` or ``failed`` when the step stopped first. A follower that stopped early leaves ``end.json``'s ``next`` short of the turn's events; the final trajectory holds them all. +An atif/1 turn's pages hold its closed root steps, one per line, named by the step ids they run between; the document's +header (its root without steps) is ``-..header.json`` beside the page where it changed, ``n`` counting +the header's versions, so the greatest is the latest; each sub-agent's new steps and header go the same way under +``sub//``; ``meta.json`` also names the schema and profile versions, the document's session and +trajectory ids and ``media_base``, the folder its ``media/`` paths resolve in; ``end.json`` says why a follow the agent +refused partway ``stopped``. The latest header with every page's steps is a prefix of the turn's stored copy. + A step's turns are linked in order: each sent turn's ``next.json`` is ``{"turn": ""}``, naming the turn sent after it, or ``{"turn": null}`` once the step has ended, so a reader of one turn goes on to the next and knows when the step is over. @@ -13,12 +20,16 @@ from __future__ import annotations import asyncio +import hashlib import json import logging -from collections.abc import AsyncIterator, Awaitable, Mapping +import re +from collections.abc import AsyncIterator, Awaitable, Callable, Mapping from contextlib import asynccontextmanager +from typing import Any, Optional from agentenv_protocol.a2a_agent import TrajectoryState +from agentenv_protocol.atif import FORMAT as ATIF from agent_env.a2a_agent.trajectory_follower import TrajectoryBatch, follow_trajectory from agent_env.store.base import ObjectAlreadyExistsError @@ -33,26 +44,48 @@ _PASSING_WRITE_SECONDS = 5 # The A2A task states a turn's trajectory ends in as themselves; any other (failed, rejected) ends it failed. _ENDED_AS = {"completed": TrajectoryState.COMPLETED, "canceled": TrajectoryState.CANCELED} +# A sub-agent's trajectory id names its folder, so only a plain file name does. +_SUB_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}") +#: Pulls a live atif/1 page's media into the run's folder: the page's steps as a document, and its session. +LiveMedia = Callable[[Mapping[str, Any], Any], Awaitable[None]] class LiveTrajectoryChunks: """The ``follow_trajectory`` sink that stores one turn's pages.""" - def __init__(self, store: ObjectStore, prefix_key: str, turn_id: str) -> None: + def __init__(self, store: ObjectStore, prefix_key: str, turn_id: str, *, media: Optional[LiveMedia] = None, + media_base: Optional[str] = None, stop: Optional[asyncio.Event] = None) -> None: self._store = store self._directory = f"{prefix_key}{turn_id}/live/" self._format_written = False self._stored = 0 self._storing: asyncio.Future | None = None self._ended = False + self._media, self._media_base, self._stop = media, media_base, stop + self._headers: dict[str, tuple[str, int]] = {} # each trajectory's folder: its header's digest, versions + self._sub_steps: dict[str, int] = {} # each sub-agent's folder: the last step id stored + self._session: Any = None + self._stopped: Optional[str] = None + #: The media pulls this turn's pages started, cancelled once it ends: its copy's own pull takes what's left. + self.pulls: list[asyncio.Task] = [] async def __call__(self, batch: TrajectoryBatch) -> None: - if batch.events: + if batch.stopped: + self._stopped = batch.stopped + return + atif = batch.format == ATIF + if batch.events or (atif and (batch.header is not None or batch.subagents)): # Shielded, so a cancelled follower's write still counts its events: ``end`` waits for it. - self._storing = asyncio.ensure_future(self._store_events(batch)) + self._storing = asyncio.ensure_future(self._store_atif(batch) if atif else self._store_events(batch)) await asyncio.shield(self._storing) if batch.format and not self._format_written: - await self._put("meta.json", json.dumps({"format": batch.format}).encode(), "application/json") + meta: dict[str, Any] = {"format": batch.format} + if atif: + header = batch.header or {} + meta.update(schema_version=batch.schema_version, profile_version=batch.profile_version, + session_id=header.get("session_id"), trajectory_id=header.get("trajectory_id"), + media_base=self._media_base) + await self._put("meta.json", json.dumps(meta).encode(), "application/json") self._format_written = True if batch.last: await self.end(batch.state) @@ -62,13 +95,57 @@ async def _store_events(self, batch: TrajectoryBatch) -> None: await self._put(f"{batch.after:08d}-{batch.next:08d}.jsonl", body, "application/x-ndjson") self._stored = batch.next + async def _store_atif(self, batch: TrajectoryBatch) -> None: + """An atif/1 page: its root steps, the header when it changed, each sub-agent's new steps and header; then, + while the turn runs, a pull of the media these new steps name.""" + name = f"{batch.after:08d}-{batch.next:08d}" + if batch.events: + await self._put(f"{name}.jsonl", _lines(batch.events), "application/x-ndjson") + if batch.header is not None: + self._session = batch.header.get("session_id", self._session) + await self._header("", name, batch.header) + new_subs = [sub for found in [await self._store_sub(s, "sub/") for s in batch.subagents] for sub in found] + self._stored = batch.next + if self._media is not None and not (self._stop is not None and self._stop.is_set()): + steps = {"steps": list(batch.events), "subagent_trajectories": new_subs} + if batch.events or new_subs: + self.pulls.append(asyncio.ensure_future(self._media(steps, self._session))) + + async def _store_sub(self, sub: Any, path: str) -> list[dict[str, Any]]: + """A sub-agent's steps not stored yet and its header if it changed, under ``path``; and its embedded sub-agents + the same way, under its folder. Returns each trajectory with only its new steps, for the media they name.""" + trajectory_id = sub.get("trajectory_id") if isinstance(sub, Mapping) else None + if not isinstance(trajectory_id, str) or not _SUB_ID.fullmatch(trajectory_id): + return [] + where = f"{path}{trajectory_id}/" + last = self._sub_steps.get(where, 0) + steps = [step for step in sub.get("steps") or [] if isinstance(step, Mapping) + and isinstance(step.get("step_id"), int) and step["step_id"] > last] + name = f"{last:08d}-{(steps[-1]['step_id'] if steps else last):08d}" + if steps: + await self._put(f"{where}{name}.jsonl", _lines(steps), "application/x-ndjson") + self._sub_steps[where] = steps[-1]["step_id"] + await self._header(where, name, {k: v for k, v in sub.items() if k not in ("steps", "subagent_trajectories")}) + found = [{"steps": steps}] if steps else [] + for child in sub.get("subagent_trajectories") or []: + found += await self._store_sub(child, f"{where}sub/") + return found + + async def _header(self, where: str, name: str, header: Mapping[str, Any]) -> None: + body = json.dumps(header, separators=(",", ":"), sort_keys=True).encode() + digest = hashlib.sha256(body).hexdigest() + seen, versions = self._headers.get(where, (None, 0)) + if digest != seen: + await self._put(f"{where}{name}.{versions + 1:04d}.header.json", body, "application/json") + self._headers[where] = (digest, versions + 1) + async def end(self, state: TrajectoryState) -> None: """Mark the turn ended in ``state`` after the events stored so far; the first mark stays.""" if self._ended: return if self._storing is not None: await asyncio.wait({self._storing}) - end = {"state": state.value, "next": self._stored} + end = {"state": state.value, "next": self._stored, **({"stopped": self._stopped} if self._stopped else {})} await self._put("end.json", json.dumps(end).encode(), "application/json") self._ended = True @@ -90,10 +167,14 @@ def __init__( previous_turn_id: str | None, headers: Mapping[str, str], format: str | None = None, + fallback_format: str | None = None, + media: Optional[LiveMedia] = None, + media_base: Optional[str] = None, ) -> None: self._endpoint = endpoint self._headers = headers self._format = format + self._fallback_format, self._media, self._media_base = fallback_format, media, media_base self._store = store self._prefix_key = prefix_key self._turn_id = turn_id @@ -111,13 +192,14 @@ def follow(self, task_id: str) -> None: self.links.append( asyncio.create_task(_in_passing(linking, self._previous_turn_id, f"linked to turn {self._turn_id}")) ) - sink = LiveTrajectoryChunks(self._store, self._prefix_key, self._turn_id) + sink = LiveTrajectoryChunks(self._store, self._prefix_key, self._turn_id, media=self._media, + media_base=self._media_base, stop=self.stop) self.sinks.append(sink) self.followers.append( asyncio.create_task( follow_trajectory( self._endpoint, task_id, sink, poll_interval_seconds=self._poll_interval_seconds, stop=self.stop, - headers=self._headers, format=self._format, + headers=self._headers, format=self._format, fallback_format=self._fallback_format, ) ) ) @@ -138,6 +220,9 @@ async def following_live_trajectory( headers: Mapping[str, str], previous_turn_id: str | None = None, format: str | None = None, + fallback_format: str | None = None, + media: Optional[LiveMedia] = None, + media_base: Optional[str] = None, ) -> AsyncIterator[LiveTurn]: """Yield the turn whose task is followed once its message is sent; then ``previous_turn_id``'s ``next.json`` names it. @@ -146,8 +231,10 @@ async def following_live_trajectory( raises, the follower is stopped at once, since the agent may be gone. Either way, a turn whose end the follower did not read is marked ended in the state the body reported, else ``canceled`` for a cancelled step or ``failed``, so readers do not wait on it. A follower's own failure is - logged and never fails the turn.""" - turn = LiveTurn(endpoint, store, prefix_key, turn_id, poll_interval_seconds, previous_turn_id, headers, format) + logged and never fails the turn. The media pulls a turn's atif/1 pages started are cancelled once it ends: the + turn's copy pulls what's left, off the turn's path.""" + turn = LiveTurn(endpoint, store, prefix_key, turn_id, poll_interval_seconds, previous_turn_id, headers, format, + fallback_format, media, media_base) stopped_as = TrajectoryState.FAILED try: @@ -175,6 +262,11 @@ async def following_live_trajectory( logger.warning( "Live trajectory of turn %s stopped (continuing): %r", turn_id, follower.exception() ) + pulls = [pull for sink in turn.sinks for pull in sink.pulls] + for pull in pulls: + pull.cancel() + if pulls: + await asyncio.wait(pulls) if turn.links: await asyncio.wait(turn.links) if turn.sinks: @@ -187,10 +279,12 @@ class LiveTurns: ``next.json``, and ``end`` marks the last turn sent as the step's last.""" def __init__(self, endpoint: str, store: ObjectStore, prefix_key: str, *, poll_interval_seconds: float, - headers: Mapping[str, str], format: str | None = None) -> None: + headers: Mapping[str, str], format: str | None = None, fallback_format: str | None = None, + media: Optional[LiveMedia] = None, media_base: Optional[str] = None) -> None: self._endpoint = endpoint self._headers = headers self._format = format + self._fallback_format, self._media, self._media_base = fallback_format, media, media_base self._store = store self._prefix_key = prefix_key self._poll_interval_seconds = poll_interval_seconds @@ -208,6 +302,9 @@ async def following(self, turn_id: str) -> AsyncIterator[LiveTurn]: headers=self._headers, previous_turn_id=self._last_sent, format=self._format, + fallback_format=self._fallback_format, + media=self._media, + media_base=self._media_base, ) as turn: try: yield turn @@ -222,6 +319,10 @@ async def end(self) -> None: await _in_passing(ending, self._last_sent, "marked last") +def _lines(items: list[Any]) -> bytes: + return b"".join(json.dumps(item, separators=(",", ":")).encode() + b"\n" for item in items) + + async def _link(store: ObjectStore, prefix_key: str, turn_id: str, next_turn_id: str | None) -> None: """Write ``turn_id``'s ``next.json``: the turn sent after it, or None after the step's last.""" body = json.dumps({"turn": next_turn_id}).encode() diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index e503ae082..b8af078b1 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -656,9 +656,14 @@ async def _converse( atif_copies = AtifCopies(context, agent, target_url, traj_ext_cached, prescribed=ATIF_FORMAT in prescribed_formats(context)) live = self._live_trajectory_target(context, card, target_url, trajectory_output_prefix) + # A run whose copy replaces native follows atif/1 live too, its media pulled as its pages come. + copied = atif_copies.replaces_native live_turns = ( LiveTurns(*live, poll_interval_seconds=self.poll_interval_seconds, headers=agent.control_headers, - format=formats.native) + format=ATIF_FORMAT if copied else formats.native, + fallback_format=formats.native if copied else None, + media=atif_copies.pull_live_media if copied else None, + media_base=atif_copies.folder if copied else None) if live is not None else None ) final_state: str = TaskState.completed.value diff --git a/tst/unit/task_step/test_prompt_agent_atif_copies.py b/tst/unit/task_step/test_prompt_agent_atif_copies.py index 77e93dbc8..5b62dfac3 100644 --- a/tst/unit/task_step/test_prompt_agent_atif_copies.py +++ b/tst/unit/task_step/test_prompt_agent_atif_copies.py @@ -48,19 +48,26 @@ def shot(self, record: dict, turn) -> None: turn.step(key=f"s{record['n']}", llm_call_count=1) -def _app(*, atif: bool = True): - """An agent that, each turn, appends one shot, a new screenshot each time, and answers.""" +def _app(*, atif: bool = True, live: bool = False, pause: float = 0.0): + """An agent that, each turn, appends one shot, a new screenshot each time, and answers; with ``pause``, a second + shot, then a third after that long, so a live reader sees the first closed while the turn runs (a step closes when + the next begins).""" shots = iter(range(1, 1000)) @a2a_agent( identity=AgentIdentity(name="solver", description="test", version="1"), - extensions=(enable(TRAJECTORY_V1, live=False, native=NATIVE, **({"atif": _Shots} if atif else {})),), + extensions=(enable(TRAJECTORY_V1, live=live, native=NATIVE, **({"atif": _Shots} if atif else {})),), ) class Agent(AgentEnvAgent): async def run(self, request: TaskRequest) -> TaskResult: request.trajectory.set_format(NATIVE) n = next(shots) request.trajectory.append({"type": "shot", "n": n, "png": base64.b64encode(png(n, 1)).decode()}) + if pause: + for wait in (0, pause): + await asyncio.sleep(wait) + n = next(shots) + request.trajectory.append({"type": "shot", "n": n, "png": base64.b64encode(png(n, 1)).decode()}) return TaskResult.text(f"shot {n}") return Agent().create_app() @@ -70,9 +77,9 @@ class _Wire(httpx.AsyncBaseTransport): """The agent at ``http://agent.test``, served in-process, and the store's grant URLs, which write into the store. A test can hold the agent's atif/1 reads until it lets them go, rewrite their answers, or rewrite any answer.""" - def __init__(self, store: GrantingObjectStore, *, atif: bool) -> None: + def __init__(self, store: GrantingObjectStore, *, atif: bool, live: bool = False, pause: float = 0.0) -> None: self.store = store - self._atif = atif + self._atif, self._live, self._pause = atif, live, pause self.restart() self.atif_reads: list[dict] = [] self.native_reads: list[dict] = [] @@ -88,7 +95,7 @@ def __init__(self, store: GrantingObjectStore, *, atif: bool) -> None: self.unreachable: set[str] = set() def restart(self) -> None: - self.app = _app(atif=self._atif) + self.app = _app(atif=self._atif, live=self._live, pause=self._pause) self._agent = httpx.ASGITransport(app=self.app) async def handle_async_request(self, request: httpx.Request) -> httpx.Response: @@ -125,13 +132,14 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: class _Run: - def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, atif: bool = True) -> None: + def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, atif: bool = True, live: bool = False, + pause: float = 0.0) -> None: monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) self.root = tmp_path / "store" self.store = GrantingObjectStore(str(self.root), reaches=True) configure(object_store=self.store) quiet_conversations(monkeypatch) - self.wire = _Wire(self.store, atif=atif) + self.wire = _Wire(self.store, atif=atif, live=live, pause=pause) self.asked: list[int] = [] route_clients(monkeypatch, self.wire) diff --git a/tst/unit/task_step/test_prompt_agent_live_atif.py b/tst/unit/task_step/test_prompt_agent_live_atif.py new file mode 100644 index 000000000..167020795 --- /dev/null +++ b/tst/unit/task_step/test_prompt_agent_live_atif.py @@ -0,0 +1,172 @@ +"""A prompt step of a run that prescribes atif/1 follows each turn's atif/1 copy live: each poll's new closed steps a +page, the document's header beside the page where it changed, the media the steps name pulled as they come, and the +pages a prefix of the turn's stored copy; a turn the agent won't serve atif/1 is followed natively, and one it stops +serving partway ends with the reason. Against a live SDK agent served in-process.""" +from __future__ import annotations + +import asyncio +import json +from pathlib import Path + +import httpx +import pytest +from agentenv_protocol.a2a_agent import TrajectoryState +from agentenv_protocol.atif import FORMAT as ATIF, media_paths, tasks + +from agent_env.a2a_agent.trajectory_follower import TrajectoryBatch, follow_trajectory +from agent_env.task_step.snapshot_utils import atif_copies +from agent_env.task_step.snapshot_utils.live_trajectory import LiveTrajectoryChunks +from tst.unit.task_step.test_prompt_agent_atif_copies import _PREFIX, NATIVE, _atifs, _Run +from tst.util.granting_object_store import GrantingObjectStore + +pytestmark = pytest.mark.usefixtures("local_stores") + + +def _live(run: _Run) -> dict[str, dict[str, bytes]]: + """Each turn's live folder, by turn id: its files by name under ``live/``.""" + turns: dict[str, dict[str, bytes]] = {} + for key in run.store.list(_PREFIX): + rest = key[len(_PREFIX):] + if "/live/" in rest: + turn, name = rest.split("/live/", 1) + turns.setdefault(turn, {})[name] = run.store.read(key) + return turns + + +def _reassembled(files: dict[str, bytes]) -> tuple[dict, list[dict]]: + """A turn's live document as a reader rebuilds it: the latest root header and every page's steps, in order.""" + headers = sorted(name for name in files if "/" not in name and name.endswith(".header.json")) + pages = sorted(name for name in files if "/" not in name and name.endswith(".jsonl")) + steps = [json.loads(line) for page in pages for line in files[page].splitlines() if line] + return json.loads(files[headers[-1]]), steps + + +@pytest.mark.asyncio +async def test_a_prescribed_turn_is_followed_as_atif_and_its_pages_are_a_prefix_of_its_stored_copy(monkeypatch, + tmp_path): + run = _Run(monkeypatch, tmp_path, live=True) + context = run.context() + + response = await run.execute(context, live_trajectory=True) + + final = run.read(_atifs(response)[-1]["url"]) + turns = _live(run) + assert len(turns) == 2 + for task, (turn, files) in zip(tasks(final), sorted(turns.items(), key=lambda kv: json.loads( + kv[1]["meta.json"])["trajectory_id"] + kv[0])): + meta = json.loads(files["meta.json"]) + assert meta["format"] == ATIF and meta["trajectory_id"] == final["trajectory_id"] + assert meta["session_id"] == final["session_id"] and meta["media_base"] == atif_copies.atif_folder( + context, "solver") + header, steps = _reassembled(files) + assert header["trajectory_id"] == final["trajectory_id"] and header["agent"] == final["agent"] + assert json.loads(files["end.json"]) == {"state": "completed", "next": steps[-1]["step_id"]} + live_steps = [step for files in turns.values() for step in _reassembled(files)[1]] + assert sorted(step["step_id"] for step in live_steps) == [step["step_id"] for step in final["steps"]] + by_id = {step["step_id"]: step for step in final["steps"]} + assert all(step == by_id[step["step_id"]] for step in live_steps) + + +@pytest.mark.asyncio +async def test_a_turns_header_is_stored_once_per_change_not_once_a_page(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path, live=True, pause=0.3) + + await run.execute(run.context(), live_trajectory=True, max_conversation_turns=1) + + [files] = _live(run).values() + headers = [name for name in files if name.endswith(".header.json")] + pages = [name for name in files if name.endswith(".jsonl")] + assert json.loads(files["meta.json"])["format"] == ATIF and len(pages) >= 2 + assert 1 <= len({files[name] for name in headers}) == len(headers) < len(pages) + 1 + + +@pytest.mark.asyncio +async def test_a_turn_whose_atif_read_is_refused_is_followed_natively(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path, live=True) + run.wire.unreachable.add("/ext/trajectory/prescribe") + + response = await run.execute(run.context(), live_trajectory=True, max_conversation_turns=1) + + assert [atif["reason"] for atif in _atifs(response)] == ["format_not_prescribed"] + [files] = _live(run).values() + assert json.loads(files["meta.json"]) == {"format": NATIVE} + assert not [name for name in files if name.endswith(".header.json")] + + +@pytest.mark.asyncio +async def test_a_live_pages_media_are_pulled_while_the_turn_runs(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path, live=True, pause=0.5) + pulled: list[list[str]] = [] + pull = atif_copies.AtifCopies.pull_live_media + + async def spy(self, document, session_id): + pulled.append(sorted(media_paths(document))) + await pull(self, document, session_id) + + monkeypatch.setattr(atif_copies.AtifCopies, "pull_live_media", spy) + context = run.context() + + response = await run.execute(context, live_trajectory=True, max_conversation_turns=1) + + [atif] = _atifs(response) + first_shot = media_paths({"steps": tasks(run.read(atif["url"]))[0].steps[:2]}) + assert first_shot and any(set(first_shot) <= set(names) for names in pulled) + assert atif["status"] == "valid" + held = {path.name for path in (run.folder(context) / "media").glob("*")} + assert {Path(name).name for names in pulled for name in names} <= held + + +@pytest.mark.asyncio +async def test_an_atif_follow_the_agent_refuses_after_its_pages_were_stored_ends_naming_why(tmp_path): + """Its pages never mix formats: the follow stops and end.json says why, the turn's final copy unaffected.""" + store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) + reads = iter([ + httpx.Response(200, json={"context_id": "c", "task_id": "t", "state": "running", "format": ATIF, + "schema_version": "ATIF-v1.8", "profile_version": "1.0", + "header": {"session_id": "c", "trajectory_id": "d"}, + "events": [{"step_id": 1, "source": "user", "message": "go"}], "next": 1, + "has_more": False}), + httpx.Response(409, json={"error": {"code": "atif_unavailable", "message": "the adapter failed"}}), + ]) + client = httpx.AsyncClient(transport=httpx.MockTransport(lambda request: next(reads))) + sink = LiveTrajectoryChunks(store, "p/", "turn-1") + + await follow_trajectory("http://agent.test/ext/trajectory", "t", sink, poll_interval_seconds=0, + stop=asyncio.Event(), client=client, format=ATIF, fallback_format=NATIVE) + await sink.end(TrajectoryState.FAILED) + + assert json.loads(store.read("p/turn-1/live/end.json")) == {"state": "failed", "next": 1, + "stopped": "atif_unavailable"} + assert json.loads(store.read("p/turn-1/live/meta.json"))["format"] == ATIF + assert store.read("p/turn-1/live/00000000-00000001.jsonl").count(b"\n") == 1 + + +@pytest.mark.asyncio +async def test_a_sub_agents_new_steps_and_changed_header_are_stored_under_its_folder_as_they_come(tmp_path): + """A page carries each sub-agent as far as it's served; only what wasn't stored yet is written, a nested one too.""" + store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) + sink = LiveTrajectoryChunks(store, "p/", "turn-1") + + def sub(n: int, *, nested: int = 0) -> dict: + inner = [{"trajectory_id": "inner", "agent": {"name": "helper"}, + "steps": [{"step_id": k, "source": "agent", "message": f"i{k}"} for k in range(1, nested + 1)]}] + return {"trajectory_id": "toolu_1", "agent": {"name": "explorer"}, + "steps": [{"step_id": k, "source": "agent", "message": f"s{k}"} for k in range(1, n + 1)], + **({"subagent_trajectories": inner} if nested else {})} + + def batch(after: int, nxt: int, subagent: dict) -> TrajectoryBatch: + return TrajectoryBatch(after=after, next=nxt, events=[{"step_id": nxt, "source": "agent", "message": "r"}], + format=ATIF, state=TrajectoryState.RUNNING, last=False, header={"session_id": "c"}, + subagents=[subagent], schema_version="ATIF-v1.8", profile_version="1.0") + + await sink(batch(0, 1, sub(2))) + await sink(batch(1, 2, sub(3, nested=1))) + await sink(batch(2, 3, sub(3, nested=1))) + + names = sorted(key[len("p/turn-1/live/"):] for key in store.list("p/turn-1/live/")) + assert [n for n in names if n.startswith("sub/toolu_1/") and n.endswith(".jsonl") and "/sub/" not in n[4:]] == [ + "sub/toolu_1/00000000-00000002.jsonl", "sub/toolu_1/00000002-00000003.jsonl"] + assert [n for n in names if n.startswith("sub/toolu_1/") and n.endswith(".header.json") and "/sub/" not in n[4:]] \ + == ["sub/toolu_1/00000000-00000002.0001.header.json"] + assert "sub/toolu_1/sub/inner/00000000-00000001.jsonl" in names + assert [n for n in names if n.endswith(".header.json") and "/" not in n] == ["00000000-00000001.0001.header.json"] From 6bd02f03cc4b8a707878623950e7d227076557f6 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:59:45 -0800 Subject: [PATCH 03/10] test(task-steps): the live atif/1 tests hold the agent's turn on an event, not a sleep The live media test failed on a loaded Linux runner: no poll fell in the 0.5 s pause, so the first screenshot's page came in the drain, which pulls nothing. The agent now holds its turn until the follower has pulled a page's media (the header test: stored a page), at most 30 s, so the mid-turn page is certain. Co-Authored-By: Claude Opus 5.5 --- .../test_prompt_agent_atif_copies.py | 28 +++++++++++-------- .../task_step/test_prompt_agent_live_atif.py | 17 +++++++++-- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/tst/unit/task_step/test_prompt_agent_atif_copies.py b/tst/unit/task_step/test_prompt_agent_atif_copies.py index 5b62dfac3..2674c96ae 100644 --- a/tst/unit/task_step/test_prompt_agent_atif_copies.py +++ b/tst/unit/task_step/test_prompt_agent_atif_copies.py @@ -6,6 +6,7 @@ import asyncio import base64 +import contextlib import json from pathlib import Path from typing import Any, Callable @@ -48,10 +49,10 @@ def shot(self, record: dict, turn) -> None: turn.step(key=f"s{record['n']}", llm_call_count=1) -def _app(*, atif: bool = True, live: bool = False, pause: float = 0.0): - """An agent that, each turn, appends one shot, a new screenshot each time, and answers; with ``pause``, a second - shot, then a third after that long, so a live reader sees the first closed while the turn runs (a step closes when - the next begins).""" +def _app(*, atif: bool = True, live: bool = False, gate: asyncio.Event | None = None): + """An agent that, each turn, appends one shot, a new screenshot each time, and answers; with ``gate``, a second + shot, then a third once ``gate`` is set (at most 30 s on), so a live reader sees the first closed while the turn runs + (a step closes when the next begins).""" shots = iter(range(1, 1000)) @a2a_agent( @@ -63,9 +64,11 @@ async def run(self, request: TaskRequest) -> TaskResult: request.trajectory.set_format(NATIVE) n = next(shots) request.trajectory.append({"type": "shot", "n": n, "png": base64.b64encode(png(n, 1)).decode()}) - if pause: - for wait in (0, pause): - await asyncio.sleep(wait) + if gate is not None: + for held in (False, True): + if held: + with contextlib.suppress(TimeoutError): + await asyncio.wait_for(gate.wait(), 30) n = next(shots) request.trajectory.append({"type": "shot", "n": n, "png": base64.b64encode(png(n, 1)).decode()}) return TaskResult.text(f"shot {n}") @@ -77,9 +80,10 @@ class _Wire(httpx.AsyncBaseTransport): """The agent at ``http://agent.test``, served in-process, and the store's grant URLs, which write into the store. A test can hold the agent's atif/1 reads until it lets them go, rewrite their answers, or rewrite any answer.""" - def __init__(self, store: GrantingObjectStore, *, atif: bool, live: bool = False, pause: float = 0.0) -> None: + def __init__(self, store: GrantingObjectStore, *, atif: bool, live: bool = False, + gate: asyncio.Event | None = None) -> None: self.store = store - self._atif, self._live, self._pause = atif, live, pause + self._atif, self._live, self._gate = atif, live, gate self.restart() self.atif_reads: list[dict] = [] self.native_reads: list[dict] = [] @@ -95,7 +99,7 @@ def __init__(self, store: GrantingObjectStore, *, atif: bool, live: bool = False self.unreachable: set[str] = set() def restart(self) -> None: - self.app = _app(atif=self._atif, live=self._live, pause=self._pause) + self.app = _app(atif=self._atif, live=self._live, gate=self._gate) self._agent = httpx.ASGITransport(app=self.app) async def handle_async_request(self, request: httpx.Request) -> httpx.Response: @@ -133,13 +137,13 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: class _Run: def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, atif: bool = True, live: bool = False, - pause: float = 0.0) -> None: + gate: asyncio.Event | None = None) -> None: monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) self.root = tmp_path / "store" self.store = GrantingObjectStore(str(self.root), reaches=True) configure(object_store=self.store) quiet_conversations(monkeypatch) - self.wire = _Wire(self.store, atif=atif, live=live, pause=pause) + self.wire = _Wire(self.store, atif=atif, live=live, gate=gate) self.asked: list[int] = [] route_clients(monkeypatch, self.wire) diff --git a/tst/unit/task_step/test_prompt_agent_live_atif.py b/tst/unit/task_step/test_prompt_agent_live_atif.py index 167020795..cbd2b6c03 100644 --- a/tst/unit/task_step/test_prompt_agent_live_atif.py +++ b/tst/unit/task_step/test_prompt_agent_live_atif.py @@ -69,7 +69,16 @@ async def test_a_prescribed_turn_is_followed_as_atif_and_its_pages_are_a_prefix_ @pytest.mark.asyncio async def test_a_turns_header_is_stored_once_per_change_not_once_a_page(monkeypatch, tmp_path): - run = _Run(monkeypatch, tmp_path, live=True, pause=0.3) + stored = asyncio.Event() + store_atif = LiveTrajectoryChunks._store_atif + + async def storing(self, batch): + await store_atif(self, batch) + if batch.events: + stored.set() + + monkeypatch.setattr(LiveTrajectoryChunks, "_store_atif", storing) + run = _Run(monkeypatch, tmp_path, live=True, gate=stored) await run.execute(run.context(), live_trajectory=True, max_conversation_turns=1) @@ -95,13 +104,17 @@ async def test_a_turn_whose_atif_read_is_refused_is_followed_natively(monkeypatc @pytest.mark.asyncio async def test_a_live_pages_media_are_pulled_while_the_turn_runs(monkeypatch, tmp_path): - run = _Run(monkeypatch, tmp_path, live=True, pause=0.5) + """The agent holds its turn open until a page's media were pulled, so the pull can only have come mid-turn.""" + held = asyncio.Event() + run = _Run(monkeypatch, tmp_path, live=True, gate=held) pulled: list[list[str]] = [] pull = atif_copies.AtifCopies.pull_live_media async def spy(self, document, session_id): pulled.append(sorted(media_paths(document))) await pull(self, document, session_id) + if media_paths(document): + held.set() monkeypatch.setattr(atif_copies.AtifCopies, "pull_live_media", spy) context = run.context() From 101e71ad1af2a3ddc524b4c1c210fdff388eac06 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:12:56 -0800 Subject: [PATCH 04/10] test(task-steps): name the live tests' gate timeout Co-Authored-By: Claude Opus 5.5 --- tst/unit/task_step/test_prompt_agent_atif_copies.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tst/unit/task_step/test_prompt_agent_atif_copies.py b/tst/unit/task_step/test_prompt_agent_atif_copies.py index 2674c96ae..5541fdd83 100644 --- a/tst/unit/task_step/test_prompt_agent_atif_copies.py +++ b/tst/unit/task_step/test_prompt_agent_atif_copies.py @@ -35,6 +35,8 @@ from tst.util.images import png NATIVE = "shots/1" +#: How long the agent holds a gated turn open for its ``gate`` at most, so a test that never sets it still ends. +_GATE_SECONDS = 30 _PREFIX = "prompt_agent_trajectories/prompt_id=solve/" @@ -51,8 +53,8 @@ def shot(self, record: dict, turn) -> None: def _app(*, atif: bool = True, live: bool = False, gate: asyncio.Event | None = None): """An agent that, each turn, appends one shot, a new screenshot each time, and answers; with ``gate``, a second - shot, then a third once ``gate`` is set (at most 30 s on), so a live reader sees the first closed while the turn runs - (a step closes when the next begins).""" + shot, then a third once ``gate`` is set (at most ``_GATE_SECONDS`` on), so a live reader sees the first closed + while the turn runs (a step closes when the next begins).""" shots = iter(range(1, 1000)) @a2a_agent( @@ -68,7 +70,7 @@ async def run(self, request: TaskRequest) -> TaskResult: for held in (False, True): if held: with contextlib.suppress(TimeoutError): - await asyncio.wait_for(gate.wait(), 30) + await asyncio.wait_for(gate.wait(), _GATE_SECONDS) n = next(shots) request.trajectory.append({"type": "shot", "n": n, "png": base64.b64encode(png(n, 1)).decode()}) return TaskResult.text(f"shot {n}") From 1ea1a9cbef942bff3cd68d5f463b273ff9120d5a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:43:47 -0800 Subject: [PATCH 05/10] fix(a2a): an atif/1 live follow reads again while its copy hasn't started, not ending at the first 404 Before any page is stored, an atif/1 cursor read the agent answers 404 is a copy that hasn't started yet, so the follower reads it again until the turn ends rather than treating the task as gone. Co-Authored-By: Claude Opus 5.5 --- .../a2a_agent/trajectory_follower.py | 11 ++++- .../task_step/test_prompt_agent_live_atif.py | 41 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/src/agent_env/a2a_agent/trajectory_follower.py b/src/agent_env/a2a_agent/trajectory_follower.py index b8d31fedb..4be2007b1 100644 --- a/src/agent_env/a2a_agent/trajectory_follower.py +++ b/src/agent_env/a2a_agent/trajectory_follower.py @@ -37,6 +37,10 @@ _ATIF_REFUSALS = frozenset({"format_not_prescribed", "atif_unavailable", "format_not_offered"}) +class _NotStarted(Exception): + """An atif/1 read answered 404 before any of the task's pages was stored: its copy may not have started yet.""" + + @dataclass(frozen=True) class TrajectoryBatch: """Events ``after`` to ``next`` of a task's trajectory, as one read returned them; ``last`` @@ -89,7 +93,8 @@ async def follow_trajectory( An atif/1 follow the agent refuses before any of its pages was stored goes on in ``fallback_format`` from the task's first event; one refused after that hands ``sink`` a batch naming why it ``stopped`` and ends, so a turn's - pages never mix formats. + pages never mix formats. Before its first page, an atif/1 read answered 404 is a copy not started yet, read again + until ``stop`` is set. Between reads it waits ``poll_interval_seconds``, or less once ``stop`` is set. Transport errors and 5xx answers are retried with backoff until ``stop`` is set, and end following after it; a @@ -107,6 +112,8 @@ async def follow_trajectory( timeout=_READ_TIMEOUT_SECONDS, ) if response.status_code == 404: + if reading == ATIF and not stored_atif and not stop.is_set(): + raise _NotStarted() logger.warning("Agent no longer knows task %s; stopped following its trajectory", task_id) return raise_for_extension_status(response, operation="trajectory get", include_body=True) @@ -130,6 +137,8 @@ async def follow_trajectory( except httpx.TransportError as exc: failures += 1 logger.warning("Live trajectory read failed (consec=%d, will retry): %r", failures, exc) + except _NotStarted: + logger.info("Task %s's atif/1 copy hasn't started yet; reading it again", task_id) else: failures = 0 atif = reading == ATIF diff --git a/tst/unit/task_step/test_prompt_agent_live_atif.py b/tst/unit/task_step/test_prompt_agent_live_atif.py index cbd2b6c03..a79adb227 100644 --- a/tst/unit/task_step/test_prompt_agent_live_atif.py +++ b/tst/unit/task_step/test_prompt_agent_live_atif.py @@ -183,3 +183,44 @@ def batch(after: int, nxt: int, subagent: dict) -> TrajectoryBatch: == ["sub/toolu_1/00000000-00000002.0001.header.json"] assert "sub/toolu_1/sub/inner/00000000-00000001.jsonl" in names assert [n for n in names if n.endswith(".header.json") and "/" not in n] == ["00000000-00000001.0001.header.json"] + + +def _page(after: int, steps: int, state: str = "running") -> httpx.Response: + events = [{"step_id": n, "source": "agent", "message": f"m{n}"} for n in range(after + 1, after + steps + 1)] + return httpx.Response(200, json={"context_id": "c", "task_id": "t", "state": state, "format": ATIF, + "schema_version": "ATIF-v1.8", "profile_version": "1.0", + "header": {"session_id": "c", "trajectory_id": "d"}, "events": events, + "next": after + steps, "has_more": False}) + + +@pytest.mark.asyncio +async def test_an_atif_follow_read_again_until_its_copy_starts_stores_every_page(tmp_path): + """A conversation's first task has no copy for a moment after the agent takes it: its 404 isn't the task gone.""" + store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) + reads = iter([httpx.Response(404), httpx.Response(404), _page(0, 2), _page(2, 1, state="completed")]) + client = httpx.AsyncClient(transport=httpx.MockTransport(lambda request: next(reads))) + sink = LiveTrajectoryChunks(store, "p/", "turn-1") + + await follow_trajectory("http://agent.test/ext/trajectory", "t", sink, poll_interval_seconds=0, + stop=asyncio.Event(), client=client, format=ATIF, fallback_format=NATIVE) + + assert json.loads(store.read("p/turn-1/live/meta.json"))["format"] == ATIF + assert json.loads(store.read("p/turn-1/live/end.json")) == {"state": "completed", "next": 3} + + +@pytest.mark.asyncio +async def test_an_atif_follow_whose_copy_never_starts_ends_with_its_turn(tmp_path): + store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) + client = httpx.AsyncClient(transport=httpx.MockTransport(lambda request: httpx.Response(404))) + sink = LiveTrajectoryChunks(store, "p/", "turn-1") + stop = asyncio.Event() + follower = asyncio.create_task(follow_trajectory( + "http://agent.test/ext/trajectory", "t", sink, poll_interval_seconds=0.01, stop=stop, client=client, + format=ATIF, fallback_format=NATIVE)) + await asyncio.sleep(0.1) + assert not follower.done() + + stop.set() + + await asyncio.wait_for(follower, 5) + assert store.list("p/turn-1/live/") == [] From fe7ed339436c330440082afee7cae094d8c3e5d9 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 12:55:58 -0800 Subject: [PATCH 06/10] refactor(task-steps): a live follow's atif/1 settings travel as one LiveAtif, and the judge's shared atif/1 helpers are public The live follow's fallback format, media pull and media folder were four arguments threaded through four layers, and LiveTurn took eleven positional ones; they're one LiveAtif now, built once by prompt_agent, and LiveTurn takes keywords. The page writer cancels its own media pulls (cancel_pulls). turn_events no longer imports atif_turns' private helpers: content_text, steps_of, calls_with_results and SubAgents are public. Co-Authored-By: Claude Opus 5.5 --- .../snapshot_utils/live_trajectory.py | 78 ++++++++++--------- .../task_step/task_steps/always_on.py | 2 +- .../task_step/task_steps/prompt_agent.py | 10 +-- .../verifiers/judge_utils/atif_turns.py | 30 +++---- .../verifiers/judge_utils/turn_events.py | 27 ++++--- 5 files changed, 78 insertions(+), 69 deletions(-) diff --git a/src/agent_env/task_step/snapshot_utils/live_trajectory.py b/src/agent_env/task_step/snapshot_utils/live_trajectory.py index 6654d9cbe..7ec6ac897 100644 --- a/src/agent_env/task_step/snapshot_utils/live_trajectory.py +++ b/src/agent_env/task_step/snapshot_utils/live_trajectory.py @@ -26,6 +26,7 @@ import re from collections.abc import AsyncIterator, Awaitable, Callable, Mapping from contextlib import asynccontextmanager +from dataclasses import dataclass from typing import Any, Optional from agentenv_protocol.a2a_agent import TrajectoryState @@ -46,28 +47,36 @@ _ENDED_AS = {"completed": TrajectoryState.COMPLETED, "canceled": TrajectoryState.CANCELED} # A sub-agent's trajectory id names its folder, so only a plain file name does. _SUB_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}") -#: Pulls a live atif/1 page's media into the run's folder: the page's steps as a document, and its session. LiveMedia = Callable[[Mapping[str, Any], Any], Awaitable[None]] +@dataclass(frozen=True) +class LiveAtif: + """A turn followed as atif/1, its native format the fallback for a turn the agent refuses atif/1 before its first + page: ``media`` pulls the media a page's new steps name (given them as a document, and the session) into + ``media_base``, the folder their ``media/`` paths resolve in.""" + + media: LiveMedia + media_base: str + + class LiveTrajectoryChunks: """The ``follow_trajectory`` sink that stores one turn's pages.""" - def __init__(self, store: ObjectStore, prefix_key: str, turn_id: str, *, media: Optional[LiveMedia] = None, - media_base: Optional[str] = None, stop: Optional[asyncio.Event] = None) -> None: + def __init__(self, store: ObjectStore, prefix_key: str, turn_id: str, *, atif: Optional[LiveAtif] = None, + stop: Optional[asyncio.Event] = None) -> None: self._store = store self._directory = f"{prefix_key}{turn_id}/live/" self._format_written = False self._stored = 0 self._storing: asyncio.Future | None = None self._ended = False - self._media, self._media_base, self._stop = media, media_base, stop + self._atif, self._stop = atif, stop self._headers: dict[str, tuple[str, int]] = {} # each trajectory's folder: its header's digest, versions self._sub_steps: dict[str, int] = {} # each sub-agent's folder: the last step id stored self._session: Any = None self._stopped: Optional[str] = None - #: The media pulls this turn's pages started, cancelled once it ends: its copy's own pull takes what's left. - self.pulls: list[asyncio.Task] = [] + self._pulls: list[asyncio.Task] = [] async def __call__(self, batch: TrajectoryBatch) -> None: if batch.stopped: @@ -84,7 +93,7 @@ async def __call__(self, batch: TrajectoryBatch) -> None: header = batch.header or {} meta.update(schema_version=batch.schema_version, profile_version=batch.profile_version, session_id=header.get("session_id"), trajectory_id=header.get("trajectory_id"), - media_base=self._media_base) + media_base=self._atif.media_base if self._atif else None) await self._put("meta.json", json.dumps(meta).encode(), "application/json") self._format_written = True if batch.last: @@ -106,15 +115,15 @@ async def _store_atif(self, batch: TrajectoryBatch) -> None: await self._header("", name, batch.header) new_subs = [sub for found in [await self._store_sub(s, "sub/") for s in batch.subagents] for sub in found] self._stored = batch.next - if self._media is not None and not (self._stop is not None and self._stop.is_set()): + if self._atif is not None and not (self._stop is not None and self._stop.is_set()): steps = {"steps": list(batch.events), "subagent_trajectories": new_subs} if batch.events or new_subs: - self.pulls.append(asyncio.ensure_future(self._media(steps, self._session))) + self._pulls.append(asyncio.ensure_future(self._atif.media(steps, self._session))) - async def _store_sub(self, sub: Any, path: str) -> list[dict[str, Any]]: + async def _store_sub(self, sub: Mapping[str, Any], path: str) -> list[dict[str, Any]]: """A sub-agent's steps not stored yet and its header if it changed, under ``path``; and its embedded sub-agents the same way, under its folder. Returns each trajectory with only its new steps, for the media they name.""" - trajectory_id = sub.get("trajectory_id") if isinstance(sub, Mapping) else None + trajectory_id = sub.get("trajectory_id") if not isinstance(trajectory_id, str) or not _SUB_ID.fullmatch(trajectory_id): return [] where = f"{path}{trajectory_id}/" @@ -139,6 +148,13 @@ async def _header(self, where: str, name: str, header: Mapping[str, Any]) -> Non await self._put(f"{where}{name}.{versions + 1:04d}.header.json", body, "application/json") self._headers[where] = (digest, versions + 1) + async def cancel_pulls(self) -> None: + """Cancel the media pulls this turn's pages started: once the turn ends, its copy's own pull takes what's left.""" + for pull in self._pulls: + pull.cancel() + if self._pulls: + await asyncio.wait(self._pulls) + async def end(self, state: TrajectoryState) -> None: """Mark the turn ended in ``state`` after the events stored so far; the first mark stays.""" if self._ended: @@ -163,18 +179,17 @@ def __init__( store: ObjectStore, prefix_key: str, turn_id: str, + *, poll_interval_seconds: float, previous_turn_id: str | None, headers: Mapping[str, str], format: str | None = None, - fallback_format: str | None = None, - media: Optional[LiveMedia] = None, - media_base: Optional[str] = None, + atif: Optional[LiveAtif] = None, ) -> None: self._endpoint = endpoint self._headers = headers self._format = format - self._fallback_format, self._media, self._media_base = fallback_format, media, media_base + self._atif = atif self._store = store self._prefix_key = prefix_key self._turn_id = turn_id @@ -192,14 +207,14 @@ def follow(self, task_id: str) -> None: self.links.append( asyncio.create_task(_in_passing(linking, self._previous_turn_id, f"linked to turn {self._turn_id}")) ) - sink = LiveTrajectoryChunks(self._store, self._prefix_key, self._turn_id, media=self._media, - media_base=self._media_base, stop=self.stop) + sink = LiveTrajectoryChunks(self._store, self._prefix_key, self._turn_id, atif=self._atif, stop=self.stop) self.sinks.append(sink) self.followers.append( asyncio.create_task( follow_trajectory( self._endpoint, task_id, sink, poll_interval_seconds=self._poll_interval_seconds, stop=self.stop, - headers=self._headers, format=self._format, fallback_format=self._fallback_format, + headers=self._headers, format=ATIF if self._atif else self._format, + fallback_format=self._format if self._atif else None, ) ) ) @@ -220,9 +235,7 @@ async def following_live_trajectory( headers: Mapping[str, str], previous_turn_id: str | None = None, format: str | None = None, - fallback_format: str | None = None, - media: Optional[LiveMedia] = None, - media_base: Optional[str] = None, + atif: Optional[LiveAtif] = None, ) -> AsyncIterator[LiveTurn]: """Yield the turn whose task is followed once its message is sent; then ``previous_turn_id``'s ``next.json`` names it. @@ -233,8 +246,8 @@ async def following_live_trajectory( for a cancelled step or ``failed``, so readers do not wait on it. A follower's own failure is logged and never fails the turn. The media pulls a turn's atif/1 pages started are cancelled once it ends: the turn's copy pulls what's left, off the turn's path.""" - turn = LiveTurn(endpoint, store, prefix_key, turn_id, poll_interval_seconds, previous_turn_id, headers, format, - fallback_format, media, media_base) + turn = LiveTurn(endpoint, store, prefix_key, turn_id, poll_interval_seconds=poll_interval_seconds, + previous_turn_id=previous_turn_id, headers=headers, format=format, atif=atif) stopped_as = TrajectoryState.FAILED try: @@ -262,11 +275,8 @@ async def following_live_trajectory( logger.warning( "Live trajectory of turn %s stopped (continuing): %r", turn_id, follower.exception() ) - pulls = [pull for sink in turn.sinks for pull in sink.pulls] - for pull in pulls: - pull.cancel() - if pulls: - await asyncio.wait(pulls) + for sink in turn.sinks: + await sink.cancel_pulls() if turn.links: await asyncio.wait(turn.links) if turn.sinks: @@ -276,15 +286,15 @@ async def following_live_trajectory( class LiveTurns: """A step's turns, followed one after another: a turn sent after another is named in that one's - ``next.json``, and ``end`` marks the last turn sent as the step's last.""" + ``next.json``, and ``end`` marks the last turn sent as the step's last. Each is read in ``format``, or as atif/1 + with ``atif``.""" def __init__(self, endpoint: str, store: ObjectStore, prefix_key: str, *, poll_interval_seconds: float, - headers: Mapping[str, str], format: str | None = None, fallback_format: str | None = None, - media: Optional[LiveMedia] = None, media_base: Optional[str] = None) -> None: + headers: Mapping[str, str], format: str | None = None, atif: Optional[LiveAtif] = None) -> None: self._endpoint = endpoint self._headers = headers self._format = format - self._fallback_format, self._media, self._media_base = fallback_format, media, media_base + self._atif = atif self._store = store self._prefix_key = prefix_key self._poll_interval_seconds = poll_interval_seconds @@ -302,9 +312,7 @@ async def following(self, turn_id: str) -> AsyncIterator[LiveTurn]: headers=self._headers, previous_turn_id=self._last_sent, format=self._format, - fallback_format=self._fallback_format, - media=self._media, - media_base=self._media_base, + atif=self._atif, ) as turn: try: yield turn diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index adc60a4a1..fd96005fa 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -385,7 +385,7 @@ def __init__(self, step: AlwaysOnTaskStep, context: TaskStepContext): self.final_sent = False self.last_reply_at: Optional[datetime] = None self.per_turn_trajectory_urls: list[Optional[str]] = [] - self.per_turn_trajectories: list[TurnTrajectory] = [] # each turn's record, beside its url + self.per_turn_trajectories: list[TurnTrajectory] = [] self.copies: Optional[AtifCopies] = None self.per_turn_parts: list[Optional[list[dict]]] = [] self.tool_calls: Optional[int] = None diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py index b8af078b1..38b2cdc46 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -64,7 +64,7 @@ trajectory_prefix_key, ) from agent_env.task_step.snapshot_utils.atif_copies import AtifCopies -from agent_env.task_step.snapshot_utils.live_trajectory import LiveTurns +from agent_env.task_step.snapshot_utils.live_trajectory import LiveAtif, LiveTurns from agent_env.task_step.snapshot_utils.snapshot_series import SnapshotConfig, SnapshotSeries logger = logging.getLogger(__name__) @@ -656,14 +656,10 @@ async def _converse( atif_copies = AtifCopies(context, agent, target_url, traj_ext_cached, prescribed=ATIF_FORMAT in prescribed_formats(context)) live = self._live_trajectory_target(context, card, target_url, trajectory_output_prefix) - # A run whose copy replaces native follows atif/1 live too, its media pulled as its pages come. - copied = atif_copies.replaces_native + live_atif = LiveAtif(atif_copies.pull_live_media, atif_copies.folder) if atif_copies.replaces_native else None live_turns = ( LiveTurns(*live, poll_interval_seconds=self.poll_interval_seconds, headers=agent.control_headers, - format=ATIF_FORMAT if copied else formats.native, - fallback_format=formats.native if copied else None, - media=atif_copies.pull_live_media if copied else None, - media_base=atif_copies.folder if copied else None) + format=formats.native, atif=live_atif) if live is not None else None ) final_state: str = TaskState.completed.value diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py index e79b3e78b..5f10b02e8 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py @@ -180,7 +180,7 @@ def _checked(self, document_url: str, path: str) -> Optional[str]: return url if self._stored[url] else None -def _text(content: Any) -> str: +def content_text(content: Any) -> str: if isinstance(content, str): return content return "\n".join(part["text"] for part in content or [] @@ -192,7 +192,7 @@ def _has_image(content: Any) -> bool: for part in content) -def _steps(trajectory: Mapping[str, Any]) -> list[Mapping[str, Any]]: +def steps_of(trajectory: Mapping[str, Any]) -> list[Mapping[str, Any]]: """A trajectory's steps a reader can walk: a stored copy may be invalid, and is still graded as stored.""" steps = trajectory.get("steps") return [step for step in steps if isinstance(step, Mapping)] if isinstance(steps, list) else [] @@ -204,7 +204,7 @@ def _results(step: Mapping[str, Any]) -> list[Mapping[str, Any]]: return [result for result in results if isinstance(result, Mapping)] if isinstance(results, list) else [] -def _by_call(step: Mapping[str, Any]) -> list[tuple[Optional[Mapping[str, Any]], list[Mapping[str, Any]]]]: +def calls_with_results(step: Mapping[str, Any]) -> list[tuple[Optional[Mapping[str, Any]], list[Mapping[str, Any]]]]: """Each tool call of the step with its results by ``source_call_id``, then the results no call names.""" calls = step.get("tool_calls") calls = [call for call in calls if isinstance(call, Mapping)] if isinstance(calls, list) else [] @@ -215,7 +215,7 @@ def _by_call(step: Mapping[str, Any]) -> list[tuple[Optional[Mapping[str, Any]], return paired + ([(None, unpaired)] if unpaired else []) -class _SubAgents: +class SubAgents: """The embedded sub-agents a trajectory's results start, each walked once. A reference names one among its trajectory's own, else the nearest around where that trajectory sits, whoever reached it, as ATIF makes an id unique only within its parent's array (the builder embeds them all in the root). A copy graded as stored may lack an id, or @@ -267,18 +267,18 @@ def compact_atif_trajectory( events: list[dict] = [] files: list[tuple[str, str]] = [] numbers = itertools.count(1) - subagents = _SubAgents(document) + subagents = SubAgents(document) calls_on = trajectory_filter.include_tool_calls results_on = trajectory_filter.include_tool_call_results def walk(trajectory: Mapping[str, Any], tag: Mapping[str, Any]) -> None: - for step in _steps(trajectory): + for step in steps_of(trajectory): if step.get("source") != "agent": continue timestamp = step.get("timestamp") or "" if trajectory_filter.include_thinking and step.get("reasoning_content"): events.append({"type": "thinking", "text": step["reasoning_content"], "timestamp": timestamp, **tag}) - for call, results in _by_call(step): + for call, results in calls_with_results(step): tool = (call or {}).get("function_name") or "" if call is not None and calls_on: events.append({"type": "tool_call", "tool": tool, "input": call.get("arguments"), @@ -302,10 +302,10 @@ def walk(trajectory: Mapping[str, Any], tag: Mapping[str, Any]) -> None: walk(document, {}) if trajectory_filter.include_response: - final = next((step for step in reversed(_steps(document)) - if step.get("source") == "agent" and _text(step.get("message")).strip()), None) + final = next((step for step in reversed(steps_of(document)) + if step.get("source") == "agent" and content_text(step.get("message")).strip()), None) if final is not None: - events.append({"type": "final_response", "text": _text(final.get("message")), + events.append({"type": "final_response", "text": content_text(final.get("message")), "timestamp": final.get("timestamp") or ""}) return events, files @@ -321,16 +321,16 @@ def transcript_from_atif( actions: list[TrajectoryAction] = [] messages: list[AgentMessage] = [] frames: list[ImageFrame] = [] - subagents = _SubAgents(document) + subagents = SubAgents(document) def walk(trajectory: Mapping[str, Any]) -> None: - for step in _steps(trajectory): + for step in steps_of(trajectory): if step.get("source") != "agent": continue - text = _text(step.get("message")) + text = content_text(step.get("message")) if text.strip(): messages.append(AgentMessage(len(actions), text)) - for call, results in _by_call(step): + for call, results in calls_with_results(step): shots: list[ImageFrame] = [] for result in results: content = result.get("content") @@ -343,7 +343,7 @@ def walk(trajectory: Mapping[str, Any]) -> None: frames.extend(shots) if call is not None: arguments = call.get("arguments") - result_text = "\n".join(t for t in (_text(r.get("content")) for r in results) if t) + result_text = "\n".join(t for t in (content_text(r.get("content")) for r in results) if t) actions.append(TrajectoryAction( index=len(actions) + 1, tool=str(call.get("function_name") or ""), args=arguments if isinstance(arguments, dict) else {}, diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py index 713e05fea..7875ff848 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/turn_events.py @@ -1,7 +1,8 @@ """One agent turn's trajectory as what happened in it: the agent's text and each tool call with its input and result, from whichever format the agent stored it in (OTel spans, OpenInference's included; Claude Code's or Gemini's -stream-json), or from the turn's atif/1 view. What each format repeats on every turn or call (the tool list, the conversation so far, signatures, token -counts) is dropped, and results are made readable: JSON envelopes unwrapped, email bodies decoded, images left out.""" +stream-json), or from the turn's atif/1 view. What each format repeats on every turn or call (the tool list, the +conversation so far, signatures, token counts) is dropped, and results are made readable: JSON envelopes unwrapped, +email bodies decoded, images left out.""" from __future__ import annotations @@ -15,8 +16,12 @@ from agentenv_protocol.atif import FORMAT as ATIF, profile_of -from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import _by_call, _SubAgents, _text -from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import _steps as _atif_steps +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( + SubAgents, + calls_with_results, + content_text, + steps_of, +) from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( extract_final_response, is_tool_span, @@ -450,18 +455,18 @@ def atif_turn_events(view: Mapping[str, Any]) -> TurnEvents: each naming it as ``subagent`` (the call that started it, as its ``parent_tool_use_id`` is natively); and the final, the closing message, an error when the turn's task didn't complete.""" events: list[dict] = [] - subagents = _SubAgents(view) + subagents = SubAgents(view) def walk(trajectory: Mapping[str, Any], tag: dict) -> None: - for step in _atif_steps(trajectory): + for step in steps_of(trajectory): if step.get("source") != "agent": continue if isinstance(step.get("reasoning_content"), str) and step["reasoning_content"].strip(): events.append({"type": "thinking", "text": step["reasoning_content"], **tag}) - text = _text(step.get("message")) + text = content_text(step.get("message")) if text.strip(): events.append({"type": "text", "text": text, **tag}) - for call, results in _by_call(step): + for call, results in calls_with_results(step): event = None if call is not None: event = {**_call(str(call.get("function_name") or ""), call.get("tool_call_id"), @@ -474,11 +479,11 @@ def walk(trajectory: Mapping[str, Any], tag: dict) -> None: walk(sub, {"subagent": sub.get("trajectory_id")}) walk(view, {}) - steps = _atif_steps(view) + steps = steps_of(view) closing = next((step for step in reversed(steps) - if step.get("source") == "agent" and _text(step.get("message")).strip()), None) + if step.get("source") == "agent" and content_text(step.get("message")).strip()), None) state = profile_of(steps[-1]).get("state") if steps else None - events.append({"type": "final", "text": _text(closing.get("message")) if closing else None, + events.append({"type": "final", "text": content_text(closing.get("message")) if closing else None, "error": state not in (None, "completed")}) return TurnEvents(ATIF, events, len(json.dumps(view))) From 1914bd46e2dc80b1f949b1b01148146c0a4c58fa Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 14:03:56 -0800 Subject: [PATCH 07/10] feat(task-steps): always_on reads each turn's atif/1 copy off the wake's path, and fills it in when the run ends A wake no longer waits for its copy: the copy is read in the background, as prompt steps read theirs, and the run's end fills in each turn's url, record and timeline fields, giving the copies still going one trajectory fetch cap more (none when the step is cancelled). A copy still going then is recorded unavailable, timeout. Native reads stay inline. AtifCopies.join takes that timeout, and its inline read is gone. A run that prescribes atif/1 to an agent offering only native now keeps an unprescribed run's timeline: the turn fields name a turn only when the run's turns share a copy's url. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 7 +- .../task_step/snapshot_utils/atif_copies.py | 50 +++++++------- .../task_step/task_steps/always_on.py | 41 ++++++++--- .../test_always_on_trajectory_formats.py | 69 +++++++++++++++++-- 4 files changed, 124 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 81e57290d..d0d034f60 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,9 +127,10 @@ or one of them only where it is used. they prompt before its conversation starts); a run's `user_overrides.trajectory_formats` beats it. None by default, so an agent builds native only, and an `atif/1` read of a conversation not prescribed it is refused (`format_not_prescribed`). A prompt step or always_on step of a run that prescribes `atif/1` reads each turn's copy - inline once the turn ends (a prompt step off the turn's path, always_on within its one trajectory fetch cap), and - stores it as `.json` under `{prefix}atif/instance_id=//` - (`metadata["atif_copies"]`, `task_step/snapshot_utils/atif_copies.py`), overwritten each turn, with the turn's aux + off the turn's path once the turn ends (always_on fills in each turn's url, record and timeline fields when its run + ends, the copies still going given one trajectory fetch cap more), and stores it as `.json` under + `{prefix}atif/instance_id=//` (`metadata["atif_copies"]`, `task_step/snapshot_utils/atif_copies.py`), + overwritten each turn, with the turn's aux log and turn context under `turns/` and the media it names pulled into `media/`; after a restart the session's earlier document names the next in `continued_trajectory_ref`. Each turn's record says how its copy checked (`AtifRecord`: `valid`, `invalid`, `newer`, `unavailable`), and a copy never fails the run. When the agent offers diff --git a/src/agent_env/task_step/snapshot_utils/atif_copies.py b/src/agent_env/task_step/snapshot_utils/atif_copies.py index 33fbf0e17..08fe9bddd 100644 --- a/src/agent_env/task_step/snapshot_utils/atif_copies.py +++ b/src/agent_env/task_step/snapshot_utils/atif_copies.py @@ -119,7 +119,7 @@ def __init__(self, context: TaskStepContext, agent: DeployedAgent, a2a_url: str, self._prescribed = prescribed self._offered = ATIF in TrajectoryFormats.of(extension).formats self.replaces_native = prescribed and self._offered - self._pending: list[tuple[int, asyncio.Task[str | None]]] = [] + self._pending: list[tuple[int, asyncio.Task[str | None], str, TurnTrajectory]] = [] #: The media files the folder holds and their sizes (None until read), listed once and kept as this step pulls #: more. self._held: dict[str, int | None] | None = None @@ -133,26 +133,8 @@ def turn(self, index: int, task_id: str, name: str, record: TurnTrajectory, *, n record["atif"] = _unavailable("format_not_offered", task_id) else: previous = self._pending[-1][1] if self._pending else None - self._pending.append((index, asyncio.create_task(self._turn(task_id, name, record, native, previous)))) - - async def read(self, index: int, task_id: str, name: str, record: TurnTrajectory, *, native: NativeRead, - timeout: float) -> Optional[str]: - """``turn`` on the caller's path, for a step that reads each turn's trajectory before it goes on (always_on): - the turn's url once ``record`` is filled, all within ``timeout``. A copy that takes longer is recorded - ``unavailable``, ``timeout``, with no time left to read native in its place; without a copy, native is read as - ever, its error raised.""" - self.turn(index, task_id, name, record, native=native) - if not self.replaces_native: - url, record["format"] = await asyncio.wait_for(native(), timeout) - return url - try: - return await asyncio.wait_for(self._pending[-1][1], timeout) - except TimeoutError: - if record.get("atif") is None: - record["atif"] = _unavailable("timeout", task_id) - logger.warning(f"agent '{self._agent.agent_name}': task {task_id}'s trajectory wasn't read within " - f"{timeout:.0f}s (continuing)") - return None + job = asyncio.create_task(self._turn(task_id, name, record, native, previous)) + self._pending.append((index, job, task_id, record)) @property def folder(self) -> str: @@ -171,17 +153,35 @@ async def pull_live_media(self, document: Mapping[str, Any], session_id: Any) -> except Exception as exc: logger.warning(f"agent '{self._agent.agent_name}': a live page's media pull failed (continuing): {exc}") - async def join(self) -> dict[int, str | None]: + async def join(self, timeout: Optional[float] = None) -> dict[int, str | None]: """Each copied turn's url, by its index, once every copy has been stored and its record filled; cancelled while - waiting, it cancels the copies left.""" + waiting, it cancels the copies left. With ``timeout``, a copy still going then is cancelled, its turn left with + no url and, when it has no record yet, recorded ``unavailable``, ``timeout``.""" try: - return {index: await job for index, job in self._pending} + if self._pending: + await asyncio.wait([job for _, job, _, _ in self._pending], timeout=timeout) + urls: dict[int, str | None] = {} + late = [] + for index, job, task_id, record in self._pending: + if job.done(): + urls[index] = job.result() + continue + job.cancel() + late.append(job) + urls[index] = None + if record.get("atif") is None: + record["atif"] = _unavailable("timeout", task_id) + logger.warning(f"agent '{self._agent.agent_name}': task {task_id}'s trajectory wasn't read within " + f"{timeout:.0f}s of the step's end (continuing)") + if late: + await asyncio.wait(late) + return urls except BaseException: self.cancel() raise def cancel(self) -> None: - for _, job in self._pending: + for _, job, _, _ in self._pending: job.cancel() async def _turn(self, task_id: str, name: str, record: TurnTrajectory, native: NativeRead, diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index d1f3f474f..3350992ae 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -1461,10 +1461,11 @@ def record() -> None: await self._schedule_read() async def _trajectory(self, task_id: str, msg_id: str, turn: str) -> tuple[Optional[str], dict]: - """The agent turn's trajectory, read within one fetch cap (TRAJECTORY_FETCH_SECONDS): its atif/1 copy when the - run prescribes atif/1 and the agent offers it, else, or when the copy can't be had, its native one. Its url and - record join the run's per-turn lists. Returns the url and, in a run that prescribes atif/1, whose turns share - one url, the timeline fields that say which turn it is and what its url holds.""" + """The agent turn's trajectory, its url and record joining the run's per-turn lists. When the run prescribes + atif/1 and the agent offers it, the turn's copy is read off the turn's path, and its url and record are filled + in when the run ends (``_settle_copies``); otherwise its native one is read within one fetch cap + (TRAJECTORY_FETCH_SECONDS). Returns the url read, and for a copied turn, whose url the run's turns share, the + timeline field that says which turn it is.""" step, card = self.step, self.agent.a2a_card or {} extension = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) record = TurnTrajectory(format=None, atif=None) @@ -1472,15 +1473,38 @@ async def _trajectory(self, task_id: str, msg_id: str, turn: str) -> tuple[Optio step._trajectory_prefix(), msg_id, card=card, sandbox_type=self.agent.sandbox_type, headers=self.agent.control_headers) if extension else _no_trajectory index = len(self.per_turn_trajectory_urls) + self.per_turn_trajectories.append(record) + self.copies.turn(index, task_id, msg_id, record, native=native) + if self.copies.replaces_native: + self.per_turn_trajectory_urls.append(None) + return None, {"turn": index} url = None try: - url = await self.copies.read(index, task_id, msg_id, record, native=native, - timeout=TRAJECTORY_FETCH_SECONDS) + url, record["format"] = await asyncio.wait_for(native(), TRAJECTORY_FETCH_SECONDS) except Exception as e: logger.warning(f"{turn}: trajectory fetch failed (continuing): {e}") self.per_turn_trajectory_urls.append(url) - self.per_turn_trajectories.append(record) - return url, ({"turn": index, "trajectory_format": record["format"]} if record["atif"] is not None else {}) + return url, {} + + async def _settle_copies(self) -> None: + """Each copied turn's url and record, and its timeline events' too, once its copy is stored: the copies still + going get one fetch cap more (TRAJECTORY_FETCH_SECONDS), none when the step is being cancelled, and one still + going then has no url.""" + if self.copies is None: + return + task = asyncio.current_task() + try: + urls = await self.copies.join(timeout=0 if task is not None and task.cancelling() + else TRAJECTORY_FETCH_SECONDS) + except Exception as e: # the record matters more than this part of it + logger.warning(f"always_on: the agent's atif/1 copies could not be joined: {type(e).__name__}: {e}") + urls = {} + for index, url in urls.items(): + self.per_turn_trajectory_urls[index] = url + for event in self.timeline: + if event.get("event") in ("agent_turn_end", "nudge") and "turn" in event: + event["trajectory_url"] = self.per_turn_trajectory_urls[event["turn"]] + event["trajectory_format"] = self.per_turn_trajectories[event["turn"]]["format"] def _kept_parts(self, parts: list[dict]) -> list[dict]: """What the prompt response keeps of one wake's parts: TURN_TEXT_CHARS of each text, until @@ -1813,6 +1837,7 @@ async def finish(self) -> None: except Exception as e: # the record matters more than this part of it logger.warning(f"always_on: could not read what was pending at the end: {e}") self.pending = {"error": [{"error": f"{type(e).__name__}: {str(e)[:200]}"}]} + await self._settle_copies() if self.end_reason == NOTHING_CAN_WAKE: # Scheduled checks would have woken the agent, so they aren't what makes a run stuck. stuck = any(items for kind, items in self.pending.items() if kind != "scheduled_checks_not_due") diff --git a/tst/unit/task_step/test_always_on_trajectory_formats.py b/tst/unit/task_step/test_always_on_trajectory_formats.py index ec1f5e3a7..25b7fafb0 100644 --- a/tst/unit/task_step/test_always_on_trajectory_formats.py +++ b/tst/unit/task_step/test_always_on_trajectory_formats.py @@ -1,6 +1,7 @@ """always_on prescribes the run's formats to the agent it prompts, once, before its first wake, and reads each turn's trajectory as prompt_agent does: a run that prescribes atif/1 to an agent that offers it has each wake's and nudge's -atif/1 copy as its trajectory, read within the one fetch cap, and every turn records what its url holds.""" +atif/1 copy as its trajectory, read off the turn's path and filled in when the run ends, and every turn records what its +url holds.""" import asyncio @@ -19,6 +20,8 @@ TRAJECTORY = {"uri": TRAJECTORY_V1.uri, "params": { "formats": ["shots/1", "atif/1"], "native": "shots/1", "default": "shots/1", "methods": {"get": {"endpoint": "/ext/trajectory"}}}} +NATIVE_ONLY = {"uri": TRAJECTORY_V1.uri, "params": { + "formats": ["shots/1"], "native": "shots/1", "default": "shots/1", "methods": {"get": {"endpoint": "/ext/trajectory"}}}} def _quiet(n, texts, rig): @@ -34,19 +37,20 @@ def _nudged(n, texts, rig): return "" -def _offering(rig: Rig, prescribed: bool): - """A run whose solver's card offers atif/1 beside its native format, prescribing atif/1 or not.""" +def _offering(rig: Rig, prescribed: bool, extension: dict = TRAJECTORY): + """A run whose solver's card offers ``extension``'s formats (atif/1 beside its native one, by default), prescribing + atif/1 or not.""" context = rig.context() solver = next(agent for agent in context.deployed_agents if agent.agent_name == "solver") - solver.a2a_card = {"capabilities": {"extensions": [TRAJECTORY]}} + solver.a2a_card = {"capabilities": {"extensions": [extension]}} if prescribed: context.metadata["user_overrides"] = {"trajectory_formats": ["atif/1"]} return context -def _reads(monkeypatch, *, copy_seconds: float = 0.0) -> dict[str, list]: +def _reads(monkeypatch, *, copy_seconds: float = 0.0, gate: asyncio.Event | None = None) -> dict[str, list]: """Native reads and atif/1 copies, by task: each native read stored under its task, each copy a valid record of - the one conversation document, taking ``copy_seconds``.""" + the one conversation document, taking ``copy_seconds`` once ``gate`` is set.""" seen: dict[str, list] = {"native": [], "copies": []} async def native(a2a_url, extension, task_id, prefix, name, **kwargs): @@ -54,6 +58,8 @@ async def native(a2a_url, extension, task_id, prefix, name, **kwargs): return StoredTrajectory(f"file:///store/native-{task_id}.json", "shots/1") async def stored(self, task_id, name): + if gate is not None: + await gate.wait() await asyncio.sleep(copy_seconds) seen["copies"].append(task_id) return AtifRecord(url=DOCUMENT, task_id=task_id, through_step=len(seen["copies"]) * 3, status="valid", rules=[], @@ -111,7 +117,36 @@ async def test_a_prescribed_runs_turns_are_their_atif_copies_each_named_in_the_t @pytest.mark.asyncio -async def test_a_copy_that_outlasts_the_fetch_cap_is_unavailable_and_the_wake_goes_on(monkeypatch, tmp_path): +async def test_a_wake_goes_on_while_its_copy_is_read_and_each_copy_fills_its_turn_when_the_run_ends(monkeypatch, + tmp_path): + gate = asyncio.Event() + seen = _reads(monkeypatch, gate=gate) + monkeypatch.setattr(ao, "TRAJECTORY_FETCH_SECONDS", 5) + + def agent(n, texts, rig): + """The wake closes with text, so a nudge follows; the wake's copy is held until the nudge runs.""" + if n == 1: + return "All set." + gate.set() + rig.quiet() + return "" + + rig = Rig(monkeypatch, tmp_path, agent=agent) + await rig.arm() + context = await rig.run(rig.step(max_wakes=2), _offering(rig, prescribed=True)) + + [response] = context.prompt_responses + records = response.target_agent_per_turn_trajectories + assert len(seen["copies"]) == len(records) == 2 + assert [r["atif"]["status"] for r in records] == ["valid", "valid"] + assert response.target_agent_per_turn_trajectory_object_urls == [DOCUMENT, DOCUMENT] + ends = [e for e in rig.stored(context)["timeline"] if e["event"] in ("agent_turn_end", "nudge") and "state" in e] + assert [(e["turn"], e["trajectory_format"], e["trajectory_url"]) for e in ends] == [ + (0, "atif/1", DOCUMENT), (1, "atif/1", DOCUMENT)] + + +@pytest.mark.asyncio +async def test_a_copy_still_going_a_fetch_cap_after_the_run_ends_is_unavailable_with_no_url(monkeypatch, tmp_path): _reads(monkeypatch, copy_seconds=5) monkeypatch.setattr(ao, "TRAJECTORY_FETCH_SECONDS", 0.05) rig = Rig(monkeypatch, tmp_path, agent=_quiet) @@ -124,6 +159,26 @@ async def test_a_copy_that_outlasts_the_fetch_cap_is_unavailable_and_the_wake_go assert (record["format"], record["atif"]["status"], record["atif"]["reason"]) == (None, "unavailable", "timeout") +@pytest.mark.asyncio +async def test_a_run_prescribing_atif_to_an_agent_offering_only_native_reads_native_and_names_no_turn(monkeypatch, + tmp_path): + seen = _reads(monkeypatch) + rig = Rig(monkeypatch, tmp_path, agent=_nudged) + await rig.arm() + context = await rig.run(rig.step(max_wakes=2), _offering(rig, prescribed=True, extension=NATIVE_ONLY)) + + [response] = context.prompt_responses + assert response.error_type is None + assert seen["copies"] == [] and len(seen["native"]) == 2 + assert response.target_agent_per_turn_trajectory_object_urls == [ + f"file:///store/native-{task_id}.json" for task_id in seen["native"]] + assert [(r["format"], r["atif"]["status"], r["atif"]["reason"]) + for r in response.target_agent_per_turn_trajectories] == [ + ("shots/1", "unavailable", "format_not_offered")] * 2 + ends = [e for e in rig.stored(context)["timeline"] if e["event"] in ("agent_turn_end", "nudge")] + assert ends and all("turn" not in e and "trajectory_format" not in e for e in ends) + + @pytest.mark.asyncio async def test_a_run_that_prescribes_nothing_reads_native_and_names_no_turn_in_the_timeline(monkeypatch, tmp_path): seen = _reads(monkeypatch) From 6ccde1122207286cf3b88b8a8e2d0b28aa55d06d Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 14:08:48 -0800 Subject: [PATCH 08/10] test(agents): the Claude Code atif/1 recorder records a conversation compacted between its turns Co-Authored-By: Claude Opus 5.5 --- tst/manual/claude_code_atif/record.py | 11 ++++++++--- .../claude_code/test_claude_code_atif_recorded.py | 9 +++++---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/tst/manual/claude_code_atif/record.py b/tst/manual/claude_code_atif/record.py index 07ac81030..ccedb6afc 100644 --- a/tst/manual/claude_code_atif/record.py +++ b/tst/manual/claude_code_atif/record.py @@ -9,9 +9,10 @@ container of it with atif/1 prescribed, through a model endpoint serving Anthropic's Messages API. For each turn it writes the native final read, the atif/1 final read (document, aux log and turn context), the atif/1 pages read live every second, and the CLI's transcripts after. The scenarios: two coding turns of one conversation, an Agent call, a -browser's screenshots through Playwright MCP beside the agent, a thinking model, the endpoint refusing every call, and -a stalled call that the bridge resumes, the last two through ``fault_proxy.py`` in a container of their own. They -cost about a dollar. Needs Docker; ``mcr.microsoft.com/playwright/mcp`` is pulled for the browser scenario. +browser's screenshots through Playwright MCP beside the agent, a thinking model, a conversation compacted between its +turns (``/compact``), the endpoint refusing every call, and a stalled call that the bridge resumes, the last two through +``fault_proxy.py`` in a container of their own. They cost about a dollar. Needs Docker; +``mcr.microsoft.com/playwright/mcp`` is pulled for the browser scenario. The key is never written: every text is checked for it, and a transcript holding it is dropped. Then ``make_fixtures.py`` writes the fixtures, keeping each request shape's tools once under ``tools/``, and running the @@ -63,6 +64,10 @@ def scenarios(thinking_model: str) -> dict[str, dict]: "retried": {"faults": "stall", "env": {"CLAUDE_API_ERROR_RETRIES": "1", "API_TIMEOUT_MS": "15000"}, "prompts": ["Run `echo first` with your Bash tool, then run `echo second` with it, then reply " "with both outputs on one line."]}, + "compacted": {"prompts": [ + "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.", + "/compact", + "Read notes.txt with your tools and reply with only its second line."]}, } 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 9fc736cae..36874588b 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 @@ -4,10 +4,11 @@ under ``tools/``, and named where they were fed. The scenarios: ``coding`` (two turns of one conversation), ``subagent`` (an Agent call), ``browser`` (screenshots from a -browser's MCP tools), ``thinking`` (a thinking model), ``api-error`` (the endpoint refusing every call) and ``retried`` -(a stalled call that the bridge resumed). Regenerate the expected documents after an intended change with: -python tst/unit/agents/claude_code/test_claude_code_atif_recorded.py. Record the runs again, as a bump of the pinned CLI -asks, with ``tst/manual/claude_code_atif/record.py``, whose docstring has the steps.""" +browser's MCP tools), ``thinking`` (a thinking model), ``compacted`` (a conversation compacted between its turns), +``api-error`` (the endpoint refusing every call) and ``retried`` (a stalled call that the bridge resumed). Regenerate +the expected documents after an intended change with: python +tst/unit/agents/claude_code/test_claude_code_atif_recorded.py. Record the runs again, as a bump of the pinned CLI asks, +with ``tst/manual/claude_code_atif/record.py``, whose docstring has the steps.""" from __future__ import annotations import json From f735a5b607101472d90e17bf3cfe7a61ae1fecfe Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:00:29 -0800 Subject: [PATCH 09/10] test(agents): a recorded Claude Code conversation compacted between its turns, pinning what its copy lacks The compacted scenario, recorded through the agent's image on the pinned CLI with atif/1 prescribed: a turn of work, a /compact turn, and a turn that reads what the summary kept. The turns around the compaction give a judge the same events from the copy as from native. The /compact turn's copy lacks what native stdout gives as notes (the summary and "Compacted") and a step for the call that wrote the summary, so its token counts leave that call out, though its cost counts it. Both are pinned until the copy has a compaction step (FD-6916). Co-Authored-By: Claude Opus 5.5 --- .../claude_code_atif/compacted.expected.json | 211 +++ tst/data/claude_code_atif/compacted.json | 1579 +++++++++++++++++ .../test_claude_code_atif_recorded.py | 26 +- 3 files changed, 1813 insertions(+), 3 deletions(-) create mode 100644 tst/data/claude_code_atif/compacted.expected.json create mode 100644 tst/data/claude_code_atif/compacted.json diff --git a/tst/data/claude_code_atif/compacted.expected.json b/tst/data/claude_code_atif/compacted.expected.json new file mode 100644 index 000000000..c721dd9ce --- /dev/null +++ b/tst/data/claude_code_atif/compacted.expected.json @@ -0,0 +1,211 @@ +{ + "schema_version": "ATIF-v1.8", + "session_id": "ctx-compacted", + "agent": { + "name": "Claude Code", + "version": "1.0.0", + "model_name": "anthropic/claude-sonnet-5-5", + "tool_definitions": { + "shared": "tools/a2f232fa81dcec06.json" + } + }, + "steps": [ + { + "step_id": 1, + "timestamp": "2026-11-23T22:10:47.698919Z", + "source": "user", + "message": "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.", + "extra": { + "agentenv": { + "context_id": "ctx-compacted", + "task_id": "3187814c-b5cc-427e-8aff-fa89353ae7b6", + "message_id": "73c2fd7665cf4d22a39088941aeedb47", + "turn": 0 + } + } + }, + { + "step_id": 2, + "timestamp": "2026-11-23T22:10:49.899Z", + "source": "agent", + "model_name": "claude-sonnet-5-5", + "message": "", + "tool_calls": [ + { + "tool_call_id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "function_name": "Bash", + "arguments": { + "command": "printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt", + "description": "Create notes.txt with three lines" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "content": "(Bash completed with no output)" + } + ] + }, + "metrics": { + "prompt_tokens": 28509, + "cached_tokens": 0, + "completion_tokens": 106, + "extra": { + "agentenv": { + "cache_write_tokens": 28507 + } + } + }, + "llm_call_count": 1 + }, + { + "step_id": 3, + "timestamp": "2026-11-23T22:10:50.839Z", + "source": "agent", + "model_name": "claude-sonnet-5-5", + "message": "ok", + "metrics": { + "prompt_tokens": 28630, + "cached_tokens": 28507, + "completion_tokens": 4, + "extra": { + "agentenv": { + "cache_write_tokens": 121 + } + } + }, + "llm_call_count": 1, + "extra": { + "agentenv": { + "state": "completed" + } + } + }, + { + "step_id": 4, + "timestamp": "2026-11-23T22:10:51.735809Z", + "source": "user", + "message": "/compact", + "extra": { + "agentenv": { + "context_id": "ctx-compacted", + "task_id": "93db87a5-3825-461b-85a2-636e23b45eaa", + "message_id": "8ec3fe03a9e342ea9ca816e236111e4a", + "turn": 1 + } + } + }, + { + "step_id": 5, + "timestamp": "2026-11-23T22:10:57.292647Z", + "source": "agent", + "message": "", + "llm_call_count": 0, + "extra": { + "agentenv": { + "state": "completed" + } + } + }, + { + "step_id": 6, + "timestamp": "2026-11-23T22:10:57.789981Z", + "source": "user", + "message": "Read notes.txt with your tools and reply with only its second line.", + "extra": { + "agentenv": { + "context_id": "ctx-compacted", + "task_id": "d98aa508-6da7-4c5d-8e18-fd76b9184490", + "message_id": "63535bbb2b3445e78152cb9bc8d5b185", + "turn": 2 + } + } + }, + { + "step_id": 7, + "timestamp": "2026-11-23T22:10:59.101Z", + "source": "agent", + "model_name": "claude-sonnet-5-5", + "message": "", + "tool_calls": [ + { + "tool_call_id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "function_name": "Read", + "arguments": { + "file_path": "/app/notes.txt" + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "content": "1\talpha\n2\tbeta\n3\tgamma\n4\t" + } + ] + }, + "metrics": { + "prompt_tokens": 29427, + "cached_tokens": 25110, + "completion_tokens": 55, + "extra": { + "agentenv": { + "cache_write_tokens": 4315 + } + } + }, + "llm_call_count": 1 + }, + { + "step_id": 8, + "timestamp": "2026-11-23T22:10:59.930Z", + "source": "agent", + "model_name": "claude-sonnet-5-5", + "message": "beta", + "metrics": { + "prompt_tokens": 29506, + "cached_tokens": 29425, + "completion_tokens": 4, + "extra": { + "agentenv": { + "cache_write_tokens": 79 + } + } + }, + "llm_call_count": 1, + "extra": { + "agentenv": { + "state": "completed" + } + } + } + ], + "final_metrics": { + "total_prompt_tokens": 116072, + "total_completion_tokens": 169, + "total_cached_tokens": 83042, + "total_cost_usd": 0.1066379, + "total_steps": 8, + "extra": { + "agentenv": { + "cost_source": "harness", + "total_cache_write_tokens": 33022 + } + } + }, + "extra": { + "agentenv": { + "version": "1.0", + "native_format": "claude-code-stream-json/1", + "adapter": { + "name": "claude-code-stream-json-atif", + "version": "0.1.0" + }, + "unmatched": { + "system": 3 + } + } + } +} diff --git a/tst/data/claude_code_atif/compacted.json b/tst/data/claude_code_atif/compacted.json new file mode 100644 index 000000000..ec54d5791 --- /dev/null +++ b/tst/data/claude_code_atif/compacted.json @@ -0,0 +1,1579 @@ +{ + "scenario": "compacted", + "cli": "2.1.322", + "turns": [ + { + "turn": { + "index": 0, + "context_id": "ctx-compacted", + "task_id": "3187814c-b5cc-427e-8aff-fa89353ae7b6", + "message_id": "73c2fd7665cf4d22a39088941aeedb47", + "agent_name": "Claude Code", + "agent_version": "1.0.0", + "agent_model": "anthropic/claude-sonnet-5-5", + "started_at": "2026-11-23T22:10:47.698919Z", + "inbound": [ + "Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok." + ], + "state": "completed", + "final": [ + "ok" + ], + "ended_at": "2026-11-23T22:10:50.869088Z", + "data": [ + { + "data": { + "tool_call_count": 1 + } + } + ] + }, + "native": [ + { + "type": "system", + "subtype": "init", + "cwd": "/app", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "tools": [ + "Task", + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "TaskStop", + "WebFetch", + "WebSearch", + "Workflow", + "Write", + "mcp__peer_agents__peer_cancel_task", + "mcp__peer_agents__peer_get_card", + "mcp__peer_agents__peer_get_task", + "mcp__peer_agents__peer_list", + "mcp__peer_agents__peer_send_message", + "mcp__peer_agents__peer_start_task" + ], + "mcp_servers": [ + { + "name": "peer_agents", + "status": "connected", + "source": "dynamic" + } + ], + "model": "anthropic/claude-sonnet-5-5", + "permissionMode": "bypassPermissions", + "slash_commands": [ + "deep-research", + "dataviz", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "doctor", + "loop", + "claude-api", + "workflow-authoring", + "run", + "run-skill-generator", + "plugin-authoring", + "agents", + "auto-mode-setup", + "autocompact", + "clear", + "color", + "compact", + "config", + "output-style", + "context", + "effort", + "fast", + "focus", + "heapdump", + "init", + "mcp", + "model", + "__remote-workflow", + "workflow-launch-exec", + "reload-plugins", + "reload-skills", + "rename", + "security-review", + "usage", + "insights", + "recap", + "goal", + "list-agents", + "team-onboarding" + ], + "terminal_slash_commands": [ + "doctor", + "color", + "focus", + "reload-plugins" + ], + "apiKeySource": "none", + "claude_code_version": "2.1.322", + "output_style": "default", + "agents": [ + "claude", + "Explore", + "general-purpose", + "Plan", + "statusline-setup" + ], + "skills": [ + "deep-research", + "dataviz", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "doctor", + "loop", + "claude-api", + "workflow-authoring", + "run", + "run-skill-generator", + "plugin-authoring" + ], + "plugins": [ + { + "name": "cc-plugin-agents-md", + "path": "builtin", + "source": "cc-plugin-agents-md@builtin" + }, + { + "name": "cc-plugin-privacy", + "path": "builtin", + "source": "cc-plugin-privacy@builtin" + }, + { + "name": "cc-plugin-plugin-authoring", + "path": "builtin", + "source": "cc-plugin-plugin-authoring@builtin" + } + ], + "capabilities": [ + "interrupt_receipt_v1", + "interrupt_cancel_queued_v1", + "interrupt_send_now_v1", + "interrupt_requeue_taken_v1", + "msg_lifecycle_v1", + "request_marker_lists_v1", + "ask_user_question_unanswered_v1", + "lifecycle_wakeup_source_v1", + "sdk_mcp_tools_list_changed", + "sdk_mcp_manifests", + "mcp_read_resource_v1", + "mcp_tool_ui_meta_v1", + "ui_surface_v1", + "mcp_call_result_not_for_model_v1", + "mcp_call_check_permissions_v1" + ], + "analytics_disabled": true, + "product_feedback_disabled": true, + "uuid": "ba2efe63-759f-4c43-b465-c9e8187556d9", + "memory_paths": { + "auto": "/home/agent/.claude/projects/-app/memory/" + }, + "original_cwd": "/app", + "additional_directories": [], + "messaging_socket_path": "/tmp/cc-socks/1096.sock", + "fast_mode_state": "off", + "fast_mode_disabled_reason": "sdk_opt_in_required", + "per_turn_effort_active": true, + "ultrathink_available": false, + "ultrathink_typed_raises": false, + "view_mode": "default" + }, + { + "type": "assistant", + "message": { + "model": "claude-sonnet-5-5", + "id": "msg_vrtx_011ChLdEeWRVHxAsDPSN33yj", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "name": "Bash", + "input": { + "command": "printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt", + "description": "Create notes.txt with three lines" + } + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 28507, + "cache_read_input_tokens": 0, + "cache_creation": { + "ephemeral_5m_input_tokens": 28507, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 16, + "speed": "standard" + }, + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "05103c57-4f92-435d-b5c0-e0f4115ca66a", + "timestamp": "2026-11-23T22:10:49.899Z", + "request_id": "req_vrtx_011ChLdEeUC7ThqZEM5ZbjNU" + }, + { + "type": "user", + "message": { + "role": "user", + "content": [ + { + "tool_use_id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "type": "tool_result", + "content": "(Bash completed with no output)", + "is_error": false + } + ] + }, + "parent_tool_use_id": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "511698fe-e874-4270-92ad-9d262420a17b", + "timestamp": "2026-11-23T22:10:49.951Z", + "tool_use_result": { + "stdout": "", + "stderr": "", + "interrupted": false, + "isImage": false, + "noOutputExpected": false + }, + "tool_result_meta": [ + { + "id": "toolu_vrtx_01Xn4XjSuqNpg2nosKGRtEK2", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "mode" + } + } + ] + }, + { + "type": "assistant", + "message": { + "model": "claude-sonnet-5-5", + "id": "msg_vrtx_011ChLdEmAmEHepkuRgEAFtA", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "text", + "text": "ok" + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 121, + "cache_read_input_tokens": 28507, + "cache_creation": { + "ephemeral_5m_input_tokens": 121, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 4, + "speed": "standard" + }, + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911", + "timestamp": "2026-11-23T22:10:50.839Z", + "request_id": "req_vrtx_011ChLdEm8nnrqLR8zzWqDVB" + }, + { + "duration_api_ms": 2651, + "stop_reason": "end_turn", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "total_cost_usd": 0.07552869999999999, + "usage": { + "input_tokens": 4, + "cache_creation_input_tokens": 28628, + "cache_read_input_tokens": 28507, + "output_tokens": 110, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 28628 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "modelUsage": { + "anthropic/claude-sonnet-5-5": { + "inputTokens": 4, + "outputTokens": 110, + "cacheReadInputTokens": 28507, + "cacheCreationInputTokens": 28628, + "webSearchRequests": 0, + "costUSD": 0.07552869999999999, + "contextWindow": 1000000, + "maxOutputTokens": 128000, + "thinkingTokens": 0, + "cacheCreationEphemeral5mInputTokens": 28628, + "cacheCreationEphemeral1hInputTokens": 0, + "canonicalModel": "claude-sonnet-5-5", + "provider": "firstParty", + "costBasis": "list" + } + }, + "permission_denials": [], + "terminal_reason": "completed", + "fast_mode_state": "off", + "fast_mode_disabled_reason": "sdk_opt_in_required", + "subagent_stats": { + "spawned": 0, + "requested": { + "background": 0, + "foreground": 0, + "unset": 0 + }, + "started_in_background": 0, + "max_depth": 0, + "spawned_by_subagents": 0, + "completed": 0, + "failed": 0, + "killed": { + "parent": 0, + "user": 0, + "system": 0 + }, + "refused": { + "depth_limit": 0, + "concurrency_limit": 0, + "budget": 0 + }, + "by_type": {} + }, + "safety_stops": 0, + "is_error": false, + "num_turns": 2, + "subtype": "success", + "api_error_status": null, + "result": "ok", + "ttft_ms": 1780, + "type": "result", + "duration_ms": 2730, + "uuid": "1c3f813d-b564-42fd-a9b9-a5a14cd5e263", + "ttft_stream_ms": 1391, + "time_to_request_ms": 60, + "first_content_frame_ms": 1391, + "queued_turn_count": 0, + "result_index": 0, + "model_usage_since_last_result": { + "anthropic/claude-sonnet-5-5": { + "inputTokens": 4, + "outputTokens": 110, + "cacheReadInputTokens": 28507, + "cacheCreationInputTokens": 28628, + "webSearchRequests": 0, + "costUSD": 0.07552869999999999, + "contextWindow": 1000000, + "maxOutputTokens": 128000, + "thinkingTokens": 0, + "cacheCreationEphemeral5mInputTokens": 28628, + "cacheCreationEphemeral1hInputTokens": 0, + "canonicalModel": "claude-sonnet-5-5", + "provider": "firstParty", + "costBasis": "list" + } + } + } + ], + "aux": [ + { + "name": "session", + "record": { + "type": "user", + "uuid": "4e39555c-5a67-4b67-86b4-2edcbb129349", + "timestamp": "2026-11-23T22:10:48.139Z", + "isSidechain": false, + "message": {} + }, + "after": 1 + }, + { + "name": "tools", + "record": { + "type": "api-request-shape", + "shapeHash": "a2f232fa81dcec0661a1b2e451f9adb1ffb7e776608fcb58b6fd742b58d640d0", + "tools": { + "shared": "tools/a2f232fa81dcec06.json" + } + }, + "after": 1 + }, + { + "name": "session", + "record": { + "type": "assistant", + "uuid": "05103c57-4f92-435d-b5c0-e0f4115ca66a", + "timestamp": "2026-11-23T22:10:49.899Z", + "isSidechain": false, + "message": { + "id": "msg_vrtx_011ChLdEeWRVHxAsDPSN33yj", + "model": "claude-sonnet-5-5", + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 28507, + "cache_read_input_tokens": 0, + "output_tokens": 106, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 28507 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "stop_reason": "tool_use" + } + }, + "after": 3 + }, + { + "name": "session", + "record": { + "type": "user", + "uuid": "511698fe-e874-4270-92ad-9d262420a17b", + "timestamp": "2026-11-23T22:10:49.951Z", + "isSidechain": false, + "message": {} + }, + "after": 3 + }, + { + "name": "session", + "record": { + "type": "assistant", + "uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911", + "timestamp": "2026-11-23T22:10:50.839Z", + "isSidechain": false, + "message": { + "id": "msg_vrtx_011ChLdEmAmEHepkuRgEAFtA", + "model": "claude-sonnet-5-5", + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 121, + "cache_read_input_tokens": 28507, + "output_tokens": 4, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 121 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "stop_reason": "end_turn" + } + }, + "after": 4 + }, + { + "name": "turn", + "record": { + "type": "turn", + "cost_usd": 0.07552869999999999 + }, + "after": 5 + } + ], + "usage": { + "tool_call_count": 1, + "input_tokens": 57139, + "output_tokens": 110, + "total_tokens": 57249, + "cache_read_tokens": 28507, + "cache_write_tokens": 28628, + "input_includes_cache": true, + "cost_usd": 0.07552869999999999, + "models": [ + { + "model": "anthropic/claude-sonnet-5-5", + "input_tokens": 57139, + "output_tokens": 110, + "cache_read_tokens": 28507, + "cache_write_tokens": 28628, + "input_includes_cache": true, + "cost_usd": 0.07552869999999999 + } + ], + "provider_details": { + "cache_creation": { + "ephemeral_5m_input_tokens": 28628, + "ephemeral_1h_input_tokens": 0 + } + } + } + }, + { + "turn": { + "index": 1, + "context_id": "ctx-compacted", + "task_id": "93db87a5-3825-461b-85a2-636e23b45eaa", + "message_id": "8ec3fe03a9e342ea9ca816e236111e4a", + "agent_name": "Claude Code", + "agent_version": "1.0.0", + "agent_model": "anthropic/claude-sonnet-5-5", + "started_at": "2026-11-23T22:10:51.735809Z", + "inbound": [ + "/compact" + ], + "state": "completed", + "final": [ + "" + ], + "ended_at": "2026-11-23T22:10:57.292647Z", + "data": [ + { + "data": { + "tool_call_count": 0 + } + } + ] + }, + "native": [ + { + "type": "system", + "subtype": "status", + "status": "compacting", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "24570ba6-05ae-4cd6-806b-f52dd2a4690c" + }, + { + "type": "system", + "subtype": "status", + "status": null, + "compact_result": "success", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "079043cd-d7ae-44ef-a43e-bc805976408e" + }, + { + "type": "system", + "subtype": "init", + "cwd": "/app", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "tools": [ + "Task", + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "TaskStop", + "WebFetch", + "WebSearch", + "Workflow", + "Write", + "mcp__peer_agents__peer_cancel_task", + "mcp__peer_agents__peer_get_card", + "mcp__peer_agents__peer_get_task", + "mcp__peer_agents__peer_list", + "mcp__peer_agents__peer_send_message", + "mcp__peer_agents__peer_start_task" + ], + "mcp_servers": [ + { + "name": "peer_agents", + "status": "connected", + "source": "dynamic" + } + ], + "model": "anthropic/claude-sonnet-5-5", + "permissionMode": "bypassPermissions", + "slash_commands": [ + "deep-research", + "dataviz", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "doctor", + "loop", + "claude-api", + "workflow-authoring", + "run", + "run-skill-generator", + "plugin-authoring", + "agents", + "auto-mode-setup", + "autocompact", + "clear", + "color", + "compact", + "config", + "output-style", + "context", + "effort", + "fast", + "focus", + "heapdump", + "init", + "mcp", + "model", + "__remote-workflow", + "workflow-launch-exec", + "reload-plugins", + "reload-skills", + "rename", + "security-review", + "usage", + "insights", + "recap", + "goal", + "list-agents", + "team-onboarding" + ], + "terminal_slash_commands": [ + "doctor", + "color", + "focus", + "reload-plugins" + ], + "apiKeySource": "none", + "claude_code_version": "2.1.322", + "output_style": "default", + "agents": [ + "claude", + "Explore", + "general-purpose", + "Plan", + "statusline-setup" + ], + "skills": [ + "deep-research", + "dataviz", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "doctor", + "loop", + "claude-api", + "workflow-authoring", + "run", + "run-skill-generator", + "plugin-authoring" + ], + "plugins": [ + { + "name": "cc-plugin-agents-md", + "path": "builtin", + "source": "cc-plugin-agents-md@builtin" + }, + { + "name": "cc-plugin-privacy", + "path": "builtin", + "source": "cc-plugin-privacy@builtin" + }, + { + "name": "cc-plugin-plugin-authoring", + "path": "builtin", + "source": "cc-plugin-plugin-authoring@builtin" + } + ], + "capabilities": [ + "interrupt_receipt_v1", + "interrupt_cancel_queued_v1", + "interrupt_send_now_v1", + "interrupt_requeue_taken_v1", + "msg_lifecycle_v1", + "request_marker_lists_v1", + "ask_user_question_unanswered_v1", + "lifecycle_wakeup_source_v1", + "sdk_mcp_tools_list_changed", + "sdk_mcp_manifests", + "mcp_read_resource_v1", + "mcp_tool_ui_meta_v1", + "ui_surface_v1", + "mcp_call_result_not_for_model_v1", + "mcp_call_check_permissions_v1" + ], + "analytics_disabled": true, + "product_feedback_disabled": true, + "uuid": "f5dddf18-db75-4de2-8255-7eb637fd4954", + "memory_paths": { + "auto": "/home/agent/.claude/projects/-app/memory/" + }, + "original_cwd": "/app", + "additional_directories": [], + "messaging_socket_path": "/tmp/cc-socks/1128.sock", + "fast_mode_state": "off", + "fast_mode_disabled_reason": "sdk_opt_in_required", + "per_turn_effort_active": true, + "ultrathink_available": false, + "ultrathink_typed_raises": false, + "view_mode": "default" + }, + { + "type": "system", + "subtype": "compact_boundary", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "5154ac5c-60a8-4618-ac8e-0c013d6d69a1", + "compact_metadata": { + "trigger": "manual", + "pre_tokens": 28634, + "post_tokens": 2804, + "cumulative_dropped_tokens": 25830, + "duration_ms": 5247, + "preserved_segment": { + "head_uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911", + "anchor_uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", + "tail_uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + }, + "preserved_messages": { + "anchor_uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", + "uuids": [ + "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + ], + "all_uuids": [ + "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + ] + } + }, + "logical_parent_uuid": "ac4dd1f5-53cd-4b6a-9cb2-86dd896fb911" + }, + { + "type": "user", + "message": { + "role": "user", + "content": "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.\n\n\nBash\n\nSummary:\n1. Primary Request and Intent:\n The user asked: \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n\n2. Key Technical Concepts:\n - Bash `printf` with redirection to write a multi-line file.\n - Working directory is /app. It is not a git repository.\n\n3. Files and Code Sections:\n - /app/notes.txt (created)\n - Holds the three requested lines.\n - Command used: `printf 'alpha\\nbeta\\ngamma\\n' > /app/notes.txt`\n - Expected content:\n ```\n alpha\n beta\n gamma\n ```\n\n4. Errors and fixes:\n - None. The command completed with no output.\n\n5. Problem Solving:\n The task was straightforward and was solved with a single command. I did not read the file back to verify it.\n\n6. All user messages:\n - \"Create notes.txt holding three lines, alpha, beta and gamma, with your Bash tool, then reply with only ok.\"\n - (A later user turn asked for this summary of the conversation. It was text-only, with no tool calls.)\n\n7. Pending Tasks:\n - Send the final reply, which must be only \"ok\".\n\n8. Current Work:\n I had just created /app/notes.txt with the Bash tool. The only step left was the user's requested one-word confirmation reply.\n\n9. Optional Next Step:\n Reply with exactly \"ok\", as the user asked (\"then reply with only ok\"). No other work is pending.\n\nIf you need specific details from before compaction (like exact code snippets, error messages, or content you generated), read the full transcript at: /home/agent/.claude/projects/-app/157c8db2-a73b-4404-9413-836b695e1757.jsonl\nContinue the conversation from where it left off without asking the user any further questions. Resume directly — do not acknowledge the summary, do not recap what was happening, do not preface with \"I'll continue\" or similar. Pick up the last task as if the break never happened.\n\nThe messages after this summary are the most recent messages from before compaction, kept verbatim. The summary was written without seeing them, so something it says has not happened yet may already have happened in them." + }, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "parent_tool_use_id": null, + "uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", + "timestamp": "2026-11-23T22:10:57.245Z", + "isReplay": false, + "isSynthetic": true + }, + { + "type": "user", + "message": { + "role": "user", + "content": "Compacted " + }, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "parent_tool_use_id": null, + "uuid": "b5822639-42f5-44c2-88c7-a2046d8722d0", + "timestamp": "2026-11-23T22:10:57.358Z", + "isReplay": true + }, + { + "is_error": false, + "duration_api_ms": 0, + "num_turns": 0, + "stop_reason": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "total_cost_usd": 0.0896014, + "usage": { + "output_tokens_details": { + "thinking_tokens": 0 + }, + "input_tokens": 0, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "output_tokens": 0, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 0 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "modelUsage": { + "anthropic/claude-sonnet-5-5": { + "inputTokens": 2015, + "outputTokens": 803, + "thinkingTokens": 0, + "cacheReadInputTokens": 57014, + "cacheCreationInputTokens": 28736, + "cacheCreationEphemeral5mInputTokens": 28736, + "cacheCreationEphemeral1hInputTokens": 0, + "webSearchRequests": 0, + "costUSD": 0.0896014, + "contextWindow": 1000000, + "maxOutputTokens": 128000, + "canonicalModel": "claude-sonnet-5-5", + "provider": "firstParty", + "costBasis": "list" + } + }, + "permission_denials": [], + "fast_mode_state": "off", + "fast_mode_disabled_reason": "sdk_opt_in_required", + "subagent_stats": { + "spawned": 0, + "requested": { + "background": 0, + "foreground": 0, + "unset": 0 + }, + "started_in_background": 0, + "max_depth": 0, + "spawned_by_subagents": 0, + "completed": 0, + "failed": 0, + "killed": { + "parent": 0, + "user": 0, + "system": 0 + }, + "refused": { + "depth_limit": 0, + "concurrency_limit": 0, + "budget": 0 + }, + "by_type": {} + }, + "safety_stops": 0, + "subtype": "success", + "result": "", + "local_command": "compact", + "type": "result", + "duration_ms": 5302, + "uuid": "97facf62-cd73-4e72-b0df-b883340b401d", + "queued_turn_count": 0, + "result_index": 0, + "model_usage_since_last_result": { + "anthropic/claude-sonnet-5-5": { + "inputTokens": 2011, + "outputTokens": 693, + "cacheReadInputTokens": 28507, + "cacheCreationInputTokens": 108, + "webSearchRequests": 0, + "costUSD": 0.0140727, + "contextWindow": 1000000, + "maxOutputTokens": 128000, + "thinkingTokens": 0, + "cacheCreationEphemeral5mInputTokens": 108, + "cacheCreationEphemeral1hInputTokens": 0, + "canonicalModel": "claude-sonnet-5-5", + "provider": "firstParty", + "costBasis": "list" + } + } + } + ], + "aux": [ + { + "name": "session", + "record": { + "type": "user", + "uuid": "b3e1507b-e172-4591-ad47-b826c3be0ac1", + "timestamp": "2026-11-23T22:10:57.245Z", + "isSidechain": false, + "message": {} + }, + "after": 6 + }, + { + "name": "session", + "record": { + "type": "user", + "uuid": "741e478b-0197-406a-b222-d32ca9fd40fa", + "timestamp": "2026-11-23T22:10:51.994Z", + "isSidechain": false, + "message": {} + }, + "after": 6 + }, + { + "name": "session", + "record": { + "type": "user", + "uuid": "e8990ee7-182d-4d62-92a2-a5bf10de0c3d", + "timestamp": "2026-11-23T22:10:51.994Z", + "isSidechain": false, + "message": {} + }, + "after": 6 + }, + { + "name": "session", + "record": { + "type": "user", + "uuid": "b5822639-42f5-44c2-88c7-a2046d8722d0", + "timestamp": "2026-11-23T22:10:57.358Z", + "isSidechain": false, + "message": {} + }, + "after": 6 + }, + { + "name": "turn", + "record": { + "type": "turn", + "cost_usd": 0.014072700000000007 + }, + "after": 7 + } + ], + "usage": { + "tool_call_count": 0, + "input_tokens": 30626, + "output_tokens": 693, + "total_tokens": 31319, + "cache_read_tokens": 28507, + "cache_write_tokens": 108, + "input_includes_cache": true, + "cost_usd": 0.014072700000000007, + "models": [ + { + "model": "anthropic/claude-sonnet-5-5", + "input_tokens": 30626, + "output_tokens": 693, + "cache_read_tokens": 28507, + "cache_write_tokens": 108, + "input_includes_cache": true, + "cost_usd": 0.014072700000000007 + } + ], + "provider_details": { + "cache_creation": { + "ephemeral_5m_input_tokens": 108, + "ephemeral_1h_input_tokens": 0 + } + } + } + }, + { + "turn": { + "index": 2, + "context_id": "ctx-compacted", + "task_id": "d98aa508-6da7-4c5d-8e18-fd76b9184490", + "message_id": "63535bbb2b3445e78152cb9bc8d5b185", + "agent_name": "Claude Code", + "agent_version": "1.0.0", + "agent_model": "anthropic/claude-sonnet-5-5", + "started_at": "2026-11-23T22:10:57.789981Z", + "inbound": [ + "Read notes.txt with your tools and reply with only its second line." + ], + "state": "completed", + "final": [ + "beta" + ], + "ended_at": "2026-11-23T22:10:59.958835Z", + "data": [ + { + "data": { + "tool_call_count": 1 + } + } + ] + }, + "native": [ + { + "type": "system", + "subtype": "init", + "cwd": "/app", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "tools": [ + "Task", + "Bash", + "CronCreate", + "CronDelete", + "CronList", + "Edit", + "EnterWorktree", + "ExitWorktree", + "ListAgents", + "Monitor", + "NotebookEdit", + "Read", + "ReportFindings", + "ScheduleWakeup", + "SendMessage", + "Skill", + "TaskStop", + "WebFetch", + "WebSearch", + "Workflow", + "Write", + "mcp__peer_agents__peer_cancel_task", + "mcp__peer_agents__peer_get_card", + "mcp__peer_agents__peer_get_task", + "mcp__peer_agents__peer_list", + "mcp__peer_agents__peer_send_message", + "mcp__peer_agents__peer_start_task" + ], + "mcp_servers": [ + { + "name": "peer_agents", + "status": "connected", + "source": "dynamic" + } + ], + "model": "anthropic/claude-sonnet-5-5", + "permissionMode": "bypassPermissions", + "slash_commands": [ + "deep-research", + "dataviz", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "doctor", + "loop", + "claude-api", + "workflow-authoring", + "run", + "run-skill-generator", + "plugin-authoring", + "agents", + "auto-mode-setup", + "autocompact", + "clear", + "color", + "compact", + "config", + "output-style", + "context", + "effort", + "fast", + "focus", + "heapdump", + "init", + "mcp", + "model", + "__remote-workflow", + "workflow-launch-exec", + "reload-plugins", + "reload-skills", + "rename", + "security-review", + "usage", + "insights", + "recap", + "goal", + "list-agents", + "team-onboarding" + ], + "terminal_slash_commands": [ + "doctor", + "color", + "focus", + "reload-plugins" + ], + "apiKeySource": "none", + "claude_code_version": "2.1.322", + "output_style": "default", + "agents": [ + "claude", + "Explore", + "general-purpose", + "Plan", + "statusline-setup" + ], + "skills": [ + "deep-research", + "dataviz", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "doctor", + "loop", + "claude-api", + "workflow-authoring", + "run", + "run-skill-generator", + "plugin-authoring" + ], + "plugins": [ + { + "name": "cc-plugin-agents-md", + "path": "builtin", + "source": "cc-plugin-agents-md@builtin" + }, + { + "name": "cc-plugin-privacy", + "path": "builtin", + "source": "cc-plugin-privacy@builtin" + }, + { + "name": "cc-plugin-plugin-authoring", + "path": "builtin", + "source": "cc-plugin-plugin-authoring@builtin" + } + ], + "capabilities": [ + "interrupt_receipt_v1", + "interrupt_cancel_queued_v1", + "interrupt_send_now_v1", + "interrupt_requeue_taken_v1", + "msg_lifecycle_v1", + "request_marker_lists_v1", + "ask_user_question_unanswered_v1", + "lifecycle_wakeup_source_v1", + "sdk_mcp_tools_list_changed", + "sdk_mcp_manifests", + "mcp_read_resource_v1", + "mcp_tool_ui_meta_v1", + "ui_surface_v1", + "mcp_call_result_not_for_model_v1", + "mcp_call_check_permissions_v1" + ], + "analytics_disabled": true, + "product_feedback_disabled": true, + "uuid": "2e434bd4-5ee2-4bec-94ed-219c8f33ab0d", + "memory_paths": { + "auto": "/home/agent/.claude/projects/-app/memory/" + }, + "original_cwd": "/app", + "additional_directories": [], + "messaging_socket_path": "/tmp/cc-socks/1147.sock", + "fast_mode_state": "off", + "fast_mode_disabled_reason": "sdk_opt_in_required", + "per_turn_effort_active": true, + "ultrathink_available": false, + "ultrathink_typed_raises": false, + "view_mode": "default" + }, + { + "type": "assistant", + "message": { + "model": "claude-sonnet-5-5", + "id": "msg_vrtx_011ChLdFMoNGHtK9Y4GciRAT", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "name": "Read", + "input": { + "file_path": "/app/notes.txt" + } + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 4315, + "cache_read_input_tokens": 25110, + "cache_creation": { + "ephemeral_5m_input_tokens": 4315, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 16, + "speed": "standard" + }, + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "4fa57f9a-b975-4129-8b8c-2ece6558e234", + "timestamp": "2026-11-23T22:10:59.101Z", + "request_id": "req_vrtx_011ChLdFMmdXvdzY8N8dheFY" + }, + { + "type": "user", + "message": { + "role": "user", + "content": [ + { + "tool_use_id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "type": "tool_result", + "content": "1\talpha\n2\tbeta\n3\tgamma\n4\t" + } + ] + }, + "parent_tool_use_id": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "06ab904f-aedd-4a29-8401-b89222982527", + "timestamp": "2026-11-23T22:10:59.121Z", + "tool_use_result": { + "type": "text", + "file": { + "filePath": "/app/notes.txt", + "content": "alpha\nbeta\ngamma\n", + "numLines": 4, + "startLine": 1, + "totalLines": 4 + } + }, + "tool_result_meta": [ + { + "id": "toolu_vrtx_01TpvkxZzmH9NnvxvZjawAsM", + "permission_decision": { + "decision": "accept", + "source": "config", + "reason_type": "mode" + } + } + ] + }, + { + "type": "assistant", + "message": { + "model": "claude-sonnet-5-5", + "id": "msg_vrtx_011ChLdFSHz5S9c3j3zQAwV1", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "text", + "text": "beta" + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 79, + "cache_read_input_tokens": 29425, + "cache_creation": { + "ephemeral_5m_input_tokens": 79, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 4, + "speed": "standard" + }, + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "uuid": "40b09b05-3260-4453-8b2d-148983651a34", + "timestamp": "2026-11-23T22:10:59.930Z", + "request_id": "req_vrtx_011ChLdFSFkTmSv8gA3dVZgs" + }, + { + "duration_api_ms": 9722, + "stop_reason": "end_turn", + "session_id": "157c8db2-a73b-4404-9413-836b695e1757", + "total_cost_usd": 0.10663790000000001, + "usage": { + "input_tokens": 4, + "cache_creation_input_tokens": 4394, + "cache_read_input_tokens": 54535, + "output_tokens": 59, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 4394 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "modelUsage": { + "anthropic/claude-sonnet-5-5": { + "inputTokens": 2019, + "outputTokens": 862, + "thinkingTokens": 0, + "cacheReadInputTokens": 111549, + "cacheCreationInputTokens": 33130, + "cacheCreationEphemeral5mInputTokens": 33130, + "cacheCreationEphemeral1hInputTokens": 0, + "webSearchRequests": 0, + "costUSD": 0.10663790000000001, + "contextWindow": 1000000, + "maxOutputTokens": 128000, + "canonicalModel": "claude-sonnet-5-5", + "provider": "firstParty", + "costBasis": "list" + } + }, + "permission_denials": [], + "terminal_reason": "completed", + "fast_mode_state": "off", + "fast_mode_disabled_reason": "sdk_opt_in_required", + "subagent_stats": { + "spawned": 0, + "requested": { + "background": 0, + "foreground": 0, + "unset": 0 + }, + "started_in_background": 0, + "max_depth": 0, + "spawned_by_subagents": 0, + "completed": 0, + "failed": 0, + "killed": { + "parent": 0, + "user": 0, + "system": 0 + }, + "refused": { + "depth_limit": 0, + "concurrency_limit": 0, + "budget": 0 + }, + "by_type": {} + }, + "safety_stops": 0, + "is_error": false, + "num_turns": 2, + "subtype": "success", + "api_error_status": null, + "result": "beta", + "ttft_ms": 1085, + "type": "result", + "duration_ms": 1919, + "uuid": "178b1ebc-e272-4a85-a1ec-6a4397991a7d", + "ttft_stream_ms": 927, + "time_to_request_ms": 55, + "first_content_frame_ms": 927, + "queued_turn_count": 0, + "result_index": 0, + "model_usage_since_last_result": { + "anthropic/claude-sonnet-5-5": { + "inputTokens": 4, + "outputTokens": 59, + "cacheReadInputTokens": 54535, + "cacheCreationInputTokens": 4394, + "webSearchRequests": 0, + "costUSD": 0.0170365, + "contextWindow": 1000000, + "maxOutputTokens": 128000, + "thinkingTokens": 0, + "cacheCreationEphemeral5mInputTokens": 4394, + "cacheCreationEphemeral1hInputTokens": 0, + "canonicalModel": "claude-sonnet-5-5", + "provider": "firstParty", + "costBasis": "list" + } + } + } + ], + "aux": [ + { + "name": "session", + "record": { + "type": "user", + "uuid": "c761d67d-0f17-453f-af10-185255d4c314", + "timestamp": "2026-11-23T22:10:58.029Z", + "isSidechain": false, + "message": {} + }, + "after": 1 + }, + { + "name": "session", + "record": { + "type": "assistant", + "uuid": "4fa57f9a-b975-4129-8b8c-2ece6558e234", + "timestamp": "2026-11-23T22:10:59.101Z", + "isSidechain": false, + "message": { + "id": "msg_vrtx_011ChLdFMoNGHtK9Y4GciRAT", + "model": "claude-sonnet-5-5", + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 4315, + "cache_read_input_tokens": 25110, + "output_tokens": 55, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 4315 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "stop_reason": "tool_use" + } + }, + "after": 3 + }, + { + "name": "session", + "record": { + "type": "user", + "uuid": "06ab904f-aedd-4a29-8401-b89222982527", + "timestamp": "2026-11-23T22:10:59.121Z", + "isSidechain": false, + "message": {} + }, + "after": 3 + }, + { + "name": "session", + "record": { + "type": "assistant", + "uuid": "40b09b05-3260-4453-8b2d-148983651a34", + "timestamp": "2026-11-23T22:10:59.930Z", + "isSidechain": false, + "message": { + "id": "msg_vrtx_011ChLdFSHz5S9c3j3zQAwV1", + "model": "claude-sonnet-5-5", + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 79, + "cache_read_input_tokens": 29425, + "output_tokens": 4, + "output_tokens_details": { + "thinking_tokens": 0 + }, + "server_tool_use": { + "web_search_requests": 0, + "web_fetch_requests": 0 + }, + "service_tier": "standard", + "cache_creation": { + "ephemeral_1h_input_tokens": 0, + "ephemeral_5m_input_tokens": 79 + }, + "inference_geo": "", + "iterations": [], + "speed": "standard", + "fallback_credit": null + }, + "stop_reason": "end_turn" + } + }, + "after": 4 + }, + { + "name": "turn", + "record": { + "type": "turn", + "cost_usd": 0.01703650000000001 + }, + "after": 5 + } + ], + "usage": { + "tool_call_count": 1, + "input_tokens": 58933, + "output_tokens": 59, + "total_tokens": 58992, + "cache_read_tokens": 54535, + "cache_write_tokens": 4394, + "input_includes_cache": true, + "cost_usd": 0.01703650000000001, + "models": [ + { + "model": "anthropic/claude-sonnet-5-5", + "input_tokens": 58933, + "output_tokens": 59, + "cache_read_tokens": 54535, + "cache_write_tokens": 4394, + "input_includes_cache": true, + "cost_usd": 0.01703650000000001 + } + ], + "provider_details": { + "cache_creation": { + "ephemeral_5m_input_tokens": 4394, + "ephemeral_1h_input_tokens": 0 + } + } + } + } + ] +} 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 36874588b..1ddbe350e 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 @@ -52,6 +52,13 @@ def recorded(scenario: str) -> tuple[list[RecordedTask], list[dict | None]]: 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 [])] @@ -86,12 +93,15 @@ def test_a_recorded_run_replays_to_its_document_under_the_live_rule(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. Its token counts leave out a turn that compacts the conversation: + the copy has no step for the call that wrote its summary yet, though its cost counts it.""" _, usage = recorded(scenario) final = replay(scenario).document["final_metrics"] + compacted = compacted_turns(scenario) 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) + total = sum(turn.get(field) or 0 for index, turn in enumerate(reported) if index not in compacted) 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)) @@ -115,6 +125,7 @@ def test_the_recordings_cover_what_the_adapter_maps(): assert any(step.get("extra", {}).get("agentenv", {}).get("attempt") == 2 for step in retried) assert any("error" in step.get("extra", {}).get("agentenv", {}) for step in documents["api-error"]["steps"]) assert any(step.get("extra", {}).get("agentenv", {}).get("reasoning") for step in documents["thinking"]["steps"]) + assert compacted_turns("compacted") == {1} @pytest.mark.parametrize("scenario", SCENARIOS) @@ -146,12 +157,21 @@ def test_a_judge_reads_each_recorded_turn_with_its_calls_results_answer_and_scre @pytest.mark.parametrize("scenario", SCENARIOS) def test_a_recorded_turns_copy_gives_a_judge_the_events_its_native_trajectory_does(scenario): """always_on's judge stages each wake from its events. A copy gives the native turn's, but for a sub-agent's prompt, - which only native stdout carries (as a note), and its closing text, which only its transcript, so the copy, has.""" + which only native stdout carries (as a note), and its closing text, which only its transcript, so the copy, has; and + for a turn that compacts the conversation, whose summary and "Compacted" only native stdout carries (as notes) until + the copy has a compaction step.""" data = json.loads((FIXTURES / f"{scenario}.json").read_text()) document = replay(scenario).document - for turn in data["turns"]: + compacted = compacted_turns(scenario) + for index, turn in enumerate(data["turns"]): native = turn_events(json.dumps(turn["native"])).events copied = atif_turn_events(task_document(document, [turn["turn"]["task_id"]])).events + if index in compacted: + notes = [e["text"] for e in native if e["type"] == "note"] + assert len(notes) == 2 and notes[0].startswith("This session is being continued") and "Compacted" in notes[1] + assert [e for e in native if e["type"] != "note"] == [{"type": "final", "text": "", "error": False}] + assert copied == [{"type": "final", "text": None, "error": False}] + continue if scenario == "subagent": assert [e["type"] for e in native if e.get("subagent")] == ["note", "tool_call"] assert [e["type"] for e in copied if e.get("subagent")] == ["tool_call", "text"] From 8a3e4b44fce5dbbe8788dc2411df9d844f4e285b Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:03:02 -0800 Subject: [PATCH 10/10] fix(task-steps): always_on cancels the atif/1 copies a run left when its end failed before joining them A run's end that raised before it joined its copies (a failed clock read, say) left them reading and writing after the step had exited; the run's close now cancels any still pending. Co-Authored-By: Claude Opus 5.5 --- .../task_step/task_steps/always_on.py | 2 ++ .../test_always_on_trajectory_formats.py | 34 ++++++++++++++++--- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 3350992ae..ed5b29281 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -485,6 +485,8 @@ async def put_back() -> None: self.undo.append((f"{what} on {env.env_id}", put_back)) def close(self) -> None: + if self.copies is not None: + self.copies.cancel() for p in self._plugin_paths: if os.path.exists(p): os.unlink(p) diff --git a/tst/unit/task_step/test_always_on_trajectory_formats.py b/tst/unit/task_step/test_always_on_trajectory_formats.py index 25b7fafb0..4ef63a5c2 100644 --- a/tst/unit/task_step/test_always_on_trajectory_formats.py +++ b/tst/unit/task_step/test_always_on_trajectory_formats.py @@ -51,16 +51,20 @@ def _offering(rig: Rig, prescribed: bool, extension: dict = TRAJECTORY): def _reads(monkeypatch, *, copy_seconds: float = 0.0, gate: asyncio.Event | None = None) -> dict[str, list]: """Native reads and atif/1 copies, by task: each native read stored under its task, each copy a valid record of the one conversation document, taking ``copy_seconds`` once ``gate`` is set.""" - seen: dict[str, list] = {"native": [], "copies": []} + seen: dict[str, list] = {"native": [], "copies": [], "cancelled": []} async def native(a2a_url, extension, task_id, prefix, name, **kwargs): seen["native"].append(task_id) return StoredTrajectory(f"file:///store/native-{task_id}.json", "shots/1") async def stored(self, task_id, name): - if gate is not None: - await gate.wait() - await asyncio.sleep(copy_seconds) + try: + if gate is not None: + await gate.wait() + await asyncio.sleep(copy_seconds) + except asyncio.CancelledError: + seen["cancelled"].append(task_id) + raise seen["copies"].append(task_id) return AtifRecord(url=DOCUMENT, task_id=task_id, through_step=len(seen["copies"]) * 3, status="valid", rules=[], reason=None, validator_version="v", adapter_version="a", aux_url=None, turn_context_url=None) @@ -145,6 +149,28 @@ def agent(n, texts, rig): (0, "atif/1", DOCUMENT), (1, "atif/1", DOCUMENT)] +@pytest.mark.asyncio +async def test_a_step_whose_end_fails_before_it_joins_its_copies_cancels_them(monkeypatch, tmp_path): + seen = _reads(monkeypatch, gate=asyncio.Event()) + finish = ao._Run.finish + + async def failing(run): + """The run's end, once its copy is held reading, failing at its first clock read.""" + async def clock_read_fails(): + raise RuntimeError("the clock read failed") + await asyncio.sleep(0.05) + run.now = clock_read_fails + await finish(run) + + monkeypatch.setattr(ao._Run, "finish", failing) + rig = Rig(monkeypatch, tmp_path, agent=_quiet) + await rig.arm() + with pytest.raises(RuntimeError, match="clock read failed"): + await rig.run(rig.step(max_wakes=1), _offering(rig, prescribed=True)) + await asyncio.sleep(0) + assert len(seen["cancelled"]) == 1 and seen["copies"] == [] + + @pytest.mark.asyncio async def test_a_copy_still_going_a_fetch_cap_after_the_run_ends_is_unavailable_with_no_url(monkeypatch, tmp_path): _reads(monkeypatch, copy_seconds=5)