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
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<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
page where it changed, each sub-agent's under `sub/<id>/`, 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
Expand Down
17 changes: 17 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
SnapshotReadObjects,
SnapshotUploadedObjects,
SnapshotWriteObjects,
SubagentCursor,
TaskEventsTrajectoryRequest,
TaskObjectTrajectoryRequest,
TaskTrajectoryRequest,
Expand Down Expand Up @@ -245,6 +246,7 @@
"SnapshotWriteObjects",
"StagingStore",
"TaskError",
"SubagentCursor",
"TaskEventsTrajectoryRequest",
"TaskObjectTrajectoryRequest",
"TaskOutcome",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,22 @@

import base64
import binascii
import hashlib
import json
import logging
import threading
import uuid
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__)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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()
Expand All @@ -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:
Expand Down Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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(
Expand Down
Loading
Loading