# Agent Bridge protocol

Status: **implemented** (Phase B, backend; `590b515`). Version `1`.
Every route, body and answer: [Agent Bridge routes](bridge-routes.md).
The interface (Agent page and panel): Phase C, [Design: Agent workspace](../design/agent-workspace.md).

All routes live under `/api/v1/bridge`. JSON everywhere; times are ISO
8601 UTC. Request bodies ignore unknown fields, including any `sender`,
`actor` or `created_by`: identity always comes from the credential.

## Who is calling

| Request | Principal |
|---|---|
| `Authorization: Bearer phm_pat_…` | The token's agent. The token is verified on every request (revocation applies to the next one). `X-Phantom-Agent: agt_…` (the `agent_id` hello returned) picks the token's agent; it must belong to the token (`403`). Without it, the token's agent seen most recently. |
| No `Authorization` | The user of the interface, under the loopback trust boundary of the whole REST API ([Agent authentication](authentication.md#remaining-trust-boundary)). |

Agents need the `bridge` grant for the action and the vault of the object:

| Action | Operations |
|---|---|
| `bridge.read` | hello, list and read conversations, messages, tasks, approvals; events; workspace context |
| `bridge.create` | open conversations, send messages and stream them, create tasks, request approvals |
| `bridge.update` | acknowledge or fail messages, claim a task and report on it under its lease |

An agent only sees conversations it takes part in and tasks assigned to
it (or unassigned) in its vaults; anything else answers `404 not_found`,
exactly like an id that does not exist. **User only**: rename, pin,
archive and context sharing of a conversation, retrying a failed message,
pausing and resuming tasks, deciding approvals (`403 permission_denied`,
`details.reason = user_only`). **Agent only**: hello, claim, progress,
complete, fail, approval requests (`details.reason = agent_identity`).
The development MCP mode does not apply to the Bridge.

## Handshake

`POST /bridge/hello` with `{"protocol": "1", "client": {"name", "version"},
"capabilities": [...]}` registers the agent of this token and client name
(`connection_type: bridge`, `protocol_version: bridge/1`, capabilities
stored as declared under `bridge`), marks it connected and records
`agent.status`. Answer:

```json
{ "agent_id": "agt_7f3c…", "protocol": "1",
  "granted": {"bridge": ["read", "create", "update"], "notes": ["read"]},
  "vaults": [1], "all_vaults": false,
  "server_capabilities": ["messages", "tasks", "streaming", "approvals", "polling", "context"],
  "resume_after": 4812, "oldest_event_id": 1,
  "heartbeat_seconds": 15, "lease_seconds": 60 }
```

`resume_after` is the head of the event log: a new client reads state over
REST and streams from there; a returning client resumes from its own last
event id. An unknown protocol answers `426` with code
`unsupported_protocol` and `details.supported: ["1"]`.

## Messages

`seq` numbers a conversation's messages from 1 with no gap: the
conversation's `last_seq` is incremented in the transaction that stores
the message, and `(conversation_id, seq)` is unique. Sending requires
`Idempotency-Key` (1 to 128 characters); a repeat with the same key by the
same sender answers `200` with the original message (`201` when created).

Sender kinds: `user`, `agent`, `provider` (Phase D), `system`. Types: the
user sends `text`, `attachment`; agents `text`, `tool_call`, `tool_result`,
`progress`, `error`, `attachment`. `approval_request` and
`approval_response` are created by the approval routes only. Content is
Markdown up to 64 000 characters; references (`[{kind, id,
revision_id?}]`, up to 50) point at research objects and never copy them.
Message content is not redacted: it is what the user or agent wrote to
the other side.

**Delivery.** A message to an agent (or provider) is `queued` until its
recipient lists the conversation (`GET …/messages`), reads the MCP inbox
or acknowledges it (`POST /messages/ack`); then `delivered`. A message to
the user is `delivered` when stored. The recipient may fail a message
(`failed` with `failed_reason`); the user may retry a failed one (back to
`queued`, `attempts + 1`). Disconnected agents never lose messages.

**Streaming.** A message sent with `streaming: true` is stored empty. The
sender posts pieces to `/messages/{id}/deltas` (each becomes an ephemeral
`message.delta {message_id, conversation_id, offset, text}`; `offset`, when
sent, must equal the text length so far or `409`), then
`/messages/{id}/finalize` stores the whole text (`message.completed`). The
provider runtime (Phase D) calls the same service in process
(`MessageStreamService.begin_provider`, `append_to`, `finalize_message`).
A stream open at a restart fails with reason `interrupted`.

## Tasks

```
queued → delivered → running → completed
   │         │          ├→ awaiting_approval → running
   │         │          ├→ paused → queued
   │         ├→ completed (without progress)
   │         └→ queued (lease expired, restart)
   ├→ paused, expired, failed
   └→ cancelled ← (any open state)
```

`app/core/bridge/tasks.py` holds the table; every change is a conditional
update from the state read, so two concurrent changes never both win.

- **Claim** (`queued → delivered`) returns `lease_id` and
  `lease_expires_at` (default 60 s, `lease_seconds` 5 to 3600) and counts
  an attempt. A claimed task answers `409 conflict`.
- **Progress, complete, fail** must present the live lease; a stale or
  expired lease answers `409 conflict` with `details.reason = stale_lease`;
  a paused, cancelled or finished task answers `409 invalid_state` with
  its `state`. The first progress starts the task (`delivered → running`);
  each one renews the lease.
- **Plan**: a progress report may carry `plan`, the agent's whole plan as
  up to 20 steps (`{title, state}`, state `pending`, `running`, `done`,
  `skipped` or `failed`). It replaces the previous plan; a report without
  one keeps it. The user sees it as a checklist on the task. A plan grants
  nothing: each step still goes through grants, scope and approvals.
  Over MCP it is the `plan` argument of `task_update`.
- **Lease expiry** (sweep every 5 s): back to `queued`, the old lease is
  stale; after `max_attempts` (default 3, up to 10) claims, `failed` with
  `error.code = lease_expired`.
- **Deadline**: an open task past `deadline_at` becomes `expired`
  (reason `deadline`), its pending approvals too.
- **Cancel**: the user or the requesting agent, from any open state;
  sets `cancel_requested_at`, ends the lease, expires pending approvals.
  **Pause / resume**: the user; pausing ends the lease.
- Assignment: the user names `assigned_agent_id` or the task goes to the
  conversation's agent; an agent's own tasks are assigned to itself; an
  unassigned task is claimable by any agent of the vault. Agents see a
  task's `context_refs` filtered by their grants.

**Restart recovery** (at start, before the first sweep): non-sensitive
`delivered` and `running` tasks return to `queued` (reason `restart`);
**sensitive tasks become `paused` (reason `restart`) and wait for a
person**; tasks past their deadline expire; pending approvals past their
expiry expire; open streams fail.

**Authorization change**: revoking or rotating a token, changing its
grants or vaults, or disconnecting an agent cancels that agent's open
tasks (reason `authorization_changed`), expires its pending approvals,
fails messages still queued for it (`failed_reason:
authorization_changed`) and closes its Bridge streams (`stream.closed`).
Nothing resumes silently; the user retries or recreates.

## Approvals

An agent asks with `POST /bridge/approvals` naming the operation, the
resources and the grant it relies on, for a task (running, under its
lease: the task waits in `awaiting_approval`, where its lease does not run
out) or a conversation. The conversation gets an `approval_request`
message. Only the user decides (`POST /bridge/approvals/{id}` with
`{"decision": "approve" | "deny"}`); either decision returns the task to
`running` with a fresh lease (`state_reason` `approved` / `denied`) and
posts an `approval_response` message. Requests expire after 30 minutes
(`expires_in` 30 s to 24 h); an expired request fails its task
(`approval_expired`). Phase B records decisions; Phase D makes provider
function calls wait for them.

## Events

Every change writes `agent_events` **in the transaction of the change**
and is announced after the commit. The id is global, increasing and never
reused (the resume cursor). Stored types:

| Type | Stored payload (`data`) | Attached when read |
|---|---|---|
| `conversation.created`, `conversation.updated` | `conversation_id`, `action` (`created`, or the changed fields) | `conversation` |
| `message.created`, `.delivered`, `.failed`, `.retried`, `.completed` | `message_id`, `conversation_id`, `seq`, `delivery` (`reason`, `approval_id` when set) | `message` |
| `task.updated` | `task_id`, `state`, `previous`, `reason` | `task` |
| `approval.requested`, `approval.decided` | `approval_id`, `task_id`, `state` | `approval` |
| `agent.status` | `agent_id` (public), `status` (`connected`, `disconnected`) | |

Ephemeral (no id, never stored, not in polling): `message.delta`,
`context.updated {window, version, vault_id}`. Stream control:
`stream.reset {cursor, reason: retention}` (the cursor is older than the
oldest kept event: refetch, then continue) and `stream.closed {reason}`
(`token_revoked`, `token_rotated`, `authorization_changed`,
`disconnected`).

The user reads every event; an agent the events of its conversations,
tasks and approvals (and its own `agent.status`) in its vaults.

- `GET /bridge/events?after=<id>`: Server-Sent Events. Each stored event is
  `id: <id>`, `event: <type>`, `data: <the event object>`. `Last-Event-ID`
  wins over `after`. A comment line every 15 s (`BRIDGE_HEARTBEAT_SECONDS`).
- `GET /bridge/events/poll?after=<id>&wait=<0..25>`: the same stored events
  as `{events, cursor, reset}`, waiting up to `wait` seconds for the first.

Retention: the newest 50 000 events and 30 days (`BRIDGE_EVENT_RETENTION`,
`BRIDGE_EVENT_MAX_DAYS`); the newest event is never deleted. Ordering is
exact on SQLite, where writers are serialised; a multi-writer database
will need a commit horizon on reads (see deferred work in
[Agent Bridge](bridge.md)).

Phantom's interface receives the same events on `/api/v1/ws`, filtered by
its subscribed vault: `bridge.conversation`, `bridge.message`,
`bridge.task`, `bridge.approval`, `agent.status`, `bridge.delta`,
`context.updated`. Each carries `{event_id, type, …payload, <object>}`
(ephemeral ones without `event_id`). After reconnecting it refetches
`messages?after_seq=`.

## Errors

The REST error body: `{"error": {"code", "message", "details"}}`.

| Status | Code | When |
|---|---|---|
| 401 | `unauthenticated`, `invalid_token`, `token_expired`, `token_revoked` | Credential refused |
| 403 | `permission_denied` | Grant or vault missing (`details {resource, action, vault_id, reason}`), user-only or agent-only operation (`reason`) |
| 404 | `not_found` | Unknown, or not visible to this agent |
| 409 | `conflict` | Duplicate claim, stale lease, offset mismatch, a concurrent change |
| 409 | `invalid_state` | Transition not allowed, archived conversation, decided approval |
| 422 | `invalid_value` | Body, header or reference refused (`details.field`) |
| 426 | `unsupported_protocol` | Unknown protocol version (`details.supported`) |

## Reference client

[`docs/examples/bridge_client.py`](../examples/bridge_client.py) (standard
library and httpx): hello, SSE with resume from a saved `Last-Event-ID`,
replying to the user's messages, claim / progress / complete, and long
polling. `tests/test_bridge_client.py` runs it against a live server.
