From 9b8721bea83b68cdf19bccd182a83b7dd5f38de0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 17:22:08 -0800 Subject: [PATCH 1/5] feat(protocol): a live atif/1 read names the header it holds and how far it holds each sub-agent A task's cursor read may name the digest of the header the reader holds and a cursor per sub-agent; the agent then answers the header's digest, leaves the header out while it's unchanged, and serves each of the task's sub-agents by its closed steps past its cursor (its header only when that changed), whether or not the step that started it has closed. A read naming neither gets today's page. The card declares both fields, and the live follower names them only to an agent whose card does, keeping its own dedupe otherwise. A page that carries only a sub-agent's new steps is stored as it comes. Integration tests hold the registry still for each test: a release publishing one of a bundle's images between two runs of it made the second plan a pull where the first built. Co-Authored-By: Claude Opus 5.5 --- .../agentenv_protocol/a2a_agent/__init__.py | 2 + .../agentenv_protocol/a2a_agent/_atif_copy.py | 53 +++++++++-- .../a2a_agent/_trajectory_log.py | 12 ++- .../agentenv_protocol/a2a_agent/extensions.py | 24 ++++- .../agentenv_protocol/a2a_agent/framework.py | 12 ++- .../tests/test_a2a_atif_serving.py | 94 +++++++++++++++++++ .../tests/test_a2a_trajectory_log.py | 4 +- .../a2a_agent/trajectory_follower.py | 63 +++++++++++-- .../snapshot_utils/live_trajectory.py | 5 +- .../task_step/task_steps/prompt_agent.py | 5 +- tst/integration/conftest.py | 8 ++ .../task_step/test_prompt_agent_live_atif.py | 94 ++++++++++++++++++- tst/unit/test_published_image_hold.py | 28 ++++++ tst/util/published_image.py | 21 ++++- 14 files changed, 394 insertions(+), 31 deletions(-) create mode 100644 tst/unit/test_published_image_hold.py diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py index 9ff177a39..5b652b2d1 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py @@ -73,6 +73,7 @@ SnapshotReadObjects, SnapshotUploadedObjects, SnapshotWriteObjects, + SubagentCursor, TaskEventsTrajectoryRequest, TaskObjectTrajectoryRequest, TaskTrajectoryRequest, @@ -245,6 +246,7 @@ "SnapshotWriteObjects", "StagingStore", "TaskError", + "SubagentCursor", "TaskEventsTrajectoryRequest", "TaskObjectTrajectoryRequest", "TaskOutcome", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_atif_copy.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_atif_copy.py index 56ec6bc26..497a5ce8e 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_atif_copy.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_atif_copy.py @@ -6,6 +6,7 @@ import base64 import binascii +import hashlib import json import logging import threading @@ -13,13 +14,14 @@ from contextlib import contextmanager from dataclasses import dataclass, field from datetime import datetime, timezone -from typing import Any, Callable, Iterable, Iterator, Sequence +from typing import Any, Callable, Iterable, Iterator, Mapping, Sequence from urllib.parse import urlsplit, urlunsplit from ..atif import FORMAT, Adapter, AdapterRun, AuxEntry, Media, ServedTurn, TurnContext from ..computer import clock as follower from ..errors import AgentEnvError from . import clock as agent_clock +from .extensions import SubagentCursor from .tasks.v1 import DataPart, FilePart, TaskError, TextPart, _thaw logger = logging.getLogger(__name__) @@ -54,13 +56,15 @@ class _Task: @dataclass(frozen=True, slots=True) class AtifPage: """A cursor page of a copy: the closed steps after ``after``, ``next`` the last one's ``step_id``, and the - sub-agents of their tasks.""" + sub-agents of their tasks; the header's digest, and with cursors, each sub-agent's.""" header: dict[str, Any] | None subagents: list[dict[str, Any]] steps: list[dict[str, Any]] next: int has_more: bool + header_digest: str | None = None + subagent_header_digests: dict[str, str] | None = None class AtifCopy: @@ -150,12 +154,15 @@ def context_read(self) -> dict[str, Any] | None: page = self._run.page() return None if page is None else self._scrub(page) - def page(self, after: int, max_steps: int, max_bytes: int, *, task_id: str | None = None) -> AtifPage: + def page(self, after: int, max_steps: int, max_bytes: int, *, task_id: str | None = None, + subagent_cursors: Mapping[str, SubagentCursor] | None = None) -> AtifPage: """The closed steps after step ``after``, of the whole context or of task ``task_id``, within both budgets; the first is always returned, so one larger than ``max_bytes`` can't stall a reader. With them, the sub-agents of every task they belong to, as far as each is served: a sub-agent can gain steps while its task runs, and the - page that serves a task's last step, which closes only as the task ends, carries them whole. The byte budget - counts what it serves, scrubbed.""" + page that serves a task's last step, which closes only as the task ends, carries them whole. With + ``subagent_cursors``, instead, each of task ``task_id``'s sub-agents with only its closed steps past its cursor + and its header only when that changed, whether or not the step that started it has closed. The byte budget + counts the root steps it serves, scrubbed.""" with self._lock: self._check() document = self._run.page() @@ -182,13 +189,36 @@ def page(self, after: int, max_steps: int, max_bytes: int, *, task_id: str | Non last = step["step_id"] header = None subagents: list[dict[str, Any]] = [] + sub_digests = None if document is not None: header = self._scrub({key: value for key, value in document.items() if key not in ("steps", "subagent_trajectories")}) - subagents = self._scrub([sub for sub in document.get("subagent_trajectories", []) - if sub_tasks.get(sub["trajectory_id"]) in tasks]) - return AtifPage(header=header, subagents=subagents, steps=served, - next=last, has_more=len(served) < len(pending)) + subs = document.get("subagent_trajectories", []) + if subagent_cursors is None: + subagents = self._scrub([sub for sub in subs if sub_tasks.get(sub["trajectory_id"]) in tasks]) + else: + subagents, sub_digests = self._subagents_past( + [sub for sub in subs if sub_tasks.get(sub["trajectory_id"]) == task_id], subagent_cursors) + return AtifPage(header=header, subagents=subagents, steps=served, next=last, + has_more=len(served) < len(pending), header_digest=None if header is None else _digest(header), + subagent_header_digests=sub_digests) + + def _subagents_past(self, subs: Sequence[dict[str, Any]], cursors: Mapping[str, SubagentCursor] + ) -> tuple[list[dict[str, Any]], dict[str, str]]: + """Each sub-agent with what its reader lacks, its closed steps past its cursor and its header if the reader's + digest is another, left out when it lacks neither; and each one's header digest.""" + served: list[dict[str, Any]] = [] + digests: dict[str, str] = {} + for sub in subs: + sub_id = sub["trajectory_id"] + cursor = cursors.get(sub_id) or SubagentCursor(after=0) + head = self._scrub({key: value for key, value in sub.items() if key != "steps"}) + digests[sub_id] = digest = _digest(head) + steps = self._scrub([step for step in sub["steps"] if step["step_id"] > cursor.after]) + changed = digest != cursor.header_digest + if steps or changed: + served.append({**(head if changed else {"trajectory_id": sub_id}), "steps": steps}) + return served, digests def _open(self, task_id: str) -> _Task | None: if self._failed is not None: @@ -220,6 +250,11 @@ def _check(self) -> None: ) +def _digest(value: Any) -> str: + """What a reader names to say it holds ``value``: the sha256 of its canonical JSON.""" + return "sha256:" + hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + def _real_now() -> datetime: return datetime.now(timezone.utc) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py index 31ec90481..86cbeec25 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py @@ -6,14 +6,14 @@ import logging from collections import OrderedDict from dataclasses import dataclass -from typing import Any, Callable, Iterable, Sequence +from typing import Any, Callable, Iterable, Mapping, Sequence from ..atif import FORMAT as ATIF_FORMAT from ..atif import Adapter from ._atif_copy import AtifCopy, AtifPage, TurnStart from ._media_spool import MediaSpool from ._turn_index import TurnIndex -from .extensions import TrajectoryState +from .extensions import SubagentCursor, TrajectoryState from .tasks.v1 import TaskError, TrajectoryLog logger = logging.getLogger(__name__) @@ -320,16 +320,18 @@ def atif_context(self, context_id: str) -> dict[str, Any] | None: return copy.context_read() def atif_task_page( - self, task_id: str, after: int, max_steps: int, max_bytes: int + self, task_id: str, after: int, max_steps: int, max_bytes: int, *, + subagent_cursors: Mapping[str, SubagentCursor] | None = None, ) -> AtifCursor | None: - """A cursor page of the task's closed atif/1 steps, in the task's state.""" + """A cursor page of the task's closed atif/1 steps, in the task's state; with ``subagent_cursors``, its + sub-agents by what the reader lacks of each (``AtifCopy.page``).""" record = self._tasks.get(task_id) copy = self._copy(record.context_id) if record is not None else None if copy is None: return None self._touch(record.context_id) state = record.state - page = copy.page(after, max_steps, max_bytes, task_id=task_id) + page = copy.page(after, max_steps, max_bytes, task_id=task_id, subagent_cursors=subagent_cursors) return AtifCursor(page=page, context_id=record.context_id, task_id=task_id, state=state) def atif_context_page( diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index f551ce057..b90d9be6d 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -276,11 +276,25 @@ class TrajectoryState(str, Enum): MAX_TRAJECTORY_READ_EVENTS = 1_000 +class SubagentCursor(ExtensionRequest): + """How far a live atif/1 reader holds one sub-agent: its last step's ``step_id``, and its header's digest.""" + + after: StrictInt = Field(ge=0) + header_digest: str = "" + + class TaskEventsTrajectoryRequest(ExtensionRequest): + """A cursor read of a task's trajectory from event ``after``. An atif/1 read may also name the digest of the header + the reader holds (``header_digest``, "" for none), which the answer then leaves out while it's unchanged, and how + far it holds each sub-agent (``subagent_cursors``, {} at first), which has the answer serve each of the task's + sub-agents by its new closed steps alone, whether or not the step that started it has closed.""" + task_id: str after: StrictInt = Field(ge=0) limit: StrictInt | None = Field(default=None, ge=1, le=MAX_TRAJECTORY_READ_EVENTS) format: TrajectoryFormat | None = None + header_digest: str | None = None + subagent_cursors: dict[str, SubagentCursor] | None = None class ContextEventsTrajectoryRequest(ExtensionRequest): @@ -309,7 +323,13 @@ class AtifEventsResponse(ExtensionResponse): ``subagents`` the embedded sub-agent trajectories of the tasks these steps belong to, as far as each is served, so the page stands alone. A sub-agent can gain steps while its task runs; a reader keeps each sub-agent's latest copy, and the page that serves a task's last step carries - them whole. The last page's header with every page's steps and the latest sub-agents is the document.""" + them whole. The last page's header with every page's steps and the latest sub-agents is the document. + + A read that named ``header_digest`` gets the header's digest, and the header only when it differs from the one the + reader holds. A read that named ``subagent_cursors`` gets each of its task's sub-agents with only the closed steps + past its cursor, and its header (the trajectory without its steps) only when that changed; ``subagent_header_digests`` + then names each one's header digest. The reader's latest header, with every page's steps and each sub-agent's + latest header and steps, is the document.""" context_id: str task_id: str @@ -322,6 +342,8 @@ class AtifEventsResponse(ExtensionResponse): events: list[Any] next: int has_more: bool + header_digest: str | None = None + subagent_header_digests: dict[str, str] | None = None def _opaque_snapshot_objects( diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index ba3dca805..2061fb562 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -905,12 +905,16 @@ def _atif_events( self, request: TaskEventsTrajectoryRequest | ContextEventsTrajectoryRequest ) -> dict[str, Any]: """An atif/1 cursor page: the copy's closed steps after step ``after``, of the task or of - the whole context.""" + the whole context. A task read that names the digest of the header it holds gets the + header's digest, and the header only when it's another; one that names sub-agent cursors + gets the task's sub-agents by what it lacks of each, with their header digests.""" max_steps = request.limit or MAX_TRAJECTORY_READ_EVENTS + held = request.header_digest if isinstance(request, TaskEventsTrajectoryRequest) else None try: if isinstance(request, TaskEventsTrajectoryRequest): cursor = self.task_trajectories.atif_task_page( - request.task_id, request.after, max_steps, MAX_TRAJECTORY_READ_BYTES + request.task_id, request.after, max_steps, MAX_TRAJECTORY_READ_BYTES, + subagent_cursors=request.subagent_cursors, ) unknown = f"Unknown task '{request.task_id}'" else: @@ -930,11 +934,13 @@ def _atif_events( task_id=cursor.task_id, state=cursor.state, **_atif_versions(page.header), - header=page.header, + header=None if held is not None and held == page.header_digest else page.header, subagents=page.subagents, events=page.steps, next=page.next, has_more=page.has_more, + header_digest=page.header_digest if held is not None else None, + subagent_header_digests=page.subagent_header_digests, ).model_dump(mode="json", exclude_none=True) async def _atif_document( diff --git a/packages/agentenv-protocol/tests/test_a2a_atif_serving.py b/packages/agentenv-protocol/tests/test_a2a_atif_serving.py index 016fd1691..758bdf498 100644 --- a/packages/agentenv-protocol/tests/test_a2a_atif_serving.py +++ b/packages/agentenv-protocol/tests/test_a2a_atif_serving.py @@ -228,6 +228,18 @@ async def _sub_agent_grows(log: TrajectoryLog, tag: str, hold: _Hold) -> TaskRes return TaskResult.text(f"{tag}: two files") +@_scenario("running") +async def _sub_agent_runs(log: TrajectoryLog, tag: str, hold: _Hold) -> TaskResult: + """Spawns a sub-agent that writes its steps while its call waits for a result, holding after each.""" + _append(log, [*_spawning(tag), {"type": "say", "step": f"{tag}-s2", "text": "sub: still listing", "agent": f"{tag}-sub"}]) + await hold.wait() + _append(log, [{"type": "say", "step": f"{tag}-s3", "text": "sub: two files", "agent": f"{tag}-sub"}]) + await hold.wait() + _append(log, [{"type": "result", "id": f"{tag}-task", "out": "two files"}, + {"type": "say", "step": f"{tag}-2", "text": f"{tag}: the explorer found two files"}]) + return TaskResult.text(f"{tag}: the explorer found two files") + + @_scenario("orphan") async def _spawn_never_answered(log: TrajectoryLog, tag: str, hold: _Hold) -> TaskResult: """Spawns a sub-agent and holds before its call's result, for a test to cancel it.""" @@ -610,6 +622,88 @@ def test_a_reader_following_the_cursor_gets_the_steps_a_sub_agent_writes_after_i assert _rebuild(pages) == document +def _held(page: dict[str, Any], held: dict[str, Any]) -> dict[str, Any]: + """The read that follows ``page`` for a reader holding ``held`` (its header and digest, and each sub-agent's), which + takes in what ``page`` served.""" + if "header" in page: + held["header"] = page["header"] + held["digest"] = page.get("header_digest", "") + for sub in page["subagents"]: + mine = held["subs"].setdefault(sub["trajectory_id"], {"steps": []}) + mine.update({key: value for key, value in sub.items() if key != "steps"}) + mine["steps"] = mine["steps"] + sub["steps"] + held["digests"] = page.get("subagent_header_digests", {}) + held["steps"] = held["steps"] + page["events"] + return {"after": page["next"], "header_digest": held["digest"], "subagent_cursors": { + sub_id: {"after": sub["steps"][-1]["step_id"] if sub["steps"] else 0, "header_digest": held["digests"][sub_id]} + for sub_id, sub in held["subs"].items()}} + + +def test_a_cursor_read_serves_a_running_sub_agents_new_steps_while_the_call_that_started_it_waits() -> None: + hold = _Hold() + held: dict[str, Any] = {"subs": {}, "steps": []} + with _serving(_toy(hold)) as client: + task_id = _send(client, "running t1", "m-1") + hold.reached() + first = _atif(client, task_id=task_id, after=0, header_digest="", subagent_cursors={}) + plain = _atif(client, task_id=task_id, after=0) + follow = _held(first, held) + hold.resume.set() + hold.reached(2) + second = _atif(client, task_id=task_id, **follow) + plain_second = _atif(client, task_id=task_id, after=plain["next"]) + again = _atif(client, task_id=task_id, **_held(second, held)) + hold.resume.set() + _ended(client, task_id) + [sub] = first["subagents"] + assert [step["step_id"] for step in sub["steps"]] == [1] and sub["agent"]["name"] == "explorer" + assert first["subagent_header_digests"] == {"t1-sub": first["subagent_header_digests"]["t1-sub"]} + # The call that started it still waits: today's read serves nothing of it, a cursor read its new step alone. + assert second["events"] == [] and plain_second["events"] == [] and plain_second["subagents"] == [] + assert [(s["trajectory_id"], [step["step_id"] for step in s["steps"]], "agent" in s) for s in second["subagents"]] \ + == [("t1-sub", [2], False)] + assert again["subagents"] == [] and "header" not in again + + +def test_a_read_naming_its_headers_digest_gets_the_header_only_when_it_changed() -> None: + hold = _Hold() + with _serving(_toy(hold)) as client: + task_id = _send(client, "grow t1", "m-1") + hold.reached() + first = _atif(client, task_id=task_id, after=0, header_digest="") + same = _atif(client, task_id=task_id, after=first["next"], header_digest=first["header_digest"]) + plain = _atif(client, task_id=task_id, after=0) + hold.resume.set() + _ended(client, task_id) + ended = _atif(client, task_id=task_id, after=same["next"], header_digest=first["header_digest"]) + assert first["header"] == plain["header"] and first["header_digest"].startswith("sha256:") + assert "header" not in same and same["header_digest"] == first["header_digest"] + # The task's end gives the header its final metrics, so it's served again under another digest. + assert ended["header"]["final_metrics"] and ended["header_digest"] != first["header_digest"] + assert "header_digest" not in plain and "subagent_header_digests" not in plain + + +def test_a_reader_following_with_cursors_rebuilds_the_tasks_document() -> None: + hold = _Hold() + held: dict[str, Any] = {"subs": {}, "steps": []} + with _serving(_toy(hold)) as client: + task_id = _send(client, "running t1", "m-1") + follow = {"after": 0, "header_digest": "", "subagent_cursors": {}} + for _ in range(2): + hold.reached(_ + 1) + follow = _held(_atif(client, task_id=task_id, **follow), held) + hold.resume.set() + _ended(client, task_id) + while True: + page = _atif(client, task_id=task_id, **follow) + follow = _held(page, held) + if not page["has_more"] and page["state"] == "completed": + break + document = _atif(client, task_id=task_id)["trajectory"] + rebuilt = {**held["header"], "steps": held["steps"], "subagent_trajectories": list(held["subs"].values())} + assert rebuilt == document + + def test_a_spawn_its_task_ended_without_answering_keeps_its_sub_agent_referenced() -> None: hold = _Hold() with _serving(_toy(hold)) as client: diff --git a/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py b/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py index 3cffa9099..cdb9a8f14 100644 --- a/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py +++ b/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py @@ -157,7 +157,7 @@ def test_live_card_advertises_the_cursor_reads() -> None: {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ] } @@ -166,6 +166,8 @@ def test_live_card_advertises_the_cursor_reads() -> None: assert card_request_accepts(request, {"task_id", "after", "limit"}) assert card_request_accepts(request, {"context_id", "after"}) assert card_request_accepts(request, {"task_id", "format"}) + assert card_request_accepts(request, {"task_id", "after", "format", "header_digest", "subagent_cursors"}) + assert not card_request_accepts(request, {"context_id", "after", "header_digest"}) with pytest.raises(TypeError, match="live must be a boolean"): enable(TRAJECTORY_V1, live="yes") diff --git a/src/agent_env/a2a_agent/trajectory_follower.py b/src/agent_env/a2a_agent/trajectory_follower.py index 4be2007b1..e4ccd7057 100644 --- a/src/agent_env/a2a_agent/trajectory_follower.py +++ b/src/agent_env/a2a_agent/trajectory_follower.py @@ -27,6 +27,7 @@ logger = logging.getLogger(__name__) _CURSOR_FIELDS = frozenset(request_fields(TaskEventsTrajectoryRequest).required) +_HELD_FIELDS = _CURSOR_FIELDS | {"format", "header_digest", "subagent_cursors"} _OPEN_STATES = frozenset({TrajectoryState.PENDING, TrajectoryState.RUNNING}) _READ_TIMEOUT_SECONDS = 30 _MAX_BACKOFF_SECONDS = 60 @@ -45,8 +46,8 @@ class _NotStarted(Exception): 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. 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.""" + ``subagents`` as far as served (by their new steps alone, each with its header, for a follow with cursors) 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 @@ -64,6 +65,46 @@ class TrajectoryBatch: TrajectorySink = Callable[[TrajectoryBatch], Awaitable[None]] +@dataclass +class _Held: + """What a follower holds of an atif/1 document, which its reads name so the agent sends only what it lacks: the + latest header and its digest, and each sub-agent's header, digest and last step. It makes each page stand alone + again, carrying the latest header and each served sub-agent's.""" + + header: dict[str, Any] | None = None + digest: str = "" + subs: dict[str, dict[str, Any]] = field(default_factory=dict) + + def request(self) -> dict[str, Any]: + return {"header_digest": self.digest, "subagent_cursors": { + sub_id: {"after": sub["after"], "header_digest": sub["digest"]} for sub_id, sub in self.subs.items()}} + + def take(self, page: AtifEventsResponse) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]: + if page.header is not None: + self.header = page.header + self.digest = page.header_digest or self.digest + digests = page.subagent_header_digests or {} + served = [] + for entry in page.subagents: + sub = self.subs.setdefault(entry["trajectory_id"], {"head": {}, "digest": "", "after": 0}) + if digests.get(entry["trajectory_id"], sub["digest"]) != sub["digest"]: + sub["head"] = {key: value for key, value in entry.items() if key != "steps"} + sub["digest"] = digests[entry["trajectory_id"]] + steps = entry.get("steps") or [] + if steps: + sub["after"] = steps[-1]["step_id"] + served.append({**sub["head"], "steps": steps}) + return self.header, served + + +def live_reads_take_cursors(card: dict) -> bool: + """Whether the agent's live atif/1 reads take the digest of the header the reader holds and a cursor per + sub-agent; an agent on an older SDK's card doesn't declare them.""" + extension = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) + method, _ = A2AAgent.operation(extension, "get") + return bool(method) and card_request_accepts(method.get("request") or {}, _HELD_FIELDS) + + def live_trajectory_endpoint(card: dict, a2a_url: str) -> str | None: """The URL of the agent's live trajectory read, or None when its card does not offer one.""" extension = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) @@ -86,6 +127,7 @@ async def follow_trajectory( headers: Mapping[str, str] | None = None, format: str | None = None, fallback_format: str | None = None, + cursors: bool = False, ) -> 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 @@ -94,7 +136,10 @@ 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. Before its first page, an atif/1 read answered 404 is a copy not started yet, read again - until ``stop`` is set. + until ``stop`` is set. With ``cursors`` (an agent whose card takes them), each atif/1 read names the digest of the + header it holds and how far it holds each sub-agent, so the agent sends the header only when it changed and each + sub-agent's steps as they close, the step that started it open or not; each batch still carries the latest header + and each served sub-agent's. 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 @@ -104,11 +149,13 @@ async def follow_trajectory( reading = format named = {"format": format} if format is not None else {} stored_atif = False + held = _Held() if cursors and format == ATIF else None async with nullcontext(client) if client is not None else httpx.AsyncClient() as http: while True: try: + holding = held.request() if held is not None and reading == ATIF else {} response = await http.post( - endpoint, json={"task_id": task_id, "after": after, **named}, headers=headers, + endpoint, json={"task_id": task_id, "after": after, **named, **holding}, headers=headers, timeout=_READ_TIMEOUT_SECONDS, ) if response.status_code == 404: @@ -145,8 +192,10 @@ async def follow_trajectory( 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, + header, subagents = (held.take(page) if held is not None else (page.header, page.subagents)) \ + if atif else (None, []) + if page.events or subagents or last: + extra = ({"header": header, "subagents": subagents, "schema_version": page.schema_version, "profile_version": page.profile_version} if atif else {}) await sink( TrajectoryBatch( @@ -160,7 +209,7 @@ async def follow_trajectory( ) ) after = page.next - stored_atif = stored_atif or (atif and bool(page.events)) + stored_atif = stored_atif or (atif and bool(page.events or subagents)) if last: return if page.has_more: 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 7ec6ac897..a095f85ee 100644 --- a/src/agent_env/task_step/snapshot_utils/live_trajectory.py +++ b/src/agent_env/task_step/snapshot_utils/live_trajectory.py @@ -54,10 +54,12 @@ 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_base``, the folder their ``media/`` paths resolve in. With ``cursors``, its reads name what the follower + holds, for an agent whose card takes that (``live_reads_take_cursors``).""" media: LiveMedia media_base: str + cursors: bool = False class LiveTrajectoryChunks: @@ -215,6 +217,7 @@ def follow(self, task_id: str) -> None: self._endpoint, task_id, sink, poll_interval_seconds=self._poll_interval_seconds, stop=self.stop, headers=self._headers, format=ATIF if self._atif else self._format, fallback_format=self._format if self._atif else None, + cursors=self._atif is not None and self._atif.cursors, ) ) ) 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 404478cfb..04075c981 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -27,7 +27,7 @@ trajectory_mode, ) from agent_env.a2a_agent.staging import draining, staged_changelogs, transfer_store -from agent_env.a2a_agent.trajectory_follower import live_trajectory_endpoint +from agent_env.a2a_agent.trajectory_follower import live_reads_take_cursors, live_trajectory_endpoint from agent_env.config.model import MODEL_PARAMS_RESERVED, ModelRole, resolve_model from agent_env.env.gateway.constants import ( DEFAULT_ROLE, @@ -657,7 +657,8 @@ 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) - live_atif = LiveAtif(atif_copies.pull_live_media, atif_copies.folder) if atif_copies.replaces_native else None + live_atif = LiveAtif(atif_copies.pull_live_media, atif_copies.folder, cursors=live_reads_take_cursors(card)) \ + if atif_copies.replaces_native else None live_turns = ( LiveTurns(*live, poll_interval_seconds=self.poll_interval_seconds, headers=agent.control_headers, format=formats.native, atif=live_atif) diff --git a/tst/integration/conftest.py b/tst/integration/conftest.py index 6f79b6565..72b5ba073 100644 --- a/tst/integration/conftest.py +++ b/tst/integration/conftest.py @@ -7,6 +7,7 @@ import pytest from agent_env.store import local_state +from tst.util.published_image import hold_registry #: The locks that guard this machine's Docker and image registry, by the start of their ids: a run's tests keep stores #: and state roots of their own, but all of them, on every pytest worker, use the one Docker and registry. @@ -30,3 +31,10 @@ def machine_locks_shared_by_the_runs_workers(): lambda id: folder / per_test(id).name if id.startswith(MACHINE_LOCKS) else per_test(id)) yield patch.undo() + + +@pytest.fixture(autouse=True) +def registry_held_still_for_each_test(monkeypatch): + """A test that runs a bundle twice expects the second run to plan what the first did, which a release publishing one + of its images between the two would change: each test sees the registry as its first lookup of each image did.""" + hold_registry(monkeypatch) 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 a79adb227..64f4dc24c 100644 --- a/tst/unit/task_step/test_prompt_agent_live_atif.py +++ b/tst/unit/task_step/test_prompt_agent_live_atif.py @@ -5,6 +5,7 @@ from __future__ import annotations import asyncio +import copy import json from pathlib import Path @@ -13,9 +14,10 @@ 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.a2a_agent.trajectory_follower import TrajectoryBatch, follow_trajectory, live_reads_take_cursors from agent_env.task_step.snapshot_utils import atif_copies from agent_env.task_step.snapshot_utils.live_trajectory import LiveTrajectoryChunks +from agent_env.task_step.task_steps import prompt_agent as pa from tst.unit.task_step.test_prompt_agent_atif_copies import _PREFIX, NATIVE, _atifs, _Run from tst.util.granting_object_store import GrantingObjectStore @@ -89,6 +91,96 @@ async def storing(self, batch): assert 1 <= len({files[name] for name in headers}) == len(headers) < len(pages) + 1 +@pytest.mark.asyncio +@pytest.mark.parametrize("cursors", [True, False], ids=["card-takes-cursors", "older-card"]) +async def test_an_agent_whose_card_takes_cursors_sends_the_header_only_when_it_changed(monkeypatch, tmp_path, cursors): + """An older agent's card doesn't take them, and it's read as before #890's follower did: the header on every read, + the stored pages the same either way. The turn holds until three reads were answered, so some find it unchanged.""" + answered = asyncio.Event() + if not cursors: + monkeypatch.setattr(pa, "live_reads_take_cursors", lambda card: False) + run = _Run(monkeypatch, tmp_path, live=True, gate=answered) + reads: list[tuple[dict, dict]] = [] + + def seen(request, path, sent, response): + if path == "/ext/trajectory" and sent.get("format") == ATIF and "after" in sent and response.status_code == 200: + reads.append((sent, json.loads(response.content))) + if len(reads) >= 3: + answered.set() + + run.wire.answer = seen + context = run.context() + response = await run.execute(context, live_trajectory=True, max_conversation_turns=1) + + [files] = _live(run).values() + header, steps = _reassembled(files) + final = run.read(_atifs(response)[-1]["url"]) + assert steps == final["steps"][:len(steps)] and header["agent"] == final["agent"] + served = [answer["header"] for _, answer in reads if "header" in answer] + if cursors: + assert all("header_digest" in sent and sent["subagent_cursors"] == {} for sent, _ in reads) + assert len(served) < len(reads) and all(a != b for a, b in zip(served, served[1:])) + else: + assert not any("header_digest" in sent or "subagent_cursors" in sent for sent, _ in reads) + assert len(served) == len(reads) + + +def test_only_a_card_declaring_the_digest_and_cursors_takes_them(monkeypatch, tmp_path): + card = _Run(monkeypatch, tmp_path, live=True).card + older = copy.deepcopy(card) + [trajectory] = [ext for ext in older["capabilities"]["extensions"] if ext["uri"].endswith("trajectory/v1")] + for branch in trajectory["params"]["methods"]["get"]["request"]["oneOf"]: + branch["optional"] = [name for name in branch.get("optional", []) if "digest" not in name and "cursor" not in name] + assert live_reads_take_cursors(card) and not live_reads_take_cursors(older) + + +@pytest.mark.asyncio +async def test_a_follow_with_cursors_stores_a_running_sub_agents_steps_before_the_call_that_started_it_closes(tmp_path): + """A read names what the follower holds; the agent sends what's new: a sub-agent's steps while the root has none.""" + store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) + sink = LiveTrajectoryChunks(store, "p/", "turn-1") + sub_head = {"trajectory_id": "toolu_1", "agent": {"name": "explorer"}} + step = lambda n, text: {"step_id": n, "source": "agent", "message": text} # noqa: E731 + answers = [ + ({"header_digest": "", "subagent_cursors": {}}, "running", { + "header": {"session_id": "c", "trajectory_id": "d"}, "header_digest": "sha256:h1", "events": [step(1, "r1")], + "next": 1, "subagents": [{**sub_head, "steps": [step(1, "s1")]}], + "subagent_header_digests": {"toolu_1": "sha256:s"}}), + ({"header_digest": "sha256:h1", "subagent_cursors": {"toolu_1": {"after": 1, "header_digest": "sha256:s"}}}, + "running", {"header_digest": "sha256:h1", "events": [], "next": 1, + "subagents": [{"trajectory_id": "toolu_1", "steps": [step(2, "s2")]}], + "subagent_header_digests": {"toolu_1": "sha256:s"}}), + ({"header_digest": "sha256:h1", "subagent_cursors": {"toolu_1": {"after": 2, "header_digest": "sha256:s"}}}, + "completed", {"header": {"session_id": "c", "trajectory_id": "d", "final_metrics": {"total_steps": 2}}, + "header_digest": "sha256:h2", "events": [step(2, "r2")], "next": 2, "subagents": [], + "subagent_header_digests": {"toolu_1": "sha256:s"}}), + ] + stored_before_root_closed: list[str] = [] + + def answer(request: httpx.Request) -> httpx.Response: + sent = json.loads(request.content) + expected, state, page = answers.pop(0) + assert {key: sent[key] for key in expected} == expected + if state == "completed": + stored_before_root_closed.extend(store.list("p/turn-1/live/sub/")) + return httpx.Response(200, json={"context_id": "c", "task_id": "t", "state": state, "format": ATIF, + "schema_version": "ATIF-v1.8", "profile_version": "1.0", "has_more": False, + **page}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(answer)) as client: + await follow_trajectory("http://agent.test/ext/trajectory", "t", sink, poll_interval_seconds=0, + stop=asyncio.Event(), client=client, format=ATIF, fallback_format=NATIVE, cursors=True) + + names = sorted(key[len("p/turn-1/live/"):] for key in store.list("p/turn-1/live/")) + assert sorted(key[len("p/turn-1/live/"):] for key in stored_before_root_closed) == [ + "sub/toolu_1/00000000-00000001.0001.header.json", "sub/toolu_1/00000000-00000001.jsonl", + "sub/toolu_1/00000001-00000002.jsonl"] + assert [n for n in names if n.endswith(".header.json") and "/" not in n] == [ + "00000000-00000001.0001.header.json", "00000001-00000002.0002.header.json"] + assert json.loads(store.read("p/turn-1/live/sub/toolu_1/00000000-00000001.0001.header.json")) == sub_head + assert not answers + + @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) diff --git a/tst/unit/test_published_image_hold.py b/tst/unit/test_published_image_hold.py new file mode 100644 index 000000000..7643467e6 --- /dev/null +++ b/tst/unit/test_published_image_hold.py @@ -0,0 +1,28 @@ +"""The integration tier's hold on the registry: a test sees each image's published digest, or that it has none, as its +first lookup of it found it, though the registry changes later in the test.""" + +from agent_env.env import published_images +from tst.util.published_image import hold_registry + +REF = "ghcr.io/example/agentenv-claude-code:src-" + "1" * 64 +OTHER = "ghcr.io/example/agentenv-echo-mcp:src-" + "2" * 64 + + +def test_an_image_published_after_the_tests_first_lookup_stays_unpublished_to_it(monkeypatch): + registry: dict[str, str] = {} + asked: list[str] = [] + + def lookup(ref): + asked.append(ref) + return registry.get(ref) + + monkeypatch.setattr(published_images, "_registry_digest", lookup) + hold_registry(monkeypatch) + assert published_images._registry_digest(REF) is None + registry[REF] = "sha256:" + "a" * 64 + registry[OTHER] = "sha256:" + "b" * 64 + assert published_images._registry_digest(REF) is None + assert published_images._registry_digest(OTHER) == "sha256:" + "b" * 64 + registry[OTHER] = "sha256:" + "c" * 64 + assert published_images._registry_digest(OTHER) == "sha256:" + "b" * 64 + assert asked == [REF, OTHER] diff --git a/tst/util/published_image.py b/tst/util/published_image.py index 806e5e9fd..69338d8dd 100644 --- a/tst/util/published_image.py +++ b/tst/util/published_image.py @@ -1,5 +1,6 @@ """Tag an image on this machine's Docker the way the gateway tier's and the base computer's fixtures do: pulled when the -registry serves the image agent-env published from the same Dockerfile and build context, else built here.""" +registry serves the image agent-env published from the same Dockerfile and build context, else built here. And hold the +registry still for a test, as the integration tier does for each.""" from __future__ import annotations @@ -8,6 +9,9 @@ import subprocess from pathlib import Path +import pytest + +from agent_env.env import published_images from agent_env.env.bootstrap import PUBLISHED_IMAGES from agent_env.env.published_images import published_pinned from agent_env.store.image_store.registry_api import read_manifest @@ -35,6 +39,21 @@ def pull_published_else_build(name: str, dockerfile: Path, context: Path, tag: s build_image(dockerfile, context, tag, platform=platform) +def hold_registry(monkeypatch: pytest.MonkeyPatch) -> None: + """For the rest of the test, each image's published digest, or that it has none, as the test's first lookup of it + found it: a release can publish an image between two runs of one test's bundle, and the second would then plan a + pull where the first built. The lookup keeps what it finds published for the process, not what it doesn't.""" + lookup = published_images._registry_digest + answers: dict[str, str | None] = {} + + def held(ref: str) -> str | None: + if ref not in answers: + answers[ref] = lookup(ref) + return answers[ref] + + monkeypatch.setattr(published_images, "_registry_digest", held) + + def _platform_image(pinned: str | None, platform: str) -> str | None: """``pinned``'s image for ``platform``, pinned by its own digest: the containerd image store keeps a pulled index whole, and ``docker save`` of one it holds only some platforms of fails.""" From 17d699cb10858bcb536289d60884f792397be3d2 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 17:26:25 -0800 Subject: [PATCH 2/5] docs(protocol): a task's cursor read names what the reader holds; the shipped agents' pinned cards declare it Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +++- packages/agentenv-protocol/README.md | 17 +++++++++++++++++ .../agents/claude_code/test_card_contract.py | 2 +- .../claude_code/test_partial_trajectory.py | 2 +- tst/unit/agents/codex/test_card_contract.py | 2 +- tst/unit/agents/codex/test_object_transfer.py | 2 +- tst/unit/agents/gemini/test_card_contract.py | 2 +- tst/unit/agents/gemini/test_object_transfer.py | 2 +- 8 files changed, 26 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d0d034f60..0add675e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -142,7 +142,9 @@ or one of them only where it is used. (`turn_events.atif_turn_events`), each such wake's end naming its turn in the step's timeline, since the turns share 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 + page where it changed, each sub-agent's under `sub//`, and the media its steps name pulled between polls. To an + agent whose card takes them (`live_reads_take_cursors`), each read names the header's digest and each sub-agent's + cursor, so the agent sends the header only when it changed and a running sub-agent's steps as they close; 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 diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index fa2a66cbd..91c19c810 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -1703,6 +1703,23 @@ included: served. A sub-agent can gain steps while its task runs, so keep each one's latest copy; the page that serves a task's last step, which closes only as the task ends, carries them whole. +- A task's cursor read may also say what the reader holds, and get only what it + lacks: + - `header_digest` is the digest of the header it holds (`""` for none). The + answer names the header's `header_digest` and leaves `header` out while the + two match. + - `subagent_cursors` maps each sub-agent's `trajectory_id` to + `{after, header_digest}`, the last `step_id` the reader holds of it and its + header's digest (`{}` at first). The answer then carries each of the task's + sub-agents by its closed steps past its cursor, whether or not the step that + started it has closed, and its header, the trajectory without `steps`, only + when that changed. A sub-agent with neither is left out, and + `subagent_header_digests` names each one's header digest. + + The card lists both fields on the task cursor read. Detect them with + `card_request_accepts(get_request, {"task_id", "after", "format", + "header_digest", "subagent_cursors"})`, and send them only to a card that + takes them. A read naming neither gets the page above. Every `atif/1` answer names `schema_version` and `profile_version` beside `format`. An adapter that raises stops its context's copy, never the turn: the diff --git a/tst/unit/agents/claude_code/test_card_contract.py b/tst/unit/agents/claude_code/test_card_contract.py index 82d569710..090947e3b 100644 --- a/tst/unit/agents/claude_code/test_card_contract.py +++ b/tst/unit/agents/claude_code/test_card_contract.py @@ -86,7 +86,7 @@ def test_request_and_response_contracts(app): {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ], } diff --git a/tst/unit/agents/claude_code/test_partial_trajectory.py b/tst/unit/agents/claude_code/test_partial_trajectory.py index 9c5d07387..ddefc4d90 100644 --- a/tst/unit/agents/claude_code/test_partial_trajectory.py +++ b/tst/unit/agents/claude_code/test_partial_trajectory.py @@ -33,7 +33,7 @@ def test_agent_card_advertises_one_get_trajectory_method_beside_the_sdks_atif_me {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ], }, diff --git a/tst/unit/agents/codex/test_card_contract.py b/tst/unit/agents/codex/test_card_contract.py index be78054f6..eaa6b85bb 100644 --- a/tst/unit/agents/codex/test_card_contract.py +++ b/tst/unit/agents/codex/test_card_contract.py @@ -117,7 +117,7 @@ def test_request_and_response_contracts(codex): {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ], } diff --git a/tst/unit/agents/codex/test_object_transfer.py b/tst/unit/agents/codex/test_object_transfer.py index e6b70c15b..5ddde77cb 100644 --- a/tst/unit/agents/codex/test_object_transfer.py +++ b/tst/unit/agents/codex/test_object_transfer.py @@ -115,7 +115,7 @@ def test_card_offers_only_the_object_forms(codex): {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ] } diff --git a/tst/unit/agents/gemini/test_card_contract.py b/tst/unit/agents/gemini/test_card_contract.py index 510fcc4b7..5d3a354c4 100644 --- a/tst/unit/agents/gemini/test_card_contract.py +++ b/tst/unit/agents/gemini/test_card_contract.py @@ -137,7 +137,7 @@ def test_request_and_response_contracts(app): {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ], } diff --git a/tst/unit/agents/gemini/test_object_transfer.py b/tst/unit/agents/gemini/test_object_transfer.py index 22192b7df..b70a0d736 100644 --- a/tst/unit/agents/gemini/test_object_transfer.py +++ b/tst/unit/agents/gemini/test_object_transfer.py @@ -61,7 +61,7 @@ def test_card_offers_every_object_form_and_no_s3_form(app): {"required": ["task_id", "objects"]}, {"required": ["context_id"]}, {"required": ["context_id", "objects"]}, - {"required": ["task_id", "after"], "optional": ["limit"]}, + {"required": ["task_id", "after"], "optional": ["limit", "header_digest", "subagent_cursors"]}, {"required": ["context_id", "after"], "optional": ["limit"]}, ], } From 0be19bd3d74e801ae1f235db7b7e07822c6dc2ab Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 17:33:39 -0800 Subject: [PATCH 3/5] test: two lookups at once of an image the registry is held still for both get the answer stored first Parallel disk builds look the disk tools image up from threads: two first lookups racing could each store their own answer, the later replacing the first, so one test could still switch between building and pulling. Co-Authored-By: Claude Opus 5.5 --- tst/unit/test_published_image_hold.py | 28 +++++++++++++++++++++++++++ tst/util/published_image.py | 14 ++++++++++---- 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/tst/unit/test_published_image_hold.py b/tst/unit/test_published_image_hold.py index 7643467e6..b1c6c6cf2 100644 --- a/tst/unit/test_published_image_hold.py +++ b/tst/unit/test_published_image_hold.py @@ -1,6 +1,8 @@ """The integration tier's hold on the registry: a test sees each image's published digest, or that it has none, as its first lookup of it found it, though the registry changes later in the test.""" +import threading + from agent_env.env import published_images from tst.util.published_image import hold_registry @@ -26,3 +28,29 @@ def lookup(ref): registry[OTHER] = "sha256:" + "c" * 64 assert published_images._registry_digest(OTHER) == "sha256:" + "b" * 64 assert asked == [REF, OTHER] + + +def test_two_lookups_at_once_both_get_the_answer_stored_first(monkeypatch): + """The first finds nothing, slowly; the second, made meanwhile, finds the image published and is stored first.""" + first_asking, second_answered = threading.Event(), threading.Event() + calls: list[str] = [] + + def lookup(ref): + calls.append(ref) + if len(calls) == 1: + first_asking.set() + second_answered.wait(5) + return None + return "sha256:" + "a" * 64 + + monkeypatch.setattr(published_images, "_registry_digest", lookup) + hold_registry(monkeypatch) + answers: dict[str, str | None] = {} + first = threading.Thread(target=lambda: answers.update(first=published_images._registry_digest(REF))) + first.start() + assert first_asking.wait(5) + answers["second"] = published_images._registry_digest(REF) + second_answered.set() + first.join(5) + assert answers["first"] == answers["second"] == published_images._registry_digest(REF) == "sha256:" + "a" * 64 + diff --git a/tst/util/published_image.py b/tst/util/published_image.py index 69338d8dd..a85c2b515 100644 --- a/tst/util/published_image.py +++ b/tst/util/published_image.py @@ -7,6 +7,7 @@ import logging import shlex import subprocess +import threading from pathlib import Path import pytest @@ -42,14 +43,19 @@ def pull_published_else_build(name: str, dockerfile: Path, context: Path, tag: s def hold_registry(monkeypatch: pytest.MonkeyPatch) -> None: """For the rest of the test, each image's published digest, or that it has none, as the test's first lookup of it found it: a release can publish an image between two runs of one test's bundle, and the second would then plan a - pull where the first built. The lookup keeps what it finds published for the process, not what it doesn't.""" + pull where the first built. The lookup keeps what it finds published for the process, not what it doesn't. Two + lookups at once, as parallel builds make, both get the answer stored first.""" lookup = published_images._registry_digest answers: dict[str, str | None] = {} + lock = threading.Lock() def held(ref: str) -> str | None: - if ref not in answers: - answers[ref] = lookup(ref) - return answers[ref] + with lock: + if ref in answers: + return answers[ref] + found = lookup(ref) + with lock: + return answers.setdefault(ref, found) monkeypatch.setattr(published_images, "_registry_digest", held) From 6e9b97f47ee04955f519f6632dead6ee74c19bcf Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 19:01:25 -0800 Subject: [PATCH 4/5] fix(a2a): an agent whose card declares the cursor fields but whose answers don't carry them is followed as before The follower took the card's word and read every answer for digests; an agent binding its own get handler answers in today's shape, so its sub-agents reached the page writer without their ids and headers, and were never stored. An answer with no sub-agent digests now passes its whole sub-agents as they are. Co-Authored-By: Claude Opus 5.5 --- .../a2a_agent/trajectory_follower.py | 7 ++++- .../task_step/test_prompt_agent_live_atif.py | 30 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/agent_env/a2a_agent/trajectory_follower.py b/src/agent_env/a2a_agent/trajectory_follower.py index e4ccd7057..1109462a8 100644 --- a/src/agent_env/a2a_agent/trajectory_follower.py +++ b/src/agent_env/a2a_agent/trajectory_follower.py @@ -80,10 +80,15 @@ def request(self) -> dict[str, Any]: sub_id: {"after": sub["after"], "header_digest": sub["digest"]} for sub_id, sub in self.subs.items()}} def take(self, page: AtifEventsResponse) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]: + """The page's latest header and its sub-agents, each with its header. An answer with no sub-agent digests is in + today's shape, from an agent whose card declares the fields but whose own handler doesn't take them, and its + whole sub-agents pass as they are.""" if page.header is not None: self.header = page.header self.digest = page.header_digest or self.digest - digests = page.subagent_header_digests or {} + if page.subagent_header_digests is None: + return self.header, page.subagents + digests = page.subagent_header_digests served = [] for entry in page.subagents: sub = self.subs.setdefault(entry["trajectory_id"], {"head": {}, "digest": "", "after": 0}) 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 64f4dc24c..d13abfacb 100644 --- a/tst/unit/task_step/test_prompt_agent_live_atif.py +++ b/tst/unit/task_step/test_prompt_agent_live_atif.py @@ -181,6 +181,36 @@ def answer(request: httpx.Request) -> httpx.Response: assert not answers +@pytest.mark.asyncio +async def test_an_agent_whose_card_declares_cursors_but_whose_answers_dont_carry_them_is_followed_as_before(tmp_path): + """Its own handler answers in today's shape, whole sub-agents and no digests: each sub-agent is still stored.""" + store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) + sink = LiveTrajectoryChunks(store, "p/", "turn-1") + sub = {"trajectory_id": "toolu_1", "agent": {"name": "explorer"}} + step = lambda n, text: {"step_id": n, "source": "agent", "message": text} # noqa: E731 + answers = [("running", [step(1, "r1")], 1, [step(1, "s1")]), ("completed", [step(2, "r2")], 2, + [step(1, "s1"), step(2, "s2")])] + named = [] + + def answer(request: httpx.Request) -> httpx.Response: + named.append("subagent_cursors" in json.loads(request.content)) + state, events, nxt, sub_steps = answers.pop(0) + return httpx.Response(200, json={"context_id": "c", "task_id": "t", "state": state, "format": ATIF, + "schema_version": "ATIF-v1.8", "profile_version": "1.0", "has_more": False, + "header": {"session_id": "c", "trajectory_id": "d"}, "events": events, + "next": nxt, "subagents": [{**sub, "steps": sub_steps}]}) + + async with httpx.AsyncClient(transport=httpx.MockTransport(answer)) as client: + await follow_trajectory("http://agent.test/ext/trajectory", "t", sink, poll_interval_seconds=0, + stop=asyncio.Event(), client=client, format=ATIF, fallback_format=NATIVE, cursors=True) + + names = sorted(key[len("p/turn-1/live/"):] for key in store.list("p/turn-1/live/") if "/sub/" in key) + assert named == [True, True] + assert names == ["sub/toolu_1/00000000-00000001.0001.header.json", "sub/toolu_1/00000000-00000001.jsonl", + "sub/toolu_1/00000001-00000002.jsonl"] + assert json.loads(store.read("p/turn-1/live/sub/toolu_1/00000000-00000001.0001.header.json")) == sub + + @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) From 0db7f4fc9cdfbc2b839edfe10dd7e848dbcba528 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 19:59:26 -0800 Subject: [PATCH 5/5] refactor(a2a): the follower holds each sub-agent as a _HeldSub, and drops what it holds on a native fallback Each held sub-agent is a typed record rather than a dict read by string keys; a sub-agent's header is taken when the answer names a digest other than the one held; a native fallback clears what the follower holds, so the loop asks only whether it holds anything. The live tests share one step helper. Co-Authored-By: Claude Opus 5.5 --- .../a2a_agent/trajectory_follower.py | 42 ++++++++++++------- .../task_step/test_prompt_agent_live_atif.py | 21 ++++++---- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/src/agent_env/a2a_agent/trajectory_follower.py b/src/agent_env/a2a_agent/trajectory_follower.py index 1109462a8..74cc04a6d 100644 --- a/src/agent_env/a2a_agent/trajectory_follower.py +++ b/src/agent_env/a2a_agent/trajectory_follower.py @@ -65,19 +65,29 @@ class TrajectoryBatch: TrajectorySink = Callable[[TrajectoryBatch], Awaitable[None]] +@dataclass +class _HeldSub: + """A sub-agent as a follower holds it: its header (the trajectory without its steps), that header's digest, and + its last step's ``step_id``.""" + + head: dict[str, Any] = field(default_factory=dict) + digest: str = "" + after: int = 0 + + @dataclass class _Held: """What a follower holds of an atif/1 document, which its reads name so the agent sends only what it lacks: the - latest header and its digest, and each sub-agent's header, digest and last step. It makes each page stand alone - again, carrying the latest header and each served sub-agent's.""" + latest header and its digest, and each sub-agent's. It makes each page stand alone again, carrying the latest + header and each served sub-agent's.""" header: dict[str, Any] | None = None digest: str = "" - subs: dict[str, dict[str, Any]] = field(default_factory=dict) + subs: dict[str, _HeldSub] = field(default_factory=dict) def request(self) -> dict[str, Any]: return {"header_digest": self.digest, "subagent_cursors": { - sub_id: {"after": sub["after"], "header_digest": sub["digest"]} for sub_id, sub in self.subs.items()}} + sub_id: {"after": sub.after, "header_digest": sub.digest} for sub_id, sub in self.subs.items()}} def take(self, page: AtifEventsResponse) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]: """The page's latest header and its sub-agents, each with its header. An answer with no sub-agent digests is in @@ -88,17 +98,17 @@ def take(self, page: AtifEventsResponse) -> tuple[dict[str, Any] | None, list[di self.digest = page.header_digest or self.digest if page.subagent_header_digests is None: return self.header, page.subagents - digests = page.subagent_header_digests served = [] for entry in page.subagents: - sub = self.subs.setdefault(entry["trajectory_id"], {"head": {}, "digest": "", "after": 0}) - if digests.get(entry["trajectory_id"], sub["digest"]) != sub["digest"]: - sub["head"] = {key: value for key, value in entry.items() if key != "steps"} - sub["digest"] = digests[entry["trajectory_id"]] + sub = self.subs.setdefault(entry["trajectory_id"], _HeldSub()) + digest = page.subagent_header_digests.get(entry["trajectory_id"]) + if digest is not None and digest != sub.digest: + sub.head = {key: value for key, value in entry.items() if key != "steps"} + sub.digest = digest steps = entry.get("steps") or [] if steps: - sub["after"] = steps[-1]["step_id"] - served.append({**sub["head"], "steps": steps}) + sub.after = steps[-1]["step_id"] + served.append({**sub.head, "steps": steps}) return self.header, served @@ -158,7 +168,7 @@ async def follow_trajectory( async with nullcontext(client) if client is not None else httpx.AsyncClient() as http: while True: try: - holding = held.request() if held is not None and reading == ATIF else {} + holding = held.request() if held is not None else {} response = await http.post( endpoint, json={"task_id": task_id, "after": after, **named, **holding}, headers=headers, timeout=_READ_TIMEOUT_SECONDS, @@ -175,7 +185,7 @@ async def follow_trajectory( 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 + reading, named, after, held = fallback_format, {"format": fallback_format}, 0, None continue logger.warning("Agent refused task %s's atif/1 trajectory (%s); stopped following it", task_id, refused) @@ -197,8 +207,10 @@ async def follow_trajectory( 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 - header, subagents = (held.take(page) if held is not None else (page.header, page.subagents)) \ - if atif else (None, []) + if held is not None: + header, subagents = held.take(page) + else: + header, subagents = (page.header, page.subagents) if atif else (None, []) if page.events or subagents or last: extra = ({"header": header, "subagents": subagents, "schema_version": page.schema_version, "profile_version": page.profile_version} if atif else {}) 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 d13abfacb..2b7db47e9 100644 --- a/tst/unit/task_step/test_prompt_agent_live_atif.py +++ b/tst/unit/task_step/test_prompt_agent_live_atif.py @@ -24,6 +24,10 @@ pytestmark = pytest.mark.usefixtures("local_stores") +def _step(n: int, text: str) -> dict: + return {"step_id": n, "source": "agent", "message": text} + + 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]] = {} @@ -130,7 +134,8 @@ def test_only_a_card_declaring_the_digest_and_cursors_takes_them(monkeypatch, tm older = copy.deepcopy(card) [trajectory] = [ext for ext in older["capabilities"]["extensions"] if ext["uri"].endswith("trajectory/v1")] for branch in trajectory["params"]["methods"]["get"]["request"]["oneOf"]: - branch["optional"] = [name for name in branch.get("optional", []) if "digest" not in name and "cursor" not in name] + branch["optional"] = [name for name in branch.get("optional", []) + if "digest" not in name and "cursor" not in name] assert live_reads_take_cursors(card) and not live_reads_take_cursors(older) @@ -140,19 +145,18 @@ async def test_a_follow_with_cursors_stores_a_running_sub_agents_steps_before_th store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) sink = LiveTrajectoryChunks(store, "p/", "turn-1") sub_head = {"trajectory_id": "toolu_1", "agent": {"name": "explorer"}} - step = lambda n, text: {"step_id": n, "source": "agent", "message": text} # noqa: E731 answers = [ ({"header_digest": "", "subagent_cursors": {}}, "running", { - "header": {"session_id": "c", "trajectory_id": "d"}, "header_digest": "sha256:h1", "events": [step(1, "r1")], - "next": 1, "subagents": [{**sub_head, "steps": [step(1, "s1")]}], + "header": {"session_id": "c", "trajectory_id": "d"}, "header_digest": "sha256:h1", + "events": [_step(1, "r1")], "next": 1, "subagents": [{**sub_head, "steps": [_step(1, "s1")]}], "subagent_header_digests": {"toolu_1": "sha256:s"}}), ({"header_digest": "sha256:h1", "subagent_cursors": {"toolu_1": {"after": 1, "header_digest": "sha256:s"}}}, "running", {"header_digest": "sha256:h1", "events": [], "next": 1, - "subagents": [{"trajectory_id": "toolu_1", "steps": [step(2, "s2")]}], + "subagents": [{"trajectory_id": "toolu_1", "steps": [_step(2, "s2")]}], "subagent_header_digests": {"toolu_1": "sha256:s"}}), ({"header_digest": "sha256:h1", "subagent_cursors": {"toolu_1": {"after": 2, "header_digest": "sha256:s"}}}, "completed", {"header": {"session_id": "c", "trajectory_id": "d", "final_metrics": {"total_steps": 2}}, - "header_digest": "sha256:h2", "events": [step(2, "r2")], "next": 2, "subagents": [], + "header_digest": "sha256:h2", "events": [_step(2, "r2")], "next": 2, "subagents": [], "subagent_header_digests": {"toolu_1": "sha256:s"}}), ] stored_before_root_closed: list[str] = [] @@ -187,9 +191,8 @@ async def test_an_agent_whose_card_declares_cursors_but_whose_answers_dont_carry store = GrantingObjectStore(str(tmp_path / "store"), reaches=True) sink = LiveTrajectoryChunks(store, "p/", "turn-1") sub = {"trajectory_id": "toolu_1", "agent": {"name": "explorer"}} - step = lambda n, text: {"step_id": n, "source": "agent", "message": text} # noqa: E731 - answers = [("running", [step(1, "r1")], 1, [step(1, "s1")]), ("completed", [step(2, "r2")], 2, - [step(1, "s1"), step(2, "s2")])] + answers = [("running", [_step(1, "r1")], 1, [_step(1, "s1")]), ("completed", [_step(2, "r2")], 2, + [_step(1, "s1"), _step(2, "s2")])] named = [] def answer(request: httpx.Request) -> httpx.Response: