Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
da76c31
feat(task-steps): prompt steps store each turn's atif/1 copy when the…
earakely-scale Nov 20, 2026
9a63195
fix(task-steps): a failed atif/1 link is retried, a malformed copy is…
earakely-scale Nov 20, 2026
7e699c5
fix(a2a-agent): what an agent staged before its call failed reaches t…
earakely-scale Nov 20, 2026
d4a1428
fix(a2a-agent): a staged call that never reached the agent collects n…
earakely-scale Nov 21, 2026
559a160
refactor(task-steps): one media check in the protocol, self-filling a…
earakely-scale Nov 21, 2026
1339deb
fix(atif): a newer copy's media are still checked
earakely-scale Nov 21, 2026
f5ff1a4
feat(task-steps): a prescribed run's atif/1 copy is its trajectory, n…
earakely-scale Nov 21, 2026
8ae95e4
feat(verifiers): judges grade a prescribed run's atif/1 turns by thei…
earakely-scale Nov 21, 2026
0f06de5
fix(verifiers): an atif/1 copy graded as stored is read without faili…
earakely-scale Nov 21, 2026
e0756a7
fix(verifiers): a judge's atif/1 view names the tools offered without…
earakely-scale Nov 22, 2026
e49bc1e
fix(verifiers): an atif/1 cut and its judges resolve each sub-agent r…
earakely-scale Nov 22, 2026
6954cdb
fix(verifiers): a sub-agent id held as a list or an object names noth…
earakely-scale Nov 22, 2026
4b04f2c
test(verifiers): a judge reads each of Claude Code's recorded turns w…
earakely-scale Nov 22, 2026
79851b0
fix(verifiers): a sub-agent with no id names nothing, so it stops no …
earakely-scale Nov 22, 2026
4dc78ea
fix(task-steps): a turn whose atif/1 copy lacks some of its media has…
earakely-scale Nov 23, 2026
43b7571
fix(verifiers): a judge's compacted atif/1 turn names each sub-agent'…
earakely-scale Nov 23, 2026
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 .agentenv/config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ agent_default = "local" # agents too

# [trajectories]
# formats = ["atif/1"] # the formats beside native a run prescribes to each agent whose trajectory it reads;
# # none by default, so agents build native only. Per run: user_overrides.trajectory_formats
# # none by default, so agents build native only. Per run: user_overrides.trajectory_formats.
# # With atif/1, a prompt step's turns are their atif/1 copies (native where one can't be had),
# # stored under {prefix}atif/instance_id=<id>/<agent>/, and its judges grade them

# [envs]
# default_gateway_env_id = "default" # the gateway every gateway deploy runs
Expand Down
13 changes: 12 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,18 @@ 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`).
(`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
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.
- 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
8 changes: 6 additions & 2 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1319,8 +1319,12 @@ the profile's spec, and `fixtures/` holds its canonical examples. The package ne
terminal state on its last step. Its `page()` is the live view, built when it's read: closed steps only, so a
reader's earlier page is always a prefix of a later one. A step is rendered once a page serves it and kept, so a
read costs one parse of the document, not a render of every step.
- **Readers** (`load`, `tasks`, `media_paths`, `strip_profile`, `is_prefix`) take any valid ATIF document, with or
without the profile, such as a Harbor task's trajectory.json.
- **Readers** (`load`, `tasks`, `task_document`, `media_paths`, `media_refs`, `strip_profile`, `is_prefix`) take any
valid ATIF document, with or without the profile, such as a Harbor task's trajectory.json. `task_document` cuts A2A
tasks out of a conversation's document as a document of their own (`tasks_document` for tasks found without ids), as a
reader showing one turn shows it. `media_refs` names each place a media
file is named, with the profile's details for it; `validate(document, media=StoredMedia(sizes))` checks those
details against files stored beside the document without reading their bytes.

## A2A agent framework

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@ cross-check that reads them; per-part origins, when a reader needs them; and an
producer's output to profile 1.0. `reader=True` checks someone else's document for reading instead: what a producer
must not write only warns, and the document fails only where agentenv couldn't read it. `media` is the folder the
document's media paths are relative to, the one holding `media/`, or the files by path; without it only the paths' form
is checked. `validate_live(pages, final)` checks what a live reader was served, page by page, with the final read. A sub-agent's task is its spawning call's, found through the references, so an embedded sub-agent that no served step references isn't held to `live-unanswered`. On
is checked. `StoredMedia(sizes)` stands for files stored beside the document whose bytes were checked against their
names as they were stored, as agent-env's worker checks each file an agent pushes: `media-bytes` then holds the
profile's sha256 to each file's name and its size to the stored one, without reading the bytes. `validate_media(document, media)` gives the `media-bytes` findings alone, for a document
newer than these models, which `validate` stops at. `media_refs` lists each
place a document names a media file, with the profile's details for it, as these checks walk them. `validate_live(pages, final)` checks what a live reader was served, page by page, with the final read. A sub-agent's task is its spawning call's, found through the references, so an embedded sub-agent that no served step references isn't held to `live-unanswered`. On
the command line: `python -m agentenv_protocol.atif validate FILE [--media DIR] [--reader]`, which prints each finding
and exits 1 when one is an error.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,35 @@
read_profile,
)
from .kit import KIT_RULES, KitResult, check_adapter
from .reader import MEDIA_PATH, Task, check, check_media, is_prefix, load, media_file, media_paths, strip_profile, tasks
from .reader import (
MEDIA_PATH,
MediaRef,
Task,
check,
check_media,
is_prefix,
load,
media_file,
media_paths,
media_refs,
strip_profile,
task_document,
tasks,
tasks_document,
)
from .runner import AdapterRun, Fed, RecordedTask, replay
from .served import AuxEntry, ContentItem, MediaItem, ServedData, ServedError, ServedMedia, ServedTurn
from .validator import RULES, Finding, Rule, errors_in, validate, validate_live
from .validator import RULES, Finding, Rule, StoredMedia, errors_in, validate, validate_live, validate_media

__all__ = [
"Adapter", "AdapterRef", "AdapterRun", "AdapterSpec", "Agent", "AgentProfile", "Arrival", "atif_adapter",
"AtifError", "AtifTurn", "AudioSource", "aux", "AuxEntry", "check", "check_adapter", "check_media", "ContentItem", "ContentPart",
"Document", "dump_profile", "errors_in", "Fed", "FinalMetrics", "FinalMetricsProfile", "Finding", "finish",
"FORMAT", "ImageSource", "is_prefix", "KIT_RULES", "KitResult", "load", "Media", "MEDIA_PATH", "media_file", "media_paths", "MediaInfo",
"MediaItem", "Metrics", "MetricsProfile", "Native", "native", "Observation", "ObservationResult",
"MediaItem", "MediaRef", "media_refs", "Metrics", "MetricsProfile", "Native", "native", "Observation", "ObservationResult",
"ObservationResultProfile", "PROFILE_KEY", "profile_of", "PROFILE_VERSION", "PROFILES", "RAW_ARGUMENTS",
"read_profile", "ReasoningBlock", "RecordedTask", "replay", "Rule", "RULES", "SCHEMA_VERSION", "Selector",
"ServedData", "ServedError", "ServedMedia", "ServedTurn", "Step", "StepData", "StepError", "StepProfile",
"strip_profile", "SubagentTrajectoryRef", "SubagentTrajectoryRefProfile", "Task", "tasks", "timestamp", "ToolCall",
"ToolCallProfile", "Trajectory", "TrajectoryProfile", "TurnContext", "validate", "validate_live", "VOCABULARIES",
"ServedData", "ServedError", "ServedMedia", "ServedTurn", "Step", "StepData", "StepError", "StepProfile", "StoredMedia",
"strip_profile", "SubagentTrajectoryRef", "SubagentTrajectoryRefProfile", "Task", "task_document", "tasks", "tasks_document", "timestamp", "ToolCall",
"ToolCallProfile", "Trajectory", "TrajectoryProfile", "TurnContext", "validate", "validate_live", "validate_media", "VOCABULARIES",
]
139 changes: 120 additions & 19 deletions packages/agentenv-protocol/src/agentenv_protocol/atif/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterator, Mapping
from typing import Any, Iterable, Iterator, Mapping

from pydantic import ValidationError

Expand Down Expand Up @@ -85,14 +85,81 @@ def tasks(document: Mapping[str, Any]) -> list[Task]:
return out


def _trajectories(document: Mapping[str, Any]) -> Iterator[Mapping[str, Any]]:
yield document
for sub in document.get("subagent_trajectories") or []:
yield from _trajectories(sub)
def task_document(document: Mapping[str, Any], task_ids: Iterable[str]) -> dict[str, Any]:
"""The A2A tasks ``task_ids`` names, cut out of ``document`` as a document of their own that ATIF's models load: their
steps in order, renumbered from 1 with each result's arrival step to match, the root's sub-agents those steps reach
kept whole (and those a kept one reaches, from any depth inside it, each reference resolved where it sits), and the
root's ``final_metrics`` and ``continued_trajectory_ref`` dropped, since they describe the whole document. A reader that shows one turn shows this. KeyError naming a task it doesn't hold."""
wanted = list(task_ids)
picked = [task for task in tasks(document) if task.task_id in wanted]
missing = [task_id for task_id in wanted if task_id not in {task.task_id for task in picked}]
if missing:
raise KeyError(f"the document holds no task {', '.join(map(repr, missing))}")
return tasks_document(document, picked)


def tasks_document(document: Mapping[str, Any], picked: Iterable[Task]) -> dict[str, Any]:
"""``task_document`` for tasks already found among ``tasks(document)``, such as the tasks of a document without the
profile, which carry no ids."""
steps = [copy.deepcopy(step) for task in picked for step in task.steps]
numbers = {step.get("step_id"): n for n, step in enumerate(steps, 1)}
for n, step in enumerate(steps, 1):
step["step_id"] = n
for result in (step.get("observation") or {}).get("results") or []:
arrived = ((result.get("extra") or {}).get(PROFILE_KEY) or {}).get("arrived")
if isinstance(arrived, dict) and "step_id" in arrived:
if arrived["step_id"] in numbers:
arrived["step_id"] = numbers[arrived["step_id"]]
else:
del arrived["step_id"]
subs = list(document.get("subagent_trajectories") or [])
resolve = _resolver(document)
reached: set[int] = set()
frontier = _reached(resolve[""], steps)
while frontier:
index = frontier.pop()
if index not in reached:
reached.add(index)
for prefix, trajectory in _trajectories(subs[index], f"subagent_trajectories[{index}]."):
frontier += _reached(resolve[prefix], trajectory.get("steps") or [])
cut = {key: copy.deepcopy(value) for key, value in document.items()
if key not in ("steps", "subagent_trajectories", "final_metrics", "continued_trajectory_ref")}
cut["steps"] = steps
kept = [copy.deepcopy(sub) for index, sub in enumerate(subs) if index in reached]
if kept:
cut["subagent_trajectories"] = kept
return cut


def _reached(visible: Mapping[Any, str], steps: Iterable[Mapping[str, Any]]) -> list[int]:
"""The index among the root's sub-agents of each one the references in ``steps`` name, or name one inside."""
return [int(_ROOT_SUB.match(visible[ref.get("trajectory_id")])[1]) for step in steps
for result in (step.get("observation") or {}).get("results") or []
for ref in result.get("subagent_trajectory_ref") or [] if ref.get("trajectory_id") in visible]


_ROOT_SUB = re.compile(r"subagent_trajectories\[(\d+)\]\.")


def _resolver(document: Mapping[str, Any], prefix: str = "",
outer: Mapping[Any, str] | None = None) -> dict[str, dict[Any, str]]:
"""For each trajectory, by its path prefix, the sub-agent each id a reference in it names: one embedded in it,
else the nearest one embedded around it, by path prefix. ATIF makes an id unique only within its parent's array,
and the builder embeds every sub-agent in the root."""
subs = list(document.get("subagent_trajectories") or [])
visible = {**(outer or {}), **{sub.get("trajectory_id"): f"{prefix}subagent_trajectories[{index}]."
for index, sub in enumerate(subs)}}
out = {prefix: visible}
for index, sub in enumerate(subs):
out.update(_resolver(sub, f"{prefix}subagent_trajectories[{index}].", visible))
return out


def _parts(value: Any) -> list[Mapping[str, Any]]:
return [p for p in value if isinstance(p, Mapping)] if isinstance(value, list) else []
def _trajectories(document: Mapping[str, Any], prefix: str = "") -> Iterator[tuple[str, Mapping[str, Any]]]:
"""The document and every sub-agent embedded in it, at any depth, with the path prefix of each."""
yield prefix, document
for index, sub in enumerate(document.get("subagent_trajectories") or []):
yield from _trajectories(sub, f"{prefix}subagent_trajectories[{index}].")


#: A media file's name, ``<sha256>.<ext>``: what its bytes are, never a secret.
Expand All @@ -118,21 +185,55 @@ def check_media(path: str, data: bytes) -> None:
raise AtifError(f"{path}'s bytes have sha256 {digest}")


@dataclass(frozen=True)
class MediaRef:
"""One place a document names a media file: its ``path``, ``where`` it's named (such as
``steps[2].message[1].source.path``), the profile's details for it ({} without) and the media type of the part
that names it, else the details' own."""

path: str
where: str
info: Mapping[str, Any]
media_type: str | None


def media_refs(document: Mapping[str, Any]) -> list[MediaRef]:
"""Every place the document and the sub-agents embedded in it name a media file, in order: in each step's message
and each result's content, the image and audio parts' paths, then the files the profile records beside them for
media ATIF has no part type for."""
refs: list[MediaRef] = []
for prefix, trajectory in _trajectories(document):
for index, step in enumerate(trajectory.get("steps") or []):
where = f"{prefix}steps[{index}]"
holders = [(where, step, step.get("message"), "message")] + [
(f"{where}.observation.results[{n}]", result, result.get("content"), "content")
for n, result in enumerate((step.get("observation") or {}).get("results") or [])]
for owner, holder, content, field_name in holders:
details = profile_of(holder).get("media") or {}
details = details if isinstance(details, Mapping) else {}
named: set[str] = set()
for n, part in enumerate(content if isinstance(content, list) else []):
source = part.get("source") if isinstance(part, Mapping) else None
if isinstance(source, Mapping) and isinstance(source.get("path"), str):
path, info = source["path"], _details(details, source["path"])
named.add(path)
refs.append(MediaRef(path, f"{owner}.{field_name}[{n}].source.path", info,
source.get("media_type") or info.get("media_type")))
refs += [MediaRef(path, f"{owner}.extra.{PROFILE_KEY}.media[{path}]", _details(details, path),
_details(details, path).get("media_type"))
for path in details if path not in named]
return refs


def _details(details: Mapping[str, Any], path: str) -> Mapping[str, Any]:
info = details.get(path)
return info if isinstance(info, Mapping) else {}


def media_paths(document: Mapping[str, Any]) -> list[str]:
"""Every media file the document names, once each, in the order they appear: image and audio parts' paths, and
the files the profile records for media ATIF has no part type for."""
seen: dict[str, None] = {}
for trajectory in _trajectories(document):
for step in trajectory.get("steps") or []:
holders = [step] + list((step.get("observation") or {}).get("results") or [])
for holder in holders:
for part in _parts(holder.get("message") if holder is step else holder.get("content")):
path = (part.get("source") or {}).get("path")
if isinstance(path, str):
seen.setdefault(path)
for path in profile_of(holder).get("media") or {}:
seen.setdefault(path)
return list(seen)
return list(dict.fromkeys(ref.path for ref in media_refs(document)))


def strip_profile(document: Mapping[str, Any]) -> dict[str, Any]:
Expand Down
Loading
Loading