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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 41 additions & 5 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1532,6 +1532,39 @@ 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.
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
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
Expand All @@ -1552,8 +1585,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
Expand Down Expand Up @@ -1882,9 +1918,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}` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -48,18 +57,19 @@ 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()

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)
Expand Down Expand Up @@ -87,7 +97,12 @@ 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."""
record = self._tasks[task_id]
Expand All @@ -101,29 +116,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
Expand Down Expand Up @@ -186,10 +206,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),
)
Expand Down Expand Up @@ -219,6 +236,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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,19 @@ 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=MAX_TRAJECTORY_FORMAT_LENGTH, pattern=r"\S")]


class TaskTrajectoryRequest(ExtensionRequest):
task_id: str
format: TrajectoryFormat | None = None


class ContextTrajectoryRequest(ExtensionRequest):
context_id: str
format: TrajectoryFormat | None = None


class TrajectoryWriteObjects(ExtensionRequest):
Expand All @@ -171,11 +178,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):
Expand All @@ -184,6 +193,7 @@ class TrajectoryUploadedObjects(ExtensionResponse):

class TrajectoryObjectsResponse(ExtensionResponse):
objects: TrajectoryUploadedObjects
format: str | None = None


class TrajectoryState(str, Enum):
Expand All @@ -204,12 +214,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):
Expand Down Expand Up @@ -1092,15 +1104,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) > MAX_TRAJECTORY_FORMAT_LENGTH):
raise ValueError(f"native must be a format id of 1 to {MAX_TRAJECTORY_FORMAT_LENGTH} 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 {}
),
)


Expand Down
Loading
Loading