Skip to content
Open
3 changes: 2 additions & 1 deletion packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1370,7 +1370,8 @@ the profile's spec, and `fixtures/` holds its canonical examples. The package ne
command's output, is `turn.system_message(text=...)`, a `source: system` step of its own. A compaction, a summary
that replaced the conversation in what the agent sees, is the message of the step of the call that wrote it,
marked by `turn.compaction(step=..., written_by="assistant" | "harness", trigger="manual" | "auto")`, its usage
that call's (profile 1.1).
that call's (profile 1.1), with the conversation's `tokens_before` and `tokens_after` when the harness counts them
(1.2).
- **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
@@ -1,6 +1,6 @@
# The agentenv profile of ATIF

Profile 1.1. agentenv records what an agent did as an ATIF v1.8 document: Harbor's
Profile 1.2. agentenv records what an agent did as an ATIF v1.8 document: Harbor's
[Agent Trajectory Interchange Format](https://github.com/harbor-framework/harbor/blob/main/rfcs/0001-trajectory-format.md),
whose models are vendored in `models/`. An agent serves it as format `atif/1`, beside its native log. What ATIF has no
typed field for, agentenv adds under `extra.agentenv` on the objects that have an `extra`. This file is the profile's spec.
Expand Down Expand Up @@ -36,7 +36,7 @@ to native exactly.
call's result by `subagent_trajectory_ref`. It belongs to the task of the call that spawned it. A sub-agent that
wrote no step is left out, and so is the reference to it. A spawning call with no result when its task ends gets
one, with no content and `status: canceled`, so its sub-agent stays referenced.
- `schema_version` is the oldest ATIF version that holds the document's fields: `ATIF-v1.8` for profile 1.1.
- `schema_version` is the oldest ATIF version that holds the document's fields: `ATIF-v1.8` for profile 1.2.
- Format id: `atif/1`. The profile's own version is the root's `extra.agentenv.version`.

## Steps
Expand All @@ -48,8 +48,9 @@ to native exactly.
the agent's words nor the user's. A reader that stages a turn for a judge shows it as a note. (1.1)
- A compaction is when the harness replaces the conversation so far with a summary, in what the agent sees from then
on. The summary is the message of the step of the model call that wrote it: a `source: agent` step carrying that
call's metrics, its profile's `compaction` saying who wrote it and what set it off. A reader that stages a turn for a
judge shows it as a note, not as the agent speaking. (1.1)
call's metrics, its profile's `compaction` saying who wrote it and what set it off (1.1), and, when the harness
counts them, the tokens of the conversation the agent sees just before and just after it (1.2). A reader that stages
a turn for a judge shows it as a note, not as the agent speaking.
- A result always sits in the step that made its call, as ATIF requires. One that arrives after that step closed records
when, in `arrived`.
- A live reader is served closed steps only, each trajectory up to its first step still waiting on a result or
Expand Down Expand Up @@ -123,7 +124,7 @@ One vocabulary, in three places:

| Object | Field | Meaning | Read by |
| --- | --- | --- | --- |
| Trajectory | `version` | The profile version: `1.1` | every reader |
| Trajectory | `version` | The profile version: `1.2` | every reader |
| Trajectory | `native_format` | The native format id the copy was built from | the worker that stores copies; renormalizing |
| Trajectory | `adapter` | The adapter's `name` and `version` | the worker that stores copies; renormalizing |
| Trajectory | `unmatched` | Native records no method took, counted by type | the adapter kit |
Expand All @@ -132,7 +133,7 @@ One vocabulary, in three places:
| Step | `attempt` | The harness attempt the step belongs to; absent means 1 | the explorer |
| Step | `error` | A step-level error: `kind`, `message`, `code` | the explorer |
| Step | `data` | On a task's last step: its final response's diagnostic DataParts, in order, each `data` and its `metadata` | the explorer |
| Step | `compaction` | On a compaction's step: who wrote the summary (`written_by`) and what set it off (`trigger`). (1.1) | judges' turn events |
| Step | `compaction` | On a compaction's step: who wrote the summary (`written_by`) and what set it off (`trigger`) (1.1), and the conversation's tokens before and after it (`tokens_before`, `tokens_after`) (1.2) | judges' turn events |
| Step | `reasoning` | Each reasoning block: `chars`, `visibility`, `signature`, `data` | resuming a session; RL replay |
| Step | `media` | Details of the media the message names, by path | media transfer; the explorer |
| ObservationResult | `status` | The result's status; absent means `ok` | the explorer, judges' turn events |
Expand All @@ -150,7 +151,9 @@ share of `reasoning_content` (0 when the provider withheld the text), its `visib
a redacted block's ciphertext as `data`, byte for byte. A step error (StepError) holds `kind`, `message` and `code`. An
arrival (Arrival) holds `at` and `step_id`. A compaction (Compaction) holds `written_by`, `assistant` for the agent's
own model or `harness`, and `trigger`, `manual` when something asked for it, such as a command, or `auto` when the
harness set it off itself. The Agent, ToolCall and SubagentTrajectoryRef profiles define no fields in 1.1.
harness set it off itself (1.1), and `tokens_before` and `tokens_after`, the tokens of the conversation the agent sees
just before and just after it, when the harness counts them (1.2). The Agent, ToolCall and SubagentTrajectoryRef
profiles define no fields in 1.2.

## Vocabularies

Expand All @@ -173,6 +176,8 @@ field added in a later minor names the version it arrived in, and a reader of a

- 1.1 adds `compaction` and `source: system` steps as the harness's own messages. Their first producer is Claude
Code's adapter, and their reader the judges' turn events.
- 1.2 adds a compaction's `tokens_before` and `tokens_after`. Their first producer is Claude Code's adapter, and their
reader the judges' turn events, which tell the judge how much of the conversation a summary replaced.
- Proposed for a later minor, with their first producer:
- `input_includes_cache` on the root and `cost_status` (`reported`, `priced` or `unpriced`), with the usage
cross-check that reads them;
Expand Down Expand Up @@ -200,8 +205,8 @@ and exits 1 when one is an error.
| `atif` | ATIF's own models, vendored from Harbor, accept it | error | error |
| `profile` | Each `extra.agentenv` parses with its profile model | error | error |
| `profile-key` | Each `extra.agentenv` holds only the fields this profile defines | error | warning |
| `profile-version` | The root's `extra.agentenv.version`, when given, is a 1.x this validator knows: 1.0 or 1.1 | error | warning |
| `compaction` | A step's `compaction` is on a `source: agent` step and names who wrote its summary | error | warning |
| `profile-version` | The root's `extra.agentenv.version`, when given, is a 1.x this validator knows: 1.0 to 1.2 | error | warning |
| `compaction` | A step's `compaction` is on a `source: agent` step and names who wrote its summary, and its token counts, when given, are whole numbers, not negative | error | warning |
| `vocabulary` | A vocabulary field holds one of its values | error | warning |
| `outside-key` | No `extra` holds a key outside `agentenv` but `ToolCall.extra.raw_arguments` | error | warning |
| `call-id` | Each `tool_call_id` is unique across the document and its sub-agents | error | warning |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
ToolCallProfile,
TrajectoryProfile,
dump_profile,
is_token_count,
profile_of,
read_profile,
)
Expand Down Expand Up @@ -74,7 +75,7 @@
"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",
"FORMAT", "ImageSource", "is_prefix", "KIT_RULES", "KitResult", "load", "Media", "MEDIA_PATH", "media_file", "media_paths", "MediaInfo",
"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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
TASK_STATES,
VISIBILITIES,
AtifError,
is_token_count,
)

#: Media types ATIF has a part type for; any other medium is written as a text note naming its file.
Expand Down Expand Up @@ -915,18 +916,24 @@ def system_message(self, *, text: str | None = None, content: Sequence[Any] | No
target.media.update(media)
self._touch(target, when)

def compaction(self, *, step: str, written_by: str, trigger: str | None = None, agent: str | None = None) -> None:
def compaction(self, *, step: str, written_by: str, trigger: str | None = None, tokens_before: int | None = None,
tokens_after: int | None = None, agent: str | None = None) -> None:
"""Mark step ``step`` a compaction: its message a summary that replaced the conversation before it in what the
agent sees, written by ``written_by`` (``assistant``, the agent's own model, or ``harness``) and set off by
``trigger`` (``manual``, something asked for it, or ``auto``). The step is the call that wrote the summary,
so its usage goes on it with ``step``. Profile 1.1."""
``trigger`` (``manual``, something asked for it, or ``auto``), the conversation counting ``tokens_before`` just
before it and ``tokens_after`` just after, when the harness counts them. The step is the call that wrote the
summary, so its usage goes on it with ``step``. Profile 1.1; its tokens 1.2."""
if written_by not in SUMMARY_WRITERS:
raise AtifError(f"written_by {written_by!r} isn't one of {', '.join(SUMMARY_WRITERS)}")
if trigger is not None and trigger not in COMPACTION_TRIGGERS:
raise AtifError(f"trigger {trigger!r} isn't one of {', '.join(COMPACTION_TRIGGERS)}")
for name, count in (("tokens_before", tokens_before), ("tokens_after", tokens_after)):
if count is not None and not is_token_count(count):
raise AtifError(f"{name} {count!r} isn't a count of tokens")
target = self._doc.step_for(_key(step), agent)
target.profile["compaction"] = {key: value for key, value in (("written_by", written_by), ("trigger", trigger))
if value is not None}
target.profile["compaction"] = {key: value for key, value in (
("written_by", written_by), ("trigger", trigger), ("tokens_before", tokens_before),
("tokens_after", tokens_after)) if value is not None}

def attempt(self, number: int) -> None:
"""A harness retry: steps from here on carry attempt ``number``."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@
},
"extra": {
"agentenv": {
"version": "1.1",
"version": "1.2",
"native_format": "toy-events/1",
"adapter": {
"name": "toy-events-atif",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
FORMAT = "atif/1"
#: The key under each ``extra`` that holds the profile.
PROFILE_KEY = "agentenv"
PROFILE_VERSION = "1.1"
PROFILE_VERSION = "1.2"
#: The ATIF version producers write: the oldest that holds the fields they use.
SCHEMA_VERSION = "ATIF-v1.8"
#: The only key outside ``extra.agentenv`` a producer writes: Harbor's, on a ToolCall whose input wasn't an object.
Expand All @@ -28,6 +28,13 @@
SUMMARY_WRITERS = ("assistant", "harness")
#: What set a compaction off: something asked for it (a command), or the harness on its own. Added in 1.1.
COMPACTION_TRIGGERS = ("manual", "auto")


def is_token_count(value: Any) -> bool:
"""Whether ``value`` counts tokens, as a compaction's ``tokens_before`` and ``tokens_after`` do: a whole number,
not a bool, not negative."""
return isinstance(value, int) and not isinstance(value, bool) and value >= 0

VOCABULARIES = {
"StepProfile.state": TASK_STATES,
"ObservationResultProfile.status": RESULT_STATUSES,
Expand Down Expand Up @@ -85,10 +92,13 @@ class StepError(_Profile):

class Compaction(_Profile):
"""A step whose message is a summary that replaced the conversation before it, in what the agent sees from then on:
who wrote it, and what set it off. Added in 1.1."""
who wrote it, and what set it off; added in 1.1. With the tokens of the conversation the agent sees just before it
and just after it, when the harness counts them; added in 1.2."""

written_by: str | None = None
trigger: str | None = None
tokens_before: int | None = None
tokens_after: int | None = None


class Arrival(_Profile):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
MediaInfo,
ReasoningBlock,
StepError,
is_token_count,
profile_of,
)
from .reader import MEDIA_PATH, _resolver, _trajectories, is_prefix, media_refs, tasks
Expand Down Expand Up @@ -69,9 +70,9 @@ class Rule:
Rule("profile", ERROR, ERROR, "Each `extra.agentenv` parses with its profile model"),
Rule("profile-key", ERROR, WARNING, "Each `extra.agentenv` holds only the fields this profile defines"),
Rule("profile-version", ERROR, WARNING, "The root's `extra.agentenv.version`, when given, is a 1.x this validator "
"knows: 1.0 or 1.1"),
"knows: 1.0 to 1.2"),
Rule("compaction", ERROR, WARNING, "A step's `compaction` is on a `source: agent` step and names who wrote its "
"summary"),
"summary, and its token counts, when given, are whole numbers, not negative"),
Rule("vocabulary", ERROR, WARNING, "A vocabulary field holds one of its values"),
Rule("outside-key", ERROR, WARNING, "No `extra` holds a key outside `agentenv` but `ToolCall.extra.raw_arguments`"),
Rule("call-id", ERROR, WARNING, "Each `tool_call_id` is unique across the document and its sub-agents"),
Expand Down Expand Up @@ -298,6 +299,11 @@ def _profiles(objects: list[tuple[str, str, Mapping[str, Any]]], found: _Finding
for name in ("written_by", "trigger"):
if compaction.get(name) is not None:
_vocabulary(f"Compaction.{name}", f"{at}.compaction.{name}", compaction[name], found)
for name in ("tokens_before", "tokens_after"):
count = compaction.get(name)
if count is not None and not is_token_count(count):
found.add("compaction", f"{at}.compaction.{name}",
f"{name} counts tokens, a whole number that isn't negative, not {count!r}")
if kind == "Trajectory" and where == "" and not _known_version(profile.get("version")):
found.add("profile-version", f"{at}.version",
f"this is profile {profile['version']!r}; the validator checks profile {PROFILE_VERSION} and "
Expand Down
20 changes: 13 additions & 7 deletions packages/agentenv-protocol/tests/test_atif_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ def say(self, r, turn):
@native(type="compact")
def compact(self, r, turn):
turn.message(step=r["step"], text=r["text"])
turn.compaction(step=r["step"], written_by=r.get("by", "assistant"), trigger=r.get("trigger"))
turn.compaction(step=r["step"], written_by=r.get("by", "assistant"), trigger=r.get("trigger"),
tokens_before=r.get("before"), tokens_after=r.get("after"))
turn.step(key=r["step"], input_tokens=100, output_tokens=20)

@native(type="system")
Expand All @@ -108,25 +109,30 @@ def system(self, r, turn):

def test_a_compaction_is_the_step_of_the_call_that_wrote_its_summary_and_the_harnesss_message_a_system_step():
run, pages = run_task([{"type": "say", "step": "s1", "text": "working"},
{"type": "compact", "step": "c1", "text": "the summary so far", "trigger": "manual"},
{"type": "compact", "step": "c1", "text": "the summary so far", "trigger": "manual",
"before": 28634, "after": 2839},
{"type": "system", "text": "Compacted"},
{"type": "say", "step": "s2", "text": "after it"}], cls=Compacting)
user, before, compaction, system, after = run.document()["steps"]
assert (compaction["source"], compaction["message"], compaction["llm_call_count"]) == (
"agent", "the summary so far", 1)
assert compaction["metrics"] == {"prompt_tokens": 100, "completion_tokens": 20}
assert profile_of(compaction)["compaction"] == {"written_by": "assistant", "trigger": "manual"}
assert profile_of(compaction)["compaction"] == {"written_by": "assistant", "trigger": "manual",
"tokens_before": 28634, "tokens_after": 2839}
assert (system["source"], system["message"]) == ("system", "Compacted")
assert not {"model_name", "metrics", "llm_call_count", "tool_calls"} & set(system)
assert after["message"] == "after it"
check(run.document())
assert all(is_prefix(a, b) for a, b in zip(pages, pages[1:]) if a is not None)


@pytest.mark.parametrize("record", [{"type": "compact", "step": "c1", "text": "x", "by": "someone"},
{"type": "compact", "step": "c1", "text": "x", "trigger": "now"}])
def test_a_compaction_names_a_writer_and_trigger_of_its_vocabularies(record):
with pytest.raises(AtifError, match="isn't one of"):
@pytest.mark.parametrize(("record", "refusal"), [
({"type": "compact", "step": "c1", "text": "x", "by": "someone"}, "isn't one of"),
({"type": "compact", "step": "c1", "text": "x", "trigger": "now"}, "isn't one of"),
({"type": "compact", "step": "c1", "text": "x", "before": -1}, "isn't a count of tokens"),
({"type": "compact", "step": "c1", "text": "x", "after": "2839"}, "isn't a count of tokens")])
def test_a_compaction_names_a_writer_and_trigger_of_its_vocabularies_and_counts_tokens(record, refusal):
with pytest.raises(AtifError, match=refusal):
run_task([record], cls=Compacting)


Expand Down
Loading
Loading