## Agent sessions — multi-turn tool-using runs

*Executa · reverse RPC (v2.1+) · Agent sessions*

Drive **stateful, tool-using Anna Agent sessions** from a stdio Executa plugin through reverse JSON-RPC — the same surface area an in-iframe `anna-app` gets, with the same auth boundaries, the same tool model, and the same wire frames. Builds on top of sampling: sampling is single-turn; agent sessions are stateful, support tool calls the host runs, emit streaming frames (`delta`, `tool_call`, `tool_result`, `final`), and support cancellation.

**Pre-requisites.** v2 negotiation only. The per-invoke `sampling_token` (minted for every installed, enabled Executa) unlocks both `agent/complete` (L1 single-turn) and `agent/session.*` (L2 multi-turn) — nothing to declare, no user toggle.

**Auth chain.** The plugin **never holds a bearer token**. Matrix host owns the secret: the plugin sends `agent/session.create` carrying the per-invoke `sampling_token`; the host mints an `app_session_token` via Nexus `POST /copilot/app/sessions/from_sampling`, caches it keyed by `(user_id, hash(plugin_name))`, and attaches it to outbound HTTP for every `run|cancel|delete`. The token is never returned to the plugin.

**Plugin/anna-app symmetry.** A Python plugin and a TypeScript anna-app should be **drop-in interchangeable** for the same agent workload. The only difference is transport: anna-app uses a postMessage channel, plugin uses stdio JSON-RPC.

**v2 limitations.** `agent/session.run` returns the whole turn in one response once it ends; with `stream: true` the host also pushes each frame live as an `agent/session.frame` notification (best-effort — the response stays authoritative). Hard cap: **4,096 frames per run** → `-32045 QUOTA_EXCEEDED`. `agent/session.history` returns `[]` until a public GET endpoint lands.

### Agent sessions (v2.1)

- **agent/complete** — L1 one-shot completion via Anna server's `POST /copilot/app/complete`. Sugar for plugins that don't need state.  `stateless`

- **agent/session.create** — Open a stateful, tool-using agent session bound to the calling user. Identity (`user_id`, `executa_id`) is derived from the sampling_token — the plugin cannot override it.  `stateful`

- **agent/session.run** — Submit a turn; the response carries the full ordered frames (`delta`, `tool_call`, `tool_result`, `final`), and with `stream: true` each frame is also pushed live as an `agent/session.frame` notification. 4,096-frame cap per run.  `live frames`

- **agent/session.history** — Read prior turns of a session. Returns `[]` until the upstream GET endpoint lands.

- **agent/session.cancel** — Abort an in-flight `run_id` on the upstream session.

- **agent/session.delete** — Idempotent teardown; drops the cached `app_session_token` and tells Nexus to delete the session.

- **agent/session.catalog** — Which platform tools a session created right now would resolve — the reverse-RPC twin of the iframe `agent.session.catalog`. Mints no session, consumes no quota.  `read-only`

---

## Detailed reference

### agent/session.create

*Reverse RPC method · Agent*

Open a stateful, tool-using agent session bound to the calling user. Validates `agent_submode` ∈ {auto, fixed}; `fixed_client_id` is required when `agent_submode='fixed'`. For one-shot completion use `agent/complete` instead. Identity (`user_id`, `executa_id`) is derived from the sampling_token claims — the plugin cannot override it.

**Signature**

```ts
session_create(*, agent_submode: Literal['auto','fixed'] = 'auto', fixed_client_id: str | None = None, label: str | None = None, quota_caps: dict | None = None, ttl_seconds: int = 600) -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

**Parameters**

- `agent_submode` (Literal['auto','fixed'], optional) — Multi-turn agent mode. `auto` rotates `client_id` per turn; `fixed` pins one.
    - `auto` is the recommended default for most plugins.
    - `fixed` additionally requires `fixed_client_id`, which must be one of the current user's registered Agent clients; otherwise Anna server returns `-32004 invalid request`.
- `fixed_client_id` (str | None, optional) — Pin one `client_id` for the whole session.
    - Only meaningful when `agent_submode='fixed'`.
    - Under `submode='auto'` it is silently stored on the session row but has no runtime effect.
    - Must belong to the current user (registered Agent client) or the call is rejected; an offline client is accepted with a warning.
- `label` (str | None, optional) — Human-readable label shown in the user's session console.
    - Max 120 chars; longer values are rejected at the Anna server pydantic boundary (HTTP 422).
    - When omitted, Anna agent substitutes the plugin display name from `ctx.plugin_name`.
- `quota_caps` (dict | None, optional) — Per-session quota / tool-scope override.
    - **The tool surface follows the App hosting the invoke.** In the conversation the default when omitted is `inherit_host_tools=True`: the session inherits the conversation's full tool kit (`granted_tools` returns `['*']`). Inside an App the session gets that App's surface instead — server-side tools plus the host-kit tools declared in the App manifest's `ui.host_api.agent.tools` — and never inherits; requesting `inherit_host_tools: True` there is ignored and reported as an `INHERIT_IGNORED` warning in `run_meta`.
    - To restrict tools (lean sandbox session), pass an explicit dict, e.g. `{"inherit_host_tools": False, "allowed_tools": ["tool_a", "tool_b"]}`. Declaration-is-consent: in the conversation the effective surface is `platform registry ∩ the executa manifest's agent_tools declaration (`["*"]` = full registry) ∩ allowed_tools` — an executa with no `agent_tools` declaration resolves ZERO sandbox tools; inside an App the hosting App's declaration takes the executa declaration's place.
    - The effective value is reflected back in `granted_tools` on the response.
- `ttl_seconds` (int, optional) — Session-token lifetime in seconds; Anna agent caches the bearer for this duration.
    - Bounded by `0 < ttl_seconds ≤ MAX_APP_SESSION_TTL_SECONDS` (7200).
    - Anna server pydantic rejects out-of-range with HTTP 422; bridge has no local validation, so the failure surfaces as `AGENT_ERR_PROVIDER_ERROR` (-32046) (the generic `Exception` arm in `_session_create`), **not** `AGENT_ERR_INVALID_REQUEST`.

### agent/session.run

*Reverse RPC method · Agent*

Submit one turn on an existing agent session. The Anna agent consumes the upstream SSE stream from Anna server `/copilot/app/agent`, tags every frame with `seq` + `stream_id`, and returns the full ordered `frames` array in a single JSON-RPC response. With `stream: true` it additionally pushes every frame to the plugin **while the run is in flight** as an `agent/session.frame` notification; the response stays complete and authoritative either way. Hard-capped at `_MAX_FRAMES_PER_RUN = 4096` frames per run; exceeding the cap aborts with `AGENT_ERR_PROVIDER_ERROR` (-32046).

**Signature**

```ts
session_run(*, app_session_uuid: str, content: str, attachments: list[dict] | None = None, recursion_limit: int = 8, run_id: str | None = None, stream: bool = False, allowed_tools: list[str] | None = None, modelPreferences: dict | None = None, system: str | None = None) -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

**Parameters**

- `app_session_uuid` (str, required) — The session handle returned by `agent/session.create`.
    - Must start with `aps_`.
    - The Anna agent looks up the cached `app_session_token` by `(uuid, owner)`; if missing or expired → `AGENT_ERR_SESSION_NOT_FOUND` (-32042).
- `content` (str, required) — Turn content (user / plugin input).
    - Validated as a non-empty string; whitespace-only is rejected with `AGENT_ERR_INVALID_REQUEST` (-32043).
- `attachments` (list[dict] | None, optional) — Optional attachments forwarded verbatim to Anna server.
    - The Anna agent does not parse or validate the payload — shape is whatever Anna server `/copilot/app/agent` currently accepts.
- `recursion_limit` (int, optional) — Max agent tool-call depth for this turn.
    - The Anna agent does not range-check the value; it is forwarded as-is.
    - Anna server pydantic enforces `1 ≤ recursion_limit ≤ 32` (`Field(ge=1, le=32)`). Out-of-range values → HTTP 422, surfaced as `AGENT_ERR_PROVIDER_ERROR` (-32046), **not** `AGENT_ERR_INVALID_REQUEST`.
- `run_id` (str | None, optional) — Idempotency / correlation id for `session.cancel`.
    - Auto-generated as `run_{16hex}` when omitted.
    - Echoed back in the response and required by `agent/session.cancel`.
    - **Required with `stream: true`** — it is the only key that ties `agent/session.frame` notifications to the run before the response arrives (the Python SDK generates one for you).
- `stream` (bool, optional) — `true` = also deliver frames live as `agent/session.frame` notifications.
    - Notification shape (host → plugin, no `id`): `{"jsonrpc":"2.0","method":"agent/session.frame","params":{"run_id","seq","frame"}}`. `seq` starts at 0 and always equals the frame's index in the response `frames`; `frame` is identical to `frames[seq]`.
    - Best-effort and never blocking: the host stops pushing for this run the first time a frame cannot be written (plugin stdin backlog above 1 MiB, or stdin closed). What was pushed is always a contiguous prefix `seq = 0..k`; the remaining frames arrive with the response.
    - All live notifications of a run are written before its response. The synthesized `final` frame is not pushed live — it arrives with the response.
    - Hosts that predate this field ignore it and answer with the buffered response only, so no capability negotiation is needed.
- `allowed_tools` (list[str] | None, optional) — Per-turn tool whitelist; overrides the session-level `quota_caps.allowed_tools` for this run only.
    - Forwarded verbatim to Anna server as the `allowed_tools` field.
    - Anna server intersects this with the session's effective tool set; tools outside it are silently dropped.
    - Pass `[]` to disable all tools for this turn (pure LLM reply).
- `modelPreferences` (dict | None, optional) — MCP-style model hint, e.g. `{"hints": [{"name": "gpt-4o"}], "costPriority": 0.2}`.
    - Camel-case to match the MCP wire spec and Anna server's `_AgentRunBody.modelPreferences` field.
    - Snake-case alias `model_preferences` is also accepted by the bridge and rewritten on the way out.
    - Anna server may ignore hints that fall outside the user's enabled model set.
- `system` (str | None, optional) — Per-turn system prompt override; prepended to the turn on Anna server.
    - Forwarded verbatim as the `system` field on the REST body.
    - Does not mutate session state — next turn falls back to the session default unless re-supplied.

### agent/session.cancel

*Reverse RPC method · Agent*

Cancel an in-flight `session.run`. Best-effort; the upstream may still emit a final frame.

**Signature**

```ts
session_cancel(*, app_session_uuid: str, run_id: str) -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

**Parameters**

- `app_session_uuid` (str, required)
- `run_id` (str, required) — The `run_id` returned by (or passed into) `session.run`.

### agent/session.history

*Reverse RPC method · Agent*

Read the persisted transcript of an agent session as MCP-shaped messages. Backed by the LangGraph checkpoint that `session.run` writes into; safe to poll, idempotent, and never mutates state. Use this to rehydrate UI after a plugin restart, sync across devices, or audit a completed conversation.

**Signature**

```ts
session_history(*, app_session_uuid: str, limit: int = 50, cursor: str | None = None) -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

**Parameters**

- `app_session_uuid` (str, required) — The session uuid to read; must match the cached token entry.
- `limit` (int, optional) — Page size; out-of-range values are rejected.
    - Bridge-side range check (`agent.py:_session_history`): values outside `[1, 200]` raise `AGENT_ERR_INVALID_REQUEST` (-32043) — the bridge does **not** clamp silently. Anna server applies the same `[1, 200]` clamp on its side as defense in depth.
    - Counts raw checkpoint messages, not turn pairs — a single user turn that triggered N tool calls contributes `1 + 2N` entries.
- `cursor` (str | None, optional) — Opaque pagination token returned by the previous page's `next_cursor`.
    - First call: pass `None` (or omit).
    - Round-trip the value verbatim; do not parse or mutate it — the format is intentionally opaque and may switch from offset-based to time-based without protocol churn.
    - Passing a malformed cursor raises `AGENT_ERR_INVALID_REQUEST`.

### agent/session.delete

*Reverse RPC method · Agent*

Drop the session and its history. **Idempotent** — calling on an unknown or already-deleted uuid still resolves successfully. The bridge always evicts the cached token before returning, so a follow-up `session.run` against the same uuid will fail with `AGENT_ERR_SESSION_NOT_FOUND`.

**Signature**

```ts
session_delete(*, app_session_uuid: str) -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

**Parameters**

- `app_session_uuid` (str, required) — The session uuid to drop; must start with `aps_`.

### agent/session.catalog

*Reverse RPC method · Agent*

Discover which platform tools a session created by this plugin **right now** would resolve — the reverse-RPC twin of the iframe `agent.session.catalog`. The tool surface follows the App hosting the invoke: inside an App it is that App's manifest declaration; in the conversation it is the plugin's own `agent_tools` declaration plus the conversation's tool kit. Read-only — mints no session, consumes no quota.

**Signature**

```ts
session_catalog() -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

### agent/complete

*Reverse RPC method · Agent*

L1 one-shot completion via Anna server's `POST /copilot/app/complete`. The bridge transparently mints a throw-away app session under the `sampling_token` (ttl 120s), issues the request, then deletes the session in a `finally` block — plugins never see the underlying token. **Not** sugar over `sampling/createMessage` (that path runs through the host's own model); this hits the user's Anna server. **Note:** the backing session is minted with `kind='agent'` (not `kind='complete'`) and used purely as transport — Anna server's `/copilot/app/complete` endpoint accepts any agent-kind app-session token, and the same MCP completion shape is returned. Behaviour matches the `anna-app` SDK's `llm.complete`; callers wanting a strict `kind='complete'` session row must issue `session.create({kind: 'complete'})` + the HTTP `/copilot/app/complete` path manually. Use this when you only need a single model reply with no tools and no multi-turn history; for stateful tool-using runs use `session.create` + `session.run`.

**Signature**

```ts
complete(*, messages: list[dict], maxTokens: int | None = None, modelPreferences: dict | None = None, systemPrompt: str | None = None, temperature: float | None = None, stopSequences: list[str] | None = None, metadata: dict | None = None) -> dict
```

**Direction:** Plugin → Anna agent → Anna server /copilot/app/*

**Parameters**

- `messages` (list[dict], required) — Non-empty array of MCP-shaped messages (`{role, content}`).
    - Validated bridge-side: must be a list with at least one entry.
    - `content` accepts a string, a single MCP block, or a block array — same contract as the iframe `llm.complete`: `{type:'text', text}` and `{type:'image', data:'<raw base64 or data: URI>', mimeType}` / `{type:'image', url}` blocks are supported. Images require a vision-capable resolved model (`APP_MODEL_NOT_VISION_CAPABLE` otherwise) and are only allowed in `user` messages.
- `maxTokens` (int | None, optional) — Hard cap on response tokens; must be `> 0` when supplied.
- `modelPreferences` (dict | None, optional) — MCP-style model hint, e.g. `{"hints": [{"name": "gpt-4o"}], "costPriority": 0.2}`.
    - Camel-case to match the MCP wire spec and Anna server's `_CompleteBody.modelPreferences` field.
    - Anna server may ignore hints that fall outside the user's enabled model set.
- `systemPrompt` (str | None, optional) — System prompt prepended on Anna server for this single call.
- `temperature` (float | None, optional) — Sampling temperature; passes through unchanged.
- `stopSequences` (list[str] | None, optional) — Stop strings forwarded to the upstream model.
- `metadata` (dict | None, optional) — Opaque metadata echoed in audit logs; not interpreted by the model.
