API Docs

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.

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.

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

2. Authentication

SchemeWhere it worksHow
API key (ak_…)Every non-admin /api/* routeAuthorization: Bearer ak_…
Session cookieEvery non-admin /api/* routeBrowser login (/api/auth/login); cookie set automatically
OAuth access tokenOIDC-aware clientsBearer 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.

EndpointAuthentication / requestResult
POST /api/auth/device/startPublic JSON {client_id, hostname:"YOUR_HOST"}; client ID is acchat-cli or auto-coder-tui201 {device_code, user_code, verification_uri, verification_uri_complete, expires_in:600, interval:5}
GET /api/auth/device/verify?user_code=ABCD-EFGHBrowser cookie; redirects to login if absentCode, registered client name, reported hostname, account, Allow / Deny form
POST /api/auth/device/verifyBrowser cookie, same-origin form and session/code-bound CSRFOne-use allow/deny; never returns a credential
POST /api/auth/device/tokenPublic 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/tokenPublic 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/statusExisting or device-issued Bearer API keyauthenticated, account email, credential name/id/expiry/issuer; no key
POST /api/auth/device/revokeDevice-issued Bearer keyIdempotent {revoked:true} for that key only; manual keys are rejected

This uses the RFC 8628 device-flow error semantics 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

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).

{
  "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

{ "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

{
  "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:

{ "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

{ "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

{
  "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

EndpointPurpose
GET /api/client/runs/{id}/files?scope=run|conversationList files attached to the run (or whole conversation)
POST /api/client/runs/{id}/filesRegister 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/initStart 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/proxyMultipart 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

EndpointPurpose
PUT /api/client/project-metaUpload project META: { instanceId, meta, refreshRequestId? }
POST /api/client/host-identityReport device identity: { instanceId, hostIdentity } → { ok, hostId }
POST /api/client/capability-usageRecord a skill/workflow invocation: `{ instanceId, kind: "skill"
GET /api/client/capability-usage?instanceId=Read back usage counters
POST /api/client/git-syncGit-sync actions: `{ action: "hello"

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.

同一实例的多个主 Bot(2026-11-06)

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

{ "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

{ "type": "bot.progress", "runId": "<uuid>",
  "event": { "type": "…", "bot_id": "…", "bot_name": "…", "phase": "…",
             "summary": "…", "detail": "…", "parent_id": "…", "role": "…" } }
{ "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)

EndpointPurpose
POST /api/client/dream/agenda/candidatesSubmit up to 100 agenda candidates
GET /api/client/dream/agenda/resultsFetch pending agenda results
POST /api/client/dream/agenda/results/ackAcknowledge 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.

EndpointPurpose
GET /api/client-agent-sync/identityWho am I — user + key identity
GET /api/client-agent-sync/sessions · /sessions/{id} · /sessions/{id}/executions · /executions/{id} · /executions/{id}/events · /executions/{id}/event-seqsRead the synced session / execution / event log
POST /api/client-agent-sync/blobs/initBegin 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 · /abortFinish or discard the upload
GET /api/client-agent-sync/blobs/{sha} · /blobs/{sha}/contentBlob metadata / bytes
GET /api/client-agent-sync/changes · /diff · /records/{kind}/{id}Delta queries for incremental sync
GET /api/client-agent-sync/exportFull export snapshot
POST /api/client-agent-sync/reconcile · /restore · /commitReconcile 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.

EndpointPurpose
GET /api/instances · DELETEList (?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&limitRun history
POST /api/instances/{id}/runsCreate 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=0Mobile/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 · /publishCancel / forward to a running agent / publish registered input files
POST .../runs/{runId}/force-cancelImmediately settle an active run as CANCELLED, without waiting for executor confirmation
GET .../runs/{runId}/previews/{previewId}/content · `GETPOST .../reviews`
`GETPATCH
POST .../conversations/open · /viewed · /dismissedOpen-state, read receipts, dismiss
`GETPOST
POST /api/instances/{id}/conversations/{convId}/messagesSend a message → creates a run. { userText, displayText?, shellAlias?, agentBackend?, agentBackendModel?, enableSubagents?, executionProfile?, projectCapability?, cursorModel?, hasFiles?, reviewBoardId?, reviewIssueId?, voiceTranscript? }
`GETPATCH .../conversations/{convId}/external-session`
POST .../conversations/{convId}/handoff · /saved-promptHandoff to another surface / save prompt
`GETPOST /api/instances/{instanceId}/conversations/{conversationId}/reports`
`GETDELETE /api/instances/{id}/files/{fileId}`
`GETPOST /api/instances/{id}/uploads/run-files`
`GETHEAD /api/storage/local`
`GETPOST /api/instances/{id}/agent-models`
`GETPOST /api/instances/{id}/project-meta`
`GETPOST /api/instances/{id}/stage`
`GETPOST
POST /api/instances/{id}/goal-controlGoal control commands
POST /api/instances/{id}/chat-syncChat sync
GET /api/runs/recentRecent runs across instances (cursor pagination)
GET /api/conversations/catalog?limit=200&offset=0&asOf&folderIdAccount-wide conversation pages, ordered by latest visible activity; limit 1–500. folderId is a folder UUID or unfiled; omit it for all conversations.
`GETPOST /api/conversation-folders`
`PATCHDELETE /api/conversation-folders/{id}`
POST /api/conversation-folders/assignAtomically assign { recordIds: [UUID, …], folderId: UUID | null, expectedFolderIds?: { "record-UUID": "previous-folder-UUID" | null } }; 1–500 owned conversations. Null removes folder membership.
GET /api/site-featuresFeature 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.

EndpointPurpose
`GETPOST /api/boards·PATCH
POST /api/boards/{id}/transfer-to-orgMove a board into an org
`GETPOST /api/boards/{id}/issues`
`GETPATCH
POST .../issues/{issueId}/execute · /approve · /approve-and-commit · /reject · /cancelIssue workflow actions
PUT .../issues/{issueId}/reorder · POST .../issues/batchOrdering & bulk ops
POST .../issues/{issueId}/files · `GETDELETE .../files/{fileId}·POST .../uploads`
`GETPOST /api/orgs·GET
GET /api/orgs/{id}/members · `PATCHDELETE .../members/{memberId}·POST /api/orgs/{id}/transfer-ownership`
`GETPOST /api/orgs/{id}/roles·PATCH
`GETPOST /api/orgs/{id}/invitations·DELETE .../invitations/{invId}·POST /api/invitations/{id}/respond`
`GETPOST /api/orgs/{id}/instances·DELETE .../instances/{instanceId}`
/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/eventsAudit log

Organization board collaboration

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

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)

EndpointPurpose
GET /api/rules/market{ items: [{ name, displayName, description, revision, downloadCount, submittedBy, createdAt }] }
GET /api/rules/{name} · /api/rules/{name}/jsonLatest 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&archProxied command-tool catalog: { count, tools, cached, fetchedAt }
POST /api/rules/submissions · POST /api/workflows/submissions · GET /api/rules/mine · /api/workflows/mineSubmit 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.

ServiceClient IDExact callback
posttomeposttomehttps://posttome.app/api/auth/sso/callback
union_memorymemory-hubhttps://union-memory.sparse-agent.com/api/auth/sso/callback
memory_gatewayauto-coder-gatewayhttps://memory.sparse-agent.com/api/auth/sso/callback
cloud_botauto-code-bothttps://bot.sparse-agent.com/api/auth/sso/callback
agent_sheetagent-sheethttps://sheet.sparse-agent.com/api/auth/sso/callback
sparse_agentsparse-agent-gatewayhttps://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

EndpointPurpose
POST /api/auth/register · /login · /logoutEmail/password session (cookie)
POST /api/auth/change-passwordAuthenticated password change
`GETPOST /desktop-login?callback=http://127.0.0.1:<port>/…&state&locale`
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-associationAndroid / iOS app-link verification
GET /api/meCurrent user (sub of the key/session)
`GETPOST /api/user-api-keys·DELETE /api/user-api-keys/{id}`
`GETPUT
`GETPOST
POST /api/handoff · GET /api/hosts/{host}/conversations · `GETPOST /api/hosts/{host}/project-instances (+/actions`)
GET /api/dream/agenda/reviews · GET .../reviews/{id} · POST .../approve · /dismissDream agenda review queue
GET /api/git/projects · `GETDELETE /api/git/operations/{id}·POST .../resolve·GET
POST /api/leadsMarketing/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

14. Official clients

Project model commands (acchat)

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)

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.

MethodPathPurpose
GET/api/client-chat/sessions?cursor=0&limit=50Account change feed including tombstones; limit 1–200
GET/api/client-chat/sessions/{id}Current session descriptor or tombstone
POST/api/client-chat/sessionsCreate, update or delete using revision comparison and a permanent request receipt
POST/api/client-chat/turnsStart/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.