From 1fc120b1939b90dfdbd096e04856b1ba4c755381 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 18 Nov 2026 13:23:54 -0800 Subject: [PATCH 1/5] feat(protocol): agent cards offer trajectory formats, reads may name one, and every answer names its format enable(TRAJECTORY_V1, native=...) lists formats, native and default on the card. Every trajectory read takes an optional format; one the card doesn't offer is refused with HTTP 400 format_not_offered before any handler runs. An AgentEnvError from any agent extension handler now answers with its status and the env servers' error body instead of an opaque 500. SDK-served reads name the format they served, a returned native_trajectory keeps its format at seal (pi's null label), and a declared native format holds the log and native trajectories to it. The proxy declares agentenv-proxy/v1. Co-Authored-By: Claude Opus 5.5 --- packages/agentenv-protocol/README.md | 45 ++- .../a2a_agent/_trajectory_log.py | 56 +++- .../agentenv_protocol/a2a_agent/extensions.py | 28 +- .../agentenv_protocol/a2a_agent/framework.py | 49 +++- .../src/agentenv_protocol/a2a_agent/proxy.py | 3 +- .../agentenv_protocol/a2a_agent/tasks/v1.py | 17 +- .../agentenv-protocol/tests/test_a2a_agent.py | 12 +- .../tests/test_a2a_object_transfers.py | 3 +- .../agentenv-protocol/tests/test_a2a_proxy.py | 4 + .../tests/test_a2a_trajectory_log.py | 260 +++++++++++++++++- src/agent_env/agents/AGENTS.md | 4 + tst/unit/a2a_agent/protocol_test.py | 35 ++- 12 files changed, 460 insertions(+), 56 deletions(-) diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index ec8b116e5..5d1f1baaa 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -1532,6 +1532,38 @@ are dropped, least recently used first; a context with a task still pending or running is never dropped, nor is the one whose task has just ended. A running task's log is logged as a warning once it passes 100 MiB. +#### Trajectory formats + +`native` declares the format of the agent's native trajectory: + +```python +enable(TRAJECTORY_V1, live=True, native="my-cli-events/1") +``` + +The card then lists three fields in the trajectory extension's `params`, beside +`methods`: + +- `formats`: the formats a read may name. +- `native`: the native trajectory's format, which never changes. +- `default`: the format a read that names none gets; for now it is `native`. + +A card without `formats` predates them, so send its reads no `format`. With +`native` declared, the log starts in that format and `set_format` is optional. +`set_format` with another format raises `ValueError`, and a task that returns a +`native_trajectory` in another format fails. + +Every trajectory read takes an optional `format`. A read naming none gets the +default. A read naming a format the card doesn't list is HTTP 400 with the error +code `format_not_offered`, and its message lists the formats the card offers. +That check comes before any handler runs, the agent's own included. + +Every read the framework answers names the format it served: `{trajectory, format}`, +`{objects, format}`, and the cursor reads' `format`. A task whose result carries a +`native_trajectory` is served in that trajectory's `format`. A context read names +the most recent format its tasks set. Readers trust a response's `format` over +the card. An agent that binds its own context reads should name, in their +responses, the format it serves. + `enable(..., description="...")` is reserved for declarations carrying configuration or metadata. It preserves the agent-specific extension prose published in the Agent Card. The versioned SDK definition provides a generic @@ -1552,8 +1584,11 @@ configuration keywords, and third-party definitions use the same public API as the built-ins. Extension request parsing and schema validation failures return HTTP 400. -Unhandled exceptions raised by an implementation handler return HTTP 500; -handlers use `HTTPException` when they intentionally need another status. +An `AgentEnvError` raised by a handler answers with its `status` and the body +`{"ok": false, "error": {code, message, retryable, applied, hint?}}`, as it does +from an env (see [Errors](#errors)). Other unhandled exceptions raised by an +implementation handler return HTTP 500 with a correlation ID; handlers use +`HTTPException` when they intentionally need another status. Passing `config=MyAgentConfig` automatically enables `AGENT_CONFIG_V1`; direct `enable(AGENT_CONFIG_V1, ...)` declarations are rejected. The model's fields become the Agent Card's @@ -1882,9 +1917,9 @@ optional field, `|` an alternative request): | Operation | Request | Response | | --- | --- | --- | | skill `add` | `{name, description, skill_md}` \| `{name, description, skill_bundle: {max_total_bytes, files: [{path, object: ReadObject}]}}` | `{name}` | -| trajectory `get` | `{task_id}` \| `{context_id}` | `{trajectory}` | -| | `{task_id \| context_id, objects: {trajectory: WriteObject}}` | `{objects: {trajectory: Uploaded}}` | -| | `{task_id \| context_id, after, limit?}` | `{context_id, task_id, state, format, events, next, has_more}` | +| trajectory `get` | `{task_id, format?}` \| `{context_id, format?}` | `{trajectory, format}` | +| | `{task_id \| context_id, objects: {trajectory: WriteObject}, format?}` | `{objects: {trajectory: Uploaded}, format}` | +| | `{task_id \| context_id, after, limit?, format?}` | `{context_id, task_id, state, format, events, next, has_more}` | | snapshot `save` | `{context_id, objects: {trajectory: WriteObject, workspace?: WriteObject}}` | `{context_id, objects: {trajectory: Uploaded, workspace?: Uploaded}}` | | snapshot `load` | `{objects: {trajectory: ReadObject, workspace?: ReadObject}, target_context_id?}` | `{context_id}` | | `enable-changelog` | `{write_namespace: WriteNamespaceGrant, roots?}` | `{roots}` | diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py index 0240712fe..731b8ca8a 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py @@ -23,6 +23,7 @@ class _TaskRecord: cancel_requested: bool = False final_state: TrajectoryState | None = None native: bytes | None = None + native_format: str | None = None @property def state(self) -> TrajectoryState: @@ -31,6 +32,14 @@ def state(self) -> TrajectoryState: return TrajectoryState.RUNNING if len(self.log) else TrajectoryState.PENDING +@dataclass(frozen=True, slots=True) +class TrajectoryBody: + """A whole trajectory as a JSON value's bytes, and the format it is in.""" + + body: bytes + format: str | None + + @dataclass(frozen=True, slots=True) class TrajectoryPage: context_id: str @@ -48,10 +57,11 @@ class TaskTrajectories: positions in a context read never shift. A context with a task pending or running is never evicted, nor is the one whose task just ended, so its final record is readable.""" - def __init__(self, max_contexts: int = MAX_CACHED_CONTEXTS) -> None: + def __init__(self, max_contexts: int = MAX_CACHED_CONTEXTS, *, native: str | None = None) -> None: if max_contexts < 1: raise ValueError("max_contexts must be positive") self._max_contexts = max_contexts + self._native = native self._tasks: dict[str, _TaskRecord] = {} self._contexts: OrderedDict[str, list[str]] = OrderedDict() @@ -59,7 +69,7 @@ def register(self, task_id: str, context_id: str) -> TrajectoryLog: """The task's log, created ``pending`` the first time the task is seen.""" record = self._tasks.get(task_id) if record is None: - log = TrajectoryLog() + log = TrajectoryLog(native=self._native) log._task_id = task_id record = self._tasks[task_id] = _TaskRecord(context_id=context_id, log=log) self._contexts.setdefault(context_id, []).append(task_id) @@ -87,12 +97,23 @@ def request_cancel(self, task_id: str) -> None: record.cancel_requested = True def seal( - self, task_id: str, state: TrajectoryState, *, native: bytes | None = None + self, + task_id: str, + state: TrajectoryState, + *, + native: bytes | None = None, + native_format: str | None = None, ) -> None: - """End the task's trajectory; the first seal wins.""" + """End the task's trajectory; the first seal wins. A native trajectory in a format + other than the card's native one is refused before anything is recorded.""" record = self._tasks[task_id] if record.final_state is not None: return + if native is not None and self._native is not None and native_format != self._native: + raise ValueError( + f"task {task_id} returned a native trajectory in {native_format!r}, " + f"not {self._native!r}, the native format the card declares" + ) if native is not None: if len(record.log): logger.warning( @@ -101,29 +122,34 @@ def seal( task_id, ) record.native = native + record.native_format = native_format record.log._sealed = True record.final_state = TrajectoryState.CANCELED if record.cancel_requested else state self._touch(record.context_id) self._evict(keep=record.context_id) - def final(self, task_id: str) -> bytes | None: - """The ended task's final trajectory as a JSON array, or None if there is none yet.""" + def final(self, task_id: str) -> TrajectoryBody | None: + """The ended task's final trajectory, a returned native one or else its log as a JSON + array, or None if there is none yet.""" record = self._tasks.get(task_id) if record is None or record.final_state is None: return None self._touch(record.context_id) if record.native is not None: - return record.native + return TrajectoryBody(record.native, record.native_format) if not len(record.log): return None - return _json_array(record.log._events) + return TrajectoryBody(_json_array(record.log._events), record.log.format) - def context_events(self, context_id: str) -> bytes | None: + def context_events(self, context_id: str) -> TrajectoryBody | None: """Every event of the context's tasks in order, as a JSON array.""" records = self._context_records(context_id) if records is None: return None - return _json_array([event for record in records for event in record.log._events]) + return TrajectoryBody( + _json_array([event for record in records for event in record.log._events]), + _context_format(records), + ) def task_page( self, task_id: str, after: int, max_events: int, max_bytes: int @@ -186,10 +212,7 @@ def context_page( context_id=context_id, task_id=task_ids[current], state=state, - format=next( - (record.log.format for record in reversed(records) if record.log.format), - None, - ), + format=_context_format(records), events=page, total=sum(lengths), ) @@ -219,6 +242,11 @@ def _evict(self, *, keep: str) -> None: del self._tasks[task_id] +def _context_format(records: list[_TaskRecord]) -> str | None: + """The most recent format any of the context's tasks set.""" + return next((record.log.format for record in reversed(records) if record.log.format), None) + + def _page( events: list[bytes], start: int, diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index e6200211d..09776d1e2 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -150,12 +150,18 @@ class SkillAddResponse(ExtensionResponse): name: str +#: A trajectory format id a read may name, such as ``my-cli-events/1``; the card's trajectory ``formats`` lists them. +TrajectoryFormat = Annotated[str, Field(min_length=1, max_length=128)] + + class TaskTrajectoryRequest(ExtensionRequest): task_id: str + format: TrajectoryFormat | None = None class ContextTrajectoryRequest(ExtensionRequest): context_id: str + format: TrajectoryFormat | None = None class TrajectoryWriteObjects(ExtensionRequest): @@ -171,11 +177,13 @@ def _json_trajectory(self) -> TrajectoryWriteObjects: class TaskObjectTrajectoryRequest(ExtensionRequest): task_id: str objects: TrajectoryWriteObjects + format: TrajectoryFormat | None = None class ContextObjectTrajectoryRequest(ExtensionRequest): context_id: str objects: TrajectoryWriteObjects + format: TrajectoryFormat | None = None class TrajectoryUploadedObjects(ExtensionResponse): @@ -204,12 +212,14 @@ class TaskEventsTrajectoryRequest(ExtensionRequest): task_id: str after: StrictInt = Field(ge=0) limit: StrictInt | None = Field(default=None, ge=1, le=MAX_TRAJECTORY_READ_EVENTS) + format: TrajectoryFormat | None = None class ContextEventsTrajectoryRequest(ExtensionRequest): context_id: str after: StrictInt = Field(ge=0) limit: StrictInt | None = Field(default=None, ge=1, le=MAX_TRAJECTORY_READ_EVENTS) + format: TrajectoryFormat | None = None class TrajectoryEventsResponse(ExtensionResponse): @@ -1092,15 +1102,23 @@ def _configure_install(**declaration: Any) -> ExtensionConfiguration: return ExtensionConfiguration(wire_params=declaration) -def _configure_trajectory(*, live: bool = False) -> ExtensionConfiguration: +def _configure_trajectory(*, live: bool = False, native: str | None = None) -> ExtensionConfiguration: """``live=True`` advertises the cursor reads, which serve the framework's log while a - task runs, and the context reads the framework answers when the agent binds none.""" + task runs, and the context reads the framework answers when the agent binds none. + ``native`` names the native log's format: the card offers it as ``formats``, ``native`` and + ``default``, and the log, a returned native trajectory and every read hold to it.""" if not isinstance(live, bool): raise TypeError("live must be a boolean") - if not live: - return ExtensionConfiguration() + if native is not None and not isinstance(native, str): + raise TypeError("native must be a format id string") + if native is not None and (not native.strip() or len(native) > 128): + raise ValueError("native must be a format id of 1 to 128 characters") return ExtensionConfiguration( - variants={"get": {"task_events", "context_events", "context", "context_objects"}} + wire_params={"formats": [native], "native": native, "default": native} if native else {}, + options={"native": native} if native else {}, + variants=( + {"get": {"task_events", "context_events", "context", "context_objects"}} if live else {} + ), ) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index ed2faaaa1..40d2b6efa 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -63,6 +63,8 @@ enable, ) from ..computer.errors import ComputerError +from ..errors import AgentEnvError +from ..types import error_body from . import clock as agent_clock from .control_token import REFUSAL, carries_control_token, log_guard, log_refusal, take_control_token from .peer_agents import PEER_MCP_PATH, PEER_MCP_SERVER_NAME, PeerAgents @@ -518,6 +520,11 @@ def _unwrap_bound_handler(handler: Callable) -> Callable: return resolved +def _agent_env_error_response(error: AgentEnvError) -> JSONResponse: + """An extension's ``AgentEnvError`` as its status and the body env servers answer with.""" + return JSONResponse(error_body(**error.fields()), status_code=error.status) + + def _opaque_extension_error(stage: str) -> HTTPException: """Log an extension failure while keeping implementation details off the wire.""" correlation_id = uuid.uuid4().hex @@ -552,7 +559,11 @@ def __init__( ) self.mcp_servers: dict[str, dict[str, Any]] = {} self.cdp_endpoints: dict[str, dict[str, Any]] = {} - self.task_trajectories = TaskTrajectories() + trajectory = self._activations.get(TRAJECTORY_V1.uri) + native = trajectory.options.get("native") if trajectory is not None else None + #: What a trajectory read may name, as the card's trajectory ``formats`` lists them. + self.trajectory_formats: tuple[str, ...] = (native,) if native else () + self.task_trajectories = TaskTrajectories(native=native) self._context_sessions = _BoundedContextSessions() self.skills: list[Mapping[str, Any]] = [] self.identity_skills: dict[str, str] = {} @@ -811,8 +822,8 @@ async def trajectory_get( ): return self._trajectory_events(request) if isinstance(request, (TaskTrajectoryRequest, TaskObjectTrajectoryRequest)): - body = self.task_trajectories.final(request.task_id) - if body is None: + trajectory = self.task_trajectories.final(request.task_id) + if trajectory is None: raise HTTPException( status_code=404, detail=( @@ -820,20 +831,35 @@ async def trajectory_get( ), ) else: - body = self.task_trajectories.context_events(request.context_id) - if body is None: + trajectory = self.task_trajectories.context_events(request.context_id) + if trajectory is None: raise HTTPException( status_code=404, detail=f"Unknown context '{request.context_id}'" ) if isinstance(request, (TaskTrajectoryRequest, ContextTrajectoryRequest)): - return {"trajectory": json.loads(body)} - uploaded = await upload(request.objects.trajectory, body) + return {"trajectory": json.loads(trajectory.body), "format": trajectory.format} + uploaded = await upload(request.objects.trajectory, trajectory.body) return { "objects": { "trajectory": uploaded.model_dump(mode="json"), - } + }, + "format": trajectory.format, } + def check_trajectory_format(self, format: str | None) -> None: + """Refuse a trajectory read naming a format the card doesn't offer, before any handler + runs, the agent's own included.""" + if format is None or format in self.trajectory_formats: + return + offered = ", ".join(self.trajectory_formats) + raise AgentEnvError( + "format_not_offered", + f"the trajectory format {format!r} is not offered; this agent offers {offered}" + if offered + else f"the trajectory format {format!r} is not offered; this agent's card lists no formats, " + "so its reads take none", + ) + def _trajectory_events( self, request: TaskEventsTrajectoryRequest | ContextEventsTrajectoryRequest ) -> TrajectoryEventsResponse: @@ -1205,8 +1231,12 @@ async def invoke(request: Request) -> JSONResponse: extension_request = None else: extension_request = request_model.model_validate(payload) + if extension_uri == TRAJECTORY_V1.uri: + self.services.check_trajectory_format(extension_request.format) except HTTPException: raise + except AgentEnvError as exc: + return _agent_env_error_response(exc) except ValidationError as exc: raise HTTPException( status_code=400, detail=_validation_error_detail(exc) @@ -1257,6 +1287,8 @@ async def invoke_and_validate() -> Any: return JSONResponse(result) except HTTPException: raise + except AgentEnvError as exc: + return _agent_env_error_response(exc) except TriggerError as exc: raise HTTPException( status_code=exc.status_code, detail=str(exc) @@ -1353,6 +1385,7 @@ async def execute(self, context: Any, event_queue: Any) -> None: if result.outcome is TaskOutcome.FAILED else TrajectoryState.COMPLETED, native=None if native is None else _encode_trajectory(native.payload), + native_format=None if native is None else native.format, ) message = updater.new_agent_message(parts=parts) if result.outcome is TaskOutcome.FAILED: diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py index 9c520d30c..15f5189f9 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py @@ -128,7 +128,7 @@ async def stopping_actions(app: Starlette) -> AsyncIterator[None]: description="An agent played from outside AgentEnv: a driver answers its turns.", version="1.0.0", ) -EXTENSIONS = (MCP_CONFIG_V1, enable(TRAJECTORY_V1, live=True), PROXY_V1) +EXTENSIONS = (MCP_CONFIG_V1, enable(TRAJECTORY_V1, live=True, native=TRAJECTORY_FORMAT), PROXY_V1) @a2a_agent(identity=IDENTITY, config=ProxyConfig, extensions=EXTENSIONS, lifespan=stopping_actions) @@ -151,7 +151,6 @@ def __init__(self, *, shell: bool = True, long_poll_seconds: float = LONG_POLL_S async def run(self, request: TaskRequest[ProxyConfig]) -> TaskResult: if any(not isinstance(part, TextPart) for part in request.parts): return TaskResult.failure("proxy.unsupported_part", "the proxy passes on text parts only") - request.trajectory.set_format(TRAJECTORY_FORMAT) turn = _Turn( task_id=request.task_id, context_id=request.context_id, diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py index 920ec7226..4f820268d 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py @@ -155,14 +155,16 @@ class TrajectoryLog: Each event is serialized as it is appended, so an event once read never changes; append from one thread at a time. Unless the result carries a ``native_trajectory``, the log is - the task's final trajectory.""" + the task's final trajectory. An agent whose card declares a ``native`` format starts with + that format, and no other may be set.""" - __slots__ = ("_events", "_size_bytes", "_format", "_sealed", "_task_id", "_warned") + __slots__ = ("_events", "_size_bytes", "_format", "_native", "_sealed", "_task_id", "_warned") - def __init__(self) -> None: + def __init__(self, *, native: str | None = None) -> None: self._events: list[bytes] = [] self._size_bytes = 0 - self._format: str | None = None + self._format: str | None = native + self._native = native self._sealed = False self._task_id: str | None = None self._warned = False @@ -176,13 +178,18 @@ def set_format(self, format: str) -> None: appended, it stays.""" if not isinstance(format, str) or not format.strip(): raise ValueError("trajectory format must be a non-empty string") + if self._native is not None and format != self._native: + raise ValueError( + f"trajectory format {format!r} is not {self._native!r}, the native format the card declares" + ) self._ensure_open() if self._events and format != self._format: raise RuntimeError("the trajectory's format cannot change once events are appended") self._format = format def append(self, event: Mapping[str, Any]) -> None: - """Record one complete event, a JSON object, after ``set_format`` has named its format.""" + """Record one complete event, a JSON object, once the log has a format: the card's + ``native``, or one ``set_format`` names.""" if not isinstance(event, Mapping): raise TypeError("a trajectory event must be a JSON object") self._ensure_open() diff --git a/packages/agentenv-protocol/tests/test_a2a_agent.py b/packages/agentenv-protocol/tests/test_a2a_agent.py index 8e8bbc709..2dd336b7b 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent.py @@ -257,14 +257,14 @@ def test_trajectory_cache_evicts_least_recently_used_context() -> None: trajectories.seal( f"task-{number}", TrajectoryState.COMPLETED, native=f"[{number}]".encode() ) - assert trajectories.final("task-1") == b"[1]" + assert trajectories.final("task-1").body == b"[1]" trajectories.register("task-3", "context-3") trajectories.seal("task-3", TrajectoryState.COMPLETED, native=b"[3]") - assert trajectories.final("task-1") == b"[1]" + assert trajectories.final("task-1").body == b"[1]" assert trajectories.final("task-2") is None - assert trajectories.final("task-3") == b"[3]" + assert trajectories.final("task-3").body == b"[3]" @pytest.mark.asyncio @@ -2066,6 +2066,7 @@ async def sdk_handler(request: TaskTrajectoryRequest | TaskObjectTrajectoryReque request = task_only.card_extensions()[0]["params"]["methods"]["get"]["request"] assert request == { "required": ["task_id"], + "optional": ["format"], "oneOf": [{}, {"required": ["objects"]}], } @@ -2085,6 +2086,7 @@ async def upload_by_context(self, request: ContextObjectTrajectoryRequest): ) request = with_context.card_extensions()[0]["params"]["methods"]["get"]["request"] assert request == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, @@ -2110,7 +2112,7 @@ async def test_default_handler_delegation_accepts_sdk_request_variant() -> None: TaskTrajectoryRequest(task_id="task-1"), ) - assert result == {"trajectory": [{"type": "result"}]} + assert result == {"trajectory": [{"type": "result"}], "format": None} def test_trajectory_override_annotates_every_sdk_variant() -> None: @@ -2899,7 +2901,7 @@ async def add_bundle_skill(self, request: BundleSkillRequest): "get", {"task_id": task["id"]}, ) - assert trajectory_response.json() == {"trajectory": [{"type": "result"}]} + assert trajectory_response.json() == {"trajectory": [{"type": "result"}], "format": "test-events/v1"} def test_run_is_required() -> None: diff --git a/packages/agentenv-protocol/tests/test_a2a_object_transfers.py b/packages/agentenv-protocol/tests/test_a2a_object_transfers.py index 41d544461..7b7acae99 100644 --- a/packages/agentenv-protocol/tests/test_a2a_object_transfers.py +++ b/packages/agentenv-protocol/tests/test_a2a_object_transfers.py @@ -572,7 +572,8 @@ def handle(request: httpx.Request) -> httpx.Response: "size_bytes": 19, "sha256": hashlib.sha256(b'[{"type":"result"}]').hexdigest(), } - } + }, + "format": None, } assert services.task_trajectories.final("task-1") is not None diff --git a/packages/agentenv-protocol/tests/test_a2a_proxy.py b/packages/agentenv-protocol/tests/test_a2a_proxy.py index fb30d86ba..43450baba 100644 --- a/packages/agentenv-protocol/tests/test_a2a_proxy.py +++ b/packages/agentenv-protocol/tests/test_a2a_proxy.py @@ -170,6 +170,9 @@ def test_the_card_offers_the_proxy_env_servers_and_a_system_prompt(): assert sorted(extensions["urn:agentenv:proxy/v1"]["params"]["methods"]) == [ "act", "claim", "next", "record", "reply", "result", "tools"] assert "urn:agentenv:mcp-config/v1" in extensions + trajectory = extensions["urn:agentenv:trajectory/v1"]["params"] + assert (trajectory["formats"], trajectory["native"], trajectory["default"]) == ( + ["agentenv-proxy/v1"], "agentenv-proxy/v1", "agentenv-proxy/v1") assert "system_prompt" in extensions["urn:agentenv:agent-config/v1"]["params"]["methods"]["set"]["request"][ "supported"] @@ -202,6 +205,7 @@ def test_a_message_is_an_open_turn_until_the_driver_replies(client): assert (turn["name"], _attrs(turn, "gen_ai.prompt"), _attrs(turn, "gen_ai.completion")) == ( "turn", {"prompt": "fix the build", "system_prompt": "be brief"}, {"content": [{"type": "text", "text": "fixed"}]}) + assert client.post("/ext/trajectory", json={"task_id": task_id}).json()["format"] == "agentenv-proxy/v1" assert _turns(client, after=seen["version"])["turns"] == [] diff --git a/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py b/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py index 175fc1235..1e1e21716 100644 --- a/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py +++ b/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py @@ -32,8 +32,9 @@ enable, extension, ) -from agentenv_protocol.a2a_agent import framework -from agentenv_protocol.a2a_agent._trajectory_log import TaskTrajectories +from agentenv_protocol import AgentEnvError +from agentenv_protocol.a2a_agent import ContextObjectTrajectoryRequest, framework +from agentenv_protocol.a2a_agent._trajectory_log import TaskTrajectories, TrajectoryBody from agentenv_protocol.a2a_agent.framework import _SdkServices from agentenv_protocol.a2a_agent.tasks import v1 as tasks_v1 @@ -150,6 +151,7 @@ def test_live_card_advertises_the_cursor_reads() -> None: request = extension_card["params"]["methods"]["get"]["request"] assert request == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, @@ -163,6 +165,7 @@ def test_live_card_advertises_the_cursor_reads() -> None: assert card_request_accepts(request, {"task_id", "after"}) assert card_request_accepts(request, {"task_id", "after", "limit"}) assert card_request_accepts(request, {"context_id", "after"}) + assert card_request_accepts(request, {"task_id", "format"}) with pytest.raises(TypeError, match="live must be a boolean"): enable(TRAJECTORY_V1, live="yes") @@ -210,7 +213,7 @@ def test_task_read_follows_a_running_task() -> None: gates.release.set() assert _within(5, lambda: _task_state(client, task_id) == "completed") final = _trajectory(client, {"task_id": task_id}) - assert final.json() == {"trajectory": _events("hello", 3)} + assert final.json() == {"trajectory": _events("hello", 3), "format": "test-events/1"} done = _trajectory(client, {"task_id": task_id, "after": 0}).json() assert done["state"] == "completed" assert done["events"] == _events("hello", 3) @@ -254,7 +257,8 @@ def test_a_failed_task_keeps_its_events(result: str, a2a_state: str) -> None: assert read["state"] == "failed" assert read["events"] == _events("hello", 3) assert _trajectory(client, {"task_id": task_id}).json() == { - "trajectory": _events("hello", 3) + "trajectory": _events("hello", 3), + "format": "test-events/1", } @@ -317,7 +321,8 @@ async def run(self, request: TaskRequest) -> TaskResult: assert _within(5, lambda: _task_state(client, task_id) == "completed") assert _trajectory(client, {"task_id": task_id}).json() == { - "trajectory": [{"native": True}] + "trajectory": [{"native": True}], + "format": "native/1", } assert _trajectory(client, {"task_id": task_id, "after": 0}).json()["events"] == [ {"live": True} @@ -347,7 +352,8 @@ def test_context_reads_span_turns_in_order() -> None: assert tail["events"] == everything[1:3] assert (tail["next"], tail["has_more"]) == (3, True) assert _trajectory(client, {"context_id": "context-1"}).json() == { - "trajectory": everything + "trajectory": everything, + "format": "test-events/1", } @@ -447,7 +453,7 @@ def test_a_sealed_log_refuses_more_events() -> None: log.append({"step": 2}) with pytest.raises(RuntimeError, match="can no longer change"): log.set_format("late/1") - assert trajectories.final("task-1") == b'[{"step":1}]' + assert trajectories.final("task-1") == TrajectoryBody(b'[{"step":1}]', "test-events/1") def test_reads_never_return_a_partial_event() -> None: @@ -513,7 +519,7 @@ def test_eviction_drops_completed_contexts_but_never_running_ones() -> None: assert trajectories.task_page("running", 0, 10, 1_000) is not None assert trajectories.final("done-1") is None assert trajectories.final("done-2") is None - assert trajectories.final("done-3") == b"[1]" + assert trajectories.final("done-3") == TrajectoryBody(b"[1]", None) def test_the_context_whose_task_just_ended_is_kept_for_its_final_read() -> None: @@ -526,7 +532,7 @@ def test_the_context_whose_task_just_ended_is_kept_for_its_final_read() -> None: trajectories.seal("ending", TrajectoryState.COMPLETED) - assert trajectories.final("ending") == b'[{"step":1}]' + assert trajectories.final("ending") == TrajectoryBody(b'[{"step":1}]', "test-events/1") def test_a_large_running_trajectory_warns_once( @@ -629,6 +635,240 @@ async def capture_upload(_target, body: bytes): response = _trajectory(client, {"task_id": task_id, "objects": {"trajectory": grant}}) assert response.status_code == 200, response.text - assert inline[0] == inline[1] == {"trajectory": _NATIVE_EVENTS} + assert inline[0] == inline[1] == {"trajectory": _NATIVE_EVENTS, "format": "test-events/1"} assert uploaded[0] == uploaded[1] assert json.loads(uploaded[1]) == _NATIVE_EVENTS + + +def _grant() -> dict[str, Any]: + return { + "media_type": "application/json", + "max_bytes": 1_000_000, + "write": { + "kind": "http-put", + "url": "https://objects.example.test/write", + "expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)) + .isoformat(timespec="seconds") + .replace("+00:00", "Z"), + }, + } + + +def _card_params(agent: AgentEnvAgent) -> dict[str, Any]: + card = agent.create_app().state.agentenv_a2a.card.model_dump(mode="json", exclude_none=True) + (extension_card,) = [ + item for item in card["capabilities"]["extensions"] if item["uri"] == TRAJECTORY_V1.uri + ] + return extension_card["params"] + + +def _native_agent(*, native: str | None = "test-events/1", live: bool = True) -> AgentEnvAgent: + @a2a_agent(identity=_IDENTITY, extensions=(enable(TRAJECTORY_V1, live=live, native=native),)) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + for event in _events(request.parts[0].text, 2): + request.trajectory.append(event) + return TaskResult.text("done") + + return Agent() + + +def test_a_card_declaring_native_offers_it_as_its_formats_and_default() -> None: + params = _card_params(_native_agent()) + + assert (params["formats"], params["native"], params["default"]) == ( + ["test-events/1"], + "test-events/1", + "test-events/1", + ) + assert params["methods"]["get"]["request"]["optional"] == ["format"] + assert not {"formats", "native", "default"} & set(_card_params(_live_agent(_Gates()))) + + +@pytest.mark.parametrize( + ("native", "error"), + [(1, TypeError), ("", ValueError), (" ", ValueError), ("x" * 129, ValueError)], +) +def test_native_must_be_a_format_id(native: Any, error: type[Exception]) -> None: + with pytest.raises(error, match="native must be"): + enable(TRAJECTORY_V1, native=native) + + +def test_a_read_naming_the_native_format_or_none_is_served_it(monkeypatch: pytest.MonkeyPatch) -> None: + async def capture_upload(_target, body: bytes): + return Uploaded(size_bytes=len(body)) + + monkeypatch.setattr(framework, "upload", capture_upload) + with TestClient(_native_agent().create_app()) as client: + task_id = _send(client, "hello", "message-1") + assert _within(5, lambda: _task_state(client, task_id) == "completed") + for named in ({}, {"format": "test-events/1"}): + assert _trajectory(client, {"task_id": task_id, **named}).json() == { + "trajectory": _events("hello", 2), + "format": "test-events/1", + } + assert _trajectory(client, {"context_id": "context-1", **named}).json() == { + "trajectory": _events("hello", 2), + "format": "test-events/1", + } + page = _trajectory(client, {"task_id": task_id, "after": 0, **named}).json() + assert (page["format"], page["events"]) == ("test-events/1", _events("hello", 2)) + uploaded = _trajectory( + client, {"task_id": task_id, "objects": {"trajectory": _grant()}, **named} + ).json() + assert uploaded["format"] == "test-events/1" + + +@pytest.mark.parametrize( + "read", + [ + {"task_id": "task-1"}, + {"task_id": "task-1", "objects": {"trajectory": "GRANT"}}, + {"task_id": "task-1", "after": 0}, + {"context_id": "context-1"}, + {"context_id": "context-1", "objects": {"trajectory": "GRANT"}}, + {"context_id": "context-1", "after": 0}, + ], +) +def test_a_read_naming_a_format_the_card_does_not_offer_is_refused(read: dict[str, Any]) -> None: + if "objects" in read: + read = {**read, "objects": {"trajectory": _grant()}} + with TestClient(_native_agent().create_app()) as client: + response = _trajectory(client, {**read, "format": "atif/1"}) + + assert response.status_code == 400 + assert response.json() == { + "ok": False, + "error": { + "code": "format_not_offered", + "message": "the trajectory format 'atif/1' is not offered; this agent offers test-events/1", + "retryable": False, + "applied": "no", + }, + } + + +def test_a_card_without_native_refuses_every_named_format() -> None: + with TestClient(_live_agent(_Gates()).create_app()) as client: + task_id = _send(client, "hello", "message-1") + assert _within(5, lambda: _task_state(client, task_id) == "completed") + response = _trajectory(client, {"task_id": task_id, "format": "test-events/1"}) + assert _trajectory(client, {"task_id": task_id}).json()["format"] == "test-events/1" + + assert response.status_code == 400 + assert response.json()["error"]["code"] == "format_not_offered" + assert "lists no formats" in response.json()["error"]["message"] + + +def test_an_unoffered_format_never_reaches_the_agents_own_handlers() -> None: + called: list[str] = [] + + @a2a_agent(identity=_IDENTITY, extensions=(enable(TRAJECTORY_V1, live=True, native="test-events/1"),)) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + return TaskResult.text("done") + + @extension(TRAJECTORY_V1.get.context) + async def context(self, request: ContextTrajectoryRequest) -> dict[str, Any]: + called.append(request.format or "") + return {"trajectory": [], "format": "test-session/1"} + + @extension(TRAJECTORY_V1.get.context_objects) + async def context_objects(self, request: ContextObjectTrajectoryRequest) -> dict[str, Any]: + raise AssertionError("not reached") + + with TestClient(Agent().create_app()) as client: + refused = _trajectory(client, {"context_id": "context-1", "format": "atif/1"}) + served = _trajectory(client, {"context_id": "context-1", "format": "test-events/1"}) + + assert refused.json()["error"]["code"] == "format_not_offered" + assert served.json() == {"trajectory": [], "format": "test-session/1"} + assert called == ["test-events/1"] + + +def test_a_declared_native_format_needs_no_set_format_and_takes_no_other() -> None: + log = TrajectoryLog(native="test-events/1") + log.append({"step": 1}) + log.set_format("test-events/1") + with pytest.raises(ValueError, match="'other/1' is not 'test-events/1', the native format the card declares"): + log.set_format("other/1") + + with TestClient(_native_agent(live=False).create_app()) as client: + task_id = _send(client, "hello", "message-1") + assert _within(5, lambda: _task_state(client, task_id) == "completed") + assert _trajectory(client, {"task_id": task_id}).json()["format"] == "test-events/1" + + +@pytest.mark.parametrize("native", [None, "pi-json-events/v1"]) +def test_a_returned_native_trajectory_keeps_its_format(native: str | None) -> None: + @a2a_agent(identity=_IDENTITY, extensions=(enable(TRAJECTORY_V1, native=native),)) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + return ( + TaskResult.builder() + .succeeded() + .add_text("done") + .native_trajectory(format="pi-json-events/v1", payload=_NATIVE_EVENTS) + .build() + ) + + with TestClient(Agent().create_app()) as client: + task_id = _send(client, "go", "message-1") + assert _within(5, lambda: _task_state(client, task_id) == "completed") + assert _trajectory(client, {"task_id": task_id}).json() == { + "trajectory": _NATIVE_EVENTS, + "format": "pi-json-events/v1", + } + + +def test_a_native_trajectory_in_another_format_fails_the_task(caplog: pytest.LogCaptureFixture) -> None: + @a2a_agent(identity=_IDENTITY, extensions=(enable(TRAJECTORY_V1, native="pi-json-events/v1"),)) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + return ( + TaskResult.builder() + .succeeded() + .add_text("done") + .native_trajectory(format="pi-json-events/v2", payload=_NATIVE_EVENTS) + .build() + ) + + with caplog.at_level(logging.ERROR), TestClient(Agent().create_app()) as client: + task_id = _send(client, "go", "message-1") + assert _within(5, lambda: _task_state(client, task_id) == "failed") + assert _trajectory(client, {"task_id": task_id}).status_code == 404 + + assert "returned a native trajectory in 'pi-json-events/v2', not 'pi-json-events/v1'" in caplog.text + + +def test_an_agent_env_error_from_an_agents_own_handler_answers_its_status_and_body() -> None: + @a2a_agent(identity=_IDENTITY, extensions=(enable(TRAJECTORY_V1, live=True),)) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + return TaskResult.text("done") + + @extension(TRAJECTORY_V1.get.context) + async def context(self, request: ContextTrajectoryRequest) -> dict[str, Any]: + raise AgentEnvError("not_ready", "the session is still starting", retryable=True, status=409) + + @extension(TRAJECTORY_V1.get.context_objects) + async def context_objects(self, request: ContextObjectTrajectoryRequest) -> dict[str, Any]: + raise RuntimeError("boom") + + with TestClient(Agent().create_app()) as client: + typed = _trajectory(client, {"context_id": "context-1"}) + opaque = _trajectory(client, {"context_id": "context-1", "objects": {"trajectory": _grant()}}) + + assert typed.status_code == 409 + assert typed.json() == { + "ok": False, + "error": { + "code": "not_ready", + "message": "the session is still starting", + "retryable": True, + "applied": "no", + }, + } + assert opaque.status_code == 500 + assert "boom" not in opaque.text + diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index 0c1c0f558..a4643c02a 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -134,6 +134,10 @@ every exception. agent-env reads what the agent did, and verifiers grade it. Call `request.trajectory.set_format(...)`, then append each native event as it happens; with `enable(TRAJECTORY_V1, live=True)` it can be read while the turn runs. The SDK serves the reads; bind `get.context` and `get.context_objects` to serve a whole conversation from your own record. +`native=""` in that `enable` declares the format: the card lists it as `formats`, `native` and `default`, +a read naming any other format is refused before your handlers run, and the log and a returned `native_trajectory` +must be in it. It needs a protocol floor that has `native`. A context read you bind names the format it serves as +`format` in its response. Reference: `enable(TRAJECTORY_V1, live=True, ...)`, `ClaudeCodeAgent.run` passing `event_callback=request.trajectory.append`, and `get_context_trajectory` / `upload_context_trajectory`. A runtime diff --git a/tst/unit/a2a_agent/protocol_test.py b/tst/unit/a2a_agent/protocol_test.py index 33548d8c5..6f6f41c19 100644 --- a/tst/unit/a2a_agent/protocol_test.py +++ b/tst/unit/a2a_agent/protocol_test.py @@ -11,6 +11,7 @@ import httpx import pytest +from starlette.testclient import TestClient from agent_env.a2a_agent import protocol from agent_env.a2a_agent.protocol import ( @@ -22,7 +23,16 @@ raise_for_extension_status, wake_poll, ) -from agentenv_protocol.a2a_agent import TaskResult, Usage +from agentenv_protocol.a2a_agent import ( + TRAJECTORY_V1, + AgentEnvAgent, + AgentIdentity, + TaskRequest, + TaskResult, + Usage, + a2a_agent, + enable, +) from agentenv_protocol.a2a_agent.framework import _to_a2a_parts @@ -56,6 +66,29 @@ def test_extension_http_error_names_the_sdk_error_code_only(): assert raised.value.response is response +def test_a_trajectory_read_naming_an_unoffered_format_names_the_sdks_code(): + @a2a_agent( + identity=AgentIdentity(name="formats", description="test", version="1"), + extensions=(enable(TRAJECTORY_V1, native="test-events/1"),), + ) + class Agent(AgentEnvAgent): + async def run(self, request: TaskRequest) -> TaskResult: + return TaskResult.text("done") + + with TestClient(Agent().create_app()) as client: + answer = client.post("/ext/trajectory", json={"task_id": "task-1", "format": "atif/1"}) + response = httpx.Response( + answer.status_code, + content=answer.content, + request=httpx.Request("POST", "https://agent.test/ext/trajectory"), + ) + + with pytest.raises(httpx.HTTPStatusError) as raised: + raise_for_extension_status(response, operation="trajectory read") + + assert str(raised.value) == "trajectory read failed with HTTP 400: format_not_offered" + + def test_extension_http_error_keeps_only_a_code_shaped_error_code(): response = httpx.Response( 502, From 83bde4ed18447e6434257e53f3aace7a85619c64 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 18 Nov 2026 13:29:57 -0800 Subject: [PATCH 2/5] test(protocol): a deployed agent offers its native trajectory format and refuses another The echo agent declares agentenv-echo-agent/v1 as its native format; an integration test deploys it on a local sandbox, runs a turn, and reads its card and trajectory over HTTP: formats, native and default on the card, the format named on cursor and final reads, and a read naming another format refused with format_not_offered, which agent-env's raise_for_extension_status reports. Co-Authored-By: Claude Opus 5.5 --- tst/data/a2a_agent/agent.py | 2 +- ...test_prompt_agent_live_trajectory_local.py | 37 ++++++++++++++++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/tst/data/a2a_agent/agent.py b/tst/data/a2a_agent/agent.py index 612cbf816..847751f7f 100644 --- a/tst/data/a2a_agent/agent.py +++ b/tst/data/a2a_agent/agent.py @@ -168,7 +168,7 @@ def _skills() -> list[str]: version="1.0.0", ), config=EchoAgentConfig, - extensions=(MCP_CONFIG_V1, CDP_CONFIG_V1, enable(TRAJECTORY_V1, live=True), TRIGGERS_V1), + extensions=(MCP_CONFIG_V1, CDP_CONFIG_V1, enable(TRAJECTORY_V1, live=True, native=TRAJECTORY_FORMAT), TRIGGERS_V1), ) class EchoAgent(AgentEnvAgent): async def run(self, request: TaskRequest[EchoAgentConfig]) -> TaskResult: 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 8c1c1ccbf..fa95206d4 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 @@ -2,7 +2,8 @@ defaults. The agents are the echo agent (tst/data/a2a_agent), which appends a step a second before its echo, so a turn runs for a few seconds; over a two-turn conversation with a user-sim, each turn is stored under its own prefix, in more than one chunk, and its chunks join to that turn's final trajectory; each turn names the one after it, and -the last none. Needs Docker and a throwaway local registry.""" +the last none. The echo agent declares its native format, which its card offers and its reads name, and a read +naming another format is refused with a code agent-env reads. Needs Docker and a throwaway local registry.""" import json import re @@ -15,6 +16,8 @@ import httpx import pytest +from agent_env.a2a_agent import A2AAgent +from agent_env.a2a_agent.protocol import raise_for_extension_status from agent_env.artifact.store import reset_artifact_store from agent_env.config import configure, get_config, reset_config, set_image_store from agent_env.store.image_store import LocalRegistryImageStore @@ -129,3 +132,35 @@ async def test_each_turn_is_stored_live_under_its_own_prefix_and_joins_to_its_fi assert json.loads(store.get(store.object_url(f"{live}end.json"))) == {"state": "completed", "next": len(final)} links = [json.loads(store.get(store.object_url(f"{prefix_key}{turn}/live/next.json"))) for turn in turns] assert links == [{"turn": turns[1]}, {"turn": None}] + + +@pytest.mark.asyncio +async def test_a_deployed_agent_serves_its_native_format_and_refuses_another(local_registry): + suffix = uuid.uuid4().hex[:8] + native = "agentenv-echo-agent/v1" + 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}", + ), + ]) + + context = await task.run() + + assert not context.metadata.get("failed_steps"), context.metadata.get("failed_steps") + [deployed] = context.deployed_agents + params = A2AAgent.find_extension(deployed.a2a_card, A2AAgent.EXT_TRAJECTORY)["params"] + assert (params["formats"], params["native"], params["default"]) == ([native], native, native) + url = deployed.a2a_url + params["endpoint"] + async with httpx.AsyncClient(timeout=30, headers=deployed.control_headers) as client: + page = (await client.post(url, json={"context_id": f"formats-{suffix}", "after": 0})).json() + assert page["format"] == native + for named in ({}, {"format": native}): + final = (await client.post(url, json={"task_id": page["task_id"], **named})).json() + assert (final["format"], [event["type"] for event in final["trajectory"]]) == (native, ["echo"]) + refused = await client.post(url, json={"task_id": page["task_id"], "format": "atif/1"}) + with pytest.raises(httpx.HTTPStatusError, match="HTTP 400: format_not_offered"): + raise_for_extension_status(refused, operation="trajectory read") + From 69f6a6a8af03690a597cb8253aed5546039e1f35 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 18 Nov 2026 13:44:39 -0800 Subject: [PATCH 3/5] test(agents): the agents' card and trajectory tests expect the optional format and the served format Claude Code's, Codex's and Gemini's unit tests pinned the trajectory request shape and the bodies of SDK-served reads exactly; the request now lists the optional format, and each read names the agent's TRAJECTORY_FORMAT. The payloads are unchanged. No agent folder changes. Co-Authored-By: Claude Opus 5.5 --- tst/unit/agents/claude_code/test_card_contract.py | 1 + tst/unit/agents/claude_code/test_object_transfer.py | 4 ++-- tst/unit/agents/claude_code/test_partial_trajectory.py | 5 +++-- tst/unit/agents/codex/test_card_contract.py | 1 + tst/unit/agents/codex/test_codex_snapshot_hardening.py | 2 +- tst/unit/agents/codex/test_live_trajectory.py | 4 ++-- tst/unit/agents/codex/test_message_contract.py | 2 +- tst/unit/agents/codex/test_object_transfer.py | 5 +++-- tst/unit/agents/gemini/test_card_contract.py | 1 + tst/unit/agents/gemini/test_message_contract.py | 2 +- tst/unit/agents/gemini/test_object_transfer.py | 9 +++++---- 11 files changed, 21 insertions(+), 15 deletions(-) diff --git a/tst/unit/agents/claude_code/test_card_contract.py b/tst/unit/agents/claude_code/test_card_contract.py index b270f971b..1a7ec6690 100644 --- a/tst/unit/agents/claude_code/test_card_contract.py +++ b/tst/unit/agents/claude_code/test_card_contract.py @@ -77,6 +77,7 @@ def test_the_config_takes_every_field_prompt_agent_sends_that_the_cli_has(app): def test_request_and_response_contracts(app): methods = {uri: ext["params"].get("methods", {}) for uri, ext in _extensions(app).items()} assert methods["urn:agentenv:trajectory/v1"]["get"]["request"] == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, diff --git a/tst/unit/agents/claude_code/test_object_transfer.py b/tst/unit/agents/claude_code/test_object_transfer.py index c1ef005bc..eaadf1168 100644 --- a/tst/unit/agents/claude_code/test_object_transfer.py +++ b/tst/unit/agents/claude_code/test_object_transfer.py @@ -92,8 +92,8 @@ async def _run_claude(**kwargs): body = store.objects["traj/trajectory-t-1.json"] assert body == json.dumps(trajectory, separators=(",", ":")).encode() - assert result == {"objects": {"trajectory": {"size_bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}}} - assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": trajectory} + assert result == {"objects": {"trajectory": {"size_bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}}, "format": a2a_server.TRAJECTORY_FORMAT} + assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": trajectory, "format": a2a_server.TRAJECTORY_FORMAT} def test_a_context_trajectory_is_uploaded_through_its_grant(monkeypatch, tmp_path, agent, client, store): diff --git a/tst/unit/agents/claude_code/test_partial_trajectory.py b/tst/unit/agents/claude_code/test_partial_trajectory.py index fe10a2379..0910bf849 100644 --- a/tst/unit/agents/claude_code/test_partial_trajectory.py +++ b/tst/unit/agents/claude_code/test_partial_trajectory.py @@ -25,6 +25,7 @@ def test_agent_card_advertises_one_get_trajectory_method(app): "get": { "method": "POST", "request": { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, @@ -195,7 +196,7 @@ async def _run_claude(**kwargs): result = client.post(TRAJECTORY_PATH, json={"task_id": task["id"]}).json() live = client.post(TRAJECTORY_PATH, json={"task_id": task["id"], "after": 0}).json() - assert result == {"trajectory": trajectory} + assert result == {"trajectory": trajectory, "format": a2a_server.TRAJECTORY_FORMAT} assert (live["format"], live["state"], live["events"]) == ( a2a_server.TRAJECTORY_FORMAT, "completed", trajectory, ) @@ -292,4 +293,4 @@ async def read(after: int) -> dict: "running", a2a_server.TRAJECTORY_FORMAT, [_INIT], ) assert (ended["events"], ended["next"], ended["has_more"]) == ([_TOOL, _DONE], 3, False) - assert final == {"trajectory": [_INIT, _TOOL, _DONE]} + assert final == {"trajectory": [_INIT, _TOOL, _DONE], "format": a2a_server.TRAJECTORY_FORMAT} diff --git a/tst/unit/agents/codex/test_card_contract.py b/tst/unit/agents/codex/test_card_contract.py index a5c20e216..be78054f6 100644 --- a/tst/unit/agents/codex/test_card_contract.py +++ b/tst/unit/agents/codex/test_card_contract.py @@ -111,6 +111,7 @@ def test_request_and_response_contracts(codex): assert set(config["set"]["request"]["schema"]["properties"]) == set(config["set"]["request"]["supported"]) assert config["get"] == {"method": "GET", "response": {"required": ["config"]}} assert methods["urn:agentenv:trajectory/v1"]["get"]["request"] == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, diff --git a/tst/unit/agents/codex/test_codex_snapshot_hardening.py b/tst/unit/agents/codex/test_codex_snapshot_hardening.py index 8704115d1..27bb57d08 100644 --- a/tst/unit/agents/codex/test_codex_snapshot_hardening.py +++ b/tst/unit/agents/codex/test_codex_snapshot_hardening.py @@ -368,7 +368,7 @@ async def exercise(): task = await codex.send(client, "go", context_id="ctx-task") return await client.post("/ext/trajectory", json={"task_id": task["id"]}) - assert asyncio.run(exercise()).json() == {"trajectory": events} + assert asyncio.run(exercise()).json() == {"trajectory": events, "format": a2a_server.TRAJECTORY_FORMAT} def test_errors_keep_the_json_detail_body(codex): diff --git a/tst/unit/agents/codex/test_live_trajectory.py b/tst/unit/agents/codex/test_live_trajectory.py index f08a06f86..c6bb2a49a 100644 --- a/tst/unit/agents/codex/test_live_trajectory.py +++ b/tst/unit/agents/codex/test_live_trajectory.py @@ -54,7 +54,7 @@ async def read(after: int) -> dict: "running", a2a_server.TRAJECTORY_FORMAT, EVENTS[:1], ) assert (ended["events"], ended["next"], ended["has_more"]) == (EVENTS[1:], 3, False) - assert final == {"trajectory": EVENTS} + assert final == {"trajectory": EVENTS, "format": a2a_server.TRAJECTORY_FORMAT} def test_a_turn_ends_its_trajectory_with_the_usage_and_model_requests_the_events_omit(codex, monkeypatch): @@ -113,4 +113,4 @@ async def read() -> dict: canceled, final = asyncio.run(exercise()) assert canceled["events"] == EVENTS[:1] - assert final == {"trajectory": EVENTS[:1]} + assert final == {"trajectory": EVENTS[:1], "format": a2a_server.TRAJECTORY_FORMAT} diff --git a/tst/unit/agents/codex/test_message_contract.py b/tst/unit/agents/codex/test_message_contract.py index add886bb4..cbdeda03f 100644 --- a/tst/unit/agents/codex/test_message_contract.py +++ b/tst/unit/agents/codex/test_message_contract.py @@ -103,7 +103,7 @@ async def exercise(): "error_code": "infra_error", "error_message": "codex CLI event limit exceeded", } - assert trajectory.json() == {"trajectory": [{"type": "thread.started", "thread_id": "tid-raise"}]} + assert trajectory.json() == {"trajectory": [{"type": "thread.started", "thread_id": "tid-raise"}], "format": a2a_server.TRAJECTORY_FORMAT} assert codex.agent.session_ref_for_context("ctx-raise") == "tid-raise" diff --git a/tst/unit/agents/codex/test_object_transfer.py b/tst/unit/agents/codex/test_object_transfer.py index e7aa971cf..ed6889118 100644 --- a/tst/unit/agents/codex/test_object_transfer.py +++ b/tst/unit/agents/codex/test_object_transfer.py @@ -109,6 +109,7 @@ def test_card_offers_only_the_object_forms(codex): } trajectory = _methods(codex, "urn:agentenv:trajectory/v1")["get"]["request"] assert trajectory == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, @@ -235,9 +236,9 @@ async def exercise(): inline, granted, again = asyncio.run(exercise()) body = store.objects["traj/trajectory.json"] - assert inline == again == {"trajectory": events} + assert inline == again == {"trajectory": events, "format": a2a_server.TRAJECTORY_FORMAT} assert body == json.dumps(events, separators=(",", ":")).encode() - assert granted == {"objects": {"trajectory": {"size_bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}}} + assert granted == {"objects": {"trajectory": {"size_bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}}, "format": a2a_server.TRAJECTORY_FORMAT} @pytest.mark.parametrize("live", [True, False]) diff --git a/tst/unit/agents/gemini/test_card_contract.py b/tst/unit/agents/gemini/test_card_contract.py index 0202ac504..510fcc4b7 100644 --- a/tst/unit/agents/gemini/test_card_contract.py +++ b/tst/unit/agents/gemini/test_card_contract.py @@ -131,6 +131,7 @@ def test_request_and_response_contracts(app): assert set(config["set"]["request"]["schema"]["properties"]) == set(config["set"]["request"]["supported"]) assert config["get"] == {"method": "GET", "response": {"required": ["config"]}} assert methods["urn:agentenv:trajectory/v1"]["get"]["request"] == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, diff --git a/tst/unit/agents/gemini/test_message_contract.py b/tst/unit/agents/gemini/test_message_contract.py index 4a20d6cb3..837873774 100644 --- a/tst/unit/agents/gemini/test_message_contract.py +++ b/tst/unit/agents/gemini/test_message_contract.py @@ -202,7 +202,7 @@ def test_a_turn_keeps_its_trajectory_failed_or_not(calls, client): task = send(client, "go") - assert client.post(TRAJECTORY_PATH, json={"task_id": task["id"]}).json() == {"trajectory": trajectory} + assert client.post(TRAJECTORY_PATH, json={"task_id": task["id"]}).json() == {"trajectory": trajectory, "format": a2a_server.TRAJECTORY_FORMAT} # ── the CLI invocation itself ──────────────────────────────────────────────────── diff --git a/tst/unit/agents/gemini/test_object_transfer.py b/tst/unit/agents/gemini/test_object_transfer.py index 2ba04af20..22192b7df 100644 --- a/tst/unit/agents/gemini/test_object_transfer.py +++ b/tst/unit/agents/gemini/test_object_transfer.py @@ -55,6 +55,7 @@ def test_card_offers_every_object_form_and_no_s3_form(app): "oneOf": [{"required": ["skill_md"]}, {"required": ["skill_bundle"]}], } assert extension_methods(app, a2a_server.TRAJECTORY_V1.uri)["get"]["request"] == { + "optional": ["format"], "oneOf": [ {"required": ["task_id"]}, {"required": ["task_id", "objects"]}, @@ -145,7 +146,7 @@ async def _run_gemini(**kwargs): monkeypatch.setattr(a2a_server, "run_gemini", _run_gemini) task_id = send(client, "go")["id"] - assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": trajectory} + assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": trajectory, "format": a2a_server.TRAJECTORY_FORMAT} granted = client.post( TRAJECTORY_PATH, @@ -153,10 +154,10 @@ async def _run_gemini(**kwargs): ).json() body = store.objects["traj/trajectory-t-1.json"] assert body == json.dumps(trajectory, separators=(",", ":")).encode() - assert granted == {"objects": {"trajectory": {"size_bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}}} + assert granted == {"objects": {"trajectory": {"size_bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}}, "format": a2a_server.TRAJECTORY_FORMAT} assert store.requests[-1].headers["content-type"] == "application/json" # The object form does not consume the trajectory: a later read of the same task still answers. - assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": trajectory} + assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": trajectory, "format": a2a_server.TRAJECTORY_FORMAT} # ── snapshot ───────────────────────────────────────────────────────────────────── @@ -484,4 +485,4 @@ async def _run_gemini(**kwargs): assert response.status_code == 502 assert response.json()["error"]["code"] == "transfer_rejected" assert "sig=" not in response.text and "trajectory-t-1" not in response.text - assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": [{"type": "message"}]} + assert client.post(TRAJECTORY_PATH, json={"task_id": task_id}).json() == {"trajectory": [{"type": "message"}], "format": a2a_server.TRAJECTORY_FORMAT} From d4b6695848183c01fede81b187234fdbf8523079 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 18 Nov 2026 13:44:59 -0800 Subject: [PATCH 4/5] refactor(protocol): one named limit for a trajectory format id's length Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/a2a_agent/extensions.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index 09776d1e2..0f5463d33 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -150,8 +150,9 @@ class SkillAddResponse(ExtensionResponse): name: str +MAX_TRAJECTORY_FORMAT_LENGTH = 128 #: A trajectory format id a read may name, such as ``my-cli-events/1``; the card's trajectory ``formats`` lists them. -TrajectoryFormat = Annotated[str, Field(min_length=1, max_length=128)] +TrajectoryFormat = Annotated[str, Field(min_length=1, max_length=MAX_TRAJECTORY_FORMAT_LENGTH)] class TaskTrajectoryRequest(ExtensionRequest): @@ -1111,8 +1112,8 @@ def _configure_trajectory(*, live: bool = False, native: str | None = None) -> E raise TypeError("live must be a boolean") if native is not None and not isinstance(native, str): raise TypeError("native must be a format id string") - if native is not None and (not native.strip() or len(native) > 128): - raise ValueError("native must be a format id of 1 to 128 characters") + if native is not None and (not native.strip() or len(native) > MAX_TRAJECTORY_FORMAT_LENGTH): + raise ValueError(f"native must be a format id of 1 to {MAX_TRAJECTORY_FORMAT_LENGTH} characters") return ExtensionConfiguration( wire_params={"formats": [native], "native": native, "default": native} if native else {}, options={"native": native} if native else {}, From 7e38921e346b0bb6f349d091a6cbb76a60060673 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Wed, 18 Nov 2026 14:40:16 -0800 Subject: [PATCH 5/5] fix(protocol): a trajectory format mismatch fails the turn as the agent's error, and the objects answer's model names its format With a native format declared, a set_format or returned native trajectory in another format raised past the agent and ended the turn as framework.unhandled_exception, an infra_error a retry repeats. It now fails the turn as an agent_error with code framework.trajectory_format_mismatch, its message naming both formats. The rule lives in the log alone: set_format and the executor's check of a returned native trajectory share it, and the seal no longer repeats it. TrajectoryObjectsResponse gains format and builds the SDK's objects answer, so the published model matches the wire; a request's format refuses a blank id, as native and set_format do; the byte-identity test reuses _grant(). Co-Authored-By: Claude Opus 5.5 --- packages/agentenv-protocol/README.md | 5 ++- .../a2a_agent/_trajectory_log.py | 8 +--- .../agentenv_protocol/a2a_agent/extensions.py | 3 +- .../agentenv_protocol/a2a_agent/framework.py | 13 ++++--- .../agentenv_protocol/a2a_agent/tasks/v1.py | 16 +++++--- .../tests/test_a2a_object_transfers.py | 2 +- .../tests/test_a2a_trajectory_log.py | 38 +++++++++++-------- 7 files changed, 48 insertions(+), 37 deletions(-) diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 5d1f1baaa..c821ea5e3 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -1549,8 +1549,9 @@ The card then lists three fields in the trajectory extension's `params`, beside A card without `formats` predates them, so send its reads no `format`. With `native` declared, the log starts in that format and `set_format` is optional. -`set_format` with another format raises `ValueError`, and a task that returns a -`native_trajectory` in another format fails. +A `set_format` or a returned `native_trajectory` in another format fails the +turn as an `agent_error` with code `framework.trajectory_format_mismatch`, whose +message names both formats. Every trajectory read takes an optional `format`. A read naming none gets the default. A read naming a format the card doesn't list is HTTP 400 with the error diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py index 731b8ca8a..05a75e757 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/_trajectory_log.py @@ -104,16 +104,10 @@ def seal( native: bytes | None = None, native_format: str | None = None, ) -> None: - """End the task's trajectory; the first seal wins. A native trajectory in a format - other than the card's native one is refused before anything is recorded.""" + """End the task's trajectory; the first seal wins.""" record = self._tasks[task_id] if record.final_state is not None: return - if native is not None and self._native is not None and native_format != self._native: - raise ValueError( - f"task {task_id} returned a native trajectory in {native_format!r}, " - f"not {self._native!r}, the native format the card declares" - ) if native is not None: if len(record.log): logger.warning( diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py index 0f5463d33..eac35f346 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/extensions.py @@ -152,7 +152,7 @@ class SkillAddResponse(ExtensionResponse): MAX_TRAJECTORY_FORMAT_LENGTH = 128 #: A trajectory format id a read may name, such as ``my-cli-events/1``; the card's trajectory ``formats`` lists them. -TrajectoryFormat = Annotated[str, Field(min_length=1, max_length=MAX_TRAJECTORY_FORMAT_LENGTH)] +TrajectoryFormat = Annotated[str, Field(min_length=1, max_length=MAX_TRAJECTORY_FORMAT_LENGTH, pattern=r"\S")] class TaskTrajectoryRequest(ExtensionRequest): @@ -193,6 +193,7 @@ class TrajectoryUploadedObjects(ExtensionResponse): class TrajectoryObjectsResponse(ExtensionResponse): objects: TrajectoryUploadedObjects + format: str | None = None class TrajectoryState(str, Enum): diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index 40d2b6efa..1906e8c6a 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -57,7 +57,9 @@ TaskObjectTrajectoryRequest, TaskTrajectoryRequest, TrajectoryEventsResponse, + TrajectoryObjectsResponse, TrajectoryState, + TrajectoryUploadedObjects, TriggerDecideRequest, TriggerRegisterRequest, enable, @@ -839,12 +841,9 @@ async def trajectory_get( if isinstance(request, (TaskTrajectoryRequest, ContextTrajectoryRequest)): return {"trajectory": json.loads(trajectory.body), "format": trajectory.format} uploaded = await upload(request.objects.trajectory, trajectory.body) - return { - "objects": { - "trajectory": uploaded.model_dump(mode="json"), - }, - "format": trajectory.format, - } + return TrajectoryObjectsResponse( + objects=TrajectoryUploadedObjects(trajectory=uploaded), format=trajectory.format + ) def check_trajectory_format(self, format: str | None) -> None: """Refuse a trajectory read naming a format the card doesn't offer, before any handler @@ -1365,6 +1364,8 @@ async def execute(self, context: Any, event_queue: Any) -> None: result = await self._run_streaming(request, updater, event_queue) else: result = await self._handler(request) + if isinstance(result, TaskResult) and result.native_trajectory is not None: + trajectory._hold_to_native(result.native_trajectory.format) except _TaskFailed as failed: result = TaskResult.failure( failed.error.code, failed.error.message, error_type=failed.error.error_type diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py index 4f820268d..0634de182 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py @@ -156,7 +156,7 @@ class TrajectoryLog: Each event is serialized as it is appended, so an event once read never changes; append from one thread at a time. Unless the result carries a ``native_trajectory``, the log is the task's final trajectory. An agent whose card declares a ``native`` format starts with - that format, and no other may be set.""" + that format, and setting or returning another fails the turn.""" __slots__ = ("_events", "_size_bytes", "_format", "_native", "_sealed", "_task_id", "_warned") @@ -178,10 +178,7 @@ def set_format(self, format: str) -> None: appended, it stays.""" if not isinstance(format, str) or not format.strip(): raise ValueError("trajectory format must be a non-empty string") - if self._native is not None and format != self._native: - raise ValueError( - f"trajectory format {format!r} is not {self._native!r}, the native format the card declares" - ) + self._hold_to_native(format) self._ensure_open() if self._events and format != self._format: raise RuntimeError("the trajectory's format cannot change once events are appended") @@ -209,6 +206,15 @@ def append(self, event: Mapping[str, Any]) -> None: def __len__(self) -> int: return len(self._events) + def _hold_to_native(self, format: str) -> None: + """Fail the turn as the agent's error when ``format``, set or returned, isn't the native + format the card declares; a retry would fail the same way.""" + if self._native is not None and format != self._native: + raise _TaskFailed( + "framework.trajectory_format_mismatch", + f"the trajectory format {format!r} is not {self._native!r}, the native format the card declares", + ) + def _ensure_open(self) -> None: if self._sealed: raise RuntimeError("the task has ended; its trajectory can no longer change") diff --git a/packages/agentenv-protocol/tests/test_a2a_object_transfers.py b/packages/agentenv-protocol/tests/test_a2a_object_transfers.py index 7b7acae99..daa500d7c 100644 --- a/packages/agentenv-protocol/tests/test_a2a_object_transfers.py +++ b/packages/agentenv-protocol/tests/test_a2a_object_transfers.py @@ -566,7 +566,7 @@ def handle(request: httpx.Request) -> httpx.Response: ) ) - assert result == { + assert result.model_dump(mode="json") == { "objects": { "trajectory": { "size_bytes": 19, diff --git a/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py b/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py index 1e1e21716..3cffa9099 100644 --- a/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py +++ b/packages/agentenv-protocol/tests/test_a2a_trajectory_log.py @@ -615,17 +615,7 @@ async def capture_upload(_target, body: bytes): return Uploaded(size_bytes=len(body)) monkeypatch.setattr(framework, "upload", capture_upload) - grant = { - "media_type": "application/json", - "max_bytes": 1_000_000, - "write": { - "kind": "http-put", - "url": "https://objects.example.test/write", - "expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)) - .isoformat(timespec="seconds") - .replace("+00:00", "Z"), - }, - } + grant = _grant() inline: list[Any] = [] for agent in (Native(), Live()): with TestClient(agent.create_app()) as client: @@ -790,7 +780,7 @@ def test_a_declared_native_format_needs_no_set_format_and_takes_no_other() -> No log = TrajectoryLog(native="test-events/1") log.append({"step": 1}) log.set_format("test-events/1") - with pytest.raises(ValueError, match="'other/1' is not 'test-events/1', the native format the card declares"): + with pytest.raises(tasks_v1._TaskFailed, match="'other/1' is not 'test-events/1', the native format the card declares"): log.set_format("other/1") with TestClient(_native_agent(live=False).create_app()) as client: @@ -821,10 +811,22 @@ async def run(self, request: TaskRequest) -> TaskResult: } -def test_a_native_trajectory_in_another_format_fails_the_task(caplog: pytest.LogCaptureFixture) -> None: +def _task_error(client: TestClient, task_id: str) -> dict[str, Any]: + response = client.post( + "/a2a", + json={"jsonrpc": "2.0", "id": "get", "method": "tasks/get", "params": {"id": task_id}}, + ) + parts = response.json()["result"]["status"]["message"]["parts"] + return next(part["data"] for part in parts if part["kind"] == "data") + + +@pytest.mark.parametrize("breaks", ["set_format", "native_trajectory"]) +def test_a_trajectory_in_another_format_fails_the_turn_as_the_agents_error(breaks: str) -> None: @a2a_agent(identity=_IDENTITY, extensions=(enable(TRAJECTORY_V1, native="pi-json-events/v1"),)) class Agent(AgentEnvAgent): async def run(self, request: TaskRequest) -> TaskResult: + if breaks == "set_format": + request.trajectory.set_format("pi-json-events/v2") return ( TaskResult.builder() .succeeded() @@ -833,12 +835,18 @@ async def run(self, request: TaskRequest) -> TaskResult: .build() ) - with caplog.at_level(logging.ERROR), TestClient(Agent().create_app()) as client: + with TestClient(Agent().create_app()) as client: task_id = _send(client, "go", "message-1") assert _within(5, lambda: _task_state(client, task_id) == "failed") assert _trajectory(client, {"task_id": task_id}).status_code == 404 + error = _task_error(client, task_id) - assert "returned a native trajectory in 'pi-json-events/v2', not 'pi-json-events/v1'" in caplog.text + assert error == { + "error_type": "agent_error", + "error_code": "framework.trajectory_format_mismatch", + "error_message": "the trajectory format 'pi-json-events/v2' is not 'pi-json-events/v1', " + "the native format the card declares", + } def test_an_agent_env_error_from_an_agents_own_handler_answers_its_status_and_body() -> None: