Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,18 +126,25 @@ 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 `<trajectory_id>.json` under `{prefix}atif/instance_id=<id>/<agent>/`
(`metadata["atif_copies"]`, `task_step/snapshot_utils/atif_copies.py`), overwritten each turn, with the turn's aux
(`format_not_prescribed`). A prompt step or always_on step of a run that prescribes `atif/1` reads each turn's copy
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 `<trajectory_id>.json` under
`{prefix}atif/instance_id=<id>/<agent>/` (`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
atif/1 the copy is the turn's trajectory, labelled `atif/1` in its `TurnTrajectory`, and a turn whose copy can't be
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. 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 `<turn>/live/`, the header beside the
page where it changed, each sub-agent's under `sub/<id>/`, 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
Expand Down
54 changes: 50 additions & 4 deletions src/agent_env/a2a_agent/trajectory_follower.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand All @@ -30,19 +32,33 @@
_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"})


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``
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
events: list[Any]
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]]
Expand All @@ -69,17 +85,25 @@ 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. 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
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:
Expand All @@ -88,22 +112,42 @@ 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)
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
logger.warning("Live trajectory read failed (consec=%d, will retry): %s", failures, exc)
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
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,
Expand All @@ -112,9 +156,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:
Expand Down
48 changes: 42 additions & 6 deletions src/agent_env/task_step/snapshot_utils/atif_copies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -133,19 +133,55 @@ 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))))
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:
"""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]:
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,
Expand Down
Loading
Loading