# auto-coder.chat API

auto-coder.chat is the cloud control plane for the Auto-Coder agent network: web dashboard, conversations, kanban boards, organizations, and the run lifecycle. Local executors — CloudBridge, `auto-coder.chat.lite`, desktop and Android clients — register an instance here, poll for work, run it on their own machine, and stream results back. Everything on this page works over plain HTTPS + JSON.

- Base URL: `https://auto-coder.chat`
- This page: `https://auto-coder.chat/skill` (HTML) · `https://auto-coder.chat/skill.md` (Markdown) · `/docs` is an alias.

## 1. Get an API key

API keys can be created inside the web app or obtained by the `acchat auth login` device flow below. Sign in, open **Dashboard → Settings** (`/{locale}/dashboard/settings`), and create a named key under **API keys**. The secret value (`ak_...`) is shown only once — copy it immediately. Keys can be revoked at any time; a revoked key returns `401`.

One `ak_` key authenticates both directions: the machine-facing client protocol and the user-facing REST API. Keep it in an environment variable or a secrets manager; never commit it.

```bash
curl -H "Authorization: Bearer ak_xxxx" https://auto-coder.chat/api/me
```

## 2. Authentication

| Scheme | Where it works | How |
|---|---|---|
| API key (`ak_…`) | Every non-admin `/api/*` route | `Authorization: Bearer ak_…` |
| Session cookie | Every non-admin `/api/*` route | Browser login (`/api/auth/login`); cookie set automatically |
| OAuth access token | OIDC-aware clients | `Bearer` token from `POST /api/oauth/token` |
| Admin session | `/api/admin/*` | Cookie session whose user has the admin flag |

Unauthenticated or revoked credentials return `401 {"error": "..."}`; missing ownership returns `404` (never a 403 leak of existence).

### Device authorization for acchat CLI and Auto-Coder TUI

Existing API keys, flags, environment variables and config files remain supported.
Use `acchat auth login` (waits by default), or `acchat auth login --no-wait` followed
by `acchat auth finish --wait 600s`. Open the verification link in a normal browser,
sign in and compare the displayed code and hostname before allowing access.
`auth status` displays the effective source/account/key name/expiry without secrets;
`auth logout` revokes only the saved device key and removes its local files.

| Endpoint | Authentication / request | Result |
| --- | --- | --- |
| `POST /api/auth/device/start` | Public JSON `{client_id, hostname:"YOUR_HOST"}`; client ID is `acchat-cli` or `auto-coder-tui` | `201 {device_code, user_code, verification_uri, verification_uri_complete, expires_in:600, interval:5}` |
| `GET /api/auth/device/verify?user_code=ABCD-EFGH` | Browser cookie; redirects to login if absent | Code, registered client name, reported hostname, account, Allow / Deny form |
| `POST /api/auth/device/verify` | Browser cookie, same-origin form and session/code-bound CSRF | One-use allow/deny; never returns a credential |
| `POST /api/auth/device/token` | Public JSON `{client_id:"acchat-cli", device_code:"PRIVATE_DEVICE_CODE"}` | `200 {access_token, token_type:"Bearer", expires_in:7776000, expires_at, credential:{id,name}, user:{email}}` |
| `POST /api/auth/device/token` | Public JSON `{client_id:"auto-coder-tui", device_code:"PRIVATE_DEVICE_CODE"}` | `200 {session_id, token_type:"Session", expires_in:2592000, expires_at, user:{email}}` |
| `GET /api/auth/device/status` | Existing or device-issued `Bearer` API key | `authenticated`, account email, credential name/id/expiry/issuer; no key |
| `POST /api/auth/device/revoke` | Device-issued `Bearer` key | Idempotent `{revoked:true}` for that key only; manual keys are rejected |

This uses the [RFC 8628 device-flow error semantics](https://www.rfc-editor.org/rfc/rfc8628#section-3.5)
with a first-party JSON API, rather than the existing OIDC `/api/oauth/token`
protocol. Pending returns HTTP 400 `authorization_pending`; denial 400
`access_denied`; expired/consumed/unknown grants 400 `expired_token`.
`slow_down` returns 429 with `Retry-After` and `interval`. Respect at least 5 seconds
between polls and increase by at least 5 after slow_down. Private device codes
are 256-bit secrets and both codes are stored only as SHA-256 hashes.

Per-device poll scheduling and issuance are transactional. Durable IP counters
limit start to 12/10 minutes, polling to 300/minute, verification to 30/10 minutes
per IP **and account**, and status/revoke to 120/minute per endpoint. The application
must be behind a trusted reverse proxy that overwrites/appends the real client
address as the final `X-Forwarded-For` hop and prevents direct public app access.
Missing/invalid addresses share one conservative bucket. Counters persist across
server restarts/replicas; expired records are pruned in bounded batches on start.

Approved grants issue named **90-day** user API keys (`acchat CLI @ YOUR_HOST`),
visible and separately revocable in the existing API Key list. Only the hash is
stored; the raw device key is never exposed in the browser list. Both shared
Bearer auth paths reject expired/revoked keys. Old keys with null expiry retain
their lifetime. Renewal requires `auth logout` then `auth login` and new consent;
there is no refresh token.

An approved `auto-coder-tui` grant issues a **30-day** user session and does not
create an API key. Send it as the `session_id` cookie on user requests. Use
`GET /api/me` to inspect it and `POST /api/auth/logout` (`/bot logout` in the TUI)
to end it. Send the cookie only to the configured origin and do not follow
redirects. A device code can only be exchanged using the client ID that requested it.

CLI precedence: flag → environment (`AUTO_CODER_CHAT_API_KEY`, then
`AUTO_CODER_CLOUD_API_KEY`) → selected legacy config → Lite config (unless
`--config` is explicit) → device credential for the selected origin. Private
files: `~/.acchat/auth/<server-hash>.json` and `<server-hash>.pending.json`
(or `ACCHAT_AUTH_DIR`); Unix file/dir modes 0600/0700, Windows protected DACL
for the current user and LocalSystem. Original config is untouched.
Timeout exits 7 and Ctrl+C preserves pending state for `auth finish`;
denial/expiry deletes it. Logout network failures still delete locally and
report that the named key must be revoked in web API Key management.

## 3. Conventions

- All bodies are JSON (`Content-Type: application/json`) unless noted; errors are `{"error": "<message>"}`.
- IDs are UUIDs unless noted. Timestamps are ISO-8601 strings.
- List endpoints paginate with `cursor` (an ISO timestamp from the previous page) and `limit` (≤ 100).
- **Run lifecycle**: `PENDING` → `CLAIMED` → `RUNNING` → `COMPLETED` | `FAILED` | `CANCELLED`. `CLAIMED` is a legal queue state — a client may hold several claimed runs and execute them serially.
- **Idempotency**: `POST .../result` accepts a client-generated `resultReceiptId` — a retry with the same id + canonical body replays the original ACK. File registration and upload-init accept `requestId` for the same purpose.
- **v2 run control**: clients that pass `runControlVersion: 1` on claim receive a stable `attemptId` and must echo it on heartbeat `runStates`, `.../result`, and cancel reports.

## 4. Client control-plane API — `/api/client/*`

The machine-facing protocol used by CloudBridge and `auto-coder.chat.lite`. All endpoints require `Bearer ak_…` and scope every object to the owning key. A typical executor loop:

`register` → (`heartbeat` + `runs/pending`)* → `claim` → download `files` → execute locally → `result`

### 4.1 `POST /api/client/register` — register / refresh an instance

Upserts an instance keyed by `(apiKey, machineId)`.

```json
{
  "machineId": "sha256-of-device+project",
  "hostIdentity": { "...": "optional stable device identity" },
  "name": "work-macbook", "platform": "darwin", "arch": "arm64",
  "appVersion": "1.4.0", "projectPath": "/abs/path/to/project",
  "hostname": "mbp.local", "ipAddress": "192.168.1.10",
  "projectMeta": { "...": "META descriptor, optional" },
  "executionProfileVersion": 1,
  "gitSyncAgentVersion": 2
}
```

→ `201/200`

```json
{ "instance": { "id": "<uuid>", "machineId": "…", "hostId": "…|null",
  "name": "…", "pollIntervalMs": 3000, "clientPollVersion": 1,
  "gitSyncVersion": 1, "gitSyncAgentVersion": 2, "projectMeta": { "…": "negotiation" } } }
```

### 4.2 `POST /api/client/heartbeat` — presence + run-state observations

```json
{
  "instanceId": "<uuid>",
  "currentRunId": "<uuid>",
  "executingRunIds": ["<uuid>"],
  "runStates": [{ "runId": "<uuid>", "attemptId": "…", "phase": "stopping",
                  "lastProgressAt": "…", "cancelReceived": true }],
  "projectMeta": {}, "projectMetaSync": {}, "projectStatus": {},
  "executionProfileVersion": 1
}
```

→ `{ "ok": true, "runControlVersion": 2, "cancelRunIds": ["<uuid>"], "staleClaimRunIds": [], "projectMeta": {…}? }`

`cancelRunIds` is authoritative: the executor must cancel those runs and confirm via `.../result` with `status: "CANCELLED"`. `staleClaimRunIds` is always `[]` (kept for old clients). Heartbeat also drives orphan recovery and project-META negotiation; invalid `runStates` entries are dropped, never fail the call.

Identical `projectMetaSync` / `projectStatus` observations do not change their stored revision or timestamps. Send actual `lastAttemptAt` / `lastSuccessAt` values for sync attempts; when `lastAttemptAt` is missing, the server supplies it on the first report or a sync transition. Manual refresh requests are still checked on each negotiation.

### 4.3 `GET|POST /api/client/runs/pending` — poll for work

`GET ?instanceId=<uuid>&executionProfileVersion=1` returns `{ "pollVersion": 1, "runs": [...] }` (≤ 10 per batch). `POST` combines a due heartbeat with the same poll:

```json
{ "pollVersion": 1, "instanceId": "<uuid>",
  "executionProfileVersion": 1,
  "heartbeat": { "currentRunId": "…", "runStates": [] } }
```

Each pending run carries `id`, `promptText`, `resultPayloads` (incl. `enableSubagents` override), `origin`, `forwardToRunning`, `createdAt`, `conversation.conversationId`, and `files[]` (`id`, `originalName`, `contentType`, `sizeBytes`).

Model-catalog helpers are offered first, then Stage helpers, then ordinary work, with older tasks first within each group. Unversioned requests skip structured execution profiles without changing those tasks. Polling never claims work; always use the claim endpoint before executing a returned run.

### 4.4 `POST /api/client/runs/{id}/claim` — atomic claim

```json
{ "recovery": false, "runControlVersion": 1 }
```

→ `{ "run": { "id", "status": "CLAIMED", "claimedAt", "recovery" }, "runControlVersion": 2, "attemptId": "<uuid>" }`

Claim is atomic — a `404` means the run is missing, not owned by this key, or already claimed. Treat `404` as a lost race, not permission to execute without claiming. `recovery: true` reclaims work after a restart.

### 4.5 `GET /api/client/runs/{id}` — read-only status check

Pure read for "whose run is this" — never refreshes timestamps, never authorizes re-execution.

→ `{ "run": { "id", "instanceId", "status", "claimedAt", "cancelRequested", "completedAt" } }`

Cross-check: the returned `instanceId` must match your own instance; `PENDING|CLAIMED|RUNNING` are never permission to rerun. Only a trusted terminal state or confirmed `CANCELLED` may settle a lost receipt.

### 4.6 `POST /api/client/runs/{id}/result` — report progress or terminal state

```json
{
  "status": "RUNNING | COMPLETED | FAILED | CANCELLED",
  "resultText": "…", "errorText": "…",
  "resultPayloads": { "result_type": "text", "…": "…" },
  "usageDetails": [{ "registered_name": "…", "provider_model_name": "…",
    "agent_type": "…", "input_tokens": 0, "output_tokens": 0,
    "input_cost": 0, "output_cost": 0, "timestamp": 0 }],
  "instanceId": "<uuid>", "attemptId": "<uuid>",
  "resultReceiptId": "client-generated-id",
  "runControl": { "stopConfirmed": true }
}
```

→ `{ "ok": true, "resultReceipt": { "id", "attemptId", "status", "duplicate" } }` or `{ "ok": true, "run": { "id", "status", "completedAt" } }`

`status: "RUNNING"` is a progress report, not evidence the executor started. Terminal reports settle run + usage + linked issue state in one transaction. If the ACK is lost, poll `GET /api/client/runs/{id}` — do not silently re-execute.

### 4.7 `POST /api/client/runs/sync` — legacy combined report

Single-shot alternative to claim+result for old clients: `{ instanceId, conversationId, promptText, status, resultText?, errorText?, resultPayloads?, usageDetails?, commandType?, metadata?, localRunId? }`.

### 4.8 Run files

| Endpoint | Purpose |
|---|---|
| `GET /api/client/runs/{id}/files?scope=run\|conversation` | List files attached to the run (or whole conversation) |
| `POST /api/client/runs/{id}/files` | Register uploaded blobs: `{ protocolVersion?: 1, files: [{ originalName, contentType, sizeBytes, blobPathname, blobUrl?, blobDownloadUrl?, storageType?, checksumSha256?, requestId?, kind? }] }` (≤ 100 per call) |
| `GET /api/client/runs/{id}/files/{fileId}` | Download a file (redirect or stream) |
| `POST /api/client/runs/{id}/uploads/init` | Start an upload: `{ filename, contentType, sizeBytes, checksumSha256?, requestId?, kind?, protocolVersion? }` → presigned target or `proxy` instruction; `413` when over the server limit |
| `POST /api/client/runs/{id}/uploads/proxy` | Multipart upload relayed through the server (fallback when presign is unavailable) |

### 4.9 `POST /api/client/runs/{id}/previews` — publish a sidebar preview

Two forms: inline content `{ path, name?, title?, kind?, contentType?, sizeBytes?, content, truncated? }` (`kind` ∈ `code|markdown|text|image|pdf|spreadsheet|document|video|audio|binary`, `content` capped at the inline limit) or a reference to an already-registered file `{ fileId, title? }`. → `{ "preview": { "id", "runId", "path", … } }`

### 4.10 Tunnel channel

`GET /api/client/tunnel/events?token=…` is an SSE stream (`text/event-stream`) delivering inbound HTTP requests addressed to `tun-<uuid>.<host>/*`. The executor answers each with `POST /api/client/tunnel/response` → `{ "ok": true }`. Create/destroy tunnels via the user API (`/api/instances/{id}/tunnels`).

### 4.11 Metadata & telemetry

| Endpoint | Purpose |
|---|---|
| `PUT /api/client/project-meta` | Upload project META: `{ instanceId, meta, refreshRequestId? }` |
| `POST /api/client/host-identity` | Report device identity: `{ instanceId, hostIdentity }` → `{ ok, hostId }` |
| `POST /api/client/capability-usage` | Record a skill/workflow invocation: `{ instanceId, kind: "skill"|"workflow", scope, name }` |
| `GET /api/client/capability-usage?instanceId=` | Read back usage counters |
| `POST /api/client/git-sync` | Git-sync actions: `{ action: "hello"|"report"|"verify"|"poll"|"progress"|"result", … }` |

### Bot exclusive UI control (2026-11-04)

One TUI, Web tab, or Android client controls a bot.cloud instance at a time.
Other clients keep watching their selected main Bot conversation. Control never waits for
coordinator or worker completion, and changing control never cancels work.

- `GET /api/instances/{id}/bot-cloud-control`: authenticated owner/org-admin read,
  `{control:null|{clientId,surface,expiresAt}}`; no lease proof is disclosed.
- `POST` to the same path: `{action:"take"|"renew"|"release",clientId:<UUID>,surface:"tui"|"web"|"android",leaseId?:<UUID>}`.
  Explicit `take` replaces the owner and returns `{ok:true,control:{clientId,leaseId,surface,expiresAt}}`.
  `renew`/`release` require the same client and lease. A stale request returns 409.
  Renew every 10 seconds; leases expire after 45 seconds. Lost leases need an explicit take.
- Send through the bound `/conversations/{convId}/messages` endpoint with
  `X-Bot-Control-Client` / `X-Bot-Control-Lease` headers, or a `botControl:{clientId,leaseId}` body.
  Missing/expired/revoked proof returns 409 `bot_control_required` without admitting input.
  Accepted receipt retries retain their original run even after takeover; use the same `clientRequestId`.
- Cancel, force-cancel, forward, delete-pending, and publish-upload actions require those headers.
  Direct `/runs` creation is refused for bot.cloud (`bot_shared_message_required`).
- Shared Bot `GET|POST /api/instances/{id}/uploads/run-files` and
  `POST /api/instances/{id}/runs/{runId}/files` also require the current lease.
  Registration accepts JSON `botControl` or the same headers; multipart upload
  accepts those headers or a JSON-encoded `botControl` form field. Upload intents
  use the headers. Missing, expired or replaced proof returns 409 `bot_control_required`.
- `bot.control` watch/SSE frames announce the new public owner. Transcript polling and lease renewal are independent.
  Current deployment stores leases beside the executing socket in the single Node process.
  Restart loses leases and requires explicit take; multiple web workers require a shared lease store first.
- Every new input goes straight to `BotRuntime.steer` after its existing claim/start checks.
  A running main turn takes it in its mailbox; an idle main opens a new turn while children continue.
  Tree settlement still waits for aggregation; overlapping inputs share one final reply on the latest input.
- Explicit recovery: send `userText:"/bot continue"` alone through that same
  bound messages endpoint, with a stable `clientRequestId` and the current
  control lease. The server stores `bot_cloud_action:"continue"` in the run
  payload and sends `botAction:"continue"` on `run.ready`; HTTP polling carries
  the same action in `resultPayloads`. Attachments/capability selections are
  rejected for this action. Ordinary text, quoted commands and taking control
  never resume an interrupted Bot. The executor calls `BotRuntime.resume`
  only after the normal durable claim/start checks, and still refuses if any
  old process in the tree is not proven stopped. It never replays the failed
  input; resend that input after recovery. Web/Android keep drafts while
  requesting recovery. Deploy the matching executor before using this action.

### 同一实例的多个主 Bot（2026-11-06）

- `GET /api/instances/{id}/bot-cloud-bots`：读取可切换主 Bot，返回
  `{version:1,defaultBotId,bots:[{id,name,phase,conversationId}],online,updatedAt}`。
  只列出未销毁的独立主 Bot，不把子 Bot 当成主 Bot。执行端暂不可达时保留缓存，
  `online:false`；旧执行端未提供目录时为 `version:0`，继续使用原共享绑定。
- `POST` 同一路径：`{name,clientRequestId:<UUID>}`，携带当前实例操控证明。
  成功返回目录和 `createdBotId`。名称去首尾空白，长度 1–80；创建不产生 LiteRun、
  用户消息或模型调用。失败且结果未确认时返回 503 `bot_create_unconfirmed`；
  使用原名称与同一 `clientRequestId` 重试，不另造请求 ID。执行端持久保存创建回执。
- 选择主 Bot 是当前界面的选择，不改写默认共享绑定、不抢占操控权，也不停止其他
  主 Bot。控制租约仍是整个实例一份。每个主 Bot 独立保存聊天、子 Bot、进展与草稿。
- 消息、恢复、历史和 SSE 使用所选 `conversationId`。服务端从目录解析主 Bot，
  将 `bot_cloud_bot_id` 写入 run 的 `resultPayloads`，WebSocket `run.ready`
  同时带 `botId`；HTTP pending 保留同一字段。客户端传入的任意 `botId` 不改变路由。
  未登记或已销毁的目标会被拒绝，不退回默认 Bot。
- 原默认 Bot 继续使用原共享 conversation ID；新主 Bot 使用稳定独立 ID。
  每个主 Bot 的最近历史窗口各为 1000 条显示记录，切换后旧请求和旧 SSE 不覆盖新页面。
- 执行端管理帧为 `bot.request:{requestId,action:"list"|"create",name?,creationId?}`，
  回复 `bot.response:{requestId,catalog:{version:1,defaultBotId,bots:[{id,name,phase}]},createdBotId?}`
  或 `error`。响应仅接受发送该请求的已授权执行端连接；8 秒无确认按失败处理，
  创建可使用原回执重试。目录最多 200 个主 Bot。无需数据库迁移。

### 4.12 bot.cloud WebSocket — `GET /api/client/bot-cloud/connect`

Push channel for CloudBridge `bot.cloud`. It does **not** replace pending poll, atomic claim, result, or heartbeat. Ordinary Project Agents keep polling. The socket never claims or executes a run.

Upgrade:

```
GET /api/client/bot-cloud/connect?instanceId=<uuid>
Authorization: Bearer ak_…
Connection: Upgrade
Upgrade: websocket
```

Same client API key as register/pending/claim. The connection is bound to that `instanceId` for its lifetime. Missing/invalid credentials → HTTP `401` on the upgrade request. Unknown, unowned, or deleted instance → `404`. There is no App Router `route.ts` for this path; a plain HTTP GET (no Upgrade) is not a WebSocket handshake and Next.js responds `404`.

**Server → client**

```json
{ "type": "run.ready", "runId": "<uuid>", "conversationId": "<public id>",
  "promptText": "…", "displayText": "…|null", "createdAt": "<ISO-8601>",
  "files": [] }
```

`conversationId` is the public conversation id (not the database UUID). `promptText` uses the same attachment-ref formatting as `runs/pending`. `createdAt` is ISO-8601 from the committed row.

`files` contains `{id,originalName,contentType,sizeBytes,downloadUrl,checksumSha256}`,
or `[]` without attachments. `downloadUrl` uses the existing authenticated
`/api/client/runs/{runId}/files/{fileId}` endpoint; a missing checksum is `null`.
Executor filenames follow pending's `fileId_originalName` convention and match
the local paths in `promptText`. Bot history and watch/SSE run events return the
same metadata with the original display filename. The web uses its existing Run
file component for `image/` previews and other filenames. Input files keep `kind=input`.

`run.ready` is sent after the creating HTTP handler has committed the LiteRun (messages without files, publish after `uploadPending` is cleared, direct runs POST, and shell-alias follow-ups) and only while the run is still claimable (`PENDING`, not `uploadPending`, not `cancelRequested`). The server awaits the WebSocket **send callback** (the frame is handed to this Node socket) before that HTTP response returns. It does **not** wait for a client ACK and does not provide multi-process or durable delivery. If `bufferedAmount` exceeds 1MiB, or a send times out or errors, the server drops that socket so reconnect replay and HTTP pending can compensate. It does not leave a nominally connected client silently missing tasks.

On connect, the server snapshots the newest currently claimable pending run as a high-water `(createdAt, id)` cutoff, then keyset-pages (size 10) every claimable row at or before that cutoff. Later pages use the previous page's captured `(createdAt, id)` as an exclusive lower bound rather than looking the last row back up as a DB cursor, so replay continues after a prior page-anchor is claimed, cancelled, or deleted. HTTP `runs/pending` stays capped at 10. Replay does not stop at a fixed 200-run cap, does not repeat page 1, and does not wait for claims or polls to advance. Rows created after the cutoff are outside this snapshot; a still-connected client gets those via live `run.ready`. Claimed, cancelled, upload-pending, and cancel-requested rows are omitted. Duplicate `run.ready` (create notify + replay, or notify + pending poll) is expected. Claim once; a second claim `404` means another executor won.

The connection stores the API key **id** only. Before further `run.ready` delivery and before persisting `bot.progress` / `bot.snapshot`, the server revalidates that key with the same `apiKeyUsable` rules (revoked / expired) and checks that the instance is still bound to it and not deleted. Failed revalidation closes the socket (`4401`). Raw keys are not kept on the connection.

**Client → server**

```json
{ "type": "bot.progress", "runId": "<uuid>",
  "event": { "type": "…", "bot_id": "…", "bot_name": "…", "phase": "…",
             "summary": "…", "detail": "…", "parent_id": "…", "role": "…" } }
```

```json
{ "type": "bot.snapshot", "runId": "<uuid>",
  "bots": [{ "id": "…", "parent_id": null, "name": "…", "role": "…",
             "phase": "…", "status": "…" }] }
```

Server assigns monotonic event `id` values per run. Client event ids are ignored. Progress for a run that does not belong to this connection's instance is rejected (`{ "type": "error", "code": "run_not_found" }`) and not persisted. Malformed JSON or unexpected frame types return `{ "type": "error", "code": "invalid_frame" }`. Oversized frames (above 64KiB) close the socket with code `1009`. `{ "type": "ping" }` → `{ "type": "pong" }`.

Progress is stored in `user_app_states` under namespace `auto-coder.bot-progress`, `scopeType=lite-run`, `scopeId=<runId>`, `stateKey=v1`, owned by the instance owner's user id. The last 1000 events are retained; older events are dropped. Snapshots replace the `bots` array. This is separate from `LiteRun.resultPayloads`.

There is no Wake WebSocket.

### 4.13 Dream agenda (internal agents)

| Endpoint | Purpose |
|---|---|
| `POST /api/client/dream/agenda/candidates` | Submit up to 100 agenda candidates |
| `GET /api/client/dream/agenda/results` | Fetch pending agenda results |
| `POST /api/client/dream/agenda/results/ack` | Acknowledge results: `{ ids: [...] }` |

## 5. Client agent-sync API — `/api/client-agent-sync/*`

Content-addressed sync protocol for offline-capable clients (Android, lite). Same `Bearer ak_…`. The cookie-authenticated twin used by the web dashboard lives at `/api/agent-sync/*` — identical handlers, session auth.

| Endpoint | Purpose |
|---|---|
| `GET /api/client-agent-sync/identity` | Who am I — user + key identity |
| `GET /api/client-agent-sync/sessions` · `/sessions/{id}` · `/sessions/{id}/executions` · `/executions/{id}` · `/executions/{id}/events` · `/executions/{id}/event-seqs` | Read the synced session / execution / event log |
| `POST /api/client-agent-sync/blobs/init` | Begin a chunked blob upload (sha-addressed) |
| `PUT /api/client-agent-sync/blobs/{sha}/chunks/{index}` | Upload one chunk |
| `POST /api/client-agent-sync/blobs/{sha}/complete` · `/abort` | Finish or discard the upload |
| `GET /api/client-agent-sync/blobs/{sha}` · `/blobs/{sha}/content` | Blob metadata / bytes |
| `GET /api/client-agent-sync/changes` · `/diff` · `/records/{kind}/{id}` | Delta queries for incremental sync |
| `GET /api/client-agent-sync/export` | Full export snapshot |
| `POST /api/client-agent-sync/reconcile` · `/restore` · `/commit` | Reconcile state, restore, and commit a sync batch |

## 6. Instance & conversation REST API

### Account-wide active runs (read-only)

`GET /api/runs/active?limit=100&cursor=OPAQUE_CURSOR` uses the same user
cookie/Bearer authentication. It returns `scope:"owned"`, `observedAt`, `runs`
and `pagination:{limit,returnedCount,hasMore,nextCursor,asOf,consistency:"live-keyset"}`.
Limit is 1–500 (default 100). Follow `nextCursor` unchanged until `hasMore:false`.
The CLI supports `acchat runs active --all` to drain these active pages directly.

Every matching owned `PENDING`, `CLAIMED` or `RUNNING` run is eligible, including
internal/helper work. Terminal records and records with completion/cancellation
timestamps are excluded. A cancellation **request** remains visible until
settlement. Rows include `id`, `instanceId`, database `conversationId`, public
`conversationShortId`, status, created/claimed/updated timestamps, cancellation,
upload and forwarding flags, `instance:{hostname,projectPath,name,lastSeenAt,heartbeat}`
and `progress:{phase,lastHeartbeatAt,lastProgressAt,attention}`. Heartbeat is
`recent` (<5 minutes), `stale`, or `unknown` (null); stale/unknown never removes
a run. Service-owned progress can be null. `RUNNING` and a recent instance
heartbeat do not prove that a particular agent process is physically running.
No prompt, display, result, error, conversation-title text, complete payloads,
project META or history aggregates are selected or returned.

Scope covers the authenticated user's non-deleted instances on non-revoked
keys, across machines/projects; shared-only organization instances are excluded.
Authorization is reapplied on every page; cursors are bound to that owner.
Immutable `(createdAt,id)` keysets prevent offset skips when earlier rows finish.
`asOf` excludes newer creations, but states remain live: unseen terminal
transitions disappear and already-read rows may finish later. Older records
reactivated behind the cursor require a new traversal. This is **not a frozen
status snapshot**. No task is claimed, cancelled, refreshed or executed by this
endpoint. Standard authentication may update the existing API-key usage timestamp.
Responses use `private, no-store` and numeric `Server-Timing` for auth/query/serialization.

`/api/runs/recent` remains a recent-conversation overview (deduplicated, bounded,
no cursor, excluding PENDING), not a complete active-run listing.

User-facing routes; accept session cookie **or** `Bearer ak_…`. Org-shared instances are additionally visible to org admins.

`POST /api/instances/{id}/runs/{runId}/force-cancel` uses the same owner/org-admin authorization as normal cancellation. It locks and re-reads the run, settles an active run as `CANCELLED`, and records `resultPayloads.srv_runControl.forceCancelledAt` without setting `stopConfirmedAt`. The executor's physical state remains unknown; late progress/results cannot reopen the run. Repeated requests return the actual terminal status without overwriting a completed/failed outcome. Normal `/cancel` still waits for executor confirmation on claimed/running runs. No request body or schema migration is required.

| Endpoint | Purpose |
|---|---|
| `GET /api/instances` · `DELETE` | List (`?lite=1` skips META and activity; `?view=list` keeps activity and skips META; `?lite=1&view=discovery` returns only `id,name,projectPath,hostname,hostId`) / delete instances. CLI: start with `acchat instances list`, then `projects locate NAME --host HOST` / `instances get ID`; explicit `--full` or `--format json` exports legacy full JSON. |
| `GET /api/instances/{id}` | Instance detail |
| `GET /api/instances/{id}/runs?conversationId&cursor&limit` | Run history |
| `POST /api/instances/{id}/runs` | Create a run directly: `{ conversationId, promptText, displayText?, hasFiles?, shellAlias?, agentBackend?, agentBackendModel?, enableSubagents?, commandType?, metadata? }` |
| `DELETE /api/instances/{id}/runs/{runId}` | Delete run record |
| `GET .../runs/{runId}/bot-progress?after=0` | Mobile/web read of bot.cloud progress. Owner or org OWNER/ADMIN. `{ events:[{id,type,bot_id,bot_name,phase,summary,detail,created_at,parent_id,role}], bots:[{id,parent_id,name,role,phase,status}] }`. `after` is a non-negative integer cursor (default 0); events with `id > after` plus the current snapshot. Instance/run mismatch → 404. Reads the instance owner's stored state (org admins see the same document). |
| `POST .../runs/{runId}/cancel` · `/forward` · `/publish` | Cancel / forward to a running agent / publish registered input files |
| `POST .../runs/{runId}/force-cancel` | Immediately settle an active run as `CANCELLED`, without waiting for executor confirmation |
| `GET .../runs/{runId}/previews/{previewId}/content` · `GET|POST .../reviews` | Preview content + review events |
| `GET|PATCH|DELETE /api/instances/{id}/conversations` | List / rename / delete conversations |
| `POST .../conversations/open` · `/viewed` · `/dismissed` | Open-state, read receipts, dismiss |
| `GET|POST|PUT|DELETE /api/instances/{id}/conversation-groups` | Sidebar grouping |
| `POST /api/instances/{id}/conversations/{convId}/messages` | **Send a message → creates a run.** `{ userText, displayText?, shellAlias?, agentBackend?, agentBackendModel?, enableSubagents?, executionProfile?, projectCapability?, cursorModel?, hasFiles?, reviewBoardId?, reviewIssueId?, voiceTranscript? }` |
| `GET|PATCH .../conversations/{convId}/external-session` | External backend session binding |
| `POST .../conversations/{convId}/handoff` · `/saved-prompt` | Handoff to another surface / save prompt |
| `GET|POST /api/instances/{instanceId}/conversations/{conversationId}/reports` | List/create the authenticated user's reports for this conversation only |
| `GET|DELETE /api/instances/{id}/files/{fileId}` | Instance-scoped file download/delete |
| `GET|POST /api/instances/{id}/uploads/run-files` | Dashboard-side run file upload |
| `GET|HEAD /api/storage/local` | Local-disk downloads via an expiring signed URL returned by an authorized file endpoint; invalid/expired signatures return `403`. Treat the URL as a temporary bearer credential. |
| `GET|POST /api/instances/{id}/agent-models` | Cached per-instance agent model catalog |
| `GET|POST /api/instances/{id}/project-meta` | Read/refresh project META |
| `GET|POST /api/instances/{id}/stage` | Stage area |
| `GET|POST|DELETE /api/instances/{id}/tunnels` | Manage port-preview tunnels |
| `POST /api/instances/{id}/goal-control` | Goal control commands |
| `POST /api/instances/{id}/chat-sync` | Chat sync |
| `GET /api/runs/recent` | Recent runs across instances (cursor pagination) |
| `GET /api/conversations/catalog?limit=200&offset=0&asOf&folderId` | Account-wide conversation pages, ordered by latest visible activity; `limit` 1–500. `folderId` is a folder UUID or `unfiled`; omit it for all conversations. |
| `GET|POST /api/conversation-folders` | Read the directory tree / create `{ name, parentId? }`. Root uses `parentId: null`. GET may include `?recordId=UUID` to also return the owned conversation's `membership: { recordId, folderId }`; unavailable/foreign records return 404. |
| `PATCH|DELETE /api/conversation-folders/{id}` | Rename/move `{ name?, parentId?, revision? }` / delete an empty folder. Omit `parentId` to keep its current parent; null moves to root. |
| `POST /api/conversation-folders/assign` | Atomically assign `{ recordIds: [UUID, …], folderId: UUID \| null, expectedFolderIds?: { "record-UUID": "previous-folder-UUID" \| null } }`; 1–500 owned conversations. Null removes folder membership. |
| `GET /api/site-features` | Feature flags for the UI |

Conversation reports are stored in the server database and scoped to the authenticated user, instance and **public** conversation ID from the URL (not the conversation's database UUID). Both methods verify instance owner/org-admin access and that the conversation belongs to that instance; even an org admin only sees their own reports. POST accepts exactly `{ "context": "上下文", "result": "结果" }`: both fields are required strings, must contain non-whitespace text and must each be at most 8000 characters. Unknown fields, malformed JSON and invalid content return 400. POST returns 201 with `{ "context": "…", "result": "…", "createdAt": "<ISO-8601>" }` in that order. GET returns 200 with `{ "reports": [ /* same shape, newest createdAt first */ ] }`, or `{ "reports": [] }` when empty. Responses use `private, no-store`. Unauthenticated requests return 401; inaccessible/deleted instances or missing/mismatched conversations return 404. There is no account-wide reports endpoint.

Preview bodies can be loaded on demand. Send `previewContent: "lazy"` in `POST .../chat-sync` or `POST .../conversations/open`, or use `GET .../runs?previewContent=lazy`. Both `resultPayloads.file_previews` and `latest_file_preview` then omit inline `content`, retaining metadata plus `contentUrl` and `contentVersion`. Fetch `contentUrl` only when opening that file, with the same session/Bearer authorization and organization scope. Cache opened content by its version; discard it when the version changes. Omitting the option (or specifying `"inline"`) preserves the existing response for older clients. Storage and upload formats are unchanged.

Conversation directories belong to the signed-in user and span that user's nodes and projects. Each conversation belongs to at most one directory; moving it preserves its original instance, project, and history. Other users' and organization-shared conversations are excluded from this personal catalog. The tree and memberships are persisted in `user_app_states` under the reserved `conversation_folders` namespace; use the directory APIs rather than generic state PUTs.

`GET /api/conversations/catalog` returns `{ conversations, pagination: { limit, offset, returnedCount, hasMore, nextOffset, asOf } }`. The row's `conversationId` is the **database record UUID** required by `recordIds`; `conversationShortId` is the public ID used by instance-scoped conversation routes. Empty conversations are included with `latestRun: null`. There is one row per conversation even if a conversation has hundreds of runs. The first 200 use `offset=0`; positions 201–400 use `offset=200`. Reuse the first response's `asOf` for subsequent pages to exclude newly arriving runs from activity ordering. Folder membership and names remain current, so a concurrent deletion or folder move may still affect a filtered page.

Folder responses contain `{ id, name, parentId, revision, conversationCount }`; counts include direct members, not descendants. POST returns 201. Invalid input returns 400, unavailable/foreign IDs 404, duplicate sibling names, cycles, stale revisions, and deletion of populated folders return 409. Tree edits and assignment batches serialize per user; any unavailable conversation rejects the entire batch. No directory operation creates or executes a run.

Clients should send `expectedFolderIds` from their catalog/membership read when assigning conversations. It must contain exactly the requested record IDs, with each previous folder ID (or null for unfiled). If any membership has changed, the whole batch returns 409 without writing; refresh and let the user reconsider. A retry whose entire batch is already at the requested destination succeeds without rewriting memberships. The field remains optional for compatibility with older clients; the current Web and Android interfaces always send it, and the built-in Agent attaches its own previously observed memberships.

## 7. Boards & organizations

The Kanban API serves personal boards (`/api/boards/*`), organization boards (`/api/orgs/*`), and the `acchat` CLI. In board order, the issue statuses are `backlog`, `design`, `todo`, `in_progress`, `in_review`, and `done`. Automatic dispatch selects issues from `todo`.

| Endpoint | Purpose |
|---|---|
| `GET|POST /api/boards` · `PATCH|DELETE /api/boards/{id}` | Personal boards CRUD |
| `POST /api/boards/{id}/transfer-to-org` | Move a board into an org |
| `GET|POST /api/boards/{id}/issues` | List/create issues: `{ title, description?, acceptanceCriteria?, status?, priority?, labels?, instanceId?, shellAlias?, … }` |
| `GET|PATCH|DELETE /api/boards/{id}/issues/{issueId}` | Issue detail/update/delete |
| `POST .../issues/{issueId}/execute` · `/approve` · `/approve-and-commit` · `/reject` · `/cancel` | Issue workflow actions |
| `PUT .../issues/{issueId}/reorder` · `POST .../issues/batch` | Ordering & bulk ops |
| `POST .../issues/{issueId}/files` · `GET|DELETE .../files/{fileId}` · `POST .../uploads` | Issue attachments |
| `GET|POST /api/orgs` · `GET|PATCH|DELETE /api/orgs/{id}` | Org CRUD |
| `GET /api/orgs/{id}/members` · `PATCH|DELETE .../members/{memberId}` · `POST /api/orgs/{id}/transfer-ownership` | Membership |
| `GET|POST /api/orgs/{id}/roles` · `PATCH|DELETE .../roles/{roleId}` | RBAC roles |
| `GET|POST /api/orgs/{id}/invitations` · `DELETE .../invitations/{invId}` · `POST /api/invitations/{id}/respond` | Invites |
| `GET|POST /api/orgs/{id}/instances` · `DELETE .../instances/{instanceId}` | Shared instance pool |
| `/api/orgs/{id}/boards/**` | Same issue surface as `/api/boards/*` plus `permissions`, `detach-to-personal`, and `/issues/{issueId}/execution` (`GET`, `/execution/messages` `POST`, `/execution/files/{fileId}` `GET`) |
| `GET /api/orgs/{id}/audit/events` | Audit log |

### Organization board collaboration

The six lanes are 待规划 (backlog), 设计 (design), 待开发 (todo), 进行中 (in_progress),
待审查 (in_review), 已完成 (done).

- Organization permission matrices can set `lanes.design` explicitly. Older saved matrices without that entry use their `todo` grants for Design.
- `GET /api/orgs/{id}/boards/{boardId}/issues` supports `status` (comma-separated values), `title` (case-insensitive substring), `label` (exact match), `sourceTaskId` (exact match), `sort`, `limit`, and `offset`. Inspect `appliedFilters` and `pagination`. Listings and counts reflect the current account's visible lanes. Reads leave issue state untouched.
- Create with `requestId` and optional `sourceTaskId`. The keys are scoped to the board. Replaying the same registration returns the existing issue and `replayed: true`, including when the issue has moved. Reusing a key with different content returns `409 ISSUE_REGISTRATION_CONFLICT`.
- Pass the issue's `updatedAt` as `expectedUpdatedAt` when updating or moving it. A stale version returns `409 ISSUE_VERSION_CONFLICT`. Batch operations accept `expectedUpdatedAts` as a map from issue ID to timestamp. Inspect every entry in `results`; `partial` signals mixed outcomes. A hidden or missing card has the same skip reason.
- `GET /api/orgs/{id}/boards/{boardId}/issues/{issueId}/collaboration` returns Bot roles, execution status, the progress timeline and current action permissions and conditions. Request the next timeline page with `?before=<nextBefore>`.
- `POST` to that collaboration endpoint with one action:
  - `progress` takes `requestId`, `summary`, optional `botId` and an array of HTTPS or HTTP `links`. It requires the current lane's comment permission.
  - `assignBots` takes `requestId`, `coordinator` and `assignee` (each `{botId, name}` or `null`), and optional `expectedUpdatedAt`. It requires issue edit permission. Bot roles are reported metadata and carry the authenticated submitting account.
  - `linkRun` takes `instanceId`, the public `conversationId`, and `runId`. It requires issue execute permission and access to the run as the instance owner or an administrator of the organization sharing that instance. It preserves each verified link and dispatches no new run. Run results settle the current attempt at `in_review` when all linked runs succeed or at `todo` once all finish and any fail or are cancelled.
  - `submitReview` takes `requestId`, `summary`, `evidence` (location/link), optional `botId`, and optional `expectedUpdatedAt`. With move permissions, it hands off an in-progress tracking card or a card with verified successful execution. In review, authorized commenters can add evidence. Active, unverified, failed, or cancelled executions block handoff.
  - `reconcileExecution` takes the observed board `runId` and `expectedUpdatedAt`. With move permissions, it repairs an in-progress card whose current board run already has a terminal result.
- `cancel` requests a stop. If `pendingConfirmation` is true, the runner still owes a terminal result. `approve` is the separate reviewer action that records completion.
- For an organization issue already in `in_review`, `approve` and collaboration's `actions.approve` use the same linked-run checks. A pending, claimed, or running linked run, including one whose cancellation is still pending, does not block approval and does not require an attachment. A missing or non-business result still returns `409 RUN_RESULT_UNKNOWN`; attachments cannot bypass it. A failed or cancelled linked run still returns `409 RUN_NOT_COMPLETED` unless this issue has at least one saved issue attachment (`lite_issue_files`). `submitReview` stays strict: an active run returns `409 RUN_ACTIVE`, a pending cancellation returns `409 RUN_CANCELLATION_PENDING`, and attachments do not waive a failed or cancelled run (`409 RUN_NOT_COMPLETED`). This linked-run check does not apply to board-dispatched executions or cards with no linked attempt; permissions are unchanged.

Use `acchat issues --help` for command syntax and `acchat --skill` for examples. Pass `--data-file` with a JSON object for multiline summaries, structured Bot assignments, or batch versions. Preserve request IDs and payloads when retrying.

## 8. Voice (speech-to-text)

`POST /api/instances/{id}/voice` — `multipart/form-data` with field `file` (`audio/wav` recommended). Returns the transcript JSON (prefer `transcript`/`raw_text`; the normalization chain is `text → normalized → repaired_text → …`). `POST .../voice/upload-intent` mints a direct-upload token for large audio; `POST .../voice/normalize` re-runs text normalization.

## 9. Market & catalog (public GET)

| Endpoint | Purpose |
|---|---|
| `GET /api/rules/market` | `{ items: [{ name, displayName, description, revision, downloadCount, submittedBy, createdAt }] }` |
| `GET /api/rules/{name}` · `/api/rules/{name}/json` | Latest approved rule content / metadata |
| `GET /api/workflows/market` · `/api/workflows/{name}` · `/api/workflows/{name}/json` · `/api/workflows/{name}/versions/{revision}` (+`/json`) | Workflow catalog & pinned revisions |
| `GET /api/tools/market?os&arch` | Proxied command-tool catalog: `{ count, tools, cached, fetchedAt }` |
| `POST /api/rules/submissions` · `POST /api/workflows/submissions` · `GET /api/rules/mine` · `/api/workflows/mine` | Submit for review / list your submissions (auth required) |

## 10. OAuth 2.0 / OIDC provider

Discovery: `GET /.well-known/openid-configuration` (issuer `https://auto-coder.chat`, `response_type=code`, PKCE `S256` only). JWKS: `GET /.well-known/jwks.json`.

1. `GET /api/oauth/authorize?client_id&redirect_uri&response_type=code&scope&state&nonce&code_challenge&code_challenge_method=S256` → consent → redirect back with `code&state&iss`.
2. `POST /api/oauth/token` — `grant_type=authorization_code`, `code`, `code_verifier` → `{ access_token, id_token, token_type: "Bearer", … }`.
3. `GET /api/oauth/userinfo` — `Bearer <access_token>` → claims.
4. `POST /api/oauth/revoke` — revoke a token.

`POST /api/oauth/native/authorize` accepts a current **account API key** in the Bearer header. Only this POST also accepts an unexpired, unrevoked `GatewayOAuthAccessToken` issued to exactly `client_id=memory-hub`, using that token's account as the authorization owner. This identity-only SSO token does not authenticate shared account/client APIs, `GET /api/me`, or `POST /api/user-api-keys`; browser cookies do not authenticate this POST. Send JSON `{ "service": "<an official service below>", "authorization_url": "<URL returned by that service's SSO start>" }`. The response remains only `{ "redirect_url": "<the service's callback with code, state and iss>" }`. The client must preserve the service's host-only SSO binding cookie and complete that exact callback. Never expose authorization URLs, codes, cookies or credentials to an Agent or logs.

This native route permits only the following exact service/client/callback combinations, with exactly `openid email` (either order), state, nonce and PKCE S256. Each callback must also remain allowed by its enabled OIDC registration or built-in configuration.

| Service | Client ID | Exact callback |
| --- | --- | --- |
| `posttome` | `posttome` | `https://posttome.app/api/auth/sso/callback` |
| `union_memory` | `memory-hub` | `https://union-memory.sparse-agent.com/api/auth/sso/callback` |
| `memory_gateway` | `auto-coder-gateway` | `https://memory.sparse-agent.com/api/auth/sso/callback` |
| `cloud_bot` | `auto-code-bot` | `https://bot.sparse-agent.com/api/auth/sso/callback` |
| `agent_sheet` | `agent-sheet` | `https://sheet.sparse-agent.com/api/auth/sso/callback` |
| `sparse_agent` | `sparse-agent-gateway` | `https://sparse-agent.com/api/auth/sso/callback` |

It neither creates registrations nor grants Memory/Sheet/model scopes. The service retains PKCE verification, signed identity validation and account policy; PostToMe still requires a previously linked account. Missing or invalid Bearers (including expired/revoked credentials or SSO tokens for any other client) return 401, invalid requests or inactive registrations return 400, oversized bodies return 413, and unavailable authorization returns 503. Responses disable caching. This route must be deployed before clients can use automatic service authorization; a 404/405 means the server has not been updated.

Registered public clients include `auto-coder-gateway` (Index Gateway), `sparse-agent-gateway` (Sparse Agent workbench), `vilian-health` (Vilian health journal), and `posttome` (PostToMe). Each has its own exact callback allowlist. `vilian-health` accepts only `https://healthy.winclaw.cn/api/auth/sso/callback`; `posttome` accepts only `https://posttome.app/api/auth/sso/callback`. These two clients use `openid email`, authorization code and PKCE S256 for interactive login; they cannot request memory or offline scopes or refresh tokens. PostToMe requires explicit association with an existing PostToMe account. Redirects and authorization codes cannot be exchanged across clients. There is no self-service client registration.

Administrators can register additional public sign-in clients under **Site settings → OIDC clients**. These database-backed clients use authorization code with mandatory PKCE S256, state and nonce, allow only `openid email`, and require no `client_secret`. HTTPS callbacks and HTTP loopback callbacks are supported; every callback is compared as a complete string, including host, port, path and query. Wildcards, fragments, userinfo credentials and external HTTP callbacks are rejected. Built-in client IDs (including a configured default ID), `acchat-cli`, and `auto-coder-tui` are reserved and cannot be overridden, edited or disabled through this feature. Built-ins remain independent of the new registry's availability. Memory/offline scopes and refresh grants remain restricted to the existing confidential Memory client.

The Agent Sheet registration uses `client_id=agent-sheet`, display name `Agent Sheet`, and exactly `http://127.0.0.1:18080/api/auth/sso/callback`. Register it through the administrator UI; no code or production callback placeholder is needed. `localhost`, different ports, trailing slashes, extra query parameters and other clients' callbacks are not interchangeable with that registered URL. Agent Sheet manages its own device-code flow and credentials independently of Chat's `acchat-cli` device authorization.

Registry changes apply to subsequent authorize, token and userinfo requests without restarting the service. Disabled clients cannot start authorization, exchange codes or use access tokens at userinfo; their token revocation endpoint remains usable. Disabling does not retroactively invalidate a signed ID token already held and verified offline by an application; it retains its original expiry. Revoked tokens remain revoked after re-enabling.

Sparse Agent cloud memory uses the confidential client `sparse-agent-gateway-memory`, with the exact callback `https://sparse-agent.com/api/memory/oauth/callback` and scopes `openid email memory:read memory:write memory:model offline_access`. Memory scopes are restricted to this client; the public workbench login client cannot request them. Authorization-code exchange, refresh, and token revocation require `client_secret_post`: include the confidential client ID and its server credential in the form body. Missing, incorrect, or duplicate credentials return `401 invalid_client` without consuming the code or refresh token. The credential is shared only between Chat and the Sparse server; never send it to a browser, Agent, URL, command-line argument, log, or shared index.

The token response includes an opaque `mem_at_` access token, a one-use rotating `mem_rt_` refresh token, `audience=auto-coder-index`, and the granted scope. Refresh at the existing token endpoint with `grant_type=refresh_token`, `client_id=sparse-agent-gateway-memory`, `client_secret`, and `refresh_token`. Scope cannot be expanded during refresh. Refresh tokens expire after 90 days without renewal; replay revokes the entire grant family. Userinfo includes `aud`, `scope`, `client_id`, and `expires_at`. Index Gateway exempts only this Chat-verified memory client from invitations; it does not grant web membership, invitations, or administrative access. Legacy memory authorizations issued to the public Sparse client must reconnect in the workbench; cloud index content is preserved.

Memory authorization survives ordinary browser logout. Revoke either memory token at `/api/oauth/revoke` to revoke the entire family. Authenticated users can list safe grant metadata with `GET /api/oauth/grants` and revoke their own grant with `POST /api/oauth/grants` and `{"id":"<grant UUID>"}`; cookie writes require a matching Origin. Raw credentials are never returned by grant listing. Interactive SSO tokens retain their original lifecycle and cannot act as memory grants.

## 11. Public & utility endpoints

| Endpoint | Purpose |
|---|---|
| `POST /api/auth/register` · `/login` · `/logout` | Email/password session (cookie) |
| `POST /api/auth/change-password` | Authenticated password change |
| `GET|POST /desktop-login?callback=http://127.0.0.1:<port>/…&state&locale` | Loopback login flow for desktop CLIs; on consent mints an `ak_` key delivered to the callback |
| `GET /open/conversation?…` | Public conversation-open page (used by completion-notification deep links) |
| `GET /tunnel/{uuid}/{path}` and `tun-<uuid>.<host>/{path}` | Public port-preview proxy fed by the client's tunnel SSE channel |
| `GET /.well-known/assetlinks.json` · `/apple-app-site-association` | Android / iOS app-link verification |
| `GET /api/me` | Current user (`sub` of the key/session) |
| `GET|POST /api/user-api-keys` · `DELETE /api/user-api-keys/{id}` | Manage API keys |
| `GET|PUT|PATCH /api/user/saved-prompts` · `/api/user/agent-backend-settings` · `/api/user/voice-correction-hints` · `GET|PUT /api/user-app-states` · `GET|PUT|DELETE /api/me/pinned-conversations` | Account data |
| `GET|POST|PUT|DELETE /api/instances/{id}/conversation-groups` | Conversation grouping |
| `POST /api/handoff` · `GET /api/hosts/{host}/conversations` · `GET|POST /api/hosts/{host}/project-instances` (+`/actions`) | Handoff + host-scoped views |
| `GET /api/dream/agenda/reviews` · `GET .../reviews/{id}` · `POST .../approve` · `/dismiss` | Dream agenda review queue |
| `GET /api/git/projects` · `GET|DELETE /api/git/operations/{id}` · `POST .../resolve` · `GET|POST /api/git/sync-plans` · `POST .../sync-plans/{id}/execute` | Git-sync plans |
| `POST /api/leads` | Marketing/book-demo form (auth + 5/min rate limit) |

### Account saved prompts

`/api/user/saved-prompts` accepts a logged-in session or `Authorization: Bearer <user API key>` and always scopes storage to the authenticated account. `GET` returns `{prompts, revision, ownerId, max:50}` with `Cache-Control: no-store`. Clients should read online when opening the library; do not maintain a separate local source of truth.

Each item contains a UUID `id`, `display` (1–80 characters), `prompt` (nonblank, at most 100,000 characters, whitespace preserved), optional `flow` (at most 2,000 characters, default empty), `showOnNewChat` (default true), and ISO-8601 `createdAt` / `updatedAt`. `source` may contain `instanceId` and `conversationId`.

Use `PATCH` for individual changes: `{operation:"create", item}`, `{operation:"update", id, display, prompt}`, `{operation:"delete", id}`, or `{operation:"import", prompts}`. Creates/imports merge by stable ID without overwriting existing IDs; updates preserve web-specific fields. Concurrent changes to separate items are retained. Import is atomic and never evicts existing prompts; exceeding the account limit returns `409`. Android uploads its legacy library once and removes the local source only after receiving confirmation for every ID; failed imports retain the source for retry.

Whole-library `PUT` requires `{prompts, revision}` using the revision from `GET`. A stale revision returns `409` and does not overwrite newer device changes; refresh and reconcile before retrying. Malformed data returns `400`, missing authentication `401`. `PATCH` returns the updated account collection and revision.

## 12. Admin

`/api/admin/*` (models, rules/workflows review queue, site settings, app API keys, leads, metrics, maintenance) requires a session cookie on an admin account. Not part of the public integration surface.

OIDC client administration also requires an administrator cookie; writes require a matching trusted Origin and JSON content type. `GET /api/admin/oidc-clients` returns `{clients, builtIn}` without secrets. `POST` accepts `{clientId, name, redirectUris: ["https://example.com/api/auth/sso/callback"], enabled: true}`. `PATCH /api/admin/oidc-clients/{clientId}` accepts a nonempty subset of `{name, redirectUris, enabled}` plus the current integer `revision`. Client IDs are immutable; stale revisions and reserved or duplicate IDs return `409`. Disable with `enabled:false`; records are retained. Invalid callbacks return `400`, unauthenticated callers `401`, non-admin callers `403`, and missing clients `404`.

## 13. Errors & limits

- `400` validation (zod first issue message) · `401` missing/revoked auth · `403` forbidden scope · `404` not found / not owned · `409` lost a race (claim, duplicates) · `413` upload over limit.
- Pending-poll batch: 10 runs. File batch register: 100. `limit` on list endpoints: ≤ 100.
- Leads: 5 submissions / minute / user.
- Inline preview `content` is capped (use file previews for large artifacts); the uploads proxy enforces a server-side byte limit — prefer `uploads/init` for presigned direct upload.

## 14. Official clients

- **CloudBridge / `auto-coder.chat.lite`** — the executor; uses everything in §4–5.
- **`acchat`** — projects, backend/model catalogs, conversations, runs and kanban CLI; uses §4 and §7 with `Bearer ak_…`. Run `acchat --help` or `acchat --skill` for commands.
- **Android PythonMiao** — uses §5 agent-sync plus conversation/run reads.

### Project model commands (`acchat`)

```sh
acchat projects list
acchat models backends --project PROJECT_NAME --host HOST
acchat models list --instance INSTANCE_ID --backend BACKEND
acchat models refresh --instance INSTANCE_ID --backend BACKEND
acchat backends models BACKEND --project PROJECT_NAME --host HOST --available
acchat backends refresh BACKEND --instance INSTANCE_ID
acchat models list --instance INSTANCE_ID --backend auto-coder --all
acchat models get --instance INSTANCE_ID --backend BACKEND --model NATIVE_ID
acchat models current --instance INSTANCE_ID --conversation CONVERSATION_ID
acchat models select --instance INSTANCE_ID --conversation CONVERSATION_ID --backend BACKEND --model MODEL
acchat models default --instance INSTANCE_ID --backend BACKEND --model MODEL
acchat conversations send --instance INSTANCE_ID --conversation CONVERSATION_ID --backend BACKEND --model MODEL userText="Hello"
```

Model commands accept an instance or an unambiguous project name/path (plus
`--host` as needed), and optional `--org ORG_ID`. Backend-specific listing
reads the saved catalog; an empty cache does not trigger refresh. Explicit
refresh uses the existing agent-models POST. Combined backend/model discovery
and selection use CloudBridge slash commands and wait for their run results.
Copy native `backend`/`model` values from the catalog without rewriting IDs.
`select` persists one conversation's exact profile; `reset --conversation ID`
follows the default; `default` chooses an exact configured project profile;
`conversations send` sets the pair for one message. Global settings and the
configured profile list are preserved. A timeout is unconfirmed, and the CLI
retains the accepted run ID instead of resubmitting the command.

`--available` keeps catalog entries with `available=true` and `active!=false`;
it is not a credentials/quota/inference probe. `--all` includes inactive native
Auto-Coder entries, requires an online instance, and cannot be combined with
`--available`. `--live` reads the instance's local catalog instead of the server
cache. A full refresh may retain last-good/fallback entries for failed providers;
inspect each model's `sources`. Results include source and counts before/after
filtering. Backends are derived from returned models, so zero-entry backends are
absent. `models get` only reads an exact model; it does not change selection.

### User API commands (`acchat` v0.3.0)

```sh
acchat api list
acchat api describe folders.assign
acchat conversations --help
acchat conversations list --project PROJECT_NAME --host HOST
acchat conversations send --instance INSTANCE_ID --conversation CONVERSATION_ID --data-file message.json
acchat runs cancel --instance INSTANCE_ID --run RUN_ID
acchat run-files upload --instance INSTANCE_ID --file report.pdf runId=RUN_ID
acchat project-meta refresh --instance INSTANCE_ID
acchat api call folders.assign --data-file assignment.json
```

The offline API directory describes 74 operations across conversations, run
lifecycle, files/previews, project capabilities, stage, goals, chat sync,
folders/pins, account preferences, app state, hosts, agenda reviews, Git sync,
audit, rules/workflows/tools and voice helpers. Group help and the full
`acchat --skill` reference are generated from the same dispatch definitions.
Existing project/model and board/issue commands remain available.

GET `key=value` fields become query parameters. Mutations accept JSON objects
via `--data` or `--data-file`; multipart uploads retain form fields. Use
`--output` for downloaded bytes. Requests never automatically repeat mutations.
Public conversation IDs and database record IDs are different; read receipts,
dismissal and folder assignment use the latter. Acceptance is not completion;
force-cancel does not prove the process has stopped.

These wrappers use user-key or public routes; they do not change server
authentication. Cookie-only administration (groups, tunnels, external-session
bindings, organization membership/roles/invitations/ownership, site features,
API key administration, rule/workflow submissions), admin routes and executor
protocols are not included. A static CLI command listing is not a guarantee
that every route exists in an older deployed server.

## 15. Account chat sessions and durable turns

These endpoints share the existing user cookie / Bearer authentication. Ownership
comes from the authenticated account; clients cannot supply a different user ID.
Android and iOS can use the same contract. A client-side queue schedules local
work; it does not claim or execute PC Cloud runs.

| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/api/client-chat/sessions?cursor=0&limit=50` | Account change feed including tombstones; limit 1–200 |
| GET | `/api/client-chat/sessions/{id}` | Current session descriptor or tombstone |
| POST | `/api/client-chat/sessions` | Create, update or delete using revision comparison and a permanent request receipt |
| POST | `/api/client-chat/turns` | Start/heartbeat/dispatch/abandonDispatch/finish a turn |
| GET | `/api/client-chat/turns/{id}` | Reconcile the turn and its actual Cloud runs before retrying |

Session writes use `{requestId,id,baseRevision,deleted,session?}`. For a live
session, `session` contains `title,pinned,interactionMode,createdAt,content,blobRefs`.
`content` is `{format:"pythonmiao.chat-session.v1",sha256,sizeBytes}`; upload and
complete the body and attachment blobs through `/api/client-agent-sync/blobs/*`
first. Each blob is account-owned; body bytes and SHA must match. A create uses
`baseRevision:0`; delete uses `deleted:true`. Titles have a 200-character limit,
blob references a 2000-item limit, body/blob size a 64 MiB limit.

A write returns `{protocolVersion:1,userId,session}`. A feed returns
`{protocolVersion:1,userId,changes:[{seq,session}],nextCursor,hasMore}`. The cursor
is an account sequence encoded as a decimal string, not a timestamp. Fetch from
zero on a new device and continue until `hasMore:false`. Apply the latest revision
per ID, including tombstones. Replaying the same request ID and body returns its
original receipt; changing a request body requires a new ID. A 409
`revision_conflict` carries the authoritative session. Network/auth/server errors
must preserve the last cache and cursor; they are never an empty successful feed.

Turn writes use `{id,sessionId,owner,action}` with stable UUIDs for `id` and
`owner`. Start requires an existing session and returns 409 `session_busy` if a
different turn owns an active lease. Heartbeat renews the lease. Dispatch adds
`dispatch:{id,instanceId,conversationId,request}` before sending the exact messages
request, whose optional `clientRequestId` equals that dispatch ID. Replaying that
messages request creates at most one run under the same account/target; deleting
a run does not permit its request ID to recreate it. `abandonDispatch` uses the
same target/ID and prevents a late request from starting cancelled work.
`finish` adds `status:COMPLETED|FAILED|CANCELLED`; outstanding runs or helper
children keep the turn waiting. Read receipts before resuming a persisted queue.
GET returns `{protocolVersion:1,turn}`, including the original dispatch requests,
actual run IDs, upload state, child-run state and lease/terminal information.
Never treat a failed read as proof that a request was not sent.

## 16. Project agents.md

`POST /api/instances/{id}/agents-md` accepts exactly a request UUID and either
`{action:"read"}` or `{action:"edit",content,expectedHash}`. `expectedHash` is the
last read SHA-256, or `"missing"` when creating the file. It returns
`202 {protocolVersion:1,runId}`. Poll
`GET /api/instances/{id}/agents-md?runId={runId}`: 202 means pending; a successful
terminal response contains `{protocolVersion:1,runId,ok:true,file}`. `file` includes
`path,relativePath,exists,content,hash,mtime,sizeBytes,characters,lines,maxBytes`.
A missing file is `exists:false`, not an empty successful file. An empty existing
file is valid. File-operation failures return `ok:false,code,message`.

The target CloudBridge advertises `projectMeta.agentsMdVersion:1` and resolves only
its own root-level case-insensitive `agents.md`. No request path is accepted.
Multiple case variants, links, binary/invalid UTF-8 or content above 102400 bytes
are rejected explicitly. Reads/writes use a hidden deterministic control run;
same-body request replay does not repeat an edit. Editing requires the prior hash.
Instance ownership and existing organization access checks apply.

For ordinary work, add `projectAgentsMd:true` to the existing messages request.
The server rejects an unsupported executor with 426 instead of ignoring rules.
The executor loads exact file text for the next model request / Goal turn /
workflow step and replaces the previous rule version, avoiding history growth.
The Android tools `read_agents_md` and `edit_agents_md` use this same contract.


### Bot main activity (2026-11-04)

The existing `bot.progress` envelope also carries `event.type = "activity"`.
`detail` is a JSON display snapshot with `v:1`, stable `id` / `message_id`,
`part`, monotonic `revision`, `role`, `content`, `tool_detail`, `tool_completed`,
and `markdown`. It contains the original TUI-visible display only.
Parts join by message ID and numeric part. Updates retain `first_id` for
transcript order; `id` advances for cursors. Older/equal revisions are idempotent.
The bounded store keeps the latest snapshot of each part (1000 events per run).
SSE and HTTP history preserve the same fields, without granting execution rights.
Original worker reports remain `type=progress`; older clients may ignore activity.
The executor coalesces display updates every 250 ms and replays its in-memory
tail on socket reconnect; unsent activity is not a durable execution receipt.


## Bot 最近消息窗口

`GET /api/instances/{instanceId}/conversations/{conversationId}/bot-history`（网页会话或 Bearer API key；实例所有者／已有组织管理员权限）。只用于已注册的 `auto-coder.bot.cloud` 实例；会话既不匹配原共享绑定、也不属于已登记主 Bot 时返回 409。

返回 `{ limit: 1000, runs: [...] }`，按创建时间、ID 从旧到新排列。所有轮次合计最多 1000 条显示记录：用户输入、回复、错误、进展／操作各算一条。最早轮次可能只保留尾部内容。每轮带 `events`、`bots` 和独立单调的 `nextId`；裁剪不能重置游标。旧记录不从 canonical 会话删除；该显示接口不提供向前翻页。响应为 `private, no-store`。Bot SSE 的初始快照使用相同窗口，后续实时事件由客户端持续裁剪。普通项目的完整历史／搜索接口契约保持不变。

网页 Bot 的首次读取、刷新与断线重连均使用这个有界快照，不能用默认 50 轮的普通 `/runs` 结果覆盖它，也不能收到一条启动回执就停止补齐历史。网页按旧到新显示，最新内容在底部；`progress` 与 `activity` 都进入同一个显示预算。`activity.detail` 的正文分片和工具输出按同一 Bot 的稳定身份／revision 合并，旧快照不能覆盖较新的修订或终态。进展缺失时，已有的最终回答也必须可见。

## Bot 文件与图片

继续使用 LiteRunFile 与现有 StorageProvider，不另建存储。入站顺序：

1. `POST /api/instances/{instanceId}/conversations/{conversationId}/messages`，带 `hasFiles: true`，取得 `uploadRunId`。
2. `POST /api/instances/{instanceId}/uploads/run-files`，multipart `runId`、`file`。单条最多 100 个输入附件，每个非空且不超过 20 MiB。
3. `POST /api/instances/{instanceId}/runs/{uploadRunId}/files` 登记 `kind: "input"`；protocol v1 的每项配对传 `requestId` 与 `checksumSha256`，保留响应中的 `files[].id`。
4. `POST /api/instances/{instanceId}/runs/{uploadRunId}/publish`，JSON `{ "fileIds": ["登记返回的 id"] }`，携带同一 Bot 操控证明（header 或 `botControl`）。清单必须非空、唯一且与这一轮已登记的 input 文件完全一致。缺少清单返回 400；文件缺失、属于别轮或为 artifact 返回 409，保持 `uploadPending`，不派发。成功后的同清单重试可安全确认成功。任何上传／登记／publish 失败都应保留草稿和附件，不继续发送空清单。

出站沿用执行端的上传与 `POST /api/client/runs/{runId}/files` 登记，明确传 `kind: "artifact"`，归属产生这份文件的 run。产物代理仍限制为 10 MiB；`file_previews` 不是本通路的必需步骤。

Bot history 与 SSE 的 `command` / `run.finished`（观看 WebSocket 为 `bot.run`）里，`run.files[]` 含 `id`、`fileId`、`runId`、`instanceId`、`kind`、`role`、`originalName`、`contentType`、`sizeBytes`、`checksumSha256`、`downloadUrl`。`(runId, role)` 标明消息归属：`input/user` 是用户输入，`artifact/assistant` 是同一轮的回复，不能将 artifact 放到用户气泡里。旧数据缺 kind 时按 input 处理。

手机使用的 `downloadUrl` 是 `/api/instances/{instanceId}/files/{fileId}`，可追加 `inline=1`，用已有用户身份认证。这里的 instanceId 始终是电脑 Bot 自己的实例，不是当前选中的项目实例。执行端 `run.ready` 保留 `/api/client/runs/{runId}/files/{fileId}` 下载地址，仅供执行端认证使用。文件登记提交后，复用现有观看通知，推送带完整文件清单的 run；未 publish 的输入不会提前发送到观看端或执行端。重连快照读取同一份 LiteRunFile。


## 主 Bot 分组（契约 1）

实例级权威目录使用 botGroups 命名空间；通用 user-app-states PUT 不允许写入。
GET /api/instances/{id}/bot-groups 支持 includeBots=1、ETag/304。
POST /api/instances/{id}/bot-groups/operations 接收 requestId、expectedRevision、action、params，可选 strict；action 为 create/rename/move/reorder/delete/undo。
GET /api/instances/{id}/bot-groups/operations/{operationId} 查询原始结果；GET 同级 operations?sinceRevision=N&limit=100 补读摘要。
GET /api/instances/{id}/bot-groups/events 提供 snapshot/changed/roots SSE，25 秒保活。SSE/WS 广播限单 Node 进程，多 worker 用 15 秒轮询兜底或另接共享总线。
用户写入须有实例管理权限和现有操控租约；执行端须使用匹配实例的凭据与 X-AC-Bot-Actor（owner runtime 已校验的 botId/runId/generation/capabilityHash，子 Bot 补充 rootBotId）。不要发送原始 capability。
403 CONTROL_REQUIRED 不占 requestId；冲突 409 含最新 state/revision；撤销窗口 24 小时。根主 Bot 未绑定会话时 Bot 写入返回 BOT_CONVERSATION_REQUIRED，不产生部分写入。
细节见仓库 docs/bot-groups/contract-v1.1.md 和 docs/bot-groups/README.md。本阶段尚未提供 @ 投递接口。


## Bot groups, mentions and deletion (contract v1.2)

Instance prefix: `/api/instances/{instanceId}`. Responses include `X-Bot-Groups-Contract: 1`. Groups GET returns revision and rootsDigest; ETag includes revision, content-only rootsDigest, rootsFresh, instanceOnline and the includeBots representation. Freshness/presence changes return 200 even at the same revision. Conditional GET supports 304 even when polling every 15 seconds. SSE `/bot-groups/events` and observer WS emit `bot.roots.updated {rootsDigest, revision}` after catalog refresh, including changes at the same group revision; fetch the new state when this digest changes. Broadcasts are local to one Node process.

- POST `/bot-mentions`: a user authenticates with a session or API key and supplies a valid control lease. The instance requires management access. Submit clientMessageId, sourceConversationId, sourceBotId, targetBotIds (1–5 distinct main bots), text and optional messageRef. Returns 202 with mentionId, expiresAt and deliveries.
- GET `/bot-mentions/{mentionId}` reads delivery states. POST `/bot-mentions/{mentionId}/deliveries/{deliveryId}/resend` uses the same authentication and control lease and accepts an optional stable requestId. Only FAILED/EXPIRED may be resent. Unaccepted deliveries expire after 24 hours.
- Executor callback POST `/api/client/bot-mentions/{deliveryId}/events` uses the exact owning instance Client API key. Types: bot.mention.ack (turnId, optional WAITING_RESUME substate), bot.mention.started (turnId), bot.mention.reply (turnId, finalText, finishedAt), bot.mention.failed (errorCode). Duplicate terminal reports have no effect. Reply cards do not create another run. Source conversation SSE and observer WS emit mention.delivery.updated.
- User group deletion requires action=delete and params.confirmText exactly equal to 确认删除 after trim. A Bot requesting deletion of a group uses POST `/bot-groups/{groupId}/delete-requests` with clientRequestId and expectedRevision, returning PENDING_CONFIRM.
- GET `/bots/{botId}/delete-preview` returns the scope fingerprint and execution capabilities. DELETE `/bots/{botId}` requires requestId, expectedChildCount, scopeFingerprint from that preview, confirmText set to 确认删除, and a genuine user session with a control lease. Bot actors instead POST `/bots/{botId}/delete-requests` with clientRequestId and expectedChildCount. HTTP 202 means EXECUTING; save the returned requestId and use GET `/bot-delete-requests/{requestId}` to reconcile the same confirmed request. GET `/bots/tombstones?since=<ISO>` returns up to 30 days of tombstones.
- The client UUID (`clientRequestId` in responses) differs from the server `bdr_…` requestId. If the first ACK is lost, cookie-only GET `/bots/{botId}/delete-requests?clientRequestId={clientUUID}` recovers an existing request for that signed-in actor/instance/target without a control lease. A 404 does not create or confirm anything. Keep the original request/body after uncertain delivery; never generate a replacement ID. DELETED with cleanupPending=true is still being reconciled.
- Preview capabilities are exact booleans `{delete,deleteDefault,force,scopeFingerprint,asyncDelete}` from the actual owner/server intersection. New delete requires delete + scopeFingerprint + asyncDelete; default/force require the corresponding capability. Missing or invalid capabilities fail closed with upgrade text. PUBLIC scope combines the owner fingerprint and frozen cloud conversation IDs/PKs/default binding; user requests never send the OWNER hash. Same-count identity changes return CHILD_COUNT_CHANGED plus a new public preview before any stop/delete.
- Deleting the default Bot clears only its matching old binding and leaves defaultBotId=null; it never remaps the old chat. Instance control/new-root creation continue, and remaining roots keep their derived conversation IDs. After admission the confirmation input interceptor is released and users may continue chatting or switch Bot. The owner outbox completes cleanup independently of open UIs.
- A Bot's pending main Bot deletion returns `confirmationWord` and displays it in the initiating conversation. The user re-enters that exact word in the same conversation with an active control lease. A changed deletion scope requires the newly displayed word.
- POST `/bots/delete-requests` with `botIds` and `clientRequestId` to request deletion of several peers at once. One user confirmation covers the exact listed selection. Status returns `botIds` and `botCount` for the entire batch.
- Only genuine user input on the request conversation can confirm/cancel a pending deletion. API key, bot/tool or executor input never confirms. Group requests and legacy pending requests use 确认删除 when that is the displayed word. Enter 取消 to cancel. An input containing 删除 that does not match the displayed word counts as one attempt; three mismatches cancel the request. Bot deletion requires an online executor supporting async deletion and scope fingerprints. Deleting the default Bot requires explicit executor support. Running subtrees require a confirmed request with `force:true` and executor support; a Bot actor still cannot delete its own root. A changed scope requires a fresh confirmation. Reuse the same requestId after timeout.
- The exact owning instance Client API key can POST `/api/client/bot-delete-requests/{requestId}/events` with `type:"bot.delete.completed"`, requestId, botId, scopeFingerprint (the executor's fingerprint), `deleted:true`, childIds and, for a batch, botIds. Retry the same completion until the server returns DELETED without cleanupPending. The server validates the receipt against the confirmed scope before deleting cloud records.
- Instance SSE and observer WS emit bot.deleted and bot.delete_request.updated. Physical cleanup covers exclusive managed local attachments only; remote blobs and native backend history are retained by this server. The owner execution protocol and precise cleanup/retry rules are documented in `docs/bot-groups/README.md`.
