diff --git a/.agentenv/config.example.toml b/.agentenv/config.example.toml index 7ca405d01..cc7ab5806 100644 --- a/.agentenv/config.example.toml +++ b/.agentenv/config.example.toml @@ -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=//, and its judges grade them # [envs] # default_gateway_env_id = "default" # the gateway every gateway deploy runs diff --git a/AGENTS.md b/AGENTS.md index f0914a63b..b0128b647 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 `.json` under `{prefix}atif/instance_id=//` + (`metadata["atif_copies"]`, `task_step/snapshot_utils/atif_copies.py`), overwritten each turn, with the turn's aux + log and turn context under `turns/` and the media it names pulled into `media/`; after a restart the session's + earlier document names the next in `continued_trajectory_ref`. Each turn's record says how its copy checked + (`AtifRecord`: `valid`, `invalid`, `newer`, `unavailable`), and a copy never fails the run. When the agent offers + 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 diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 6c24801b9..358b6dd40 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -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 diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md b/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md index 811658112..442ee29d1 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/PROFILE.md @@ -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. diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py index 85bfb47d5..dda27d843 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/__init__.py @@ -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", ] diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/reader.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/reader.py index 6d493f7f5..83cc03bfd 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/reader.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/reader.py @@ -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 @@ -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, ``.``: what its bytes are, never a secret. @@ -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]: diff --git a/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py b/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py index 7675a0200..8cb2cc30e 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/atif/validator.py @@ -26,7 +26,7 @@ StepError, profile_of, ) -from .reader import MEDIA_PATH, is_prefix, tasks +from .reader import MEDIA_PATH, _resolver, _trajectories, is_prefix, media_refs, tasks ERROR = "error" WARNING = "warning" @@ -131,17 +131,26 @@ def no_constant(name: str) -> Any: return None, [Finding("json", ERROR, "", str(exc))] +@dataclass(frozen=True) +class StoredMedia: + """Media files stored beside a document by one who checked each file's bytes against its name, as the worker does + each file an agent pushes: their sizes by path, None where the store can't tell. Given these, ``validate`` holds + the profile's sha256 to each name and its size to the stored file's without reading the bytes.""" + + sizes: Mapping[str, int | None] + + def validate(document: Any, *, reader: bool = False, - media: Path | Mapping[str, bytes] | None = None) -> list[Finding]: + media: Path | Mapping[str, bytes] | StoredMedia | None = None) -> list[Finding]: """Every finding for ``document``. ``reader`` checks someone else's document for reading rather than a producer's - output. ``media`` is the folder the document's media paths are relative to, or the files by path; without it, only - the paths' form is checked.""" + output. ``media`` is the folder the document's media paths are relative to, the files by path, or the files stored + beside it (``StoredMedia``); without it, only the paths' form is checked.""" found = _Findings(reader) _check(document, found, media) return found.items -def _check(document: Any, found: _Findings, media: Path | Mapping[str, bytes] | None) -> None: +def _check(document: Any, found: _Findings, media: Path | Mapping[str, bytes] | StoredMedia | None) -> None: if not isinstance(document, Mapping): found.add("json", "", "a document is a JSON object") return @@ -210,13 +219,6 @@ def validate_live(pages: Sequence[Mapping[str, Any] | None], final: Mapping[str, # What the document holds -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}].") - - def _count(value: Any) -> int | None: """A token count as ATIF's models read it, a numeric string included, or None when there is none.""" try: @@ -321,20 +323,6 @@ def _outside_keys(objects: list[tuple[str, str, Mapping[str, Any]]], found: _Fin f"the profile names no key outside extra.{PROFILE_KEY} here") -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 _calls_and_references(document: Mapping[str, Any], found: _Findings) -> None: resolve = _resolver(document) seen: dict[str, str] = {} @@ -397,15 +385,35 @@ def _usage(document: Mapping[str, Any], found: _Findings) -> None: f"cache reads and writes ({cache}) exceed prompt_tokens ({prompt}), which include them") -def _media(document: Mapping[str, Any], found: _Findings, media: Path | Mapping[str, bytes] | None) -> None: - for where, path, info in _media_paths(document): +def validate_media(document: Mapping[str, Any], media: Path | Mapping[str, bytes] | StoredMedia, *, + reader: bool = False) -> list[Finding]: + """The ``media-bytes`` findings alone, for a document ``media_refs`` can walk, whether or not ATIF's models accept + it: a document newer than these models, which ``validate`` stops at, still names files a reader needs.""" + found = _Findings(reader) + _media_files(document, found, media) + return found.items + + +def _media(document: Mapping[str, Any], found: _Findings, + media: Path | Mapping[str, bytes] | StoredMedia | None) -> None: + for ref in media_refs(document): + if "://" in ref.path: + found.add("media-path", ref.where, + f"{ref.path!r} is a URL; the profile's media are files beside the document") + elif not MEDIA_PATH.match(ref.path): + found.add("media-path", ref.where, f"{ref.path!r} isn't media/.") + if media is not None: + _media_files(document, found, media) + + +def _media_files(document: Mapping[str, Any], found: _Findings, media: Path | Mapping[str, bytes] | StoredMedia) -> None: + for ref in media_refs(document): + where, path, info = ref.where, ref.path, ref.info if "://" in path: - found.add("media-path", where, f"{path!r} is a URL; the profile's media are files beside the document") continue named = MEDIA_PATH.match(path) - if not named: - found.add("media-path", where, f"{path!r} isn't media/.") - if media is None: + if isinstance(media, StoredMedia): + _stored(found, where, path, named, info, media) continue data = _media_bytes(media, path) if data is None: @@ -420,24 +428,16 @@ def _media(document: Mapping[str, Any], found: _Findings, media: Path | Mapping[ found.add("media-bytes", where, f"the profile gives {info['bytes']} bytes, but the file has {len(data)}") -def _media_paths(document: Mapping[str, Any]) -> Iterator[tuple[str, str, Mapping[str, Any]]]: - """Each media path the document names, where, and the profile's details for it.""" - for where, step in _steps(document): - holders = [(f"{where}.message", step, step.get("message"))] + [ - (f"{where}.observation.results[{n}].content", result, result.get("content")) - for n, result in enumerate(_results(step))] - for at, holder, parts in holders: - details = profile_of(holder).get("media") or {} - details = details if isinstance(details, Mapping) else {} - paths = [(f"{at}[{n}].source.path", part["source"]["path"]) - for n, part in enumerate(parts if isinstance(parts, list) else []) - if isinstance(part, Mapping) and isinstance((part.get("source") or {}).get("path"), str)] - listed = {path for _, path in paths} - owner = at.rsplit(".", 1)[0] - paths += [(f"{owner}.extra.{PROFILE_KEY}.media[{path}]", path) for path in details if path not in listed] - for path_where, path in paths: - info = details.get(path) - yield path_where, path, info if isinstance(info, Mapping) else {} +def _stored(found: _Findings, where: str, path: str, named: re.Match[str] | None, info: Mapping[str, Any], + media: StoredMedia) -> None: + if path not in media.sizes: + found.add("media-bytes", where, f"{path} isn't in the media given") + return + if named and info.get("sha256") is not None and info["sha256"] != named["sha256"]: + found.add("media-bytes", where, f"the profile gives sha256 {info['sha256']}, but the name has {named['sha256']}") + size = media.sizes[path] + if info.get("bytes") is not None and size is not None and info["bytes"] != size: + found.add("media-bytes", where, f"the profile gives {info['bytes']} bytes, but the file has {size}") def _media_bytes(media: Path | Mapping[str, bytes], path: str) -> bytes | None: diff --git a/packages/agentenv-protocol/tests/test_atif_reader.py b/packages/agentenv-protocol/tests/test_atif_reader.py index ef16f4105..3d93253e1 100644 --- a/packages/agentenv-protocol/tests/test_atif_reader.py +++ b/packages/agentenv-protocol/tests/test_atif_reader.py @@ -1,10 +1,23 @@ """Reading documents with or without the profile: strict loading, slicing into tasks, media paths, stripping the profile, and telling a live page from a later read.""" +import copy import json import pytest -from agentenv_protocol.atif import AtifError, check, is_prefix, load, media_paths, strip_profile, tasks +from agentenv_protocol.atif import ( + AtifError, + check, + errors_in, + is_prefix, + load, + media_paths, + media_refs, + strip_profile, + task_document, + tasks, + validate, +) from atif_cases import FIXTURES @@ -52,6 +65,72 @@ def test_media_paths_lists_every_file_once_including_the_ones_atif_has_no_part_f assert all((FIXTURES / path).exists() for path in media_paths(fixture(name))) +def test_media_refs_name_each_place_a_file_is_named_with_its_details_and_media_type(): + refs = media_refs(fixture("computer_use")) + assert list(dict.fromkeys(ref.path for ref in refs)) == media_paths(fixture("computer_use")) + part = next(ref for ref in refs if ref.where.endswith(".source.path")) + assert part.media_type and part.media_type.startswith("image/") and part.info.get("sha256") == part.path[6:70] + odd = media_refs(fixture("odd_parts")) + noted = [ref for ref in odd if ".extra.agentenv.media[" in ref.where] + assert noted and all(ref.media_type == ref.info.get("media_type") for ref in noted) + nested = {**fixture("coding"), "subagent_trajectories": [fixture("computer_use")]} + assert all(ref.where.startswith("subagent_trajectories[0].steps[") for ref in media_refs(nested)) + assert len(media_refs(nested)) == len(refs) + + +def test_a_task_cut_out_of_a_document_is_a_document_of_its_own(): + document = fixture("two_turns") + first, second = tasks(document) + cut = task_document(document, [second.task_id]) + assert errors_in(validate(cut)) == [] + assert [step["step_id"] for step in cut["steps"]] == [1, 2, 3] + assert [{**step, "step_id": 0} for step in cut["steps"]] == [{**step, "step_id": 0} for step in second.steps] + assert "final_metrics" not in cut and cut["session_id"] == document["session_id"] + both = task_document(document, [first.task_id, second.task_id]) + assert errors_in(validate(both)) == [] and len(both["steps"]) == len(document["steps"]) + with pytest.raises(KeyError, match="task-none"): + task_document(document, ["task-none"]) + + +def test_a_cut_keeps_the_sub_agents_its_steps_reach_and_remaps_arrivals(): + document = fixture("subagent") + [task] = tasks(document) + assert [sub["trajectory_id"] for sub in task_document(document, [task.task_id])["subagent_trajectories"]] == ["sub1"] + nested = copy.deepcopy(document) + sub1 = nested["subagent_trajectories"][0] + nested["subagent_trajectories"].append({**copy.deepcopy(sub1), "trajectory_id": "sub2"}) + nested["subagent_trajectories"].append({**copy.deepcopy(sub1), "trajectory_id": "unreached"}) + sub1["steps"][0]["observation"]["results"][0]["subagent_trajectory_ref"] = [{"trajectory_id": "sub2"}] + cut = task_document(nested, [task.task_id]) + assert [sub["trajectory_id"] for sub in cut["subagent_trajectories"]] == ["sub1", "sub2"] + late = fixture("two_turns") + [result] = late["steps"][7]["observation"]["results"] # step 8, the second task's call + result.setdefault("extra", {}).setdefault("agentenv", {})["arrived"] = {"at": "2026-11-04T17:09:12.004Z", "step_id": 9} + earlier = late["steps"][1]["observation"]["results"][0] # step 2, arriving during the second task + earlier.setdefault("extra", {}).setdefault("agentenv", {})["arrived"] = {"at": "2026-11-04T17:09:12.004Z", "step_id": 8} + second = task_document(late, [tasks(late)[1].task_id]) + assert second["steps"][1]["observation"]["results"][0]["extra"]["agentenv"]["arrived"]["step_id"] == 3 + first = task_document(late, [tasks(late)[0].task_id]) + assert first["steps"][1]["observation"]["results"][0]["extra"]["agentenv"]["arrived"] == { + "at": "2026-11-04T17:09:12.004Z"} + + + +def test_a_cut_resolves_each_reference_where_it_sits_at_any_depth(): + """sub1 embeds inner, whose reference names the root's sibling, so the cut keeps sibling; sub1's own reference names + its own inner, so the root's inner, which that shadows, is left out.""" + document = fixture("subagent") + [task] = tasks(document) + sub1 = document["subagent_trajectories"][0] + inner, decoy, sibling = ({**copy.deepcopy(sub1), "trajectory_id": name} for name in ("inner", "inner", "sibling")) + inner["steps"][0]["observation"]["results"][0]["subagent_trajectory_ref"] = [{"trajectory_id": "sibling"}] + sub1["steps"][0]["observation"]["results"][0]["subagent_trajectory_ref"] = [{"trajectory_id": "inner"}] + sub1["subagent_trajectories"] = [inner] + document["subagent_trajectories"] += [decoy, sibling] + cut = task_document(document, [task.task_id]) + assert [sub["trajectory_id"] for sub in cut["subagent_trajectories"]] == ["sub1", "sibling"] + assert [finding for finding in validate(cut) if finding.rule == "reference"] == [] + def test_a_page_is_a_prefix_only_when_its_steps_lead_every_trajectory(): final = fixture("subagent") page = {**final, "steps": final["steps"][:2], diff --git a/packages/agentenv-protocol/tests/test_atif_validator.py b/packages/agentenv-protocol/tests/test_atif_validator.py index 5f61970bb..6de40b289 100644 --- a/packages/agentenv-protocol/tests/test_atif_validator.py +++ b/packages/agentenv-protocol/tests/test_atif_validator.py @@ -9,7 +9,16 @@ import pytest -from agentenv_protocol.atif import KIT_RULES, RULES, errors_in, validate, validate_live +from agentenv_protocol.atif import ( + KIT_RULES, + RULES, + StoredMedia, + errors_in, + media_refs, + validate, + validate_live, + validate_media, +) from agentenv_protocol.atif.__main__ import main from atif_cases import CASES, FIXTURES, build @@ -142,6 +151,32 @@ def test_media_bytes_are_checked_against_their_name_and_profile(): assert "media-bytes" in _rules(errors_in(validate(document, media={path: b"not the screenshot"}))) +def test_stored_media_hold_the_profile_to_each_files_name_and_stored_size_without_its_bytes(): + document = _fixture("computer_use") + sizes = {ref.path: ref.info["bytes"] for ref in media_refs(document)} + assert validate(document, media=StoredMedia(sizes)) == [] + assert validate(document, media=StoredMedia(dict.fromkeys(sizes))) == [] # a store that can't tell sizes + [first, *_] = sizes + missing = errors_in(validate(document, media=StoredMedia({p: n for p, n in sizes.items() if p != first}))) + assert [(f.rule, f.message) for f in missing] == [("media-bytes", f"{first} isn't in the media given")] + resized = errors_in(validate(document, media=StoredMedia({**sizes, first: sizes[first] + 1}))) + assert [f.rule for f in resized] == ["media-bytes"] and "bytes" in resized[0].message + [holder] = [result for step in document["steps"] for result in (step.get("observation") or {}).get("results", []) + if first in (result.get("extra") or {}).get("agentenv", {}).get("media", {})] + holder["extra"]["agentenv"]["media"][first]["sha256"] = "0" * 64 + renamed = errors_in(validate(document, media=StoredMedia(sizes))) + assert [f.rule for f in renamed] == ["media-bytes"] and "but the name has" in renamed[0].message + + +def test_media_are_checked_on_their_own_for_a_document_newer_than_the_models(): + document = {**_fixture("computer_use"), "schema_version": "ATIF-v1.9"} + sizes = {ref.path: ref.info["bytes"] for ref in media_refs(document)} + assert _rules(errors_in(validate(document, reader=True, media=StoredMedia({})))) == {"atif"} + assert validate_media(document, StoredMedia(sizes), reader=True) == [] + assert _rules(errors_in(validate_media(document, StoredMedia({}), reader=True))) == {"media-bytes"} + assert validate_media(document, FIXTURES) == [] + + def test_totals_sum_the_sub_agents_steps_and_skip_a_count_a_step_lacks(): document = _fixture("subagent") root = sum(s["metrics"]["prompt_tokens"] for s in document["steps"] if s.get("metrics")) diff --git a/src/agent_env/a2a_agent/object_transfer.py b/src/agent_env/a2a_agent/object_transfer.py index 4934a2a0b..26018af95 100644 --- a/src/agent_env/a2a_agent/object_transfer.py +++ b/src/agent_env/a2a_agent/object_transfer.py @@ -190,19 +190,13 @@ async def invoke_transfer( try: if staged is not None: await staged.push() - async with httpx.AsyncClient() as client: - send = client.post if verb == "POST" else client.put - resp = await send(url, json=call.payload, headers=headers, timeout=timeout) try: - raise_for_extension_status(resp, operation=operation, include_body=call.mode == "legacy") - except httpx.HTTPStatusError as exc: - hint = _STAGING_UNREACHABLE if staged is not None else ( - unreachable_hint(call.payload) if call.mode == "objects" else None - ) - if hint is None or not str(exc).endswith(f": {_TRANSFER_UNAVAILABLE}"): - raise - raise httpx.HTTPStatusError(f"{exc}. {hint}", request=exc.request, response=exc.response) from exc - body = resp.json() + body = await _send(url, call, verb=verb, operation=operation, timeout=timeout, headers=headers, + staged=staged is not None) + except Exception as exc: + if staged is not None and not isinstance(exc, _UNSENT): + await _collect_staged(staged, operation) + raise if staged is not None: await staged.pull() finally: @@ -213,6 +207,36 @@ async def invoke_transfer( return body +async def _send(url: str, call: TransferCall, *, verb: Literal["POST", "PUT"], operation: str, timeout: float, + headers: Mapping[str, str] | None, staged: bool) -> Any: + """The agent's answer to ``call``, raising for an error status with a hint when the agent couldn't reach the + objects the call named: its own staging when ``staged``, else the grants' store.""" + async with httpx.AsyncClient() as client: + send = client.post if verb == "POST" else client.put + resp = await send(url, json=call.payload, headers=headers, timeout=timeout) + try: + raise_for_extension_status(resp, operation=operation, include_body=call.mode == "legacy") + except httpx.HTTPStatusError as exc: + hint = _STAGING_UNREACHABLE if staged else unreachable_hint(call.payload) if call.mode == "objects" else None + if hint is None or not str(exc).endswith(f": {_TRANSFER_UNAVAILABLE}"): + raise + raise httpx.HTTPStatusError(f"{exc}. {hint}", request=exc.request, response=exc.response) from exc + return resp.json() + + +#: Failures of a call that never reached the agent, which therefore staged nothing to collect. +_UNSENT = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout) + + +async def _collect_staged(staged: StagedObjectStore, operation: str) -> None: + """Move what the agent wrote before its call failed into the store, as an upload through a grant reaches it + whether or not the answer does; best-effort, so the call's own error is the one raised.""" + try: + await staged.pull() + except Exception as exc: + logger.warning(f"{operation}: collecting what the agent staged before the call failed: {exc}") + + def parse_response(model: type[_Response], body: Any, *, operation: str) -> _Response: """Validate an agent's ``operation`` response, ignoring fields this release does not know.""" try: diff --git a/src/agent_env/a2a_agent/protocol.py b/src/agent_env/a2a_agent/protocol.py index 74e9305f7..6a5dff9f5 100644 --- a/src/agent_env/a2a_agent/protocol.py +++ b/src/agent_env/a2a_agent/protocol.py @@ -45,6 +45,18 @@ class AgentUnreachableError(TimeoutError): _REFUSED = " (the agent refused its control token: the record it was sent from has none, or another deployment's)" +def extension_error_code(response: httpx.Response) -> str | None: + """The SDK error code an extension's error answer names, such as ``format_not_prescribed``, when it names one in + the SDK's form: the agent writes the body, so anything else is no code.""" + try: + body = response.json() + except ValueError: + return None + error = body.get("error") if isinstance(body, Mapping) else None + code = error.get("code") if isinstance(error, Mapping) else None + return code if isinstance(code, str) and _ERROR_CODE.fullmatch(code) else None + + def raise_for_extension_status( response: httpx.Response, *, operation: str, include_body: bool = False ) -> None: @@ -53,16 +65,7 @@ def raise_for_extension_status( try: response.raise_for_status() except httpx.HTTPStatusError as exc: - if include_body: - detail = response.text[:500] - else: - try: - body = response.json() - except ValueError: - body = None - error = body.get("error") if isinstance(body, Mapping) else None - code = error.get("code") if isinstance(error, Mapping) else None - detail = code if isinstance(code, str) and _ERROR_CODE.fullmatch(code) else "" + detail = response.text[:500] if include_body else extension_error_code(response) or "" status = f"{operation} failed with HTTP {response.status_code}" refused = _REFUSED if response.status_code == 401 else "" if refused: diff --git a/src/agent_env/task_step/context.py b/src/agent_env/task_step/context.py index 5bb8abdfb..dbf22a199 100644 --- a/src/agent_env/task_step/context.py +++ b/src/agent_env/task_step/context.py @@ -8,7 +8,7 @@ from collections.abc import Callable from contextvars import ContextVar from dataclasses import dataclass, field -from typing import Any, Optional, TypedDict +from typing import Any, Literal, Optional, TypedDict from agentenv_protocol import client as protocol_v1 @@ -235,13 +235,60 @@ def sandbox_overrides(sandbox: str) -> dict[str, str]: ) +AtifStatus = Literal["valid", "invalid", "newer", "unavailable"] + + +class AtifRecord(TypedDict): + """A turn's atif/1 copy: the stored document, the turn's A2A task in it and the step it reached at that turn (each + turn's copy is a prefix of the next), how it checked (``valid``, ``invalid`` with the rules it broke, ``newer`` than + this worker reads as a producer's, or ``unavailable`` with why in ``reason``), the versions that made and checked + it, and the turn's aux log and turn context.""" + + url: Optional[str] + task_id: Optional[str] + through_step: Optional[int] + status: AtifStatus + rules: list[str] + reason: Optional[str] + validator_version: Optional[str] + adapter_version: Optional[str] + aux_url: Optional[str] + turn_context_url: Optional[str] + + +class AtifAgentCopies(TypedDict): + """One agent's atif/1 copies in a run: the folder they're stored in, and the trajectory id of each session's (A2A + context's) latest document, which a restart's next document is linked from.""" + + folder: str + sessions: dict[str, str] + + +class AtifCopiesMetadata(TypedDict): + """``metadata["atif_copies"]``: the id a run's atif/1 folders are named by (its instance id, else one made for + it), and each agent's copies.""" + + run: str + agents: dict[str, AtifAgentCopies] + + class TurnTrajectory(TypedDict): - """What a turn's trajectory reads left, beside its native copy's url in the per-turn list: the native copy's - format, as the agent's answer named it (None from an agent that names none), and its atif/1 copy, None when the - agent offers none.""" + """What a turn's trajectory reads left, beside its url in the per-turn list: the format of the trajectory stored at + that url, as its answer named it (None from an agent that names none), and its atif/1 copy, None when the run + doesn't prescribe atif/1. In a run that prescribes atif/1 to an agent that offers it, the url is the copy's + document and the format ``atif/1``; a turn whose copy couldn't be had, or whose copy's media didn't all arrive, has + its native trajectory there instead.""" - native_format: Optional[str] - atif: Optional[dict[str, Any]] + format: Optional[str] + atif: Optional[AtifRecord] + + +def turn_trajectories(records: Optional[list[dict[str, Any]]]) -> Optional[list[TurnTrajectory]]: + """Stored per-turn records as TurnTrajectory, an older record's ``native_format`` read as its format.""" + if records is None: + return None + return [TurnTrajectory(format=record.get("format", record.get("native_format")), atif=record.get("atif")) + for record in records] @dataclass @@ -305,7 +352,7 @@ def from_dict(cls, data: dict) -> PromptResponse: step_id=data.get("step_id"), structured_output=data.get("structured_output"), usage=data.get("usage"), - target_agent_per_turn_trajectories=data.get("target_agent_per_turn_trajectories"), + target_agent_per_turn_trajectories=turn_trajectories(data.get("target_agent_per_turn_trajectories")), ) diff --git a/src/agent_env/task_step/snapshot_utils/atif_copies.py b/src/agent_env/task_step/snapshot_utils/atif_copies.py new file mode 100644 index 000000000..bd2dc3d16 --- /dev/null +++ b/src/agent_env/task_step/snapshot_utils/atif_copies.py @@ -0,0 +1,343 @@ +"""A run's atif/1 copies: when the run prescribes atif/1 to an agent that offers it, each turn's copy of the +conversation is the turn's trajectory. It's read inline from the agent once the turn ends and stored as +``.json`` in the run's folder for that agent, overwritten each turn, with the turn's aux log and turn +context beside it and the media it names pulled into its ``media/``; it's checked as a producer's document and the turn +records how it checked. The reads run one after another, off the turn's path, so the next message isn't held for them. +A copy that can't be had never fails the run: that turn's native trajectory is read in its place, as it is for a copy +whose media didn't all arrive, which its judges would read without them.""" +from __future__ import annotations + +import asyncio +import importlib.metadata +import json +import logging +import mimetypes +import re +import uuid +from collections.abc import Awaitable, Callable, Mapping +from typing import Any, Optional + +import httpx +from agentenv_protocol.a2a_agent import TrajectoryMediaResponse +from agentenv_protocol.a2a_agent.extensions import MAX_MEDIA_OBJECTS +from agentenv_protocol.atif import ( + FORMAT as ATIF, + MEDIA_PATH, + PROFILE_VERSION, + SCHEMA_VERSION, + MediaRef, + StoredMedia, + errors_in, + media_refs, + profile_of, + validate, + validate_media, +) + +from agent_env.a2a_agent import A2AAgent +from agent_env.a2a_agent.object_transfer import ( + DEFAULT_TRAJECTORY_MAX_BYTES, + TRANSFER_TIMEOUT_SECONDS, + TrajectoryFormats, + TransferCall, + invoke_transfer, + write_object, +) +from agent_env.a2a_agent.protocol import extension_error_code +from agent_env.a2a_agent.staging import transfer_store +from agent_env.config import get_config +from agent_env.store.object_store import ObjectStore +from agent_env.store.object_store.object_store import issues_grants_to +from agent_env.task_step.context import ( + AtifAgentCopies, + AtifCopiesMetadata, + AtifRecord, + AtifStatus, + DeployedAgent, + TaskStepContext, + TurnTrajectory, +) +from agent_env.task_step.snapshot_utils.agent_state_capture import trajectory_prefix_key + +logger = logging.getLogger(__name__) + +#: Reads a turn's native trajectory: where it was stored, None when the agent returned none, and its format. +NativeRead = Callable[[], Awaitable[tuple[Optional[str], Optional[str]]]] +#: Where a run records its atif/1 folders (``AtifCopiesMetadata``). +ATIF_COPIES_KEY = "atif_copies" +VALID: AtifStatus = "valid" +INVALID: AtifStatus = "invalid" +NEWER: AtifStatus = "newer" +UNAVAILABLE: AtifStatus = "unavailable" +#: The rule a copy breaks when a media file it names isn't stored as named. +MEDIA_BYTES = "media-bytes" +#: A trajectory id the worker stores a document under: the agent mints it, so it must be a plain file name. +_DOCUMENT_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}") +_VERSION = re.compile(r"(\d+)\.(\d+)") +#: How many hex digits name a run with no instance id, as the other run-scoped folders name it (``adhoc-``). +_ADHOC_ID_CHARS = 12 +#: How much of an invalid copy's first finding its record keeps as the reason; ``rules`` names every rule broken. +_REASON_CHARS = 300 +_VALIDATOR_VERSION = importlib.metadata.version("agentenv-framework-protocol") + + +def atif_folder(context: TaskStepContext, agent_name: str) -> str: + """The run's folder for ``agent_name``'s atif/1 copies, ``{prefix}atif/instance_id={id}/{agent_name}/``, recorded + in ``metadata["atif_copies"]``; a run with no instance id gets one ``adhoc-`` for all its agents.""" + return _copies_of(context, agent_name)["folder"] + + +def _copies_of(context: TaskStepContext, agent_name: str) -> AtifAgentCopies: + copies: AtifCopiesMetadata = context.metadata.setdefault(ATIF_COPIES_KEY, AtifCopiesMetadata( + run=context.instance_id or f"adhoc-{uuid.uuid4().hex[:_ADHOC_ID_CHARS]}", agents={})) + if agent_name not in copies["agents"]: + config = get_config() + folder = config.get_object_store().object_url( + f"{config.get_artifact_key_prefix()}atif/instance_id={copies['run']}/{agent_name}/") + copies["agents"][agent_name] = AtifAgentCopies(folder=folder if folder.endswith("/") else f"{folder}/", + sessions={}) + return copies["agents"][agent_name] + + +class _Unavailable(Exception): + def __init__(self, reason: str) -> None: + super().__init__(reason) + self.reason = reason + + +class AtifCopies: + """A step's atif/1 copies of one agent's conversation. When the run prescribes atif/1 to an agent that offers it + (``replaces_native``), each turn's copy is the turn's trajectory: ``turn`` starts reading it once the turn ends, a + turn whose copy can't be had, or whose copy's media didn't all arrive, has its native trajectory read at once + instead (the requested format is best effort), and ``join`` fills each turn's record and gives each turn's url. Otherwise the step reads native as ever, and a + turn's record has None when the run doesn't prescribe atif/1, or ``unavailable`` with ``format_not_offered`` when + the agent doesn't offer it.""" + + def __init__(self, context: TaskStepContext, agent: DeployedAgent, a2a_url: str, + extension: Mapping[str, Any] | None, *, prescribed: bool) -> None: + self._context, self._agent, self._a2a_url, self._extension = context, agent, a2a_url, extension + 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]]] = [] + #: 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 + + def turn(self, index: int, task_id: str, name: str, record: TurnTrajectory, *, native: NativeRead) -> None: + """Turn ``index``'s trajectory, its ended A2A task ``task_id``: into ``record`` and, through ``join``, its url, + the copy's aux log and turn context stored under ``name``. ``native`` reads the turn's native trajectory.""" + if not self._prescribed: + record["atif"] = None + elif not self._offered: + record["atif"] = _unavailable("format_not_offered", task_id) + else: + previous = self._pending[-1][1] if self._pending else None + self._pending.append((index, asyncio.create_task(self._turn(task_id, name, record, native, previous)))) + + async def join(self) -> dict[int, str | None]: + """Each copied turn's url, by its index, once every copy has been stored and its record filled; cancelled while + waiting, it cancels the copies left.""" + try: + return {index: await job for index, job in self._pending} + except BaseException: + self.cancel() + raise + + def cancel(self) -> None: + for _, job in self._pending: + job.cancel() + + async def _turn(self, task_id: str, name: str, record: TurnTrajectory, native: NativeRead, + previous: asyncio.Task[str | None] | None) -> str | None: + if previous is not None: # each copy overwrites the one before, so they're stored in turn order + await asyncio.wait([previous]) + record["atif"] = atif = await self._copy(task_id, name) + missing_media = MEDIA_BYTES in atif["rules"] + if atif["status"] != UNAVAILABLE and not missing_media: + record["format"] = ATIF + return atif["url"] + if missing_media: + logger.warning(f"agent '{self._agent.agent_name}': the atif/1 copy of task {task_id} lacks media its judges " + f"would read, so its native trajectory is read in its place (continuing)") + try: # at once, while the agent still holds it + url, native_format = await native() + except Exception as exc: + logger.warning(f"agent '{self._agent.agent_name}': task {task_id}'s native trajectory, read in place of its " + f"atif/1 copy, failed too (continuing): {exc}") + url, native_format = None, None + if url is None and missing_media: # the copy without some media is more than no trajectory + record["format"] = ATIF + return atif["url"] + record["format"] = native_format + return url + + async def _copy(self, task_id: str, name: str) -> AtifRecord: + try: + return await self._stored(task_id, name) + except Exception as exc: + reason = _reason(exc) + logger.warning(f"agent '{self._agent.agent_name}': the atif/1 copy of task {task_id} is unavailable " + f"({reason}; continuing): {exc}") + return _unavailable(reason, task_id) + + async def _stored(self, task_id: str, name: str) -> AtifRecord: + _, path = A2AAgent.operation(self._extension, "get") + body = await invoke_transfer( + self._a2a_url + path, TransferCall("legacy", {"task_id": task_id, "format": ATIF}), verb="POST", + operation="atif/1 trajectory get", timeout=TRANSFER_TIMEOUT_SECONDS, headers=self._agent.control_headers) + document = body.get("trajectory") if isinstance(body, Mapping) else None + if not isinstance(document, Mapping): + raise _Unavailable("no_document") + trajectory_id = document.get("trajectory_id") + if not isinstance(trajectory_id, str) or not _DOCUMENT_ID.fullmatch(trajectory_id): + raise _Unavailable("invalid_trajectory_id") + store = get_config().get_object_store() + folder = trajectory_prefix_key(store, atif_folder(self._context, self._agent.agent_name)) + url = await _put(store, f"{folder}{trajectory_id}.json", document) + aux_url = None if body.get("aux") is None else await _put(store, f"{folder}turns/{name}/aux.json", body["aux"]) + turn_context_url = None if body.get("turn_context") is None else await _put( + store, f"{folder}turns/{name}/turn_context.json", body["turn_context"]) + root = profile_of(document) + newer = _newer(document.get("schema_version"), SCHEMA_VERSION) or _newer(root.get("version"), PROFILE_VERSION) + try: + refs = _first_refs(document) + except (AttributeError, TypeError): # a shape no ATIF has, which the validator reports; nothing to walk + refs = None + media = None + if refs is not None: + session_id = document.get("session_id") + if isinstance(session_id, str): + await self._link(store, folder, session_id, trajectory_id) + media = StoredMedia(await self._pull_media(refs, session_id, store, folder)) + found = await asyncio.to_thread(validate, document, reader=newer) + if media is not None: # on its own, since validate stops at a document newer than its models + found += await asyncio.to_thread(validate_media, document, media, reader=newer) + errors = errors_in(found) + status = NEWER if newer else INVALID if errors else VALID + if status == INVALID: + logger.warning(f"agent '{self._agent.agent_name}': the atif/1 copy of task {task_id} is invalid " + f"(continuing): {errors[0]}") + steps = document.get("steps") + last = steps[-1] if isinstance(steps, list) and steps and isinstance(steps[-1], Mapping) else {} + adapter = root.get("adapter") + return AtifRecord( + url=url, task_id=task_id, through_step=last.get("step_id") if isinstance(last.get("step_id"), int) else None, + status=status, rules=sorted({finding.rule for finding in errors}), + reason=str(errors[0])[:_REASON_CHARS] if errors else None, validator_version=_VALIDATOR_VERSION, + adapter_version=adapter.get("version") if isinstance(adapter, Mapping) else None, + aux_url=aux_url, turn_context_url=turn_context_url, + ) + + async def _link(self, store: ObjectStore, folder: str, session_id: str, trajectory_id: str) -> None: + """Point the session's earlier document, when a restart began this one, to this one: the agent that wrote + the earlier one may be gone, so the worker sets its ``continued_trajectory_ref``. The session names this one + only once that's done, so a link that fails is made by a later turn.""" + sessions = _copies_of(self._context, self._agent.agent_name)["sessions"] + earlier = sessions.get(session_id) + if earlier is not None and earlier != trajectory_id: + key = f"{folder}{earlier}.json" + try: + document = json.loads(await asyncio.to_thread(store.read, key)) + document["continued_trajectory_ref"] = f"{trajectory_id}.json" + await _put(store, key, document) + except Exception as exc: + logger.warning(f"agent '{self._agent.agent_name}': linking {earlier} to {trajectory_id} failed, so a " + f"later turn tries again (continuing): {exc}") + return + sessions[session_id] = trajectory_id + + async def _pull_media(self, refs: Mapping[str, MediaRef], context_id: Any, store: ObjectStore, + folder: str) -> dict[str, int | None]: + """The media files the folder holds, with their sizes, once the agent has pushed what the document names + (``refs``) and the folder lacks. A file the agent answers missing or failed for may be stored already, by a + push whose answer was lost, so the store is asked before it's counted missing; a held file's size is read from + the store once.""" + if self._held is None: + listed = await asyncio.to_thread(store.list, f"{folder}media/") + self._held = {key[len(folder):]: None for key in listed} + held = await self._pushed(refs, context_id, store, folder, self._held) + for path in refs: + if path in held and held[path] is None: + metadata = await asyncio.to_thread(store.get_object_metadata, f"{folder}{path}") + held[path] = None if metadata is None else metadata.size + return held + + async def _pushed(self, refs: Mapping[str, MediaRef], context_id: Any, store: ObjectStore, folder: str, + held: dict[str, int | None]) -> dict[str, int | None]: + """``held``, with what the agent pushed of the files the document names that it lacks.""" + wanted = [path for path in refs if MEDIA_PATH.match(path) and path not in held] + method, endpoint = A2AAgent.operation(self._extension, "media") + card, sandbox_type = self._agent.a2a_card, self._agent.sandbox_type + if not wanted or method is None or endpoint is None or ( + transfer_store(store, self._a2a_url, card, sandbox_type=sandbox_type) is store + and not issues_grants_to(store, sandbox_type)): + return held + cap = store.max_single_upload_bytes + wanted = [path for path in wanted if cap is None or (refs[path].info.get("bytes") or 0) <= cap] + unconfirmed: list[str] = [] + for start in range(0, len(wanted), MAX_MEDIA_OBJECTS): + batch = wanted[start:start + MAX_MEDIA_OBJECTS] + grants = transfer_store(store, self._a2a_url, card, sandbox_type=sandbox_type) # one per call + objects = { + path: write_object(grants, grants.object_url(f"{folder}{path}"), media_type=_media_type(refs[path]), + max_bytes=max(refs[path].info.get("bytes") or DEFAULT_TRAJECTORY_MAX_BYTES, 1)) + .model_dump(mode="json") + for path in batch + } + try: + pushed = await invoke_transfer( + self._a2a_url + endpoint, TransferCall("objects", {"context_id": context_id, "objects": objects}), + verb="POST", operation="trajectory media", timeout=TRANSFER_TIMEOUT_SECONDS, + response_model=TrajectoryMediaResponse, store=grants, headers=self._agent.control_headers) + except Exception as exc: + logger.warning(f"agent '{self._agent.agent_name}': the media push of {len(batch)} files failed " + f"(continuing): {exc}") + unconfirmed += batch + continue + held.update({path: uploaded.size_bytes for path, uploaded in pushed.objects.items()}) + unconfirmed += [*pushed.missing, *pushed.failed] + for path in unconfirmed: + metadata = await asyncio.to_thread(store.get_object_metadata, f"{folder}{path}") + if metadata is not None: + held[path] = metadata.size + return held + + +def _first_refs(document: Mapping[str, Any]) -> dict[str, MediaRef]: + """Each media file the document names, by path, as the first place names it.""" + refs: dict[str, MediaRef] = {} + for ref in media_refs(document): + refs.setdefault(ref.path, ref) + return refs + + +def _media_type(ref: MediaRef) -> str: + return ref.media_type or mimetypes.guess_type(ref.path)[0] or "application/octet-stream" + + +def _newer(version: Any, ours: str) -> bool: + got, have = _VERSION.search(str(version or "")), _VERSION.search(ours) + return got is not None and (int(got[1]), int(got[2])) > (int(have[1]), int(have[2])) + + +async def _put(store: ObjectStore, key: str, value: Any) -> str: + body = json.dumps(value, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode() + return await asyncio.to_thread(store.put, key, body, content_type="application/json", allow_overwrite=True) + + +def _reason(exc: Exception) -> str: + if isinstance(exc, _Unavailable): + return exc.reason + if isinstance(exc, httpx.HTTPStatusError): + return extension_error_code(exc.response) or f"http_{exc.response.status_code}" + if isinstance(exc, httpx.TimeoutException): + return "timeout" + if isinstance(exc, httpx.TransportError): + return "unreachable" + return type(exc).__name__ + + +def _unavailable(reason: str, task_id: str) -> AtifRecord: + return AtifRecord(url=None, task_id=task_id, through_step=None, status=UNAVAILABLE, rules=[], reason=reason, + validator_version=None, adapter_version=None, aux_url=None, turn_context_url=None) diff --git a/src/agent_env/task_step/snapshot_utils/snapshot_series.py b/src/agent_env/task_step/snapshot_utils/snapshot_series.py index 049533361..ea81da532 100644 --- a/src/agent_env/task_step/snapshot_utils/snapshot_series.py +++ b/src/agent_env/task_step/snapshot_utils/snapshot_series.py @@ -17,6 +17,8 @@ from datetime import datetime, timezone from typing import Optional +from agentenv_protocol.atif import FORMAT as ATIF_FORMAT + from agent_env.store.ids import derive_id, is_local_id, validate_local_id from agent_env.task_step.context import TaskStepContext, dual_keyed from agent_env.task_step.snapshot_utils import agent_state_capture as capture @@ -530,14 +532,16 @@ def _recorded_trajectory_uri(self, context: TaskStepContext) -> Optional[str]: Matched on ``a2a_context_id``, newest-first: a retry can restore a context snapshot taken during an earlier attempt, so that attempt's response for the same ``prompt_id`` can still be present and would otherwise attach a - previous conversation's trajectory to this capture. + previous conversation's trajectory to this capture. A response whose last turn + is its atif/1 copy gives none: the series' other rows are native reads. """ for prompt in reversed(context.prompt_responses): if ( prompt.prompt_id == self.prompt_id and prompt.a2a_context_id == self.a2a_context_id ): - return prompt.agent_trajectory_object_url + turns = prompt.target_agent_per_turn_trajectories or [] + return None if turns and turns[-1]["format"] == ATIF_FORMAT else prompt.agent_trajectory_object_url # None is legitimate: the response is recorded only after the turn loop, so # a capture during an in-flight or failed run has no entry yet. return None diff --git a/src/agent_env/task_step/task_steps/always_on.py b/src/agent_env/task_step/task_steps/always_on.py index 7991b2179..c769ecdc1 100644 --- a/src/agent_env/task_step/task_steps/always_on.py +++ b/src/agent_env/task_step/task_steps/always_on.py @@ -601,7 +601,7 @@ async def _configure_agents(self) -> None: if negotiated: await protocol.post_agent_config(self.target_url + negotiated.endpoint, negotiated.fields, headers=self.agent.control_headers) - await prescribe_formats(ctx, step.id, self.agent, self.target_url) + await prescribe_formats(ctx, step.id, self.agent, self.target_url, formats=()) # native until it reads atif/1 solver_model = negotiated.fields.get("model") if negotiated else None ctx.record_model(ModelRole.SOLVER.record_key, step.id, solver_model) self.usage.start(ModelRole.SOLVER, solver_model, self.agent) 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 513530368..5af87308b 100644 --- a/src/agent_env/task_step/task_steps/prompt_agent.py +++ b/src/agent_env/task_step/task_steps/prompt_agent.py @@ -15,6 +15,7 @@ import httpx from a2a.types import TaskState from agentenv_protocol.a2a_agent import card_request_accepts +from agentenv_protocol.atif import FORMAT as ATIF_FORMAT from agent_env.a2a_agent import A2AAgent, conversation_store from agent_env.a2a_agent import protocol @@ -62,6 +63,7 @@ trajectory_object_url, trajectory_prefix_key, ) +from agent_env.task_step.snapshot_utils.atif_copies import AtifCopies from agent_env.task_step.snapshot_utils.live_trajectory import LiveTurns from agent_env.task_step.snapshot_utils.snapshot_series import SnapshotConfig, SnapshotSeries @@ -645,6 +647,8 @@ async def _converse( source_agent_per_turn_prompt_parts: list[list[dict] | None] = [] traj_ext_cached = A2AAgent.find_extension(card, A2AAgent.EXT_TRAJECTORY) formats = TrajectoryFormats.of(traj_ext_cached) + 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_turns = ( LiveTurns(*live, poll_interval_seconds=self.poll_interval_seconds, headers=agent.control_headers, @@ -724,17 +728,21 @@ def record_turn() -> None: ) if traj_ext_cached: + read_native = functools.partial( + fetch_native_trajectory, target_url, traj_ext_cached, sent_task_id, trajectory_output_prefix, + target_a2a_task_id, card=card, sandbox_type=agent.sandbox_type, headers=agent.control_headers, + ) stored = StoredTrajectory() - try: - stored = await fetch_native_trajectory( - target_url, traj_ext_cached, sent_task_id, trajectory_output_prefix, - target_a2a_task_id, card=card, sandbox_type=agent.sandbox_type, - headers=agent.control_headers, - ) - except Exception as e: - logger.warning(f"Turn {turn+1} trajectory fetch failed (continuing): {e}") + if not atif_copies.replaces_native: # the run's copy, read off the turn's path, replaces native + try: + stored = await read_native() + except Exception as e: + logger.warning(f"Turn {turn+1} trajectory fetch failed (continuing): {e}") per_turn_trajectory_urls.append(stored.url) - per_turn_trajectories.append(TurnTrajectory(native_format=stored.format, atif=None)) + turn_record = TurnTrajectory(format=stored.format, atif=None) + per_turn_trajectories.append(turn_record) + atif_copies.turn(len(per_turn_trajectory_urls) - 1, sent_task_id, target_a2a_task_id, turn_record, + native=read_native) final_task_id = sent_task_id final_state = target_state @@ -789,10 +797,15 @@ def record_turn() -> None: logger.info(f"Turn {turn+1}: nothing to send the agent; ending multi-turn (nothing_to_send)") conversation_store.mark_closed(conversation_id) break + except BaseException: + atif_copies.cancel() + raise finally: # On failure too, so a reader of the last turn knows no other follows. if live_turns is not None: await live_turns.end() + for index, url in (await atif_copies.join()).items(): + per_turn_trajectory_urls[index] = url await self._persist_env_trigger_state(context) @@ -1405,15 +1418,17 @@ def prescribed_formats(context: TaskStepContext) -> tuple[str, ...]: return tuple(formats) -async def prescribe_formats(context: TaskStepContext, step_id: str, agent: DeployedAgent, a2a_url: str) -> None: - """Have the agent build the run's trajectory formats (``prescribed_formats``) beside native for the conversations it - starts from now on, when its card offers the trajectory extension's ``prescribe``; an agent whose SDK predates it - builds what it always has. What was prescribed and what the agent builds go into +async def prescribe_formats(context: TaskStepContext, step_id: str, agent: DeployedAgent, a2a_url: str, *, + formats: tuple[str, ...] | None = None) -> None: + """Have the agent build ``formats``, by default the run's (``prescribed_formats``), beside native for the + conversations it starts from now on, when its card offers the trajectory extension's ``prescribe``; an agent whose + SDK predates it builds what it always has. What was prescribed and what the agent builds go into ``metadata["trajectory_formats"][step_id]``, and a prescribed format the agent can't build is warned of. A connection error is retried; after a failure the agent builds what it was last prescribed, native only unless an - earlier step prescribed more, and the run goes on: its judges read native either way.""" - formats = prescribed_formats(context) + earlier step prescribed more, and the run goes on: a turn whose prescribed copy the agent didn't build has its + native trajectory read in its place.""" + formats = prescribed_formats(context) if formats is None else formats extension = A2AAgent.find_extension(agent.a2a_card or {}, A2AAgent.EXT_TRAJECTORY) method, path = A2AAgent.operation(extension, "prescribe") offered = TrajectoryFormats.of(extension).formats @@ -1460,7 +1475,7 @@ async def fetch_native_trajectory( *, sandbox_type: str | None, headers: Mapping[str, str], card: dict | None = None, ) -> StoredTrajectory: """A turn's native trajectory, read by ``a2a_server_task_id`` and stored under ``target_a2a_task_id``. A card that - offers formats is asked for its native one by name, so the copy judges read stays native whatever the card's + offers formats is asked for its native one by name, so a run that prescribes none reads native whatever the card's default; one that offers none gets the read it always has.""" get_method, get_path = A2AAgent.operation(traj_ext, "get") store = transfer_store(get_config().get_object_store(), a2a_url, card, sandbox_type=sandbox_type) diff --git a/src/agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py b/src/agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py index 0ff8c8797..050ff92c3 100644 --- a/src/agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py @@ -17,6 +17,7 @@ from agent_env.task_step.context import PromptResponse, StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef from agent_env.task_step.task_step import TaskStepDependency +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import AtifDocuments, atif_turns, turns from agent_env.task_step.task_steps.verifiers.run_context import load_run_context from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score from agent_env.task_step.task_steps.verifiers.verifier import Verification, VerifierTaskStep @@ -29,7 +30,9 @@ class EnvOutcomeVerifierTaskStep(VerifierTaskStep): """Runs the artifact's ``verify(mcp_url)``; a ``run`` parameter also gets the ``Run`` of ``prompt_id``, a - ``trajectory`` parameter that prompt's agent trajectory, and an ``env_url`` parameter the env's address, which the + ``trajectory`` parameter that prompt's agent trajectory (one document per turn, each read by its label: + ``_trajectory``), a ``trajectory_formats`` parameter each turn's label, such as ``atif/1`` or the agent's native + format, and an ``env_url`` parameter the env's address, which the protocol client takes as it is: like every step, ``verify`` runs under ``Task.run``'s grant of each deployed env's control token, so its calls reach the env's framework-only routes as written.""" @@ -125,6 +128,8 @@ async def verify(self, context: TaskStepContext) -> Verification: keywords["run"] = await load_run_context(context, self._graded_prompt(context)) if "trajectory" in parameters: keywords["trajectory"] = await asyncio.to_thread(_trajectory, self._graded_prompt(context)) + if "trajectory_formats" in parameters: + keywords["trajectory_formats"] = _trajectory_formats(self._graded_prompt(context)) results = await module.verify(deployed.mcp_url, **keywords) finally: if os.path.exists(tmp_path): @@ -148,10 +153,27 @@ def _graded_prompt(self, context: TaskStepContext) -> Optional[PromptResponse]: def _trajectory(prompt_response: Optional[PromptResponse]) -> Optional[list]: - """The agent's trajectory of ``prompt_response``, one document per turn as the agent stored it, None for a turn it - stored none of; None when it stored none at all.""" + """The agent's trajectory of ``prompt_response``, one document per turn by its label, None for a turn it stored none + of; None when it stored none at all. A native turn's document is as the agent stored it; an atif/1 turn's is that + turn alone, its A2A task cut out of the conversation's ATIF document (``agentenv_protocol.atif.task_document``: + steps numbered from 1, sub-agents it reaches kept, ``final_metrics`` dropped), its media paths relative to that + document's folder.""" urls = ((prompt_response.target_agent_per_turn_trajectory_object_urls or [prompt_response.agent_trajectory_object_url]) if prompt_response is not None else []) if not any(urls): return None - return [json.loads(get_config().get_object_store_at(url).get(url)) if url else None for url in urls] + if atif_turns(prompt_response) is None: + return [json.loads(get_config().get_object_store_at(url).get(url)) if url else None for url in urls] + documents = AtifDocuments() + return [None if source is None else documents.view(source) if source.atif + else json.loads(get_config().get_object_store_at(source.url).get(source.url)) + for source in turns(prompt_response)] + + +def _trajectory_formats(prompt_response: Optional[PromptResponse]) -> Optional[list[Optional[str]]]: + """Each turn's label, beside ``_trajectory``'s entries: what that turn's document is, None where it says none.""" + if prompt_response is None: + return None + records = prompt_response.target_agent_per_turn_trajectories or [] + urls = prompt_response.target_agent_per_turn_trajectory_object_urls or [prompt_response.agent_trajectory_object_url] + return [records[index]["format"] if index < len(records) else None for index in range(len(urls))] diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py new file mode 100644 index 000000000..e79b3e78b --- /dev/null +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/atif_turns.py @@ -0,0 +1,368 @@ +"""A prompt's atif/1 turns as judges read them. A run that prescribes atif/1 stores each turn's copy of the +conversation at one url that its later turns overwrite, so a turn labelled ``atif/1`` is read as its own A2A task cut +out of the document there (``task_document``): that turn alone, a document ATIF's models load. A turn with any other +label keeps the native readers. Each document is read once per judge, and the media a view names are read from the +document's folder, each checked against its name. A view names the tools its agents were offered, as a native turn does, +without their descriptions and schemas, which run to tens of thousands of tokens a turn.""" + +from __future__ import annotations + +import base64 +import hashlib +import itertools +import json +import logging +from collections.abc import Callable, Hashable, Mapping +from dataclasses import dataclass +from typing import Any, Optional + +from agentenv_protocol.atif import FORMAT, AtifError, check_media, media_file, media_paths, tasks, tasks_document + +from agent_env.config import get_config +from agent_env.store.base import NotFoundError +from agent_env.task_step.context import PromptResponse +from agent_env.task_step.task_steps.verifiers.judge_utils.frame_selection import ( + AgentMessage, + TrajectoryAction, + Transcript, +) +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import ( + _TOOL_RESULT_FILES_DIR, + _TOOL_RESULT_MAX_INLINE_SIZE, + ImageFrame, + TrajectoryFilter, +) + +logger = logging.getLogger(__name__) + +ATIF = FORMAT + + +#: How much of a media file is hashed at a time when it's checked for staging, so a check holds no whole file. +_HASH_CHUNK = 1 << 20 +#: Each image format a frame's bytes can name, by its file's leading bytes. +_IMAGE_SIGNATURES = ((b"\x89PNG\r\n\x1a\n", "image/png"), (b"\xff\xd8\xff", "image/jpeg"), (b"GIF87a", "image/gif"), + (b"GIF89a", "image/gif")) + + +@dataclass(frozen=True) +class TurnSource: + """A turn's stored trajectory: its url and, for a turn labelled atif/1, the A2A task its view cuts out of the + document there and the step the turn reached, which finds the task in a copy without the profile's ids; + ``task_id`` None reads the url as the native readers do.""" + + url: str + task_id: Optional[str] = None + through_step: Optional[int] = None + + @property + def atif(self) -> bool: + return self.task_id is not None + + +def turns(prompt_response: PromptResponse) -> list[Optional[TurnSource]]: + """Each entry of the per-turn url list as its source, by its record's label, None for a turn that stored none.""" + records = prompt_response.target_agent_per_turn_trajectories or [] + sources: list[Optional[TurnSource]] = [] + for index, url in enumerate(prompt_response.target_agent_per_turn_trajectory_object_urls or []): + record = records[index] if index < len(records) else None + copy = (record.get("atif") or {}) if record is not None and record.get("format") == ATIF else {} + if copy.get("url") and copy.get("task_id"): + sources.append(TurnSource(copy["url"], copy["task_id"], copy.get("through_step"))) + else: + sources.append(TurnSource(url) if url else None) + return sources + + +def atif_turns(prompt_response: PromptResponse) -> Optional[list[TurnSource]]: + """The turns with a stored trajectory, in order, when any is labelled atif/1; None leaves the whole response to the + native readers, so a run that prescribes nothing is read as it always was.""" + sources = [source for source in turns(prompt_response) if source is not None] + return sources if any(source.atif for source in sources) else None + + +def media_url(document_url: str, path: str) -> str: + """Where a document's media part ``path`` is stored: its folder's ``media/.``, never anywhere else.""" + media_file(path) + return f"{document_url.rsplit('/', 1)[0]}/{path}" + + +def _tool_names(trajectory: Mapping[str, Any]) -> dict[str, Any]: + """``trajectory`` with each agent block's tool definitions cut to their names, its sub-agents' at any depth too.""" + view = dict(trajectory) + agent = view.get("agent") + if isinstance(agent, Mapping) and isinstance(agent.get("tool_definitions"), list): + view["agent"] = {**agent, "tool_definitions": [ + {"type": "function", "function": {"name": entry["function"]["name"]}} + for entry in agent["tool_definitions"] + if isinstance(entry, Mapping) and isinstance(entry.get("function"), Mapping) and "name" in entry["function"]]} + if isinstance(view.get("subagent_trajectories"), list): + view["subagent_trajectories"] = [_tool_names(sub) if isinstance(sub, Mapping) else sub + for sub in view["subagent_trajectories"]] + return view + + +class AtifDocuments: + """The atif/1 documents one judge reads, each read once, and the turn views cut from them. A media file's bytes are + read only when a judge is handed them, and staging keeps only whether each file is stored as its name says.""" + + def __init__(self) -> None: + self._documents: dict[str, dict[str, Any]] = {} + self._views: dict[TurnSource, dict[str, Any]] = {} + self._stored: dict[str, bool] = {} + + def document(self, url: str) -> dict[str, Any]: + if url not in self._documents: + self._documents[url] = json.loads(get_config().get_object_store_at(url).get(url)) + return self._documents[url] + + def view(self, source: TurnSource) -> dict[str, Any]: + """The turn alone, as a document of its own: its task cut out of the conversation's document, found by its id, + else, in a copy without the profile, as the task ending at the turn's step. A copy neither finds the turn in, or + whose steps can't be sliced, is the turn's view as stored, since the requested trajectory is best effort.""" + if source not in self._views: + document = self.document(source.url) + try: + found = tasks(document) + picked = ([task for task in found if task.task_id == source.task_id] + or [task for task in found if task.steps and task.steps[-1].get("step_id") == source.through_step]) + view = tasks_document(document, picked[:1]) if picked else None + except (AttributeError, TypeError): + view = None + if view is None: + logger.warning(f"the atif/1 copy at {source.url} holds neither task {source.task_id} nor a task ending at " + f"step {source.through_step}, so its judge reads the copy as stored") + view = document + self._views[source] = _tool_names(view) + return self._views[source] + + def text(self, source: TurnSource) -> str: + return json.dumps(self.view(source), ensure_ascii=False) + + def media(self, document_url: str, path: str) -> Optional[bytes]: + """The media file ``path`` of the document at ``document_url``, checked against its name; None, logged, for one + that isn't ``media/.``, isn't stored or holds other bytes, which the judge goes without.""" + try: + url = media_url(document_url, path) + data = get_config().get_object_store_at(url).get(url) + check_media(path, data) + except (NotFoundError, AtifError) as exc: + logger.warning(f"ATIF media {path!r} of {document_url} skipped: {exc}") + return None + return data + + def staged_media(self, source: TurnSource) -> list[tuple[str, str]]: + """``(path, url)`` of each media file the turn's view names that is stored as its name says, each hashed as it + streams in and its bytes let go, so staging a long run's screenshots holds none of them.""" + try: + paths = media_paths(self.view(source)) + except (AttributeError, TypeError): # a copy graded as stored whose shape names no media a reader can find + paths = [] + return [(path, url) for path in paths if (url := self._checked(source.url, path)) is not None] + + def _checked(self, document_url: str, path: str) -> Optional[str]: + try: + url = media_url(document_url, path) + except AtifError as exc: + logger.warning(f"ATIF media {path!r} of {document_url} skipped: {exc}") + return None + if url not in self._stored: + digest = hashlib.sha256() + try: + with get_config().get_object_store_at(url).open(url) as stream: + for chunk in iter(lambda: stream.read(_HASH_CHUNK), b""): + digest.update(chunk) + self._stored[url] = digest.hexdigest() == media_file(path) + except NotFoundError: + self._stored[url] = False + if not self._stored[url]: + logger.warning(f"ATIF media {path} of {document_url} skipped: not stored as its name says") + return url if self._stored[url] else None + + +def _text(content: Any) -> str: + if isinstance(content, str): + return content + return "\n".join(part["text"] for part in content or [] + if isinstance(part, Mapping) and part.get("type") == "text" and isinstance(part.get("text"), str)) + + +def _has_image(content: Any) -> bool: + return isinstance(content, list) and any(isinstance(part, Mapping) and part.get("type") == "image" + for part in content) + + +def _steps(trajectory: Mapping[str, Any]) -> list[Mapping[str, Any]]: + """A trajectory's steps a reader can walk: a stored copy may be invalid, and is still graded as stored.""" + steps = trajectory.get("steps") + return [step for step in steps if isinstance(step, Mapping)] if isinstance(steps, list) else [] + + +def _results(step: Mapping[str, Any]) -> list[Mapping[str, Any]]: + observation = step.get("observation") + results = observation.get("results") if isinstance(observation, Mapping) else None + return [result for result in results if isinstance(result, Mapping)] if isinstance(results, list) else [] + + +def _by_call(step: Mapping[str, Any]) -> list[tuple[Optional[Mapping[str, Any]], list[Mapping[str, Any]]]]: + """Each tool call of the step with its results by ``source_call_id``, then the results no call names.""" + calls = step.get("tool_calls") + calls = [call for call in calls if isinstance(call, Mapping)] if isinstance(calls, list) else [] + results = _results(step) + ids = {call.get("tool_call_id") for call in calls} + paired = [(call, [r for r in results if r.get("source_call_id") == call.get("tool_call_id")]) for call in calls] + unpaired = [r for r in results if r.get("source_call_id") not in ids] + return paired + ([(None, unpaired)] if unpaired else []) + + +class _SubAgents: + """The embedded sub-agents a trajectory's results start, each walked once. A reference names one among its + trajectory's own, else the nearest around where that trajectory sits, whoever reached it, as ATIF makes an id unique + only within its parent's array (the builder embeds them all in the root). A copy graded as stored may lack an id, or + hold one as a list or an object, and such an id names nothing.""" + + def __init__(self, document: Mapping[str, Any]) -> None: + self._walked: set[int] = set() + self._visible: dict[int, dict[Any, Mapping[str, Any]]] = {} + self._scope(document, {}) + + def _scope(self, trajectory: Mapping[str, Any], outer: Mapping[Any, Mapping[str, Any]]) -> None: + subs = trajectory.get("subagent_trajectories") + subs = [sub for sub in subs if isinstance(sub, Mapping)] if isinstance(subs, list) else [] + named = {_name(sub.get("trajectory_id")): sub for sub in subs} + visible = {**outer, **{name: sub for name, sub in named.items() if name is not None}} + self._visible[id(trajectory)] = visible + for sub in subs: + self._scope(sub, visible) + + def started(self, trajectory: Mapping[str, Any], result: Mapping[str, Any]) -> list[Mapping[str, Any]]: + visible = self._visible[id(trajectory)] + refs = result.get("subagent_trajectory_ref") + found = [] + for ref in refs if isinstance(refs, list) else []: + sub = visible.get(_name(ref.get("trajectory_id"))) if isinstance(ref, Mapping) else None + if sub is not None and id(sub) not in self._walked: + self._walked.add(id(sub)) + found.append(sub) + return found + + +def _name(trajectory_id: Any) -> Any: + return trajectory_id if isinstance(trajectory_id, Hashable) else None + + +def _sub_name(sub: Mapping[str, Any]) -> Any: + return _name(sub.get("trajectory_id")) + + +def compact_atif_trajectory( + document: Mapping[str, Any], trajectory_filter: TrajectoryFilter, result_file_prefix: str = "", +) -> tuple[list[dict], list[tuple[str, str]]]: + """``compact_otel_trajectory``'s events from an ATIF document, in step order: an agent step's + ``reasoning_content`` as thinking, each tool call and then its results (one over the inline size or holding an + image written out to a file, as the OTel compaction does), and the root's last agent message as the final + response; each with its step's timestamp. A sub-agent's events follow the result that started it, which names it in + ``starts_subagents``, and each names it as ``subagent``, so a judge tells its calls from the main agent's, as a + native Claude Code turn's ``parent_tool_use_id`` does.""" + events: list[dict] = [] + files: list[tuple[str, str]] = [] + numbers = itertools.count(1) + subagents = _SubAgents(document) + calls_on = trajectory_filter.include_tool_calls + results_on = trajectory_filter.include_tool_call_results + + def walk(trajectory: Mapping[str, Any], tag: Mapping[str, Any]) -> None: + for step in _steps(trajectory): + if step.get("source") != "agent": + continue + timestamp = step.get("timestamp") or "" + if trajectory_filter.include_thinking and step.get("reasoning_content"): + events.append({"type": "thinking", "text": step["reasoning_content"], "timestamp": timestamp, **tag}) + for call, results in _by_call(step): + tool = (call or {}).get("function_name") or "" + if call is not None and calls_on: + events.append({"type": "tool_call", "tool": tool, "input": call.get("arguments"), + "timestamp": timestamp, **tag}) + for result in results: + started = subagents.started(trajectory, result) + names = {"starts_subagents": [_sub_name(sub) for sub in started]} if started else {} + if results_on: + output = result.get("content") + output_json = json.dumps(output) + if len(output_json) > _TOOL_RESULT_MAX_INLINE_SIZE or _has_image(output): + path = f"{_TOOL_RESULT_FILES_DIR}/{result_file_prefix}tool_call_result_{next(numbers)}.json" + files.append((path, output_json)) + events.append({"type": "tool_result", "tool": tool, "output_file": path, + "timestamp": timestamp, **tag, **names}) + else: + events.append({"type": "tool_result", "tool": tool, "output": output, + "timestamp": timestamp, **tag, **names}) + for sub in started: + walk(sub, {"subagent": _sub_name(sub)}) + + walk(document, {}) + if trajectory_filter.include_response: + final = next((step for step in reversed(_steps(document)) + if step.get("source") == "agent" and _text(step.get("message")).strip()), None) + if final is not None: + events.append({"type": "final_response", "text": _text(final.get("message")), + "timestamp": final.get("timestamp") or ""}) + return events, files + + +def transcript_from_atif( + document: Mapping[str, Any], media: Callable[[str], Optional[bytes]], +) -> tuple[Transcript, list[ImageFrame]]: + """The agent's steps as ``transcript_from_raw`` reads a native run, a sub-agent's after the result that started it: + each tool call an action, its screenshot the first image of its results, its result their text; each agent message + placed after the calls before it. And every image of the steps' results in order, the frames a final-frames judge + takes the last of, each typed by its bytes as the native reader types them. ``media`` reads a part's file, None for + one the judge goes without.""" + actions: list[TrajectoryAction] = [] + messages: list[AgentMessage] = [] + frames: list[ImageFrame] = [] + subagents = _SubAgents(document) + + def walk(trajectory: Mapping[str, Any]) -> None: + for step in _steps(trajectory): + if step.get("source") != "agent": + continue + text = _text(step.get("message")) + if text.strip(): + messages.append(AgentMessage(len(actions), text)) + for call, results in _by_call(step): + shots: list[ImageFrame] = [] + for result in results: + content = result.get("content") + for part in content if isinstance(content, list) else []: + source = part.get("source") if isinstance(part, Mapping) and part.get("type") == "image" else None + data = media(source["path"]) if isinstance(source, Mapping) and source.get("path") else None + if data is not None: + shots.append(ImageFrame(media_type=_image_type(data, source.get("media_type")), + data=base64.b64encode(data).decode())) + frames.extend(shots) + if call is not None: + arguments = call.get("arguments") + result_text = "\n".join(t for t in (_text(r.get("content")) for r in results) if t) + actions.append(TrajectoryAction( + index=len(actions) + 1, tool=str(call.get("function_name") or ""), + args=arguments if isinstance(arguments, dict) else {}, + screenshot=shots[0].data if shots else None, result=result_text or None, + screenshot_media_type=shots[0].media_type if shots else None)) + for result in results: + for sub in subagents.started(trajectory, result): + walk(sub) + + walk(document) + return Transcript(actions, messages), frames + + +def _image_type(data: bytes, declared: Optional[str]) -> str: + """An image's media type by its leading bytes, which a judge's model checks the payload against; the type its part + declares only when the bytes don't say.""" + for signature, media_type in _IMAGE_SIGNATURES: + if data.startswith(signature): + return media_type + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + return declared or "image/png" diff --git a/src/agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py b/src/agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py index f7715cd37..2b512b4d7 100644 --- a/src/agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +++ b/src/agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py @@ -52,6 +52,7 @@ class TrajectoryAction: args: dict screenshot: str | None # raw base64 of the post-action screenshot, if the span had one result: object = None # the tool result minus its `screenshot`; None if nothing is left + screenshot_media_type: str | None = None # the screenshot's type when its reader knew it; else read from its bytes @dataclass(frozen=True) @@ -351,7 +352,8 @@ def _labeled_frames(actions: list[TrajectoryAction], picked: set[int], wants: li parts.extend(pins.get(j, ())) parts.append(f"action {j}") frames.append(LabeledFrame(" ".join(part for part in parts if part), - ImageFrame(media_type=media_type_for_b64(a.screenshot), data=a.screenshot))) + ImageFrame(media_type=a.screenshot_media_type or media_type_for_b64(a.screenshot), + data=a.screenshot))) return frames diff --git a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py index 4783d742a..8e8ba4cce 100644 --- a/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +++ b/src/agent_env/task_step/task_steps/verifiers/rubrics_verifier.py @@ -57,6 +57,13 @@ agent_error_text, fetch_container_logs, ) +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( + AtifDocuments, + TurnSource, + atif_turns, + compact_atif_trajectory, + transcript_from_atif, +) from agent_env.task_step.task_steps.verifiers.judge_utils.frame_selection import ( LabeledFrame, Transcript, @@ -419,10 +426,13 @@ def _override_or(overrides: dict, key: str, stored: Optional[int]) -> Optional[i def _as_of_turn(prompt_response: PromptResponse, turn: Optional[int]) -> PromptResponse: """A copy of a multi-turn PromptResponse cut off after ``turn``, or the original when there is nothing to cut. The stored response is the conversation's last reply, so a cut copy points the - judge at the end of the turn's own trajectory instead of leaking later turns. A failed turn + judge at the end of the turn's own trajectory instead of leaking later turns; the per-turn records are cut with the + urls, since an atif/1 turn's url is a document its later turns overwrite and only its record's task is the turn's + own. A failed turn ends the conversation, so every turn before the last completed: the stored error is the last turn's and is dropped from a cut copy.""" turn_urls = prompt_response.target_agent_per_turn_trajectory_object_urls or [] + records = prompt_response.target_agent_per_turn_trajectories prompt_parts = prompt_response.source_agent_per_turn_prompt_parts # Per-turn prompt parts are recorded every turn; per-turn trajectories only when the agent # exposes them, so the turn count comes from whichever is longer. @@ -437,6 +447,7 @@ def _as_of_turn(prompt_response: PromptResponse, turn: Optional[int]) -> PromptR return replace( prompt_response, target_agent_per_turn_trajectory_object_urls=turn_urls[:turn], + target_agent_per_turn_trajectories=records[:turn] if records is not None else None, agent_trajectory_object_url=turn_urls[turn - 1], source_agent_per_turn_prompt_parts=prompt_parts[:turn] if prompt_parts is not None else None, structured_output=None, @@ -481,6 +492,7 @@ class RubricsVerifierTaskStep(VerifierTaskStep): "conversation turn, in chronological order. Read every file, in order, to judge the " "full conversation; actions the agent took in earlier turns count." ) + _ATIF_FILES_NOTE: ClassVar[str] = "\n\nNOTE: The trajectory path above is a DIRECTORY holding {held}. {atif}{media}" _CONTEXT_FACTS_LEAD: ClassVar[str] = ( "These values were measured from the run's record. Rely on them over what the screenshots or " "trajectory text appear to show." @@ -854,6 +866,9 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: per_turn_uris = [u for u in (prompt_response.target_agent_per_turn_trajectory_object_urls or []) if u] if self.use_trajectory and not (per_turn_uris or prompt_response.agent_trajectory_object_url): raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'") + # A run whose turns are atif/1 copies reads each turn by its label; one with none keeps the native path. + atif = atif_turns(prompt_response) if self.use_trajectory else None + documents = AtifDocuments() overrides = context.metadata.get("user_overrides", {}) use_agent_judge = run["use_agent_judge"] @@ -883,14 +898,22 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: ) # Per-run dir so per-turn files can't collide with a prior run's on a reused (agent_name) - # judge sandbox — a shorter run would otherwise leave stale later-turn files behind. - multiturn_dir = f"{self.TRAJECTORY_CONTAINER_DIR}/{uuid.uuid4().hex[:12]}" if multiturn else None + # judge sandbox — a shorter run would otherwise leave stale later-turn files behind. An atif/1 run's + # media sit beside its turns, so it gets one even for a single turn. + multiturn_dir = (f"{self.TRAJECTORY_CONTAINER_DIR}/{uuid.uuid4().hex[:12]}" + if multiturn or atif is not None else None) # Single-file compaction is only needed off the multi-turn path. It reads the trajectory, # and for the DEFAULT filter writes a compacted copy back, so it runs on a thread. - compacted = _CompactedTrajectory.empty() if multiturn else await asyncio.to_thread( - self._compact_trajectory, prompt_response, filter_to_apply, criteria=criteria, - label_ids={real: short for short, real in real_by_short.items()}) + label_ids = {real: short for short, real in real_by_short.items()} + if multiturn: + compacted = _CompactedTrajectory.empty() + elif atif is not None: + compacted = await asyncio.to_thread(self._compact_atif_turn, atif[0], documents, filter_to_apply, + criteria=criteria, label_ids=label_ids) + else: + compacted = await asyncio.to_thread(self._compact_trajectory, prompt_response, filter_to_apply, + criteria=criteria, label_ids=label_ids) if not use_agent_judge: compacted.tool_result_files = [] # only an agent judge's container reads them; they can be large if self._spec().cites_evidence and not compacted.per_criterion: @@ -923,6 +946,7 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: auto_deployed_judge = None staged: Optional[StagedTrajectory] = None + atif_note = "" judge_agent = None judge_a2a_url: Optional[str] = None judge_sandbox_id: Optional[str] = None @@ -983,7 +1007,11 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: provider = build_sandbox_provider(judge_sandbox_type) if judge_sandbox_type else get_agent_sandbox_provider() sandbox = await provider.get_sandbox(judge_sandbox_id) staged = await self.stage_trajectory(context, stored_response, run_context, sandbox, judge_container) - if staged is None and multiturn: + if staged is None and atif is not None: + media = await self._stage_atif_turns( + sandbox, atif, multiturn_dir, filter_to_apply, judge_container, documents) + atif_note = self._atif_note(atif, filter_to_apply, media=media) + elif staged is None and multiturn: await self._load_per_turn_trajectories( sandbox, per_turn_uris, multiturn_dir, filter_to_apply, judge_container) elif staged is None: @@ -1027,11 +1055,13 @@ async def _judged(self, context: TaskStepContext) -> RubricsVerdict: if staged is not None: trajectory_path = staged.path elif self.use_trajectory: - trajectory_path = multiturn_dir if multiturn else self.TRAJECTORY_CONTAINER_PATH + trajectory_path = multiturn_dir if multiturn or atif is not None else self.TRAJECTORY_CONTAINER_PATH else: image_blocks = compacted.image_blocks # Direct judge embeds the trajectory inline; DEFAULT has no pre-rendered text. - if multiturn: + if multiturn and atif is not None: + trajectory_inline = await asyncio.to_thread(self._atif_turns_text, atif, filter_to_apply, documents) + elif multiturn: trajectory_inline = await asyncio.to_thread(self._merge_per_turn_text, per_turn_uris, filter_to_apply) else: trajectory_inline = compacted.inline_text @@ -1059,6 +1089,8 @@ def eval_prompt_for(batch: list[dict]) -> str: ) if staged is not None: prompt += staged.prompt_note + elif atif_note: + prompt += atif_note elif self.use_trajectory and multiturn: prompt += self._MULTITURN_DIR_NOTE.format(n=len(per_turn_uris)) else: @@ -1352,6 +1384,121 @@ def _filter_trajectory_content( ) return json.dumps(filtered), tool_result_files + def _atif_turn_content(self, source: TurnSource, documents: AtifDocuments, + trajectory_filter: Optional[TrajectoryFilter], + result_file_prefix: str = "") -> tuple[str, list[tuple[str, str]]]: + """An atif/1 turn's text for a judge: its view, or under the DEFAULT filter its compaction, with the tool-result + files that writes out. A SCREENSHOT filter leaves it as it is, as it leaves a native turn for an agent judge.""" + if trajectory_filter is None or trajectory_filter.compaction_type != CompactionType.DEFAULT: + return documents.text(source), [] + events, files = compact_atif_trajectory(documents.view(source), trajectory_filter, + result_file_prefix=result_file_prefix) + return json.dumps(events), files + + def _compact_atif_turn(self, source: TurnSource, documents: AtifDocuments, + filter_to_apply: Optional[TrajectoryFilter], criteria: list[dict], + label_ids: dict[str, str]) -> _CompactedTrajectory: + """``_compact_trajectory`` for a run of one atif/1 turn: its view's text, its DEFAULT compaction (written back + as the native one is, for the entry to record), or its SCREENSHOT frames from the media its results name.""" + if filter_to_apply is not None and filter_to_apply.compaction_type == CompactionType.SCREENSHOT: + return self._compact_atif_screenshot(source, documents, filter_to_apply, criteria, label_ids) + text, files = self._atif_turn_content(source, documents, filter_to_apply) + if filter_to_apply is None: + return _CompactedTrajectory(inline_text=text) + config = get_config() + compact_key = f"{config.get_artifact_key_prefix()}compacted-trajectories/{uuid.uuid4().hex}.json" + compact_url = config.get_object_store().put(compact_key, text.encode(), content_type="application/json") + return _CompactedTrajectory(inline_text=text, tool_result_files=files, compact_object_url=compact_url) + + def _compact_atif_screenshot(self, source: TurnSource, documents: AtifDocuments, tf: TrajectoryFilter, + criteria: list[dict], label_ids: dict[str, str]) -> _CompactedTrajectory: + """``_compact_screenshot`` for an atif/1 turn: the actions from its tool calls and the frames from its results' + image parts, each read from the document's media.""" + view = documents.view(source) + transcript, frames = transcript_from_atif(view, lambda path: documents.media(source.url, path)) + per_criterion = tf.frame_strategy == FrameStrategy.PER_CRITERION + if per_criterion: + exclude = re.compile(tf.evidence_exclude_pattern, re.I) if tf.evidence_exclude_pattern else None + always_show = {label: re.compile(pattern, re.I) for label, pattern in (tf.always_show_actions or {}).items()} + labeled = select_frames_per_criterion(transcript.actions, criteria, max_frames=tf.frame_budget, + exclude_pattern=exclude, always_show=always_show, label_ids=label_ids) + image_blocks = _labeled_image_blocks(labeled) + else: + image_blocks = [_image_url_block(f) for f in frames[-tf.screenshot_last_n:]] + if tf.trajectory_text == TrajectoryText.ACTION_LOG: + inline_text = action_log(transcript.actions, messages=transcript.messages, max_lines=tf.action_log_max_lines) + else: + inline_text = strip_trajectory_images(json.dumps(view, ensure_ascii=False)) + return _CompactedTrajectory.for_screenshot(inline_text, image_blocks, + per_criterion=per_criterion and bool(image_blocks)) + + async def _stage_atif_turns(self, sandbox, sources: list[TurnSource], container_dir: str, + trajectory_filter: Optional[TrajectoryFilter], container: Optional[str], + documents: AtifDocuments) -> bool: + """Each turn into ``container_dir`` as turn_NN.json by its label: an atif/1 turn's view (or its DEFAULT + compaction) with the media it names in the folder's ``media/``, a native one as the multi-turn path loads it. + Whether any media was staged.""" + tool_result_files: list[tuple[str, str]] = [] + media: dict[str, str] = {} + for i, source in enumerate(sources, start=1): + dest = f"{container_dir}/turn_{i:02d}.json" + prefix = f"turn_{i:02d}_" if len(sources) > 1 else "" + if source.atif: + text, files = await asyncio.to_thread(self._atif_turn_content, source, documents, trajectory_filter, + prefix) + media.update(await asyncio.to_thread(documents.staged_media, source)) + elif trajectory_filter is not None: + text, files = await asyncio.to_thread(self._filter_trajectory_content, source.url, trajectory_filter, + prefix) + else: + await sandbox.write_file_from_object(source.url, dest, **into_container(container)) + continue + await sandbox.write_file_from_text(text, dest, **into_container(container)) + tool_result_files.extend(files) + for path, url in media.items(): + await sandbox.write_file_from_object(url, f"{container_dir}/{path}", **into_container(container)) + if tool_result_files: + await self._load_tool_result_files(sandbox, tool_result_files, container) + logger.info(f"Loaded {len(sources)} turns ({sum(s.atif for s in sources)} atif/1) into {container_dir}, " + f"{len(media)} media files, {len(tool_result_files)} tool-result files") + return bool(media) + + def _atif_note(self, sources: list[TurnSource], trajectory_filter: Optional[TrajectoryFilter], *, + media: bool) -> str: + """What the agent judge is told of the turn files ``_stage_atif_turns`` wrote: which are ATIF and how media + paths in them resolve.""" + names = [f"turn_{i:02d}.json" for i in range(1, len(sources) + 1)] + if len(names) == 1: + held = f"one file, {names[0]}, the turn being graded" + else: + held = (f"{len(names)} files named {names[0]} … {names[-1]}, one per conversation turn, in chronological " + "order; read every file, in order, to judge the full conversation, since actions the agent took in " + "earlier turns count") + atif = [name for name, source in zip(names, sources) if source.atif] + subject = (f"{atif[0]} is" if len(atif) == 1 else "Each file is" if len(atif) == len(names) + else f"Each of {', '.join(atif)} is") + compacted = trajectory_filter is not None and trajectory_filter.compaction_type == CompactionType.DEFAULT + what = ("a compacted event list made from its turn's ATIF (Agent Trajectory Interchange Format) document." + if compacted else "an ATIF (Agent Trajectory Interchange Format, v1.8) document holding its turn " + "alone, its steps numbered from 1.") + where = (" A media path in a turn file, or in a tool-result file it names (media/.), is relative " + "to this directory." if media else "") + return self._ATIF_FILES_NOTE.format(held=held, atif=f"{subject} {what}", media=where) + + def _atif_turns_text(self, sources: list[TurnSource], trajectory_filter: Optional[TrajectoryFilter], + documents: AtifDocuments) -> str: + """``_merge_per_turn_text`` by each turn's label: an atif/1 turn's view, or its DEFAULT compaction.""" + parts = [] + for i, source in enumerate(sources, start=1): + if source.atif: + text, _ = self._atif_turn_content(source, documents, trajectory_filter, f"turn_{i:02d}_") + elif trajectory_filter is not None: + text, _ = self._filter_trajectory_content(source.url, trajectory_filter, f"turn_{i:02d}_") + else: + text = self._read_trajectory_text(source.url) + parts.append(f"===== Turn {i} =====\n{text}") + return "\n\n".join(parts) + async def _prompt_llm_judge( self, eval_prompt: str, diff --git a/tst/data/verifier_golden/judge_inputs.json b/tst/data/verifier_golden/judge_inputs.json index 4ef0d4f17..c309397d2 100644 --- a/tst/data/verifier_golden/judge_inputs.json +++ b/tst/data/verifier_golden/judge_inputs.json @@ -1814,5 +1814,735 @@ "chars": 13255 } } - ] + ], + "model_atif_one_turn": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "aaa80059a48c5bc5ece33ea5ce54fb16c241fdb2f72e25d455bd7a073f94a058", + "chars": 5462 + }, + "images": null, + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_one_turn_of_two_tasks_compacted": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "d464f7a037b02ec87d4e9c98ca225e945a0a91fe3c51a78c4a1a55a267ee0036", + "chars": 2376 + }, + "images": null, + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_two_turns": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "920bfc169a3fa0ac487056e7f6df39b2bad5913e0edd4fd3792718197f341039", + "chars": 8120 + }, + "images": null, + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_two_turns_compacted": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "3ce50bc425ea69335e54a4ecda53d5b7bf6397ecc6b02caaec901ff1dff50dae", + "chars": 3587 + }, + "images": null, + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_two_turns_first_native": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "645f63dda7b6c1ff6ccdcb8c6c944afb99d15e9be5b4a8e603ad7a054d7bf287", + "chars": 27161 + }, + "images": null, + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_screenshots_final_frames": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "dbf833e8bc5b8c6ff351c7d6acf9890aafc6bb8b6c6441b1323b712c1ef4ec2c", + "chars": 6807 + }, + "images": [ + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,c2NyZWVuc2hvdC0y" + } + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,c2NyZWVuc2hvdC0z" + } + } + ], + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_graded_up_to_turn_one": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "fc4d20b129b2578b564f11edde9825ed9ca65d7d486accdeee4aa43845d8ee4a", + "chars": 6791 + }, + "images": null, + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "model_atif_screenshots_per_criterion": { + "calls": [ + { + "model": "judge-model", + "prompt": { + "sha256": "6a919437607cb33acfe2c8b8b87a32465aca466b2be3ffbaf3c95adb86e93fd9", + "chars": 4793 + }, + "images": [ + { + "type": "text", + "text": "FRAME: final action 1" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,c2NyZWVuc2hvdC0x" + } + }, + { + "type": "text", + "text": "FRAME: final action 2" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,c2NyZWVuc2hvdC0y" + } + }, + { + "type": "text", + "text": "FRAME: final action 3" + }, + { + "type": "image_url", + "image_url": { + "url": "data:image/png;base64,c2NyZWVuc2hvdC0z" + } + } + ], + "system": null, + "cached_prefix": null + } + ], + "files": {} + }, + "agent_atif_one_turn_with_media": { + "calls": [ + { + "prompt": { + "sha256": "fa79f3b4a8fca45e04d701f5f1e1306659a895620f58e5f9cf68d015a0d4b97c", + "chars": 2405 + } + } + ], + "files": { + "/tmp/prompt_trajectory_turns//media/482405b002a62efa8516c36709a7a100637507670576fa73a20ad5420d55c66f.png": { + "text": "screenshot-3" + }, + "/tmp/prompt_trajectory_turns//media/69a8aa01fe5537076d023dd5e9cc4275b39fc0434aa6483a9f58b66ef2f3c896.png": { + "text": "screenshot-2" + }, + "/tmp/prompt_trajectory_turns//media/82e60066a2de261b6653bcdda90d1cb9a7af2f474cecd82e8d371e8384d72315.png": { + "text": "screenshot-1" + }, + "/tmp/prompt_trajectory_turns//turn_01.json": { + "text": { + "sha256": "f05cae8d13ffa493013f44b958ea947a1e7d74200dc8b740e8ed59593cb861e4", + "chars": 3440 + } + } + } + }, + "agent_atif_one_turn_compacted": { + "calls": [ + { + "prompt": { + "sha256": "8355d04711b32d2085e535cfa363416be766a2442f1897ecc3e743be2a64d7b7", + "chars": 2390 + } + } + ], + "files": { + "/tmp/prompt_trajectory_turns//media/482405b002a62efa8516c36709a7a100637507670576fa73a20ad5420d55c66f.png": { + "text": "screenshot-3" + }, + "/tmp/prompt_trajectory_turns//media/69a8aa01fe5537076d023dd5e9cc4275b39fc0434aa6483a9f58b66ef2f3c896.png": { + "text": "screenshot-2" + }, + "/tmp/prompt_trajectory_turns//media/82e60066a2de261b6653bcdda90d1cb9a7af2f474cecd82e8d371e8384d72315.png": { + "text": "screenshot-1" + }, + "/tmp/prompt_trajectory_turns//turn_01.json": { + "text": { + "sha256": "bef77b5565c7398eb385f0f60269cceb3c1d58f5a130f837634d61e8cc44fefc", + "chars": 792 + } + }, + "/tmp/tool_call_results/tool_call_result_1.json": { + "text": "[{\"type\": \"image\", \"source\": {\"media_type\": \"image/png\", \"path\": \"media/82e60066a2de261b6653bcdda90d1cb9a7af2f474cecd82e8d371e8384d72315.png\"}}]" + }, + "/tmp/tool_call_results/tool_call_result_2.json": { + "text": "[{\"type\": \"image\", \"source\": {\"media_type\": \"image/png\", \"path\": \"media/69a8aa01fe5537076d023dd5e9cc4275b39fc0434aa6483a9f58b66ef2f3c896.png\"}}]" + }, + "/tmp/tool_call_results/tool_call_result_3.json": { + "text": "[{\"type\": \"image\", \"source\": {\"media_type\": \"image/png\", \"path\": \"media/482405b002a62efa8516c36709a7a100637507670576fa73a20ad5420d55c66f.png\"}}]" + } + } + }, + "agent_atif_two_turns": { + "calls": [ + { + "prompt": { + "sha256": "fe704ffcd05e23d7cc6e3e36bc5c9935da15f2ede0aa889c0220955c54d4bc70", + "chars": 2443 + } + } + ], + "files": { + "/tmp/prompt_trajectory_turns//turn_01.json": { + "text": { + "sha256": "4c39faba9decd82d3b793558c93f27016152f10753ffb843b0e44ae9ef195e5a", + "chars": 4670 + } + }, + "/tmp/prompt_trajectory_turns//turn_02.json": { + "text": { + "sha256": "fd9b198db1817038df9bcdadf192958d15c3f29287bd82b4d85c7b04e1726ce1", + "chars": 1388 + } + } + } + }, + "agent_atif_two_turns_compacted": { + "calls": [ + { + "prompt": { + "sha256": "bfb86951e32a057d3ba8a364cc6316d60f6e0da733250c557f6a7b73cbdb4326", + "chars": 2428 + } + } + ], + "files": { + "/tmp/prompt_trajectory_turns//turn_01.json": { + "text": { + "sha256": "542febcbb8d311b39c101bf0871a7ace37144d42ca4f2185cbe738b37ab6e7e0", + "chars": 1171 + } + }, + "/tmp/prompt_trajectory_turns//turn_02.json": { + "text": "[{\"type\": \"tool_call\", \"tool\": \"Edit\", \"input\": {\"file_path\": \"tests/test_parse.py\", \"old_string\": \"\", \"new_string\": \"def test_offset(): ...\"}, \"timestamp\": \"\"}, {\"type\": \"tool_result\", \"tool\": \"Edit\", \"output\": \"The file tests/test_parse.py has been updated.\", \"timestamp\": \"\"}, {\"type\": \"final_response\", \"text\": \"Added test_offset.\", \"timestamp\": \"\"}]" + }, + "/tmp/tool_call_results/turn_01_tool_call_result_1.json": { + "text": { + "sha256": "d6389c121cea53ec82587068550d7235bcec95c093d198950fbf79d29bfd2ea4", + "chars": 1430 + } + } + } + }, + "agent_atif_two_turns_first_native": { + "calls": [ + { + "prompt": { + "sha256": "fb7e7ea7905a6855c56b908bcc5df4fd84ea6a303f35b27c0da0a5cabd03620e", + "chars": 2446 + } + } + ], + "files": { + "/tmp/prompt_trajectory_turns//turn_01.json": { + "text": { + "sha256": "919e68cb5e5ff44462a474b2466b1d6fd44022d980db4568581f601b36994b6d", + "chars": 23711 + } + }, + "/tmp/prompt_trajectory_turns//turn_02.json": { + "text": { + "sha256": "fd9b198db1817038df9bcdadf192958d15c3f29287bd82b4d85c7b04e1726ce1", + "chars": 1388 + } + } + } + }, + "scripted_verify_atif": { + "url": "http://mcp", + "trajectory": [ + [ + { + "type": "system", + "subtype": "init", + "cwd": "/app", + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "tools": [ + "mcp__apps__browser_click", + "mcp__apps__browser_close", + "mcp__apps__browser_drag", + "mcp__apps__browser_fill_form", + "mcp__apps__browser_handle_dialog", + "mcp__apps__browser_hover", + "mcp__apps__browser_navigate", + "mcp__apps__browser_navigate_back", + "mcp__apps__browser_press_key", + "mcp__apps__browser_resize", + "mcp__apps__browser_select_option", + "mcp__apps__browser_snapshot" + ], + "mcp_servers": [ + { + "name": "apps", + "status": "connected" + } + ], + "model": "claude-opus-5-5", + "permissionMode": "bypassPermissions", + "slash_commands": [ + "deep-research", + "design-sync", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "loop", + "claude-api", + "run", + "run-skill-generator", + "clear", + "compact", + "context", + "heapdump", + "init", + "reload-skills", + "review", + "security-review", + "usage", + "insights", + "goal", + "team-onboarding" + ], + "apiKeySource": "none", + "claude_code_version": "2.1.177", + "output_style": "default", + "agents": [ + "claude", + "Explore", + "general-purpose", + "Plan", + "statusline-setup" + ], + "skills": [ + "deep-research", + "design-sync", + "update-config", + "verify", + "debug", + "code-review", + "simplify", + "batch", + "fewer-permission-prompts", + "loop", + "claude-api", + "run", + "run-skill-generator" + ], + "plugins": [], + "analytics_disabled": false, + "product_feedback_disabled": false, + "uuid": "ae6a3cf3-999c-4907-8283-7db48f3c7c41", + "memory_paths": { + "auto": "/root/.claude/projects/-app/memory/" + }, + "fast_mode_state": "off" + }, + { + "type": "assistant", + "message": { + "model": "claude-opus-5-5", + "id": "msg_011CgZ27di7jDQ2FrfnSaqQu", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": "toolu_014S2or6YhfoaiEFUJU21h4E", + "name": "mcp__apps__gmail_get_thread", + "input": { + "user_email": "tess.marlowe@example.test", + "thread_id": "nw-1187" + } + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 3613, + "cache_read_input_tokens": 55808, + "cache_creation": { + "ephemeral_5m_input_tokens": 3613, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 8 + }, + "input_transformations": [], + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "cc813fa8-840b-4c22-ae09-7e9b553ac8f3" + }, + { + "type": "user", + "message": { + "role": "user", + "content": [ + { + "tool_use_id": "toolu_014S2or6YhfoaiEFUJU21h4E", + "type": "tool_result", + "content": { + "sha256": "18baeda3e6122970719ef82eb0ea05c0bb18163b7607886f3629a16f0fe13a49", + "chars": 5127 + } + } + ] + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "ce3d07b7-8976-4063-9752-852eee77ba2c", + "timestamp": "2026-10-30T20:03:32.476Z", + "tool_use_result": { + "content": { + "sha256": "18baeda3e6122970719ef82eb0ea05c0bb18163b7607886f3629a16f0fe13a49", + "chars": 5127 + }, + "structuredContent": { + "result": { + "sha256": "b54f1e197b9abe7f6c56cc134e5149fe77bd066884c9e568139ed8d22139e004", + "chars": 4694 + } + } + } + }, + { + "type": "assistant", + "message": { + "model": "claude-opus-5-5", + "id": "msg_011CgZ3amiSMU2XRHLsZ5hE8", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "thinking", + "thinking": "", + "signature": "CAQStgUKEggTEAIYAjgBQgh0aGlua2luZxIM5FH92PjkGiAY1XucGgzURGHQaHkLkApdkq4iMJZBlxvXqmfzZvbrIcoaHI9XuRyTOR0zM7cdjOgSLrqWNlI/" + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 4, + "cache_creation_input_tokens": 2036, + "cache_read_input_tokens": 465148, + "cache_creation": { + "ephemeral_5m_input_tokens": 2036, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 4 + }, + "input_transformations": [], + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "411de34e-c6ac-492f-86dc-99f0b0483cb6" + }, + { + "type": "assistant", + "message": { + "model": "claude-opus-5-5", + "id": "msg_011CgZ3amiSMU2XRHLsZ5hE8", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "tool_use", + "id": "toolu_01KhowokbuAvM2xyD8EwpXH9", + "name": "mcp__apps__gmail_list_messages", + "input": { + "user_email": "tess.marlowe@example.test", + "query": "from:packright.example.test newer_than:2d" + } + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 4, + "cache_creation_input_tokens": 2036, + "cache_read_input_tokens": 465148, + "cache_creation": { + "ephemeral_5m_input_tokens": 2036, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 4 + }, + "input_transformations": [], + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "103b2889-3b01-43a9-966a-46dc28d3be45" + }, + { + "type": "user", + "message": { + "role": "user", + "content": [ + { + "tool_use_id": "toolu_01KhowokbuAvM2xyD8EwpXH9", + "type": "tool_result", + "content": "{\"result\":\"{\\\"messages\\\": [], \\\"resultSizeEstimate\\\": 0, \\\"nextPageToken\\\": null}\"}" + } + ] + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "f0b36a3b-49cd-48b2-a329-58f671a4f73b", + "timestamp": "2026-10-30T20:22:48.018Z", + "tool_use_result": { + "content": "{\"result\":\"{\\\"messages\\\": [], \\\"resultSizeEstimate\\\": 0, \\\"nextPageToken\\\": null}\"}", + "structuredContent": { + "result": "{\"messages\": [], \"resultSizeEstimate\": 0, \"nextPageToken\": null}" + } + } + }, + { + "type": "assistant", + "message": { + "model": "claude-opus-5-5", + "id": "msg_011CgZ3azQBb9hRitvxJB4qS", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "thinking", + "thinking": "", + "signature": "CAQS3wYKEggTEAIYAjgBQgh0aGlua2luZxIMa2rBO+8KWmCdvVF4GgzyV/1KKvqQeg9REUciMMkbAyQV+klA/oGe8KHFfdllylKG6ClKyX27M/VmuvU3aEMV" + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 171, + "cache_read_input_tokens": 467184, + "cache_creation": { + "ephemeral_5m_input_tokens": 171, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 5 + }, + "input_transformations": [], + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "b920b9d3-d877-4751-b211-9c3686f86f17" + }, + { + "type": "assistant", + "message": { + "model": "claude-opus-5-5", + "id": "msg_011CgZ3azQBb9hRitvxJB4qS", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "text", + "text": "Still nothing from PackRight. I'll note the contingency on the plan and the calendar so it doesn't get lost:" + } + ], + "container": null, + "stop_reason": null, + "stop_sequence": null, + "stop_details": null, + "usage": { + "input_tokens": 2, + "cache_creation_input_tokens": 171, + "cache_read_input_tokens": 467184, + "cache_creation": { + "ephemeral_5m_input_tokens": 171, + "ephemeral_1h_input_tokens": 0 + }, + "output_tokens": 5 + }, + "input_transformations": [], + "context_management": null + }, + "parent_tool_use_id": null, + "session_id": "daeab2f0-9b66-4fa3-ab68-c6ecae85beee", + "uuid": "b81fbbf6-0d84-4c09-bd31-ce33af50baf2" + } + ], + { + "schema_version": "ATIF-v1.8", + "session_id": "ctx-7f3a", + "agent": { + "name": "toy", + "version": "1.0", + "model_name": "claude-opus-5-5" + }, + "extra": { + "agentenv": { + "version": "1.0", + "native_format": "toy-events/1", + "adapter": { + "name": "toy-events-atif", + "version": "0.1.0" + }, + "unmatched": { + "system": 1 + } + } + }, + "steps": [ + { + "step_id": 1, + "timestamp": "2026-11-04T17:05:00.000Z", + "source": "user", + "message": "Also cover a +05:30 offset.", + "extra": { + "agentenv": { + "context_id": "ctx-7f3a", + "task_id": "task-91c3", + "message_id": "msg-a2", + "turn": 1 + } + } + }, + { + "step_id": 2, + "source": "agent", + "model_name": "claude-opus-5-5", + "message": "", + "tool_calls": [ + { + "tool_call_id": "toolu_05", + "function_name": "Edit", + "arguments": { + "file_path": "tests/test_parse.py", + "old_string": "", + "new_string": "def test_offset(): ..." + } + } + ], + "observation": { + "results": [ + { + "source_call_id": "toolu_05", + "content": "The file tests/test_parse.py has been updated." + } + ] + }, + "metrics": { + "prompt_tokens": 32240, + "cached_tokens": 31700, + "completion_tokens": 90, + "extra": { + "agentenv": { + "cache_write_tokens": 400 + } + } + }, + "llm_call_count": 1 + }, + { + "step_id": 3, + "source": "agent", + "model_name": "claude-opus-5-5", + "message": "Added test_offset.", + "metrics": { + "prompt_tokens": 32360, + "cached_tokens": 32100, + "completion_tokens": 12, + "extra": { + "agentenv": { + "cache_write_tokens": 120 + } + } + }, + "llm_call_count": 1, + "extra": { + "agentenv": { + "state": "completed" + } + } + } + ] + } + ] + } } diff --git a/tst/integration/task_step/test_prompt_agent_live_trajectory_local.py b/tst/integration/task_step/test_prompt_agent_live_trajectory_local.py index 3216fd1e6..38b7a29b9 100644 --- a/tst/integration/task_step/test_prompt_agent_live_trajectory_local.py +++ b/tst/integration/task_step/test_prompt_agent_live_trajectory_local.py @@ -13,13 +13,11 @@ import hashlib import json import re -import struct import shutil import socket import subprocess import time import uuid -import zlib import httpx import pytest @@ -41,6 +39,7 @@ from agent_env.task_step.task_steps.snapshot_agent_state import SnapshotAgentStateTaskStep from tst.integration.utils.registry import REGISTRY_IMAGE from tst.util.a2a_test_agent import put_test_agent +from tst.util.images import png pytestmark = pytest.mark.integration @@ -156,7 +155,7 @@ async def test_each_turn_is_stored_live_under_its_own_prefix_and_joins_to_its_fi finals = context.prompt_responses[-1].target_agent_per_turn_trajectory_object_urls assert len(finals) == 2 and all(finals) assert context.prompt_responses[-1].target_agent_per_turn_trajectories == [ - {"native_format": "agentenv-echo-agent/v1", "atif": None}] * 2 + {"format": "agentenv-echo-agent/v1", "atif": None}] * 2 turns = [store.get_object_key(url).removeprefix(f"{prefix_key}trajectory-").removesuffix(".json") for url in finals] assert len(set(turns)) == 2 for turn, final_url in zip(turns, finals): @@ -174,14 +173,19 @@ async def test_each_turn_is_stored_live_under_its_own_prefix_and_joins_to_its_fi @pytest.mark.asyncio async def test_a_deployed_agent_serves_its_native_format_and_atif_and_refuses_another(local_registry): + """And the run, which prescribes atif/1, has the turn's copy as its trajectory, stored in its folder with the image's + file beside it, and reads no native trajectory.""" suffix = uuid.uuid4().hex[:8] native = "agentenv-echo-agent/v1" + image = png(6, 4) agent = put_test_agent(f"trajectory-formats-agent-{suffix}") task = Task.put(id=f"trajectory-formats-{suffix}", steps=[ _deploy(agent, "solver"), PromptAgentTaskStep( - id="ask", version=None, prompt_id="ask", agent_name="solver", prompt="hello", - context_id=f"formats-{suffix}", + id="ask", version=None, prompt_id="ask", agent_name="solver", context_id=f"formats-{suffix}", + parts=[{"kind": "text", "text": "hello"}, + {"kind": "file", "file": {"bytes": base64.b64encode(image).decode(), "mimeType": "image/png", + "name": "shot.png"}}], ), ]) @@ -204,11 +208,24 @@ async def test_a_deployed_agent_serves_its_native_format_and_atif_and_refuses_an document = atif["trajectory"] assert (atif["format"], atif["schema_version"], atif["profile_version"]) == (ATIF, SCHEMA_VERSION, PROFILE_VERSION) assert errors_in(validate(document)) == [] - assert [step["message"] for step in document["steps"]] == ["hello", "Echo: hello"] + [shot] = media_paths(document) + assert document["steps"][0]["message"] == [{"type": "text", "text": "hello"}, + {"type": "image", "source": {"media_type": "image/png", "path": shot}}] + assert document["steps"][1]["message"].startswith("Echo: hello") assert (document["session_id"], atif["turn_context"]["task_id"]) == (f"formats-{suffix}", page["task_id"]) assert cursor["events"] == document["steps"] and cursor["header"]["trajectory_id"] == document["trajectory_id"] with pytest.raises(httpx.HTTPStatusError, match="HTTP 400: format_not_offered"): raise_for_extension_status(refused, operation="trajectory read") + [turn] = context.prompt_responses[-1].target_agent_per_turn_trajectories + record, store = turn["atif"], get_config().get_object_store() + folder = context.metadata["atif_copies"]["agents"]["solver"]["folder"] + assert (turn["format"], record["status"], record["rules"]) == (ATIF, "valid", []) + assert context.prompt_responses[-1].target_agent_per_turn_trajectory_object_urls == [record["url"]] + assert record["url"] == f"{folder}{document['trajectory_id']}.json" + assert json.loads(store.get(record["url"])) == document + assert json.loads(store.get(record["turn_context_url"])) == atif["turn_context"] + assert store.get(f"{folder}{shot}") == image + assert errors_in(validate(document, media={shot: store.get(f"{folder}{shot}")})) == [] @pytest.mark.asyncio @@ -272,15 +289,6 @@ async def test_a_model_key_a_command_prints_is_redacted_in_atif_and_kept_in_the_ assert errors_in(validate(atif["trajectory"])) == [] -def _png(width: int, height: int) -> bytes: - def chunk(kind: bytes, body: bytes) -> bytes: - return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body)) - - pixels = zlib.compress(b"".join(b"\x00" + b"\x00\x00\x00" * width for _ in range(height))) - return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) - + chunk(b"IDAT", pixels) + chunk(b"IEND", b"")) - - @pytest.mark.asyncio async def test_a_deployed_agent_pushes_its_copys_media_under_exact_object_grants(local_registry): suffix = uuid.uuid4().hex[:8] @@ -289,7 +297,7 @@ async def test_a_deployed_agent_pushes_its_copys_media_under_exact_object_grants context = await Task.put(id=f"media-{suffix}", steps=[_deploy(agent, "solver")]).run() assert not context.metadata.get("failed_steps"), context.metadata.get("failed_steps") [deployed] = context.deployed_agents - image = _png(6, 4) + image = png(6, 4) parts = [{"kind": "text", "text": "look"}, {"kind": "file", "file": {"bytes": base64.b64encode(image).decode(), "mimeType": "image/png", "name": "shot.png"}}] diff --git a/tst/unit/a2a_agent/staging_test.py b/tst/unit/a2a_agent/staging_test.py index 8be0b64a4..424402e91 100644 --- a/tst/unit/a2a_agent/staging_test.py +++ b/tst/unit/a2a_agent/staging_test.py @@ -266,6 +266,79 @@ async def test_a_trajectory_upload_lands_in_the_store(agent, store): assert store.get(target) == b'[{"type": "result"}]' +def _losing_answers_to(app, path: str): + """``app``, whose answers to requests for ``path`` are lost once it has served them.""" + + async def losing(scope, receive, send): + if scope["type"] == "http" and scope["path"] == path: + async def dropped(message) -> None: + pass + + await app(scope, receive, dropped) + await PlainTextResponse("the answer was lost", status_code=504)(scope, receive, send) + return + await app(scope, receive, send) + + return losing + + +@pytest.mark.asyncio +async def test_what_the_agent_staged_reaches_the_store_when_its_answer_is_lost(agent, store, monkeypatch): + """As an upload through a grant does: the object the agent wrote is in the store whether or not its answer + arrives, so a caller that finds the agent has let go of it can still find it there.""" + card = _card(agent) + _, path = _method(card, TRAJECTORY_V1.uri, "get") + real_async_client = httpx._client.AsyncClient # the fixture already serves the agent through the patched one + losing = _losing_answers_to(agent, path) + monkeypatch.setattr(httpx, "AsyncClient", + lambda **kwargs: real_async_client(transport=httpx.ASGITransport(app=losing), **kwargs)) + granting = transfer_store(store, URL, card, sandbox_type="modal") + target = store.object_url("trajectories/t.json") + + with pytest.raises(httpx.HTTPStatusError, match="HTTP 504"): + await fetch_trajectory(URL + path, {"task_id": "t"}, upload=TrajectoryUpload.to(granting, target), store=granting) + + assert store.get(target) == b'[{"type": "result"}]' + + +class _Unreachable(httpx.AsyncBaseTransport): + """The agent, except that requests for ``path`` never reach it.""" + + def __init__(self, app, path: str) -> None: + self._agent, self._path = httpx.ASGITransport(app=app), path + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + if request.url.path == self._path: + raise httpx.ConnectError("unreachable", request=request) + return await self._agent.handle_async_request(request) + + +@pytest.mark.asyncio +async def test_a_staged_call_that_never_reached_the_agent_collects_nothing(agent, store, monkeypatch): + """So an unreachable agent's call fails at once, not after collection's retries.""" + card = _card(agent) + _, path = _method(card, TRAJECTORY_V1.uri, "get") + real_async_client = httpx._client.AsyncClient # the fixture already serves the agent through the patched one + monkeypatch.setattr(httpx, "AsyncClient", + lambda **kwargs: real_async_client(transport=_Unreachable(agent, path), **kwargs)) + collected: list[int] = [] + real_pull = StagedObjectStore.pull + + async def pull(self) -> None: + collected.append(1) + await real_pull(self) + + monkeypatch.setattr(StagedObjectStore, "pull", pull) + granting = transfer_store(store, URL, card, sandbox_type="modal") + + with pytest.raises(httpx.ConnectError): + await fetch_trajectory(URL + path, {"task_id": "t"}, + upload=TrajectoryUpload.to(granting, store.object_url("trajectories/t.json")), + store=granting) + + assert collected == [] + + async def _enable_changelog(agent, store) -> tuple[str, staging.StagedNamespace]: card = _card(agent) granting = transfer_store(store, URL, card, sandbox_type="modal") diff --git a/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py b/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py index c4e0f95f3..e7880ee07 100644 --- a/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py +++ b/tst/unit/agents/claude_code/test_claude_code_atif_recorded.py @@ -21,8 +21,13 @@ if __name__ == "__main__": sys.path.insert(0, str(REPO)) -from agentenv_protocol.atif import RecordedTask, check_adapter # noqa: E402 +from agentenv_protocol.atif import RecordedTask, check_adapter, check_media, task_document, tasks # noqa: E402 +from agent_env.task_step.task_steps.verifiers.judge_utils.atif_turns import ( # noqa: E402 + compact_atif_trajectory, + transcript_from_atif, +) +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter # noqa: E402 from tst.unit.agents.claude_code.agent import claude_code_atif # noqa: E402 FIXTURES = REPO / "tst" / "data" / "claude_code_atif" @@ -110,6 +115,32 @@ def test_the_recordings_cover_what_the_adapter_maps(): assert any(step.get("extra", {}).get("agentenv", {}).get("reasoning") for step in documents["thinking"]["steps"]) +@pytest.mark.parametrize("scenario", SCENARIOS) +def test_a_judge_reads_each_recorded_turn_with_its_calls_results_answer_and_screenshots(scenario): + """What the judges take from each turn's copy, cut out as its own task: every tool call and result, a sub-agent's + included, the final answer, and each screenshot as a frame whose bytes match its name.""" + kit = replay(scenario) + for task in tasks(kit.document): + view = task_document(kit.document, [task.task_id]) + steps = [step for trajectory in _trajectories(view) for step in trajectory["steps"] if step["source"] == "agent"] + results = [result for step in steps for result in (step.get("observation") or {}).get("results") or ()] + images = [part for result in results for part in result.get("content") or () + if isinstance(part, dict) and part.get("type") == "image"] + events, _ = compact_atif_trajectory(view, TrajectoryFilter()) + kinds = [event["type"] for event in events] + assert kinds.count("tool_call") == sum(len(step.get("tool_calls") or ()) for step in steps) + assert kinds.count("tool_result") == len(results) + assert ("final_response" in kinds) == any(isinstance(step.get("message"), str) and step["message"].strip() + for step in view["steps"] if step["source"] == "agent") + transcript, frames = transcript_from_atif(view, lambda path: check_media(path, kit.media[path]) or kit.media[path]) + assert len(transcript.actions) == kinds.count("tool_call") + assert len(frames) == len(images) + if scenario == "browser": + assert images and frames + if scenario == "subagent": + assert [event["tool"] for event in events if event["type"] == "tool_call" and event.get("subagent")] == ["Bash"] + + def test_from_atif_reads_harbors_own_conversion_of_a_recorded_session(): harbor = json.loads((FIXTURES / "harbor" / "subagent.harbor.json").read_text()) tasks, _ = recorded("subagent") diff --git a/tst/unit/task_step/prompt_agent_rig.py b/tst/unit/task_step/prompt_agent_rig.py new file mode 100644 index 000000000..1d3602583 --- /dev/null +++ b/tst/unit/task_step/prompt_agent_rig.py @@ -0,0 +1,38 @@ +"""What tests of a prompt step against an agent served in process share: the conversation store kept quiet, every +HTTP client sent to the agent, and the agent the step prompts, deployed from its own card.""" + +from __future__ import annotations + +from typing import Any + +import httpx +import pytest + +from agent_env.task_step.context import DeployedAgent +from agent_env.task_step.task_steps import prompt_agent as pa + +#: The conversation store calls a prompt step makes, which these tests keep from reaching a store. +CONVERSATION_STORE_CALLS = ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", + "get_conversation") +AGENT_URL = "http://agent.test" + + +def quiet_conversations(monkeypatch: pytest.MonkeyPatch) -> None: + for name in CONVERSATION_STORE_CALLS: + monkeypatch.setattr(pa.conversation_store, name, lambda *args, **kwargs: None) + + +def route_clients(monkeypatch: pytest.MonkeyPatch, transport: httpx.AsyncBaseTransport, **options: Any) -> None: + """Send every ``httpx.AsyncClient`` in this process through ``transport``, with ``options`` such as event hooks.""" + real_client = httpx._client.AsyncClient # the class itself, so routing twice replaces rather than nests + monkeypatch.setattr(httpx, "AsyncClient", + lambda *args, **kwargs: real_client(*args, **{**kwargs, "transport": transport, **options})) + + +def card_of(app: Any) -> dict: + """An SDK agent app's card, as its well-known route serves it.""" + return app.state.agentenv_a2a.card.model_dump(mode="json", exclude_none=True) + + +def deployed(card: dict, *, name: str = "solver", url: str = AGENT_URL) -> DeployedAgent: + return DeployedAgent(agent_name=name, api_url=url, a2a_url=url, a2a_card=card) diff --git a/tst/unit/task_step/run_context_object_url_test.py b/tst/unit/task_step/run_context_object_url_test.py index b6f11b4ef..2689aae09 100644 --- a/tst/unit/task_step/run_context_object_url_test.py +++ b/tst/unit/task_step/run_context_object_url_test.py @@ -61,8 +61,8 @@ def test_every_field_round_trips_through_the_stored_form(): "model": "m", "error_type": "agent_error", "error_code": "c", "error_message": "e", "agent_session_id": "s", "a2a_context_id": "ctx", "agent_name": "solver", "step_id": "solve", "structured_output": {"a": 1}, "usage": [{"role": "solver", "turns": 2}], - "target_agent_per_turn_trajectories": [{"native_format": "echo/1", "atif": None}, - {"native_format": None, "atif": None}]} + "target_agent_per_turn_trajectories": [{"format": "echo/1", "atif": None}, + {"format": None, "atif": None}]} response = dataclasses.replace(_neutral(), **values) unset = [f.name for f in dataclasses.fields(PromptResponse) if getattr(response, f.name) == (f.default if f.default is not dataclasses.MISSING else None)] @@ -70,6 +70,12 @@ def test_every_field_round_trips_through_the_stored_form(): assert PromptResponse.from_dict(response.to_dict()) == response +def test_a_turn_record_stored_before_its_label_was_named_format_reads_as_its_format(): + response = PromptResponse.from_dict({"prompt_id": "p1", "response": "done", "target_agent_per_turn_trajectories": [ + {"native_format": "echo/1", "atif": None}]}) + assert response.target_agent_per_turn_trajectories == [{"format": "echo/1", "atif": None}] + + def test_the_legacy_key_wins_when_the_two_disagree(): """Only a raw-doc writer outside the model can make them differ, and today's know only the legacy key.""" response = PromptResponse.from_dict({"prompt_id": "p1", "response": "done", "agent_trajectory_s3_uri": _URL, diff --git a/tst/unit/task_step/test_always_on_trajectory_formats.py b/tst/unit/task_step/test_always_on_trajectory_formats.py index 9fc0ce6d0..f1bb0de3e 100644 --- a/tst/unit/task_step/test_always_on_trajectory_formats.py +++ b/tst/unit/task_step/test_always_on_trajectory_formats.py @@ -1,10 +1,10 @@ -"""always_on prescribes the run's trajectory formats to the agent it prompts, once, before its first wake, so the agent -builds atif/1 for the run's conversation only when the run prescribes it.""" +"""always_on prescribes no format beside native to the agent it prompts, once, before its first wake, whatever the run +prescribes: until always_on reads atif/1 copies, its conversations build native only, even on an agent an earlier step +prescribed atif/1.""" import pytest from agent_env.task_step.task_steps import always_on as ao -from agent_env.task_step.task_steps import prompt_agent as pa from tst.unit.task_step.always_on_harness import SOLVER, Rig pytestmark = pytest.mark.usefixtures("local_stores") @@ -12,11 +12,11 @@ @pytest.mark.asyncio @pytest.mark.parametrize("formats", [["atif/1"], None]) -async def test_always_on_prescribes_the_runs_formats_to_its_agent_before_its_first_wake(monkeypatch, tmp_path, formats): +async def test_always_on_prescribes_native_only_to_its_agent_before_its_first_wake(monkeypatch, tmp_path, formats): happened: list[tuple] = [] - async def prescribe(context, step_id, agent, a2a_url): - happened.append(("prescribe", step_id, agent.agent_name, a2a_url, pa.prescribed_formats(context))) + async def prescribe(context, step_id, agent, a2a_url, *, formats=None): + happened.append(("prescribe", step_id, agent.agent_name, a2a_url, formats)) def agent(n, texts, rig): happened.append(("wake", n)) @@ -32,6 +32,6 @@ def agent(n, texts, rig): await rig.run(rig.step(), context) - assert happened[0] == ("prescribe", "week", "solver", SOLVER, tuple(formats or ())) + assert happened[0] == ("prescribe", "week", "solver", SOLVER, ()) assert [event for event in happened if event[0] == "prescribe"] == [happened[0]] assert happened[1][0] == "wake" diff --git a/tst/unit/task_step/test_prompt_agent.py b/tst/unit/task_step/test_prompt_agent.py index e64f7d260..a03948399 100644 --- a/tst/unit/task_step/test_prompt_agent.py +++ b/tst/unit/task_step/test_prompt_agent.py @@ -239,10 +239,11 @@ async def sdk_get(request: TaskTrajectoryRequest | TaskObjectTrajectoryRequest): return extension -async def _one_turn(monkeypatch, tmp_path, extension: dict, answer: Callable[[dict], dict] - ) -> tuple[PromptResponse, list[dict], LocalFilesystemObjectStore]: +async def _one_turn(monkeypatch, tmp_path, extension: dict, answer: Callable[[dict], dict], *, + formats: list[str] | None = None) -> tuple[PromptResponse, list[dict], LocalFilesystemObjectStore]: """One turn of a prompt step against an agent whose card carries ``extension`` and whose trajectory reads - ``answer`` gives each body: the step's prompt response, the read bodies it sent and the store it wrote to.""" + ``answer`` gives each body, in a run that prescribes ``formats``: the step's prompt response, the read bodies it + sent and the store it wrote to.""" store = LocalFilesystemObjectStore(str(tmp_path)) configure(object_store=store) for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", @@ -257,6 +258,8 @@ def trajectory(request: httpx.Request) -> httpx.Response: FakeA2AAgents({"http://agent.test": [{"kind": "text", "text": "Echo: hi"}]}, other=trajectory).serve(monkeypatch) context = TaskStepContext(instance_id="ti-1") + if formats is not None: + context.metadata["user_overrides"] = {"trajectory_formats": formats} context.deployed_agents.append(DeployedAgent( agent_name="solver", api_url="http://agent.test", a2a_url="http://agent.test", a2a_card={"capabilities": {"extensions": [extension]}}, @@ -276,14 +279,29 @@ async def test_sdk_agent_on_the_local_store_still_records_its_trajectory(monkeyp uri = response.agent_trajectory_object_url assert requests == [{"task_id": "task-1"}] - assert response.target_agent_per_turn_trajectories == [{"native_format": None, "atif": None}] + assert response.target_agent_per_turn_trajectories == [{"format": None, "atif": None}] assert store.get_object_key(uri).startswith("prompt_agent_trajectories/trajectory-") assert json.loads(store.get(uri)) == [{"type": "echo", "output": "Echo: hi"}] +@pytest.mark.asyncio +async def test_a_card_from_before_formats_in_a_run_that_prescribes_atif_reads_native_as_ever(monkeypatch, tmp_path): + """A pinned image's card names no formats, so it can't build atif/1: its turn stays native, read as it always was, + and its record says why (Y4-7, Y4-10).""" + response, requests, store = await _one_turn( + monkeypatch, tmp_path, _trajectory_extension(), + lambda body: {"trajectory": [{"type": "echo", "output": "Echo: hi"}]}, formats=["atif/1"]) + + assert requests == [{"task_id": "task-1"}] + [turn] = response.target_agent_per_turn_trajectories + assert turn["format"] is None and (turn["atif"]["status"], turn["atif"]["reason"]) == ( + "unavailable", "format_not_offered") + assert json.loads(store.get(response.agent_trajectory_object_url)) == [{"type": "echo", "output": "Echo: hi"}] + + @pytest.mark.asyncio async def test_a_card_that_offers_formats_is_asked_for_its_native_one_whatever_its_default(monkeypatch, tmp_path): - """A card whose default is atif/1, as F10 flips agents to, still gives judges the native copy they read.""" + """A card whose default is atif/1 is still read as native by name in a run that doesn't prescribe atif/1.""" extension = _trajectory_extension(native="echo/1") extension["params"].update(formats=["echo/1", "atif/1"], default="atif/1") @@ -292,7 +310,7 @@ async def test_a_card_that_offers_formats_is_asked_for_its_native_one_whatever_i lambda body: {"trajectory": [{"type": "echo"}], "format": body.get("format", "atif/1")}) assert requests == [{"task_id": "task-1", "format": "echo/1"}] - assert response.target_agent_per_turn_trajectories == [{"native_format": "echo/1", "atif": None}] + assert response.target_agent_per_turn_trajectories == [{"format": "echo/1", "atif": None}] assert json.loads(store.get(response.agent_trajectory_object_url)) == [{"type": "echo"}] diff --git a/tst/unit/task_step/test_prompt_agent_atif_copies.py b/tst/unit/task_step/test_prompt_agent_atif_copies.py new file mode 100644 index 000000000..77e93dbc8 --- /dev/null +++ b/tst/unit/task_step/test_prompt_agent_atif_copies.py @@ -0,0 +1,547 @@ +"""A prompt step stores each turn's atif/1 copy when the run prescribes atif/1: read inline from the agent once the turn +ends, stored as ``.json`` in the run's folder for the agent with its aux log, turn context and media, +checked, and recorded per turn beside the native copy, off the turn's path. Against a live SDK agent served in-process, +whose uploads land in a granting local store.""" +from __future__ import annotations + +import asyncio +import base64 +import json +from pathlib import Path +from typing import Any, Callable +from urllib.parse import unquote + +import httpx +import pytest +from agentenv_protocol.a2a_agent import ( + TRAJECTORY_V1, + AgentEnvAgent, + AgentIdentity, + TaskRequest, + TaskResult, + a2a_agent, + enable, +) +from agentenv_protocol.atif import FORMAT as ATIF, Adapter, atif_adapter, errors_in, media_paths, native, tasks, validate + +from agent_env.config import configure +from agent_env.task_step.context import PromptResponse, TaskStepContext +from agent_env.task_step.snapshot_utils import atif_copies +from agent_env.task_step.task_steps import prompt_agent as pa +from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep +from tst.unit.task_step.prompt_agent_rig import card_of, deployed, quiet_conversations, route_clients +from tst.util.granting_object_store import GRANT_ORIGIN, GrantingObjectStore +from tst.util.images import png + +NATIVE = "shots/1" +_PREFIX = "prompt_agent_trajectories/prompt_id=solve/" + + +@atif_adapter(native_format=NATIVE, version="2.1.0", input_includes_cache=False) +class _Shots(Adapter): + """Each native shot a step: its caption and its screenshot.""" + + @native(type="shot") + def shot(self, record: dict, turn) -> None: + image = turn.media(base64.b64decode(record["png"]), "image/png") + turn.message(step=f"s{record['n']}", content=[f"shot {record['n']}", image]) + turn.step(key=f"s{record['n']}", llm_call_count=1) + + +def _app(*, atif: bool = True): + """An agent that, each turn, appends one shot, a new screenshot each time, and answers.""" + shots = iter(range(1, 1000)) + + @a2a_agent( + identity=AgentIdentity(name="solver", description="test", version="1"), + extensions=(enable(TRAJECTORY_V1, live=False, native=NATIVE, **({"atif": _Shots} if atif else {})),), + ) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + request.trajectory.set_format(NATIVE) + n = next(shots) + request.trajectory.append({"type": "shot", "n": n, "png": base64.b64encode(png(n, 1)).decode()}) + return TaskResult.text(f"shot {n}") + + return Agent().create_app() + + +class _Wire(httpx.AsyncBaseTransport): + """The agent at ``http://agent.test``, served in-process, and the store's grant URLs, which write into the store. + A test can hold the agent's atif/1 reads until it lets them go, rewrite their answers, or rewrite any answer.""" + + def __init__(self, store: GrantingObjectStore, *, atif: bool) -> None: + self.store = store + self._atif = atif + self.restart() + self.atif_reads: list[dict] = [] + self.native_reads: list[dict] = [] + self.media_requests: list[dict] = [] + self.prescriptions: list[dict] = [] + self.hold: asyncio.Event | None = None + #: Set once an atif/1 read has arrived, whether or not it's held. + self.read_arrived = asyncio.Event() + self.answered_atif_reads = 0 + self.rewrite_atif: Callable[[dict], dict] | None = None + self.answer: Callable[[httpx.Request, str, dict, httpx.Response], httpx.Response | None] | None = None + #: Paths the agent never receives a request for: each is answered 503. + self.unreachable: set[str] = set() + + def restart(self) -> None: + self.app = _app(atif=self._atif) + self._agent = httpx.ASGITransport(app=self.app) + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + body = await request.aread() + if request.url.host == httpx.URL(GRANT_ORIGIN).host: + self.store.put(unquote(request.url.path.lstrip("/")), body, content_type=request.headers["content-type"], + allow_overwrite=True) + return httpx.Response(200, request=request) + sent = json.loads(body) if body and request.method == "POST" else {} + path = request.url.path + if path in self.unreachable: + return httpx.Response(503, request=request) + atif_read = path == "/ext/trajectory" and sent.get("format") == ATIF and "after" not in sent + if path == "/ext/trajectory" and not atif_read and "after" not in sent: + self.native_reads.append(sent) + if atif_read: + self.atif_reads.append(sent) + self.read_arrived.set() + if self.hold is not None: + await self.hold.wait() + elif path == "/ext/trajectory/media": + self.media_requests.append(sent) + elif path == "/ext/trajectory/prescribe": + self.prescriptions.append(sent) + response = await self._agent.handle_async_request(request) + self.answered_atif_reads += atif_read + if atif_read and self.rewrite_atif is not None and response.status_code == 200: + await response.aread() + response = httpx.Response(200, json=self.rewrite_atif(json.loads(response.content)), request=request) + if self.answer is not None: + await response.aread() + response = self.answer(request, path, sent, response) or response + return response + + +class _Run: + def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, atif: bool = True) -> None: + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) + self.root = tmp_path / "store" + self.store = GrantingObjectStore(str(self.root), reaches=True) + configure(object_store=self.store) + quiet_conversations(monkeypatch) + self.wire = _Wire(self.store, atif=atif) + self.asked: list[int] = [] + route_clients(monkeypatch, self.wire) + + async def ask(user_side, number: int, reply: str, parts: list[dict]) -> dict: + self.asked.append(number) + return {"message": [{"kind": "text", "text": f"again {number}"}]} + + monkeypatch.setattr(pa._UserSide, "ask", ask) + + @property + def card(self) -> dict: + return card_of(self.wire.app) + + def context(self, formats: list[str] | None = (ATIF,), **kwargs) -> TaskStepContext: + context = TaskStepContext(instance_id="ti-1", **kwargs) + if formats is not None: + context.metadata["user_overrides"] = {"trajectory_formats": list(formats)} + return context + + async def execute(self, context: TaskStepContext, *, card: dict | None = None, **step) -> PromptResponse: + context.deployed_agents[:] = [deployed(card or self.card)] + step.setdefault("max_conversation_turns", 2) + step.setdefault("user_a2a_url", "http://user.test") # whose answers ``ask`` stands in for + await PromptAgentTaskStep(id="solve", version=None, prompt="go", agent_name="solver", poll_interval_seconds=0, + trajectory_output_prefix=self.store.object_url(_PREFIX), **step).execute(context) + return context.prompt_responses[-1] + + def read(self, url: str) -> Any: + return json.loads(self.store.get(url)) + + def folder(self, context: TaskStepContext) -> Path: + return self.root / self.store.get_object_key(context.metadata["atif_copies"]["agents"]["solver"]["folder"]) + + +def _atifs(response: PromptResponse) -> list[dict | None]: + return [turn["atif"] for turn in response.target_agent_per_turn_trajectories] + + +@pytest.mark.asyncio +async def test_a_run_that_prescribes_atif_has_each_turns_copy_as_its_trajectory_and_reads_no_native( + monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + context = run.context() + + response = await run.execute(context) + + first, second = _atifs(response) + folder = context.metadata["atif_copies"]["agents"]["solver"]["folder"] + assert context.metadata["atif_copies"]["run"] == "ti-1" + assert folder == f"{run.store.object_url('atif/instance_id=ti-1/solver')}/" + document = run.read(second["url"]) + assert first["url"] == second["url"] == f"{folder}{document['trajectory_id']}.json" + assert response.target_agent_per_turn_trajectory_object_urls == [first["url"], second["url"]] + assert response.agent_trajectory_object_url == second["url"] + assert [turn["format"] for turn in response.target_agent_per_turn_trajectories] == [ATIF, ATIF] + assert [first["task_id"], second["task_id"]] == [task.task_id for task in tasks(document)] + assert [first["status"], second["status"]] == ["valid", "valid"] + assert first["rules"] == second["rules"] == [] and first["reason"] is None + assert first["adapter_version"] == "2.1.0" and first["validator_version"] == atif_copies._VALIDATOR_VERSION + assert first["through_step"] < second["through_step"] == document["steps"][-1]["step_id"] + assert document["session_id"] == response.a2a_context_id + assert len(media_paths(document)) == 2 + assert errors_in(validate(document, media=run.folder(context))) == [] + for record in (first, second): + assert record["aux_url"].startswith(f"{folder}turns/") and run.read(record["aux_url"]) == [] + assert run.read(record["turn_context_url"])["state"] == "completed" + assert [read["format"] for read in run.wire.atif_reads] == [ATIF, ATIF] + assert run.wire.native_reads == [] and not run.store.list(_PREFIX) + + +@pytest.mark.asyncio +async def test_a_run_that_prescribes_nothing_reads_and_stores_native_only(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + context = run.context(formats=None) + + response = await run.execute(context) + + assert _atifs(response) == [None, None] + assert run.wire.atif_reads == [] and run.wire.media_requests == [] + assert "atif_copies" not in context.metadata and not run.store.list("atif/") + + +@pytest.mark.asyncio +async def test_an_agent_that_doesnt_offer_atif_keeps_its_native_trajectory_as_ever(monkeypatch, tmp_path): + """Known before the first turn, so the step reads native on each turn's path, as a run that prescribes nothing.""" + run = _Run(monkeypatch, tmp_path, atif=False) + + response = await run.execute(run.context()) + + assert [(atif["status"], atif["reason"]) for atif in _atifs(response)] == [ + ("unavailable", "format_not_offered")] * 2 + assert run.wire.atif_reads == [] and len(run.wire.native_reads) == 2 + assert [turn["format"] for turn in response.target_agent_per_turn_trajectories] == [NATIVE, NATIVE] + assert [run.read(url)[0]["type"] for url in response.target_agent_per_turn_trajectory_object_urls] == ["shot"] * 2 + + +def _natives(run: _Run, response: PromptResponse) -> list[str | None]: + """The format of what each turn's url holds, read back.""" + return [None if url is None else ("shot" if isinstance(run.read(url), list) else ATIF) + for url in response.target_agent_per_turn_trajectory_object_urls] + + +@pytest.mark.asyncio +async def test_a_turn_whose_copy_the_agent_refuses_has_its_native_trajectory_read_in_its_place(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + run.wire.unreachable.add("/ext/trajectory/prescribe") + + response = await run.execute(run.context()) + + assert [(atif["status"], atif["reason"]) for atif in _atifs(response)] == [ + ("unavailable", "format_not_prescribed")] * 2 + assert [turn["format"] for turn in response.target_agent_per_turn_trajectories] == [NATIVE, NATIVE] + assert _natives(run, response) == ["shot", "shot"] and len(run.wire.native_reads) == 2 + assert response.error_type is None + + +@pytest.mark.asyncio +async def test_one_turns_failed_copy_falls_back_to_native_and_the_others_keep_theirs(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + failed: list[str] = [] + + def first_read_fails(request: httpx.Request, path: str, sent: dict, + response: httpx.Response) -> httpx.Response | None: + if path == "/ext/trajectory" and sent.get("format") == ATIF and not failed: + failed.append(sent["task_id"]) + return httpx.Response(500, request=request) + return None + + run.wire.answer = first_read_fails + + response = await run.execute(run.context()) + + assert [turn["format"] for turn in response.target_agent_per_turn_trajectories] == [NATIVE, ATIF] + assert [atif["status"] for atif in _atifs(response)] == ["unavailable", "valid"] + assert _natives(run, response) == ["shot", ATIF] and [read["task_id"] for read in run.wire.native_reads] == failed + assert response.agent_trajectory_object_url == _atifs(response)[1]["url"] + + +@pytest.mark.asyncio +async def test_a_turn_whose_copy_and_native_trajectory_both_fail_has_none(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + run.wire.answer = lambda request, path, sent, response: ( + httpx.Response(500, request=request) if path == "/ext/trajectory" else None) + + response = await run.execute(run.context(), max_conversation_turns=1) + + assert response.target_agent_per_turn_trajectory_object_urls == [None] + assert response.target_agent_per_turn_trajectories == [{"format": None, "atif": _atifs(response)[0]}] + assert response.agent_trajectory_object_url is None and response.error_type is None + + +@pytest.mark.asyncio +async def test_a_copy_that_fails_validation_is_stored_and_recorded_invalid_with_its_rules(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + + def stray_key(answer: dict) -> dict: + answer["trajectory"]["extra"]["elsewhere"] = {"x": 1} + return answer + + run.wire.rewrite_atif = stray_key + + response = await run.execute(run.context()) + + [first, second] = _atifs(response) + assert first["status"] == second["status"] == "invalid" + assert first["rules"] == ["outside-key"] and "outside-key" in first["reason"] + assert run.read(second["url"])["extra"]["elsewhere"] == {"x": 1} + assert response.error_type is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("field, version", [("schema_version", "ATIF-v1.9"), ("profile", "1.1")]) +async def test_a_copy_newer_than_the_worker_is_stored_and_recorded_newer(monkeypatch, tmp_path, field, version): + run = _Run(monkeypatch, tmp_path) + + def newer(answer: dict) -> dict: + if field == "schema_version": + answer["trajectory"]["schema_version"] = version + else: + answer["trajectory"]["extra"]["agentenv"]["version"] = version + return answer + + run.wire.rewrite_atif = newer + + response = await run.execute(run.context()) + + assert [atif["status"] for atif in _atifs(response)] == ["newer", "newer"] + assert run.read(_atifs(response)[-1]["url"])["schema_version"] == ( + version if field == "schema_version" else "ATIF-v1.8") + + +@pytest.mark.asyncio +async def test_a_newer_copys_missing_media_are_in_its_rules(monkeypatch, tmp_path): + """ATIF's models stop at a newer schema, and the copy's media are still checked.""" + run = _Run(monkeypatch, tmp_path) + card = run.card + trajectory = next(e for e in card["capabilities"]["extensions"] if e["uri"] == TRAJECTORY_V1.uri) + del trajectory["params"]["methods"]["media"] + + def newer(answer: dict) -> dict: + answer["trajectory"]["schema_version"] = "ATIF-v1.9" + return answer + + run.wire.rewrite_atif = newer + + response = await run.execute(run.context(), card=card, max_conversation_turns=1) + + [atif] = _atifs(response) + assert (atif["status"], atif["rules"]) == ("newer", ["atif", "media-bytes"]) + assert response.target_agent_per_turn_trajectories[0]["format"] == NATIVE + + +@pytest.mark.asyncio +async def test_a_copy_whose_media_didnt_arrive_is_recorded_and_its_turn_reads_native_in_its_place(monkeypatch, tmp_path): + """Its judges would read the turn without those files, which the native trajectory holds.""" + run = _Run(monkeypatch, tmp_path) + response = await run.execute(run.context(), card=_without_media(run.card)) + + assert [(atif["status"], atif["rules"]) for atif in _atifs(response)] == [("invalid", ["media-bytes"])] * 2 + assert run.wire.media_requests == [] + assert [turn["format"] for turn in response.target_agent_per_turn_trajectories] == [NATIVE, NATIVE] + assert _natives(run, response) == ["shot", "shot"] and len(run.wire.native_reads) == 2 + assert all(run.read(atif["url"])["steps"] for atif in _atifs(response)) + + +@pytest.mark.asyncio +async def test_a_copy_whose_media_didnt_arrive_stays_the_trajectory_when_native_cant_be_read(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + run.wire.answer = lambda request, path, sent, response: ( + httpx.Response(500, request=request) if path == "/ext/trajectory" and sent.get("format") != ATIF else None) + + response = await run.execute(run.context(), card=_without_media(run.card), max_conversation_turns=1) + + [atif] = _atifs(response) + assert (atif["status"], atif["rules"]) == ("invalid", ["media-bytes"]) + assert response.target_agent_per_turn_trajectories[0]["format"] == ATIF + assert response.target_agent_per_turn_trajectory_object_urls == [atif["url"]] + + +def _without_media(card: dict) -> dict: + """The card with no media method, so the worker can't ask for a copy's media.""" + trajectory = next(e for e in card["capabilities"]["extensions"] if e["uri"] == TRAJECTORY_V1.uri) + del trajectory["params"]["methods"]["media"] + return card + + +@pytest.mark.asyncio +async def test_a_file_whose_push_answer_was_lost_is_found_in_the_store_and_not_asked_for_again(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + lost: list[str] = [] + + def lose_first_push(request: httpx.Request, path: str, sent: dict, + response: httpx.Response) -> httpx.Response | None: + if path == "/ext/trajectory/media" and not lost: + lost.extend(sent["objects"]) + raise httpx.ReadTimeout("the answer was lost", request=request) + return None + + run.wire.answer = lose_first_push + context = run.context() + + response = await run.execute(context) + + assert [atif["status"] for atif in _atifs(response)] == ["valid", "valid"] + [first_shot] = lost + assert [list(request["objects"]) for request in run.wire.media_requests] == [ + [first_shot], [path for path in media_paths(run.read(_atifs(response)[-1]["url"])) if path != first_shot]] + + run.wire.media_requests.clear() + await run.execute(context, max_conversation_turns=1, context_id=None) + assert all(first_shot not in request["objects"] for request in run.wire.media_requests) + + +@pytest.mark.asyncio +async def test_a_restart_between_steps_links_the_sessions_earlier_document_to_the_next(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + context = run.context() + before = await run.execute(context, context_id="talk", max_conversation_turns=1) + run.wire.restart() + + after = await run.execute(context, context_id="talk", max_conversation_turns=1) + + earlier, later = run.read(_atifs(before)[0]["url"]), run.read(_atifs(after)[0]["url"]) + assert earlier["session_id"] == later["session_id"] == "talk" + assert earlier["trajectory_id"] != later["trajectory_id"] + assert earlier["continued_trajectory_ref"] == f"{later['trajectory_id']}.json" + assert "continued_trajectory_ref" not in later + assert errors_in(validate(earlier, media=run.folder(context))) == [] + assert context.metadata["atif_copies"]["agents"]["solver"]["sessions"] == {"talk": later["trajectory_id"]} + + +@pytest.mark.asyncio +async def test_the_user_sides_next_message_goes_out_before_the_turns_atif_copy_is_read(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + run.wire.hold = asyncio.Event() + real_ask = pa._UserSide.ask + + async def ask(user_side, number: int, reply: str, parts: list[dict]) -> dict: + await asyncio.wait_for(run.wire.read_arrived.wait(), 10) + assert run.wire.answered_atif_reads == 0 # the turn's read is still held, and the user side is asked anyway + run.wire.hold.set() + return await real_ask(user_side, number, reply, parts) + + monkeypatch.setattr(pa._UserSide, "ask", ask) + + response = await asyncio.wait_for(run.execute(run.context()), 30) + + assert run.asked == [1] and [atif["status"] for atif in _atifs(response)] == ["valid", "valid"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("trajectory_id", ["../elsewhere", "a/b", "", None]) +async def test_a_trajectory_id_that_isnt_a_plain_file_name_is_refused(monkeypatch, tmp_path, trajectory_id): + run = _Run(monkeypatch, tmp_path) + + def renamed(answer: dict) -> dict: + answer["trajectory"]["trajectory_id"] = trajectory_id + return answer + + run.wire.rewrite_atif = renamed + + response = await run.execute(run.context(), max_conversation_turns=1) + + assert [(atif["status"], atif["reason"]) for atif in _atifs(response)] == [ + ("unavailable", "invalid_trajectory_id")] + assert not run.store.list("atif/") + + +def test_a_run_without_an_instance_id_keeps_one_folder_run_for_all_its_agents(tmp_path): + configure(object_store=GrantingObjectStore(str(tmp_path))) + context = TaskStepContext() + + solver, judge = atif_copies.atif_folder(context, "solver"), atif_copies.atif_folder(context, "judge") + + run = context.metadata["atif_copies"]["run"] + assert run.startswith("adhoc-") and len(run) == len("adhoc-") + 12 + assert solver.endswith(f"atif/instance_id={run}/solver/") and judge.endswith(f"atif/instance_id={run}/judge/") + assert atif_copies.atif_folder(context, "solver") == solver + + +@pytest.mark.asyncio +async def test_a_link_that_fails_is_made_by_a_later_turn_and_its_turn_keeps_its_copy(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + context = run.context() + before = await run.execute(context, context_id="talk", max_conversation_turns=1) + earlier_url = _atifs(before)[0]["url"] + run.wire.restart() + real_read, failed = run.store.read, [] + + def read_failing_once(key: str) -> bytes: + if key.endswith(earlier_url.rsplit("/", 1)[1]) and not failed: + failed.append(key) + raise OSError("the store blinked") + return real_read(key) + + monkeypatch.setattr(run.store, "read", read_failing_once) + + after = await run.execute(context, context_id="talk", max_conversation_turns=2) + + assert failed and [atif["status"] for atif in _atifs(after)] == ["valid", "valid"] + later = run.read(_atifs(after)[-1]["url"]) + assert run.read(earlier_url)["continued_trajectory_ref"] == f"{later['trajectory_id']}.json" + + +@pytest.mark.asyncio +async def test_a_copy_that_doesnt_read_as_atif_is_stored_and_recorded_invalid(monkeypatch, tmp_path): + run = _Run(monkeypatch, tmp_path) + + def broken(answer: dict) -> dict: + answer["trajectory"]["steps"] = [None] + return answer + + run.wire.rewrite_atif = broken + + response = await run.execute(run.context(), max_conversation_turns=1) + + [atif] = _atifs(response) + assert (atif["status"], atif["rules"], atif["through_step"]) == ("invalid", ["atif"], None) + assert run.read(atif["url"])["steps"] == [None] and run.wire.media_requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("field", ["bytes", "sha256"]) +async def test_a_profile_that_misdescribes_a_stored_file_makes_the_copy_invalid(monkeypatch, tmp_path, field): + run = _Run(monkeypatch, tmp_path) + + def misdescribed(answer: dict) -> dict: + for step in answer["trajectory"]["steps"]: + for info in (step.get("extra") or {}).get("agentenv", {}).get("media", {}).values(): + info[field] = info[field] + 1 if field == "bytes" else "0" * 64 + return answer + + run.wire.rewrite_atif = misdescribed + + response = await run.execute(run.context(), max_conversation_turns=1) + + [atif] = _atifs(response) + assert (atif["status"], atif["rules"]) == ("invalid", ["media-bytes"]) + assert ("bytes" if field == "bytes" else "sha256") in atif["reason"] + assert _natives(run, response) == ["shot"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", ["x" * 5000, "Not A Code", 7]) +async def test_an_error_code_the_sdk_wouldnt_send_isnt_kept_as_the_reason(monkeypatch, tmp_path, code): + run = _Run(monkeypatch, tmp_path) + run.wire.answer = lambda request, path, sent, response: ( + httpx.Response(409, json={"error": {"code": code}}, request=request) + if path == "/ext/trajectory" and sent.get("format") == ATIF else None) + + response = await run.execute(run.context(), max_conversation_turns=1) + + assert [(atif["status"], atif["reason"]) for atif in _atifs(response)] == [("unavailable", "http_409")] diff --git a/tst/unit/task_step/test_prompt_agent_live_trajectory.py b/tst/unit/task_step/test_prompt_agent_live_trajectory.py index 5fde34290..e0b14b89f 100644 --- a/tst/unit/task_step/test_prompt_agent_live_trajectory.py +++ b/tst/unit/task_step/test_prompt_agent_live_trajectory.py @@ -20,10 +20,11 @@ from agent_env.config import configure from agent_env.store.object_store import LocalFilesystemObjectStore -from agent_env.task_step.context import DeployedAgent, TaskStepContext +from agent_env.task_step.context import TaskStepContext from agent_env.task_step.snapshot_utils import live_trajectory from agent_env.task_step.task_steps import prompt_agent as pa from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep +from tst.unit.task_step.prompt_agent_rig import card_of, deployed, quiet_conversations, route_clients _PREFIX = "prompt_agent_trajectories/prompt_id=solve/" _EVENTS = [{"type": "system", "subtype": "init"}, {"type": "assistant", "step": 0}] @@ -73,18 +74,14 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch, tmp_path, *, live: bool, wai native: str | None = None, atif: bool = False) -> None: self.store = LocalFilesystemObjectStore(str(tmp_path)) configure(object_store=self.store) - for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"): - monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: None) + quiet_conversations(monkeypatch) app = _agent(self.store, live=live, wait_for_chunk=wait_for_chunk, native=native, atif=atif).create_app() - self.card = app.state.agentenv_a2a.card.model_dump(mode="json", exclude_none=True) + self.card = card_of(app) self.cursor_reads: list[dict] = [] self.final_reads: list[dict] = [] #: Every request the step sent, in order: its path and, for a JSON-RPC call, its method. self.sent: list[str] = [] self.prescriptions: list[dict] = [] - transport = httpx.ASGITransport(app=app) - real_client = httpx.AsyncClient - async def record(request: httpx.Request) -> None: body = json.loads(await request.aread()) if request.method == "POST" else {} self.sent.append(body.get("method", request.url.path) if isinstance(body, dict) else request.url.path) @@ -93,17 +90,11 @@ async def record(request: httpx.Request) -> None: elif request.url.path == "/ext/trajectory/prescribe": self.prescriptions.append(body) - monkeypatch.setattr( - httpx, - "AsyncClient", - lambda *a, **kw: real_client(*a, transport=transport, event_hooks={"request": [record]}, **kw), - ) + route_clients(monkeypatch, httpx.ASGITransport(app=app), event_hooks={"request": [record]}) async def execute(self, step: PromptAgentTaskStep, context: TaskStepContext | None = None) -> TaskStepContext: context = context or TaskStepContext(instance_id="ti-1") - context.deployed_agents.append( - DeployedAgent(agent_name="solver", api_url="http://agent.test", a2a_url="http://agent.test", a2a_card=self.card) - ) + context.deployed_agents.append(deployed(self.card)) return await step.execute(context) def step(self, **kwargs) -> PromptAgentTaskStep: @@ -127,9 +118,10 @@ async def test_a_prompt_step_prescribes_the_runs_formats_before_its_first_messag assert run.prescriptions == [{"formats": formats or []}] assert run.sent.index("/ext/trajectory/prescribe") < run.sent.index("message/send") assert context.metadata["trajectory_formats"]["solve"]["built"] == ["test-events/1", *(formats or [])] - [final] = run.final_reads + assert [read["format"] for read in run.final_reads] == ([ATIF] if formats else ["test-events/1"]) async with httpx.AsyncClient() as client: - read = await client.post("http://agent.test/ext/trajectory", json={"task_id": final["task_id"], "format": ATIF}) + read = await client.post("http://agent.test/ext/trajectory", + json={"task_id": run.final_reads[0]["task_id"], "format": ATIF}) assert read.status_code == (200 if formats else 409) @@ -154,7 +146,7 @@ async def test_every_read_names_the_native_format_a_card_offers_and_the_turn_rec assert run.cursor_reads and {read.get("format") for read in run.cursor_reads} == {native} assert [read.get("format") for read in run.final_reads] == [native] assert result.prompt_responses[-1].target_agent_per_turn_trajectories == [ - {"native_format": "test-events/1", "atif": None}] + {"format": "test-events/1", "atif": None}] @pytest.mark.asyncio diff --git a/tst/unit/task_step/verifiers/judge_utils/test_atif_turns.py b/tst/unit/task_step/verifiers/judge_utils/test_atif_turns.py new file mode 100644 index 000000000..be965d8b3 --- /dev/null +++ b/tst/unit/task_step/verifiers/judge_utils/test_atif_turns.py @@ -0,0 +1,287 @@ +from __future__ import annotations + +import base64 +import json +import logging + +import pytest +from agentenv_protocol.atif import AtifError, errors_in, strip_profile, task_document, validate + +from agent_env.config import get_config +from agent_env.task_step.context import PromptResponse +from agent_env.task_step.task_steps.verifiers.judge_utils import atif_turns as T +from agent_env.task_step.task_steps.verifiers.judge_utils.frame_selection import select_frames_per_criterion +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter +from tst.util import atif_runs + +pytestmark = pytest.mark.usefixtures("local_stores") + +SHOT = "media/82e60066a2de261b6653bcdda90d1cb9a7af2f474cecd82e8d371e8384d72315.png" + + +def _response(urls, records) -> PromptResponse: + return PromptResponse(prompt_id="p", response="", target_agent_per_turn_trajectory_object_urls=urls, + target_agent_per_turn_trajectories=records) + + +def test_each_turn_is_read_by_its_label(): + url = atif_runs.stored("two_turns") + response = _response(["file:///native.json", None, url], + [atif_runs.native("task-91c2"), atif_runs.native("task-x"), + atif_runs.record(url, "task-91c3", 9)]) + assert T.turns(response) == [T.TurnSource("file:///native.json"), None, T.TurnSource(url, "task-91c3", 9)] + assert T.atif_turns(response) == [T.TurnSource("file:///native.json"), T.TurnSource(url, "task-91c3", 9)] + + +@pytest.mark.parametrize("records", [None, [atif_runs.native("task-1")], [{"format": "x", "atif": None}], + [{"format": "atif/1", "atif": None}]]) +def test_a_response_with_no_atif_turn_is_left_to_the_native_readers(records): + response = _response(["file:///a.json"], records) + assert T.atif_turns(response) is None + assert T.turns(response) == [T.TurnSource("file:///a.json")] + + +def test_a_view_is_the_turns_own_task_and_each_document_is_read_once(monkeypatch): + url = atif_runs.stored("two_turns") + store = get_config().get_object_store() + reads: list[str] = [] + get = store.get + monkeypatch.setattr(type(store), "get", lambda self, u: reads.append(u) or get(u)) + documents = T.AtifDocuments() + first, second = (documents.view(T.TurnSource(url, task)) for task in ("task-91c2", "task-91c3")) + whole = atif_runs.fixture("two_turns") + assert first == task_document(whole, ["task-91c2"]) and second == task_document(whole, ["task-91c3"]) + assert [step["message"] for step in second["steps"]][0] == "Also cover a +05:30 offset." + assert "final_metrics" not in second + assert reads == [url] + assert json.loads(documents.text(T.TurnSource(url, "task-91c3"))) == second + + +def test_a_copy_without_the_profile_finds_its_turn_by_the_step_it_reached(): + """Every profile field is optional, so a copy may carry no task ids: its turn is the task ending at its step.""" + url = atif_runs.stored("two_turns", document=strip_profile(atif_runs.fixture("two_turns"))) + view = T.AtifDocuments().view(T.TurnSource(url, "task-91c3", 9)) + assert [step["step_id"] for step in view["steps"]] == [1, 2, 3] and errors_in(validate(view)) == [] + + +def test_a_copy_the_turn_cant_be_found_in_is_read_as_stored(caplog): + """The requested trajectory is best effort: a judge grades what the copy holds rather than nothing.""" + url = atif_runs.stored("two_turns") + caplog.set_level(logging.WARNING) + assert T.AtifDocuments().view(T.TurnSource(url, "task-gone", 99)) == atif_runs.fixture("two_turns") + broken = atif_runs.stored("two_turns", document={**atif_runs.fixture("two_turns"), "steps": [None]}, media=False) + assert T.AtifDocuments().view(T.TurnSource(broken, "task-91c2", 6))["steps"] == [None] + assert sum("reads the copy as stored" in record.message for record in caplog.records) == 2 + + +def test_staging_hashes_each_file_once_and_keeps_none_of_its_bytes(monkeypatch): + url = atif_runs.stored("computer_use") + store = get_config().get_object_store() + opened: list[str] = [] + real_open = type(store).open + monkeypatch.setattr(type(store), "open", lambda self, u: opened.append(u) or real_open(self, u)) + documents = T.AtifDocuments() + source = T.TurnSource(url, "task-c1", 5) + staged = documents.staged_media(source) + assert len(staged) == 3 and documents.staged_media(source) == staged + assert len(opened) == 3 and all(isinstance(held, bool) for held in documents._stored.values()) + + +def test_a_screenshot_is_typed_by_its_bytes_not_the_type_its_part_declares(): + jpeg = b"\xff\xd8\xff\xe0" + b"j" * 16 + document = atif_runs.fixture("computer_use") + _, frames = T.transcript_from_atif(document, lambda path: jpeg) + assert {frame.media_type for frame in frames} == {"image/jpeg"} + _, frames = T.transcript_from_atif(document, lambda path: b"not an image") + assert {frame.media_type for frame in frames} == {"image/png"} + + +def test_a_sub_agents_screenshots_are_actions_and_frames_after_the_call_that_started_it(): + parent = atif_runs.fixture("subagent") + child = atif_runs.fixture("computer_use") + parent["subagent_trajectories"][0]["steps"] = child["steps"] + transcript, frames = T.transcript_from_atif(parent, lambda path: b"\x89PNG\r\n\x1a\n" + path.encode()) + assert len(frames) == 3 and sum(action.screenshot is not None for action in transcript.actions) == 3 + + +def test_media_resolve_in_the_documents_folder_checked_against_their_names(caplog): + url = atif_runs.stored("computer_use") + documents = T.AtifDocuments() + assert documents.media(url, SHOT) == b"screenshot-1" + assert T.media_url(url, SHOT) == f"{url.rsplit('/', 1)[0]}/{SHOT}" + with pytest.raises(AtifError): + T.media_url(url, "../secrets.json") + caplog.set_level(logging.WARNING) + assert documents.media(url, "media/../../x.png") is None + assert documents.media(url, "media/" + "0" * 64 + ".png") is None + store = get_config().get_object_store() + store.put(f"{atif_runs.folder()}{SHOT}", b"another file", allow_overwrite=True) + assert T.AtifDocuments().media(url, SHOT) is None + assert sum("skipped" in record.message for record in caplog.records) == 3 + + +def test_staged_media_are_those_stored_as_named(): + url = atif_runs.stored("computer_use", media=False) + source = T.TurnSource(url, "task-c1") + assert T.AtifDocuments().staged_media(source) == [] + atif_runs.stored("computer_use") + staged = T.AtifDocuments().staged_media(source) + assert [path for path, _ in staged] == [ + SHOT, "media/69a8aa01fe5537076d023dd5e9cc4275b39fc0434aa6483a9f58b66ef2f3c896.png", + "media/482405b002a62efa8516c36709a7a100637507670576fa73a20ad5420d55c66f.png"] + assert all(media == T.media_url(url, path) for path, media in staged) + + +def test_the_default_compaction_gives_the_otel_compactions_events(): + view = task_document(atif_runs.fixture("two_turns"), ["task-91c2"]) + events, files = T.compact_atif_trajectory(view, TrajectoryFilter(), result_file_prefix="turn_01_") + assert [(e["type"], e["tool"]) for e in events if e["type"] != "final_response"] == [ + ("tool_call", "Bash"), ("tool_result", "Bash"), ("tool_call", "Read"), ("tool_result", "Read"), + ("tool_call", "Edit"), ("tool_result", "Edit"), ("tool_call", "Bash"), ("tool_result", "Bash")] + assert events[0] == {"type": "tool_call", "tool": "Bash", "input": {"command": "pytest tests/test_parse.py -q"}, + "timestamp": ""} + assert events[3] == {"type": "tool_result", "tool": "Read", + "output_file": "/tmp/tool_call_results/turn_01_tool_call_result_1.json", "timestamp": ""} + assert [path for path, _ in files] == ["/tmp/tool_call_results/turn_01_tool_call_result_1.json"] + assert json.loads(files[0][1]).startswith("2026-01-01T03:04:05Z") + assert events[-1] == {"type": "final_response", "text": "parse_date now accepts a trailing Z; all 3 tests in " + "tests/test_parse.py pass.", "timestamp": ""} + thinking, _ = T.compact_atif_trajectory(view, TrajectoryFilter(include_thinking=True, include_tool_calls=False, + include_tool_call_results=False, + include_response=False)) + assert thinking == [{"type": "thinking", "text": "Run the failing test first to see the error.", "timestamp": ""}] + + +def test_the_default_compaction_writes_out_image_results_and_walks_sub_agents(): + events, files = T.compact_atif_trajectory(atif_runs.fixture("computer_use"), TrajectoryFilter()) + assert [e.get("output_file") for e in events if e["type"] == "tool_result"] == [ + f"/tmp/tool_call_results/tool_call_result_{n}.json" for n in (1, 2, 3)] + assert json.loads(files[0][1])[0]["source"]["path"] == SHOT + events, _ = T.compact_atif_trajectory(atif_runs.fixture("subagent"), TrajectoryFilter()) + assert [(e["type"], e.get("tool")) for e in events] == [ + ("tool_call", "Task"), ("tool_result", "Task"), ("tool_call", "Bash"), ("tool_result", "Bash"), + ("final_response", None)] + assert events[-1]["text"] == "There are three: a.toml, b.toml and c.toml." + + +def test_a_transcript_takes_actions_from_tool_calls_and_frames_from_result_images(): + url = atif_runs.stored("computer_use") + documents = T.AtifDocuments() + transcript, frames = T.transcript_from_atif(atif_runs.fixture("computer_use"), + lambda path: documents.media(url, path)) + assert [(a.index, a.tool, a.args.get("action")) for a in transcript.actions] == [ + (1, "computer", "screenshot"), (2, "computer", "left_click"), (3, "computer", "type")] + assert [base64.b64decode(a.screenshot) for a in transcript.actions] == [ + b"screenshot-1", b"screenshot-2", b"screenshot-3"] + assert [(f.media_type, base64.b64decode(f.data)) for f in frames] == [ + ("image/png", b"screenshot-1"), ("image/png", b"screenshot-2"), ("image/png", b"screenshot-3")] + assert [(m.after_action, m.text) for m in transcript.messages] == [(3, "B2 is now 42 and the file is saved.")] + transcript, frames = T.transcript_from_atif(atif_runs.fixture("computer_use"), lambda path: None) + assert frames == [] and all(a.screenshot is None for a in transcript.actions) + + +def test_a_copy_graded_as_stored_that_cant_be_walked_is_read_without_failing(): + """An invalid copy is still the turn's trajectory: every reader skips what isn't a step, a result or a call.""" + document = {**atif_runs.fixture("computer_use")} + document["steps"] = [None, *document["steps"], "not a step"] + document["steps"][2] = {**document["steps"][2], "observation": "not an observation", "tool_calls": [None]} + events, _ = T.compact_atif_trajectory(document, TrajectoryFilter()) + transcript, frames = T.transcript_from_atif(document, lambda path: b"\x89PNG\r\n\x1a\n") + assert events and transcript.actions and frames + url = atif_runs.stored("computer_use", document={**document, "steps": [None]}, media=False) + assert T.AtifDocuments().staged_media(T.TurnSource(url, "task-c1", 5)) == [] + + +def test_a_sub_agent_nested_in_another_is_found_among_its_parents_children(): + """ATIF makes an id unique only within its parent's array, so a reference resolves there first.""" + parent = atif_runs.fixture("subagent") + child = parent["subagent_trajectories"][0] + grandchild = {**atif_runs.fixture("computer_use"), "trajectory_id": "sub1"} + [result] = child["steps"][0]["observation"]["results"] + result["subagent_trajectory_ref"] = [{"trajectory_id": "sub1"}] + child["subagent_trajectories"] = [grandchild] + events, _ = T.compact_atif_trajectory(parent, TrajectoryFilter()) + transcript, frames = T.transcript_from_atif(parent, lambda path: b"\x89PNG\r\n\x1a\n") + assert {e["tool"] for e in events if e["type"] == "tool_call"} >= { + call["function_name"] for step in grandchild["steps"] for call in step.get("tool_calls") or []} + assert len(frames) == 3 + + + +def _agent(trajectory_id, call, *refs, subs=()): + """A trajectory whose one step calls ``call`` and whose result starts the sub-agents ``refs`` name.""" + result = {"source_call_id": call, "content": "ok", "subagent_trajectory_ref": [{"trajectory_id": r} for r in refs]} + step = {"step_id": 1, "source": "agent", "message": "", + "tool_calls": [{"tool_call_id": call, "function_name": call, "arguments": {}}], + "observation": {"results": [result]}} + return {"trajectory_id": trajectory_id, "agent": {"name": call}, "steps": [step], "subagent_trajectories": list(subs)} + + +def test_a_sub_agent_resolves_its_references_where_it_sits_not_where_it_was_reached_from(): + """B sits in the root, so the X it starts is the root's, though A, whose own X shadows the root's, started B.""" + document = _agent(None, "root", "A", subs=[_agent("A", "in A", "B", subs=[_agent("X", "A's X")]), + _agent("B", "in B", "X"), _agent("X", "root's X")]) + events, _ = T.compact_atif_trajectory(document, TrajectoryFilter()) + transcript, _ = T.transcript_from_atif(document, lambda path: None) + walked = ["root", "in A", "in B", "root's X"] + assert [event["tool"] for event in events if event["type"] == "tool_call"] == walked + assert [action.tool for action in transcript.actions] == walked + + + +def test_a_sub_agents_compacted_events_name_it_as_does_the_result_that_started_it(): + """So a judge tells a sub-agent's calls from the main agent's, as a native turn's ``parent_tool_use_id`` does.""" + document = _agent(None, "root", "A", subs=[_agent("A", "in A", "B", subs=[_agent("B", "in B")])]) + events, _ = T.compact_atif_trajectory(document, TrajectoryFilter()) + assert [(e["type"], e["tool"], e.get("subagent"), e.get("starts_subagents")) for e in events] == [ + ("tool_call", "root", None, None), ("tool_result", "root", None, ["A"]), + ("tool_call", "in A", "A", None), ("tool_result", "in A", "A", ["B"]), + ("tool_call", "in B", "B", None), ("tool_result", "in B", "B", None)] + +def test_an_id_missing_or_held_as_a_list_or_an_object_names_nothing_and_stops_no_walk(): + """A copy graded as stored may hold one anywhere, in a sub-agent nothing references too.""" + missing = _agent("gone", "no id") + del missing["trajectory_id"] + unused = _agent("unused", "never", subs=[_agent([], "bad id"), missing]) + document = _agent(None, "root", "A", {"x": 1}, None, subs=[_agent("A", "in A", ["A"]), unused, missing]) + events, _ = T.compact_atif_trajectory(document, TrajectoryFilter()) + transcript, _ = T.transcript_from_atif(document, lambda path: None) + assert [event["tool"] for event in events if event["type"] == "tool_call"] == ["root", "in A"] + assert [action.tool for action in transcript.actions] == ["root", "in A"] + +def test_a_screenshots_type_read_from_its_bytes_reaches_per_criterion_frames(): + gif = b"GIF89a" + b"g" * 16 + transcript, _ = T.transcript_from_atif(atif_runs.fixture("computer_use"), lambda path: gif) + shot = next(action for action in transcript.actions if action.screenshot) + assert shot.screenshot_media_type == "image/gif" + [labeled] = select_frames_per_criterion([shot], [{"id": "c", "description": "the page"}], max_frames=1) + assert labeled.frame.media_type == "image/gif" + + +def test_a_view_names_the_tools_offered_without_their_schemas(): + """An agent's tool definitions run to tens of thousands of tokens; a judge sees their names, as a native turn has + them.""" + def offered(*names): + return [{"type": "function", "function": {"name": name, "description": "long " * 500, + "parameters": {"type": "object"}}} for name in names] + whole = atif_runs.fixture("two_turns") + whole["agent"] = {**whole["agent"], "tool_definitions": offered("Bash", "Read")} + url = atif_runs.stored("two_turns", document=whole) + documents = T.AtifDocuments() + view = documents.view(T.TurnSource(url, "task-91c3")) + assert view["agent"]["tool_definitions"] == [{"type": "function", "function": {"name": "Bash"}}, + {"type": "function", "function": {"name": "Read"}}] + assert documents.document(url)["agent"]["tool_definitions"] == offered("Bash", "Read") + assert errors_in(validate(view)) == [] + as_stored = documents.view(T.TurnSource(url, "task-gone", 99)) + assert [entry["function"] for entry in as_stored["agent"]["tool_definitions"]] == [{"name": "Bash"}, {"name": "Read"}] + + +def test_a_sub_agents_tools_are_cut_to_their_names_at_any_depth(): + leaf = {"trajectory_id": "leaf", "agent": {"name": "leaf", "tool_definitions": [ + {"type": "function", "function": {"name": "Grep", "parameters": {"type": "object"}}}]}, "steps": []} + middle = {"trajectory_id": "mid", "agent": {"name": "mid"}, "steps": [], "subagent_trajectories": [leaf]} + cut = T._tool_names({"agent": {"name": "root"}, "steps": [], "subagent_trajectories": [middle]}) + assert cut["subagent_trajectories"][0]["subagent_trajectories"][0]["agent"]["tool_definitions"] == [ + {"type": "function", "function": {"name": "Grep"}}] + assert leaf["agent"]["tool_definitions"][0]["function"]["parameters"] == {"type": "object"} diff --git a/tst/unit/task_step/verifiers/test_judge_inputs.py b/tst/unit/task_step/verifiers/test_judge_inputs.py index a1c11247d..2401645b6 100644 --- a/tst/unit/task_step/verifiers/test_judge_inputs.py +++ b/tst/unit/task_step/verifiers/test_judge_inputs.py @@ -1,8 +1,10 @@ """Every built-in judge's input, pinned: what a model judge is sent (its prompt, images, system prompt and cached prefix), what an agent judge is given (its prompt and every file staged in its sandbox) and what a scripted verify is -called with, for runs whose native trajectories are stored as a run stores them. Each is what its golden file holds, +called with, for runs whose trajectories are stored as a run stores them. A native run's is what its golden file holds, recorded before prompt steps kept per-turn trajectory records, and stays so byte for byte when the run's prompt -responses carry those records, read back from the stored form. Re-record after a deliberate change with +responses carry records saying each turn's trajectory is native, read back from the stored form. A run that prescribed +atif/1 (the ``*_atif_*`` cases) is judged from each turn's copy, the turn's own task cut out of the conversation's +document, and a turn whose copy couldn't be had from its native trajectory. Re-record after a deliberate change with ``AGENTENV_TEST_RECORD_GOLDEN=1`` and review the file's diff. Several cases build their runs with other tests' setups (the always_on rig, user_sim_judge's fakes, the rubrics golden test's and run_context's helpers), so a change to one of those is re-recorded here too.""" @@ -24,7 +26,7 @@ from agent_env.config import get_config from agent_env.env.env import DeployedEnv from agent_env.providers.sandbox_providers import sandbox_provider -from agent_env.task_step.context import DeployedAgent, PromptResponse, TaskStepContext +from agent_env.task_step.context import AtifRecord, DeployedAgent, PromptResponse, TaskStepContext from agent_env.task_step.task_steps.verifiers import always_on_agent_verifier from agent_env.task_step.task_steps.verifiers.env_outcome_verifier import EnvOutcomeVerifierTaskStep from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter @@ -33,7 +35,7 @@ from tst.unit.task_step.verifiers import test_rubrics_verifier_golden as G from tst.unit.task_step.verifiers import test_run_context as R from tst.unit.task_step.verifiers import test_user_sim_judge as T -from tst.util import verifier_golden +from tst.util import atif_runs, verifier_golden pytestmark = pytest.mark.usefixtures("local_stores") @@ -64,11 +66,17 @@ def _tool_span(n: int) -> dict: def _recorded_form(context: TaskStepContext) -> TaskStepContext: - """``context`` as a run that kept per-turn trajectory records leaves it, read back from its stored form.""" + """``context`` as a run whose per-turn records say each turn's trajectory is native leaves it: one that prescribed + atif/1 to an agent whose copies couldn't be had, so each turn fell back to native, read back from its stored form. + A run that prescribes nothing records the same with ``atif`` None, and its judges get the same input.""" for response in context.prompt_responses: turns = response.target_agent_per_turn_trajectory_object_urls or [response.agent_trajectory_object_url] response.target_agent_per_turn_trajectories = [ - {"native_format": "claude-code-stream-json", "atif": None} for _ in turns] + {"format": "claude-code-stream-json", + "atif": AtifRecord(url=None, task_id=f"task-{n}", through_step=None, status="unavailable", rules=[], + reason="format_not_prescribed", validator_version=None, adapter_version=None, + aux_url=None, turn_context_url=None)} + for n, _ in enumerate(turns)] return TaskStepContext.from_dict(context.to_dict()) @@ -124,6 +132,42 @@ def _run(*, turns: int = 1, agent_url: bool = True, first_turn_missing: bool = F source_agent_per_turn_prompt_parts=[None, *[[{"kind": "text", "text": "And for Friday?"}]] * (len(urls) - 1)])]) +def _stored_form(context: TaskStepContext) -> TaskStepContext: + return TaskStepContext.from_dict(context.to_dict()) + + +async def _pinned_atif(case: str, judged: Callable[[Callable[[TaskStepContext], TaskStepContext]], Awaitable[Any]] + ) -> None: + """``judged``'s input for a run that prescribed atif/1 is the golden file's, as the run is and read back from its + stored form.""" + got = _normalised(await judged(lambda context: context)) + verifier_golden.check(FILE, case, _digested(got)) + if not verifier_golden.RECORDING: + assert _normalised(await judged(_stored_form)) == got + + +def _atif_run(name: str = "two_turns", *, tasks: tuple[str, ...] = ("task-91c2", "task-91c3"), + native_first: bool = False, media: bool = True) -> TaskStepContext: + """A prompt step's context whose turns are ``tasks`` of the fixture ``name``, each an atif/1 copy at the one url + the turns share, the step's own url the last turn's; ``native_first``: the first turn's copy couldn't be had, so + its native trajectory was read in its place; ``media`` off, the media it names weren't stored.""" + url = atif_runs.stored(name, media=media) + through = atif_runs.through_steps(name) + urls: list[str | None] = [] + records = [] + for n, task_id in enumerate(tasks): + if native_first and n == 0: + urls.append(_stored("turn-1.json", TURNS[0])) + records.append(atif_runs.native(task_id)) + else: + urls.append(url) + records.append(atif_runs.record(url, task_id, through[task_id])) + return TaskStepContext(instance_id="inst-1", prompt_responses=[PromptResponse( + prompt_id="p1", response="Done.", prompt_text="Fix parse_date.", agent_trajectory_object_url=urls[-1], + target_agent_per_turn_trajectory_object_urls=urls, target_agent_per_turn_trajectories=records, + source_agent_per_turn_prompt_parts=[None, *[[{"kind": "text", "text": "And the offset?"}]] * (len(urls) - 1)])]) + + class _Judge: """Every judge call answered passing, and what each was given.""" @@ -210,6 +254,43 @@ async def test_a_model_judges_input_is_pinned(case): await _pinned(case, _model_judged(step_kw, run)) +_FINAL_FRAMES = {"use_trajectory": True, + "trajectory_filter": TrajectoryFilter(compaction_type="screenshot", screenshot_last_n=2)} +MODEL_ATIF_CASES = { + "model_atif_one_turn": ({"use_trajectory": True}, lambda: _atif_run("computer_use", tasks=("task-c1",))), + "model_atif_one_turn_of_two_tasks_compacted": ({"use_trajectory": True, "trajectory_filter": TrajectoryFilter()}, + lambda: _atif_run(tasks=("task-91c3",))), + "model_atif_two_turns": ({"use_trajectory": True}, _atif_run), + "model_atif_two_turns_compacted": ({"use_trajectory": True, "trajectory_filter": TrajectoryFilter()}, _atif_run), + "model_atif_two_turns_first_native": ({"use_trajectory": True}, lambda: _atif_run(native_first=True)), + "model_atif_screenshots_final_frames": (_FINAL_FRAMES, lambda: _atif_run("computer_use", tasks=("task-c1",))), +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("case", MODEL_ATIF_CASES) +async def test_a_model_judges_input_on_atif_turns_is_pinned(case): + step_kw, run = MODEL_ATIF_CASES[case] + await _pinned_atif(case, _model_judged(step_kw, run)) + + +@pytest.mark.asyncio +async def test_a_model_judges_input_on_atif_turns_graded_up_to_a_turn_is_pinned(): + """Turn 1's own task, though its url's document holds turn 2's too.""" + def run(): + context = _atif_run() + context.metadata["user_overrides"] = {"step_params": {"verify": {"grade_up_to_turn": 1}}} + return context + + await _pinned_atif("model_atif_graded_up_to_turn_one", _model_judged({"use_trajectory": True}, run)) + + +@pytest.mark.asyncio +async def test_a_model_judges_screenshots_from_atif_media_are_pinned(): + await _pinned_atif("model_atif_screenshots_per_criterion", _model_judged( + _SCREENSHOTS, lambda: _atif_run("computer_use", tasks=("task-c1",)), answer=lambda ids: G._evidence(ids))) + + @pytest.mark.asyncio async def test_a_model_judges_input_graded_up_to_a_turn_is_pinned(): def run(): @@ -274,6 +355,24 @@ async def test_an_agent_judges_prompt_and_staged_files_are_pinned(monkeypatch, c await _pinned(case, _agent_judged(monkeypatch, step_kw, run)) +AGENT_ATIF_CASES = { + "agent_atif_one_turn_with_media": ({"use_trajectory": True}, + lambda: _atif_run("computer_use", tasks=("task-c1",))), + "agent_atif_one_turn_compacted": ({"use_trajectory": True, "trajectory_filter": TrajectoryFilter()}, + lambda: _atif_run("computer_use", tasks=("task-c1",))), + "agent_atif_two_turns": ({"use_trajectory": True}, _atif_run), + "agent_atif_two_turns_compacted": ({"use_trajectory": True, "trajectory_filter": TrajectoryFilter()}, _atif_run), + "agent_atif_two_turns_first_native": ({"use_trajectory": True}, lambda: _atif_run(native_first=True)), +} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("case", AGENT_ATIF_CASES) +async def test_an_agent_judges_prompt_and_staged_files_on_atif_turns_are_pinned(monkeypatch, case): + step_kw, run = AGENT_ATIF_CASES[case] + await _pinned_atif(case, _agent_judged(monkeypatch, step_kw, run)) + + @pytest.mark.asyncio async def test_an_unstaged_always_on_judges_input_is_pinned(monkeypatch, tmp_path): rig, run = await A._run(monkeypatch, tmp_path) @@ -348,3 +447,20 @@ async def judged(form): return done.metadata["verifications"]["v"]["results"][0]["given"] await _pinned("scripted_verify", judged) + + +@pytest.mark.asyncio +async def test_what_a_scripted_verify_is_called_with_on_atif_turns_is_pinned(monkeypatch): + """A native turn as the agent stored it, an atif/1 turn its own task.""" + script = (b"async def verify(url, trajectory):\n" + b" return [{'id': 'c', 'score': 1.0, 'given': {'url': url, 'trajectory': trajectory}}]\n") + monkeypatch.setattr(FileArtifact, "get", staticmethod(lambda id, version=None: SimpleNamespace(load=lambda: script))) + + async def judged(form): + context = _atif_run(native_first=True) + context.deployed_envs.append(DeployedEnv(env_id="e", env_version=1, mcp_url="http://mcp")) + step = EnvOutcomeVerifierTaskStep(id="outcome", version=None, env_id="e", file_artifact_id="s", verifier_id="v") + done = await step.execute(form(context)) + return done.metadata["verifications"]["v"]["results"][0]["given"] + + await _pinned_atif("scripted_verify_atif", judged) diff --git a/tst/unit/task_step/verifiers/test_rubrics_verifier_atif.py b/tst/unit/task_step/verifiers/test_rubrics_verifier_atif.py new file mode 100644 index 000000000..d0a9f911a --- /dev/null +++ b/tst/unit/task_step/verifiers/test_rubrics_verifier_atif.py @@ -0,0 +1,186 @@ +"""A run that prescribed atif/1 is judged from each turn's copy: the turn's own task cut out of the conversation's +document, with the media it names, and a turn whose copy couldn't be had from its native trajectory.""" + +from __future__ import annotations + +import json +import logging +import re +from types import SimpleNamespace + +import pytest +from agentenv_protocol.atif import load, strip_profile + +from agent_env.artifact.artifacts.file import FileArtifact +from agent_env.config import get_config +from agent_env.env.env import DeployedEnv +from agent_env.task_step.task_steps.verifiers.env_outcome_verifier import EnvOutcomeVerifierTaskStep +from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import TrajectoryFilter +from tst.unit.task_step.verifiers import test_judge_inputs as J +from tst.unit.task_step.verifiers import test_rubrics_verifier_golden as G +from tst.util import atif_runs + +pytestmark = pytest.mark.usefixtures("local_stores") + +FIRST, SECOND = "parse_date without changing the test", "Also cover a +05:30 offset." + + +def _turn_texts(prompt: str) -> list[str]: + return re.split(r"===== Turn \d+ =====\n", prompt.split("", 1)[1].split("")[0])[1:] + + +async def _model_prompt(step_kw: dict, run) -> str: + given = await J._model_judged(step_kw, run)(lambda context: context) + return given["calls"][0]["prompt"] + + +@pytest.mark.asyncio +async def test_a_direct_judge_reads_each_turn_alone_under_its_marker(): + first, second = _turn_texts(await _model_prompt({"use_trajectory": True}, J._atif_run)) + first, second = json.loads(first.strip()), json.loads(second.strip()) + assert FIRST in first["steps"][0]["message"] and second["steps"][0]["message"] == SECOND + assert [s["step_id"] for s in second["steps"]] == [1, 2, 3] + assert "final_metrics" not in first and "final_metrics" not in second + load(second) + + +@pytest.mark.asyncio +async def test_a_turn_of_a_document_another_prompt_shares_is_cut_to_its_own_task(): + prompt = await _model_prompt({"use_trajectory": True, "trajectory_filter": TrajectoryFilter()}, + lambda: J._atif_run(tasks=("task-91c3",))) + events = json.loads(prompt.split("", 1)[1].split("")[0]) + assert [(e["type"], e["tool"]) for e in events[:2]] == [("tool_call", "Edit"), ("tool_result", "Edit")] + assert events[-1] == {"type": "final_response", "text": "Added test_offset.", "timestamp": ""} + assert "pytest tests/test_parse.py" not in prompt + + +@pytest.mark.asyncio +async def test_graded_up_to_a_turn_no_later_turn_leaks(): + def run(): + context = J._atif_run() + context.metadata["user_overrides"] = {"step_params": {"verify": {"grade_up_to_turn": 1}}} + return context + + prompt = await _model_prompt({"use_trajectory": True}, run) + assert FIRST in prompt and SECOND not in prompt and "Added test_offset" not in prompt + + +@pytest.mark.asyncio +async def test_a_mixed_run_reads_each_turn_by_its_label(): + native, atif = _turn_texts(await _model_prompt({"use_trajectory": True}, lambda: J._atif_run(native_first=True))) + assert native.strip() == J.TURNS[0] + assert json.loads(atif.strip())["steps"][0]["message"] == SECOND + + +@pytest.mark.asyncio +async def test_final_frames_come_from_the_media_its_results_name(): + given = await J._model_judged(J._FINAL_FRAMES, lambda: J._atif_run("computer_use", tasks=("task-c1",)))( + lambda context: context) + assert [block["image_url"]["url"] for block in given["calls"][0]["images"]] == [ + "data:image/png;base64,c2NyZWVuc2hvdC0y", "data:image/png;base64,c2NyZWVuc2hvdC0z"] + + +@pytest.mark.asyncio +async def test_a_frame_whose_media_is_missing_or_mismatched_is_skipped(caplog): + caplog.set_level(logging.WARNING) + + def run(): + context = J._atif_run("computer_use", tasks=("task-c1",)) + store = get_config().get_object_store() + store.put(f"{atif_runs.folder()}media/69a8aa01fe5537076d023dd5e9cc4275b39fc0434aa6483a9f58b66ef2f3c896.png", + b"not the frame", allow_overwrite=True) + return context + + given = await J._model_judged(J._FINAL_FRAMES, run)(lambda context: context) + assert [block["image_url"]["url"] for block in given["calls"][0]["images"]] == [ + "data:image/png;base64,c2NyZWVuc2hvdC0x", "data:image/png;base64,c2NyZWVuc2hvdC0z"] + assert any("skipped" in record.message and "sha256" in record.message for record in caplog.records) + + +@pytest.mark.asyncio +async def test_a_per_criterion_judge_with_no_stored_media_is_skipped(): + step = G._step(**J._SCREENSHOTS) + step._prompt_llm_judge = J._Judge(lambda ids: G._evidence(ids)).model + done = await step.execute(J._atif_run("computer_use", tasks=("task-c1",), media=False)) + assert [row["id"] for row in done.metadata["verifications"]["vid"]["results"]] == ["no_screenshots"] + + +@pytest.mark.asyncio +async def test_an_agent_judge_gets_each_turn_and_its_media_in_a_folder_of_its_own(monkeypatch): + runs = [await J._agent_judged(monkeypatch, {"use_trajectory": True}, + lambda: J._atif_run("computer_use", tasks=("task-c1",)))(lambda context: context) + for _ in range(2)] + folders = [{path.rsplit("/", 2)[0] if "/media/" in path else path.rsplit("/", 1)[0] for path in given["files"]} + for given in runs] + assert all(len(folder) == 1 for folder in folders) and folders[0] != folders[1] + files, prompt = runs[0]["files"], runs[0]["calls"][0]["prompt"] + (folder,) = folders[0] + assert folder in prompt + load(json.loads(files[f"{folder}/turn_01.json"]["text"])) + assert sorted(path for path in files if "/media/" in path) == sorted( + f"{folder}/{path}" for path in ["media/82e60066a2de261b6653bcdda90d1cb9a7af2f474cecd82e8d371e8384d72315.png", + "media/69a8aa01fe5537076d023dd5e9cc4275b39fc0434aa6483a9f58b66ef2f3c896.png", + "media/482405b002a62efa8516c36709a7a100637507670576fa73a20ad5420d55c66f.png"]) + assert "turn_01.json is an ATIF (Agent Trajectory Interchange Format, v1.8) document" in prompt + assert "is relative to this directory" in prompt + + +@pytest.mark.asyncio +async def test_an_agent_judge_on_a_mixed_run_is_told_which_turns_are_atif(monkeypatch): + given = await J._agent_judged(monkeypatch, {"use_trajectory": True}, + lambda: J._atif_run(native_first=True))(lambda context: context) + prompt = given["calls"][0]["prompt"] + assert "2 files named turn_01.json … turn_02.json" in prompt and "turn_02.json is an ATIF" in prompt + assert "media/" not in prompt + texts = [file["text"] for path, file in sorted(given["files"].items())] + assert texts[0] == J.TURNS[0] and json.loads(texts[1])["steps"][0]["message"] == SECOND + + +@pytest.mark.asyncio +async def test_an_agent_judge_on_compacted_turns_gets_each_turns_tool_results(monkeypatch): + given = await J._agent_judged(monkeypatch, {"use_trajectory": True, "trajectory_filter": TrajectoryFilter()}, + J._atif_run)(lambda context: context) + assert [path for path in given["files"] if path.startswith("/tmp/tool_call_results/")] == [ + "/tmp/tool_call_results/turn_01_tool_call_result_1.json"] + assert "Each file is a compacted event list" in given["calls"][0]["prompt"] + + +@pytest.mark.asyncio +async def test_a_scripted_verify_gets_each_turn_by_its_label(monkeypatch): + script = b"async def verify(url, trajectory):\n return [{'id': 'c', 'score': 1.0, 'given': trajectory}]\n" + monkeypatch.setattr(FileArtifact, "get", staticmethod(lambda id, version=None: SimpleNamespace(load=lambda: script))) + context = J._atif_run() + context.prompt_responses[0].target_agent_per_turn_trajectory_object_urls.insert(0, None) + context.prompt_responses[0].target_agent_per_turn_trajectories.insert(0, atif_runs.native("task-0")) + context.deployed_envs.append(DeployedEnv(env_id="e", env_version=1, mcp_url="http://mcp")) + step = EnvOutcomeVerifierTaskStep(id="outcome", version=None, env_id="e", file_artifact_id="s", verifier_id="v") + given = (await step.execute(context)).metadata["verifications"]["v"]["results"][0]["given"] + assert given[0] is None + assert [doc["steps"][0]["message"] for doc in given[1:]][1] == SECOND + assert FIRST in given[1]["steps"][0]["message"] + assert all("final_metrics" not in doc for doc in given[1:]) + + +@pytest.mark.asyncio +async def test_a_copy_without_the_profile_is_graded_turn_by_turn(): + """Every profile field is optional: a copy whose tasks carry no ids is cut at the step each turn reached.""" + def run(): + context = J._atif_run() + atif_runs.stored("two_turns", document=strip_profile(atif_runs.fixture("two_turns"))) + return context + + first, second = _turn_texts(await _model_prompt({"use_trajectory": True}, run)) + first, second = json.loads(first.strip()), json.loads(second.strip()) + assert FIRST in first["steps"][0]["message"] and second["steps"][0]["message"] == SECOND + assert [s["step_id"] for s in second["steps"]] == [1, 2, 3] + + +@pytest.mark.asyncio +async def test_a_scripted_verify_can_ask_for_each_turns_label(monkeypatch): + script = b"async def verify(url, trajectory_formats):\n return [{'id': 'c', 'score': 1.0, 'given': trajectory_formats}]\n" + monkeypatch.setattr(FileArtifact, "get", staticmethod(lambda id, version=None: SimpleNamespace(load=lambda: script))) + context = J._atif_run(native_first=True) + context.deployed_envs.append(DeployedEnv(env_id="e", env_version=1, mcp_url="http://mcp")) + step = EnvOutcomeVerifierTaskStep(id="outcome", version=None, env_id="e", file_artifact_id="s", verifier_id="v") + given = (await step.execute(context)).metadata["verifications"]["v"]["results"][0]["given"] + assert given == ["claude-code-stream-json", "atif/1"] diff --git a/tst/util/atif_runs.py b/tst/util/atif_runs.py new file mode 100644 index 000000000..5cd4037a4 --- /dev/null +++ b/tst/util/atif_runs.py @@ -0,0 +1,55 @@ +"""Prompt responses whose turns are atif/1 copies, stored as a prompt step that prescribes atif/1 stores them: the +conversation's document at one url its turns share, its media in the folder's ``media/``, and each turn's record naming +the turn's A2A task and the step it reached. The documents are the protocol's ATIF fixtures.""" + +from __future__ import annotations + +import json +from importlib.resources import files +from pathlib import Path +from typing import Any, Optional + +from agentenv_protocol.atif import media_paths, tasks + +from agent_env.config import get_config +from agent_env.task_step.context import AtifRecord, TurnTrajectory + +FIXTURES = Path(str(files("agentenv_protocol.atif").joinpath("fixtures"))) + + +def fixture(name: str) -> dict[str, Any]: + return json.loads((FIXTURES / f"{name}.json").read_text()) + + +def folder(run: str = "inst-1", agent: str = "agent") -> str: + return f"{get_config().get_artifact_key_prefix()}atif/instance_id={run}/{agent}/" + + +def stored(name: str, *, document: Optional[dict[str, Any]] = None, media: bool = True, run: str = "inst-1") -> str: + """The fixture ``name`` (or ``document``) stored as an agent's copy, ``.json`` in the run's folder, with + the media it names beside it unless ``media`` is off; its url.""" + store, where = get_config().get_object_store(), folder(run) + document = fixture(name) if document is None else document + for path in media_paths(document) if media else []: + store.put(f"{where}{path}", (FIXTURES / path).read_bytes(), allow_overwrite=True) + return store.put(f"{where}{name}.json", json.dumps(document).encode(), content_type="application/json", + allow_overwrite=True) + + +def through_steps(name: str) -> dict[str, int]: + """Each of the fixture's tasks, by id, with the step its copy reached when that task ended.""" + return {task.task_id: task.steps[-1]["step_id"] for task in tasks(fixture(name))} + + +def record(url: str, task_id: str, through_step: Optional[int], *, status: str = "valid") -> TurnTrajectory: + """An atif/1 turn's record: its trajectory is the copy at ``url``.""" + return TurnTrajectory(format="atif/1", atif=AtifRecord( + url=url, task_id=task_id, through_step=through_step, status=status, rules=[], reason=None, + validator_version="0.0.0", adapter_version="0.1.0", aux_url=None, turn_context_url=None)) + + +def native(task_id: str, native_format: str = "claude-code-stream-json") -> TurnTrajectory: + """A turn whose copy couldn't be had, its native trajectory read in its place.""" + return TurnTrajectory(format=native_format, atif=AtifRecord( + url=None, task_id=task_id, through_step=None, status="unavailable", rules=[], reason="timeout", + validator_version=None, adapter_version=None, aux_url=None, turn_context_url=None)) diff --git a/tst/util/images.py b/tst/util/images.py new file mode 100644 index 000000000..6932f2307 --- /dev/null +++ b/tst/util/images.py @@ -0,0 +1,17 @@ +"""Small real images for tests that move media: a PNG whose header a reader can size, built without Pillow.""" + +from __future__ import annotations + +import struct +import zlib + + +def png(width: int, height: int) -> bytes: + """A black ``width`` by ``height`` RGB PNG.""" + + def chunk(kind: bytes, body: bytes) -> bytes: + return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body)) + + pixels = zlib.compress(b"".join(b"\x00" + b"\x00\x00\x00" * width for _ in range(height))) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", pixels) + chunk(b"IEND", b""))