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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1393,6 +1393,14 @@ the profile's spec, and `fixtures/` holds its canonical examples. The package ne
marked by `turn.compaction(step=..., written_by="assistant" | "harness", trigger="manual" | "auto")`, its usage
that call's (profile 1.1), with the conversation's `tokens_before` and `tokens_after` when the harness counts them
(1.2).
- **Ids an endpoint gives again.** A call id is unique across a document, but an endpoint may repeat one, as vLLM
numbers each response's calls from zero (`functions.<name>:<index>`). `turn.tool_call_id(native_id)` gives the id
to write such a call under, reserved for it: the endpoint's own, or, once the document holds it or gave it out, its
first number the document hasn't, `<native_id>#2`, `#3` and on. The call's result names that id, so an adapter keeps
which of its calls a result answers.
- **Values as agents' records give them.** `timestamp_ms` writes a time given in epoch milliseconds as `timestamp`
writes one; `decode_base64` and `decode_data_url` give back the bytes of base64 text and of a
`data:<type>;base64,...` URL, read with `b64decode(validate=True)`, with its media type, for `turn.media`. Each returns None for a value it doesn't read.
- **The runner** (`AdapterRun`, `replay`) feeds one A2A context's records through one adapter instance, a task at a
time. It writes each task's user step from its `TurnContext`, and the final response once, with the task's
terminal state on its last step. Its `page()` is the live view, built when it's read: closed steps only, so a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@
vendored; ``PROFILE.md`` beside this module is the profile's spec. The package needs only the protocol's base
dependencies, so anything can read a document or write an adapter."""
from .adapter import Adapter, AdapterSpec, Native, Selector, atif_adapter, aux, finish, native
from .builder import AtifTurn, Document, Media, TurnContext, timestamp
from .builder import (
AtifTurn,
Document,
Media,
TurnContext,
decode_base64,
decode_data_url,
timestamp,
timestamp_ms,
)
from .models import (
Agent,
AudioSource,
Expand Down Expand Up @@ -74,12 +83,12 @@
"Adapter", "AdapterRef", "AdapterRun", "AdapterSpec", "Agent", "AgentProfile", "Arrival", "atif_adapter",
"AtifError", "AtifTurn", "AudioSource", "aux", "AuxEntry", "check", "check_adapter", "check_media", "Compaction",
"COMPACTION_TRIGGERS", "ContentItem", "ContentPart",
"Document", "dump_profile", "errors_in", "Fed", "FinalMetrics", "FinalMetricsProfile", "Finding", "finish",
"decode_base64", "decode_data_url", "Document", "dump_profile", "errors_in", "Fed", "FinalMetrics", "FinalMetricsProfile", "Finding", "finish",
"FORMAT", "ImageSource", "is_prefix", "is_token_count", "KIT_RULES", "KitResult", "load", "Media", "MEDIA_PATH", "media_file", "media_paths", "MediaInfo",
"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", "StoredMedia",
"strip_profile", "SubagentTrajectoryRef", "SUMMARY_WRITERS", "SubagentTrajectoryRefProfile", "Task", "task_document", "tasks", "tasks_document", "timestamp", "ToolCall",
"strip_profile", "SubagentTrajectoryRef", "SUMMARY_WRITERS", "SubagentTrajectoryRefProfile", "Task", "task_document", "tasks", "tasks_document", "timestamp", "timestamp_ms", "ToolCall",
"ToolCallProfile", "Trajectory", "TrajectoryProfile", "TurnContext", "validate", "validate_live", "validate_media", "VOCABULARIES",
]
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
every value is JSON. A live reader is served closed steps only, so nothing it has seen ever changes."""
from __future__ import annotations

import base64
import binascii
import hashlib
import json
import math
Expand Down Expand Up @@ -46,6 +48,7 @@
"text/csv": ".csv", "application/json": ".json", "application/zip": ".zip",
}
_TIME = re.compile(r"^(\d{4}-\d{2}-\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?([Zz]|[+-]\d{2}:?\d{2})$")
_DATA_URL = re.compile(r"data:(?P<type>[\w.+-]+/[\w.+-]+);base64,(?P<data>.*)", re.S)
_JOIN = "\n\n"
_UNSET: Any = object()
_KILOBYTE = 1000
Expand Down Expand Up @@ -76,13 +79,49 @@ def timestamp(value: str | datetime | None) -> str | None:
except ValueError as exc:
raise AtifError(f"{value!r}: {exc}") from exc
moment = _utc(parsed, value)
text = (f"{moment.year:04d}-{moment.month:02d}-{moment.day:02d}T{moment.hour:02d}:{moment.minute:02d}:"
f"{moment.second:02d}")
text = _seconds(moment)
if digits:
text += f".{moment.microsecond // _US_PER_MS:03d}" if len(digits) <= 3 else f".{moment.microsecond:06d}"
return text + "Z"


def timestamp_ms(value: Any) -> str | None:
"""A time given as an integer count of milliseconds since the Unix epoch, as ``timestamp`` writes a time to the
millisecond; None for any other value, and for a count past the years a datetime holds."""
if not isinstance(value, int) or isinstance(value, bool):
return None
seconds, millis = divmod(value, _MS_PER_SECOND)
try:
moment = datetime.fromtimestamp(seconds, tz=timezone.utc)
except (OverflowError, OSError, ValueError):
return None
return f"{_seconds(moment)}.{millis:03d}Z"


def decode_base64(value: Any) -> bytes | None:
"""The bytes standard base64 text holds, read as ``base64.b64decode(value, validate=True)`` reads it: a character
outside the alphabet, or padding it refuses, is no bytes. None for any other value too."""
if not isinstance(value, str):
return None
try:
return base64.b64decode(value, validate=True)
except (binascii.Error, ValueError):
return None


def decode_data_url(value: Any) -> tuple[bytes, str] | None:
"""The bytes and media type a ``data:<type>;base64,<data>`` URL holds; None for any other value, and for base64
that doesn't check strictly."""
found = _DATA_URL.fullmatch(value) if isinstance(value, str) else None
data = decode_base64(found["data"]) if found is not None else None
return None if data is None else (data, found["type"])


def _seconds(moment: datetime) -> str:
return (f"{moment.year:04d}-{moment.month:02d}-{moment.day:02d}T{moment.hour:02d}:{moment.minute:02d}:"
f"{moment.second:02d}")


def _utc(moment: datetime, value: Any) -> datetime:
try:
return moment.astimezone(timezone.utc)
Expand Down Expand Up @@ -255,6 +294,7 @@ def __init__(self, spec: AdapterSpec, sink: Callable[[str, bytes], None] | None
self._root: _Trajectory | None = None
self._subs: dict[str, _Trajectory] = {}
self._call_home: dict[str, tuple[_Trajectory, _Step]] = {}
self._given: set[str] = set()
self._spawned: dict[str, str] = {}
self._unmatched: Counter[str] = Counter()
self._unmatched_at_end: list[dict[str, int]] = []
Expand Down Expand Up @@ -376,6 +416,15 @@ def call(self, step: _Step, call: dict[str, Any]) -> None:
step.pending.add(call["tool_call_id"])
self._call_home[call["tool_call_id"]] = (self._owner(step), step)

def reserve_call_id(self, native_id: Any) -> str:
_str(native_id, "tool_call_id", optional=False)
call_id, number = native_id, 1
while call_id in self._call_home or call_id in self._given:
number += 1
call_id = f"{native_id}#{number}"
self._given.add(call_id)
return call_id

def result(self, call_id: str, content: Sequence[Any], status: str, exit_code: int | None,
at: str | None) -> None:
if not isinstance(call_id, str) or call_id not in self._call_home:
Expand Down Expand Up @@ -821,6 +870,13 @@ def tool_call(self, *, step: str, tool_call_id: str, function_name: str, argumen
self._doc.call(target, call)
self._touch(target, when)

def tool_call_id(self, native_id: str) -> str:
"""The id to write a call the endpoint gave ``native_id`` under, reserved for it: ``native_id``, or, when the
document holds that id or gave it out already, as an endpoint can give an id again (vLLM numbers each
response's calls from zero, ``functions.<name>:<index>``), the first of ``<native_id>#2``, ``#3``, … it hasn't.
The call's result names the id this returns."""
return self._doc.reserve_call_id(native_id)

def tool_result(self, *, source_call_id: str, text: str | None = None, content: Sequence[Any] | None = None,
status: str = "ok", exit_code: int | None = None, time: str | datetime | None = None) -> None:
"""A result, written in its call's step. One that comes after that step closed keeps when it arrived."""
Expand Down
229 changes: 229 additions & 0 deletions packages/agentenv-protocol/tests/test_atif_adapter_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,229 @@
"""What the builder offers every adapter beside its steps: an id for a call whose id the endpoint gave before, a time
given in epoch milliseconds, and the bytes of base64 text or a data URL."""
import base64
import binascii
import re
from datetime import datetime, timezone

import pytest
from hypothesis import given, settings, strategies as st

from agentenv_protocol.atif import (
Adapter,
AdapterRun,
AtifError,
Document,
TurnContext,
atif_adapter,
decode_base64,
decode_data_url,
errors_in,
native,
timestamp,
timestamp_ms,
validate,
)


@atif_adapter(native_format="ids/1", version="0.1.0", input_includes_cache=False)
class Repeating(Adapter):
"""Calls as an endpoint that numbers each response's calls from zero gives them, each result naming its call by the
endpoint's id, which this answers in the order the calls came."""

def __init__(self, turn):
self.open: dict[str, list[str]] = {}

@native(type="call")
def call(self, r, turn):
call_id = turn.tool_call_id(r["id"])
self.open.setdefault(r["id"], []).append(call_id)
turn.tool_call(step=r["step"], tool_call_id=call_id, function_name="read", arguments={})

@native(type="result")
def result(self, r, turn):
turn.tool_result(source_call_id=self.open[r["id"]].pop(0), text=r["out"])


def context(index):
return TurnContext(index=index, context_id="ctx", task_id=f"t{index}", message_id=f"m{index}",
inbound=["go"], agent_name="toy", started_at="2026-11-29T10:00:00Z")


def calls_and_results(document):
steps = [step for step in document["steps"] if step["source"] == "agent"]
return ([call["tool_call_id"] for step in steps for call in step.get("tool_calls") or ()],
{(result["source_call_id"], result["content"]) for step in steps
for result in (step.get("observation") or {}).get("results") or ()})


def test_an_id_the_endpoint_gives_again_is_numbered_in_every_task_and_each_result_answers_its_own_call():
run = AdapterRun(Repeating)
for index in range(2):
run.start_task(context(index))
for step in ("a", "b"):
run.native({"type": "call", "step": f"{index}{step}", "id": "functions.read:0"})
run.native({"type": "result", "id": "functions.read:0", "out": f"{index}{step}"})
run.end_task()
ids, results = calls_and_results(run.document())
assert ids == ["functions.read:0", "functions.read:0#2", "functions.read:0#3", "functions.read:0#4"]
assert results == {("functions.read:0", "0a"), ("functions.read:0#2", "0b"), ("functions.read:0#3", "1a"),
("functions.read:0#4", "1b")}
assert not errors_in(validate(run.document()))


def test_a_number_skips_a_form_the_endpoint_gave_as_an_id_of_its_own():
run = AdapterRun(Repeating)
run.start_task(context(0))
for native_id in ("call_0#2", "call_0", "call_0"):
run.native({"type": "call", "step": "s", "id": native_id})
run.end_task()
assert calls_and_results(run.document())[0] == ["call_0#2", "call_0", "call_0#3"]


def document():
doc = Document(Repeating.spec)
return doc, doc.start_task(context(0))


def test_an_id_given_out_is_taken_before_its_call_is_written_and_one_written_without_it_is_taken_too():
doc, turn = document()
first, second = turn.tool_call_id("x"), turn.tool_call_id("x")
turn.tool_call(step="s", tool_call_id="y", function_name="read", arguments={})
assert (first, second, turn.tool_call_id("y")) == ("x", "x#2", "y#2")
turn.tool_call(step="s", tool_call_id=second, function_name="read", arguments={})
turn.tool_call(step="s", tool_call_id=first, function_name="read", arguments={})
assert turn.tool_call_id("x") == "x#3"


def test_a_sub_agents_calls_share_the_documents_ids():
doc, turn = document()
turn.tool_call(step="s", tool_call_id=turn.tool_call_id("task"), function_name="task", arguments={})
turn.subagent("sub", spawned_by="task")
turn.tool_call(step="sub-1", tool_call_id=turn.tool_call_id("task"), function_name="read", arguments={},
agent="sub")
turn.tool_result(source_call_id="task#2", text="read")
turn.tool_result(source_call_id="task", text="done")
doc.end_task()
assert [call["tool_call_id"] for call in doc.document()["subagent_trajectories"][0]["steps"][0]["tool_calls"]] \
== ["task#2"]


@pytest.mark.parametrize("native_id", [None, "", 7, ["x"]])
def test_an_id_that_isnt_a_non_empty_string_is_refused_as_a_call_under_it_is(native_id):
_, turn = document()
with pytest.raises(AtifError) as refused:
turn.tool_call_id(native_id)
with pytest.raises(AtifError) as written:
turn.tool_call(step="s", tool_call_id=native_id, function_name="read", arguments={})
assert str(refused.value) == str(written.value)


OPERATIONS = st.lists(st.one_of(
st.tuples(st.just("give"), st.sampled_from(["a", "b", "a#2", "a#3", "b#2#2", "a#2#2"])),
st.tuples(st.just("write"), st.integers(min_value=0, max_value=30)),
st.tuples(st.just("own"), st.sampled_from(["a", "a#2", "a#4", "b#2", "c"])),
st.tuples(st.just("task"), st.none())), max_size=60)


@settings(max_examples=400, deadline=None)
@given(OPERATIONS)
def test_every_id_given_out_is_the_first_free_form_of_its_native_and_writes_without_a_clash(operations):
"""Ids given out, calls written under some of them and under ids of their own, across tasks: each id given out is
its native or that native's first number no call holds and no earlier id given out is, and the document stays
valid."""
doc, turn = document()
given_out: list[str] = []
written: set[str] = set()
index = 0
for operation, value in operations:
if operation == "give":
call_id = turn.tool_call_id(value)
forms = [value] + [f"{value}#{n}" for n in range(2, 100)]
assert call_id == next(form for form in forms if form not in written and form not in given_out)
given_out.append(call_id)
elif operation == "write" and given_out:
call_id = given_out[value % len(given_out)]
if call_id not in written:
turn.tool_call(step=f"s{index}", tool_call_id=call_id, function_name="read", arguments={})
written.add(call_id)
elif operation == "own" and value not in written and value not in given_out:
turn.tool_call(step=f"s{index}", tool_call_id=value, function_name="read", arguments={})
written.add(value)
elif operation == "task":
doc.end_task()
index += 1
turn = doc.start_task(context(index))
doc.end_task()
assert not errors_in(validate(doc.document()))


@settings(max_examples=400, deadline=None)
@given(st.lists(st.sampled_from(["a", "b", "a#2", "a#2#2", "b#3"]), max_size=40))
def test_ids_given_out_are_those_of_the_loop_every_adapter_wrote_for_itself(natives):
"""The rule eight adapters each kept a copy of: an id, else its first number not yet given out."""
_, turn = document()
taken: set[str] = set()
for native_id in natives:
expected, n = native_id, 1
while expected in taken:
n += 1
expected = f"{native_id}#{n}"
taken.add(expected)
assert turn.tool_call_id(native_id) == expected


_MILLISECOND = datetime(1970, 1, 1, 0, 0, 0, 1000, tzinfo=timezone.utc) - datetime(1970, 1, 1, tzinfo=timezone.utc)


@pytest.mark.parametrize(("millis", "written"), [
(0, "1970-01-01T00:00:00.000Z"), (1764410400123, "2025-11-29T10:00:00.123Z"),
(-1, "1969-12-31T23:59:59.999Z"), (1764410400999, "2025-11-29T10:00:00.999Z")])
def test_a_time_in_epoch_milliseconds_is_written_to_the_millisecond(millis, written):
assert timestamp_ms(millis) == written


@pytest.mark.parametrize("value", [None, True, False, 1.5, "1764410400123", 10 ** 20, -(10 ** 20)])
def test_anything_but_an_integer_a_datetime_holds_is_no_time(value):
assert timestamp_ms(value) is None


@given(st.integers(min_value=-62_135_596_800_000, max_value=253_402_300_799_999))
def test_every_time_in_epoch_milliseconds_reads_back_as_the_same_millisecond(millis):
written = timestamp_ms(millis)
assert timestamp(written) == written
moment = datetime.fromisoformat(written.replace("Z", "+00:00"))
assert (moment - datetime(1970, 1, 1, tzinfo=timezone.utc)) // _MILLISECOND == millis


@given(st.binary(max_size=64))
def test_base64_and_a_data_url_give_back_their_bytes(data):
text = base64.b64encode(data).decode()
assert decode_base64(text) == data
assert decode_data_url(f"data:image/png;base64,{text}") == (data, "image/png")


@given(st.text(max_size=24))
def test_text_decodes_only_as_strict_base64_does(text):
try:
expected = base64.b64decode(text, validate=True)
except (binascii.Error, ValueError):
expected = None
assert decode_base64(text) == expected


@pytest.mark.parametrize("value", [None, b"aGk=", 7, "aGk", "aG k=", "aGk=\n", "a-_=", "data:image/png;base64,aGk"])
def test_bytes_text_or_base64_that_doesnt_check_strictly_is_nothing(value):
assert decode_base64(value) is None
assert decode_data_url(value) is None


@pytest.mark.parametrize("value", [
"data:image/png,aGk=", "data:;base64,aGk=", "data:image;base64,aGk=", "data:image/png;charset=x;base64,aGk=",
" data:image/png;base64,aGk=", "data:image/png;base64,aGk"])
def test_a_data_url_names_its_media_type_and_base64_and_nothing_else(value):
assert decode_data_url(value) is None


def test_a_data_url_keeps_its_media_type_as_written():
assert decode_data_url("data:application/vnd.ms-excel;base64,aGk=") == (b"hi", "application/vnd.ms-excel")
assert re.fullmatch(r"[\w.+-]+/[\w.+-]+", decode_data_url("data:image/svg+xml;base64,")[1])
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ dev = [
"zstandard>=0.23",
"griffelib==2.3.0", # the plugin API check; exact, since what it reports as a break changes between releases
"tomli-w==1.2.0", # the Codex agent's config writer, which only its image installs; its tests import it
"hypothesis>=6.100", # the property tests of the judge score parse
"hypothesis>=6.100", # the property tests of the judge score parse and of the ATIF builder's adapter helpers
"moto>=5.0.0",
"psycopg2-binary>=2.9.0", # the gateway server module's driver; outside its container only the tests import it
"regex>=2023.12.25", # the gateway's trigger predicates, matched under a timeout; outside its container only the tests import it
Expand Down
Loading