Client Protocoldoc/{zh,en}/design/client-protocol.md

Client Communication Protocol (`httpapi` v2)

Status: accepted 2026-11-26. P0, P1a and P1b are implemented in plugins/httpapi, on the Host port plugin.ClientHost and the provider contract plugin.RecordProvider (ADR 0015); sect

Status: accepted 2026-11-26. P0, P1a and P1b are implemented in plugins/httpapi, on the Host port plugin.ClientHost and the provider contract plugin.RecordProvider (ADR 0015); section 6 lists what is left out. This is the single protocol between the Orquelo Host and its thin clients. Related: architecture · deployment · ADR 0006 · ADR 0012 · client repository jazy333/orquelo-app.

1. Background

1.1 Clients

Every durable fact (runs, inbox, CAS questions, tool ledger, artifacts, delivery outbox) stays in the Go Host; clients are thin.

  1. jazy333/orquelo-app (Flutter). Desktop (macOS, Windows, Linux) can run a bundled orquelo as a sidecar on 127.0.0.1 or connect to a remote Host. Mobile (iOS, Android) is remote only, paired by QR code. Web is the same code against a same-origin proxy or an allowed CORS origin.
  2. orquelo tui (Go), attached to a local or remote Host; detaching never cancels a run. Proposed design: terminal UI.
  3. Across channels: a task started in Feishu can be followed in the TUI and approved on a phone; an answer on any channel settles it everywhere.

1.2 What v1 lacked

httpapi v1 had five endpoints and a JSON-lines outbox. It had no live stream, trusted a body user under one static token, had no uploads or artifact downloads, no conversation or question lists, no structured errors, and saw only its own connection's runs.

1.3 Constraints

  • ◆Clients never embed the Host or read orquelo.db; everything goes through this protocol.
  • ◆No client-specific Host branches: the pipeline Transport → Trigger → Runtime → Presentation → Delivery is unchanged. The Host gains one optional, generic port (plugin.ClientHost) and one optional provider port (plugin.WorkspaceDiffer).
  • ◆Field names come from pkg/plugin (RunView, QuestionView, SignInView, ArtifactRef, WorkspaceRequest, WorkspaceInfo, GoalRequest, Error).

2. Transport, authentication and errors

2.1 Channels and handshake

Commands and queries are JSON over HTTP under /v1, live updates are SSE at GET /v1/stream, and files are multipart uploads and streamed downloads. GET /v1/health needs no token:

json
{"status":"ok","protocol_version":2,"host_version":"0.4.2","host_id":"hs_…","mode":"loopback","capabilities":["messages","runs","questions","sse","pair","uploads","artifacts","catalog","workspaces","diff","deliveries"]}

mode is loopback when the listen address is a loopback one, else network. protocol_version grows only with a breaking change. On a Host without ClientHost, only messages, runs and questions are listed and the v2 routes answer 501 host.unsupported.

2.2 Who a request acts for

  1. Static token (v1, unchanged): Authorization: Bearer <token>. The client is a trusted proxy, for example a desktop sidecar or the operator's own service. It names the user with the body user, the X-Orquelo-User header or ?user=. A static-token call that names nobody keeps the v1 view of this connection's runs and conversations.
  2. Paired device: a signed-in client calls POST /v1/auth/pair/start and gets an 8-character code, valid once for 5 minutes. A QR code carries {host_url, code, host_id}. The new device sends POST /v1/auth/pair/exchange {code, device_name, platform} without a token and gets {device_id, token:"orq_dev_…", user, host_id}. The Host keeps only the token's SHA-256 (devices.json in the instance's data directory). After five wrong codes in a minute, exchanges get 429 for that minute. A device acts only as its user: a body, header or query naming anyone else is 400 auth.user_not_allowed. Its conversations are kept under <user>:; for example c1 becomes alice:c1.
  3. CORS is off by default. cors_allow_origins lists exact origins, and "*" is refused when the instance is built.
  4. Local client (terminal UI G5, built 2026-12-04). An instance with local_client lets orquelo tui on the same machine attach without pairing. It needs a loopback listen address, or the instance is refused. Each time its listener is up it writes local-client.json to its data directory, {url, token, user}, mode 0600, by a rename; the token is new at each start and starts with orq_loc_, and the file is removed when the instance stops. That token acts as local_user (local by default, the console's local user) and, like a device, names no one else (400 auth.user_not_allowed); a token of another start is 401. Its conversations are kept under <user>:, as a device's. The instance options channel, reply_format and questions give its runs the terminal's channel context: the channel name the model sees (plugin.ChannelNamer), the reply format and the question note.

Identity across channels is the Host's: a request's sender is resolved to a principal on this connection, and the person-scoped reads use that principal's user (ADR 0012 links).

2.3 Errors

Every non-2xx response carries:

json
{"error":{"code":"question.already_resolved","message_key":"question.already_resolved","params":{"reason":"already_approved"},"message":"…","retryable":false,"data":{"reason":"already_approved","current_version":2,"question":{…}}}}

code and message_key are stable and language-independent; message is for people. Statuses: 400 bad input, 401 unknown or revoked token, 403 not allowed, 404 missing or another person's, 409 CAS conflict or a delivery that is not failed, 413 too large, 429 rate limited, 501 Host without app-client support, 503 with Retry-After while the Host stops (host.stopping).

2.4 One service, many protocols

The protocol lives in a protocol-neutral service, plugins/httpapi/service, and HTTP is only its first adapter. Each operation a client calls is one service method that takes the caller and plain values: Send, History, GetRun, Answer, Subscribe and the rest. Each method fails with a stable code, which service.ClassOf sorts into a class such as invalid, forbidden, conflict or unavailable.

  • ◆The pipeline. Send is this channel's way into Trigger through TransportHost.Submit. Replies come back through the channel's own Present and Deliver, like any channel's, into the history and the stream. Reads and controls are direct calls on ClientHost, as a Feishu card click's are: they need a result now, so they are not events.
  • ◆What an adapter does. It authenticates, decodes, calls one operation and encodes, and it maps each class to one status of its own. It holds no protocol rule.
  • ◆Shared state. Every adapter of an instance shares one service, so a device paired over one protocol works over all of them.
  • ◆Keeping adapters complete. A test holds the HTTP routes to the service's operations, so no operation can be left without a route. WebSocket and gRPC are not built. When they are, they become listeners of the same instance held to the same list, and gRPC uses typed .proto messages.

3. HTTP API

3.1 Health and devices (P0)

Method and pathRequestResponse
GET /v1/healthno token200 as in 2.1
POST /v1/auth/pair/starttoken; static-token callers name the user, devices pair for themselves200 {code, expires_at, host_id}
POST /v1/auth/pair/exchangeno token; {code, device_name, platform}200 {device_id, token, user, host_id}; 401 auth.pair_code_invalid; 429 auth.rate_limited
GET /v1/auth/devicestoken200 {devices:[{id, name, platform, user, created_at, last_seen, current}]}, the caller's, or all for an admin
DELETE /v1/auth/devices/{id}the owner or an admin204; the token is refused at once and the device's open streams close

3.2 Conversations, messages and runs (P0)

Method and pathRequestResponse
GET /v1/conversations?state=active&limit= (at most 100, 50 by default) &cursor=&workspace=200 {conversations:[{id, connection, kind, last_input, active_run_id, active_state, last_run_id, last_state, pending_questions, runtime, updated_at, workspace?}], next_cursor?}, the person's on every connection, by their newest run; workspace is the newest run's accepted path, else its workspace name, and ?workspace= keeps only those whose workspace is that (a path compared clean); next_cursor is absent on the last page, and pages never repeat or skip a conversation; a cursor the Host did not give is 400 request.bad_cursor
POST /v1/messages{id, conversation?, text, attachments?:[{upload_id}], runtime?, workspace?, goal?, labels?, user?, name?, locale?, timezone?, context_from?:{connection?, conversation}} (terminal channel C3, C6: locale is a BCP 47 tag the run speaks to people in, ahead of the connection's default, else 400 request.bad_locale; timezone is an IANA zone for the run's dates, else 400 request.bad_timezone, and neither says who the sender is; context_from carries the recent turns of another of the person's conversations, this connection's when connection is empty, as the message's channel context, else 404 conversation.unknown; an attachment {path} is 400 attachment.path_not_allowed until the local client may send one)202 {event_id, conversation}; idempotent by id; 503 with Retry-After while stopping
GET /v1/conversations/{id}/messages?after_seq=N&limit= (v1's ?after=N still lists the replies only, without role: user and latest_seq)200 {messages:[{seq, delivery_id, conversation, role, user?, kind, text, runtime, question?, file?, update_of?, created_at}], latest_seq}
GET /v1/events/{id}, GET /v1/runs/{id}path id200 RunDetail: RunView plus connection, conversation_id, runtime, input, workspace, created_at, started_at, finished_at; another person's run is 404 run.unknown
GET /v1/runs/{id}/activitypath id200 RunActivity {run_id, conversation_id, active, at, view}: the latest structured progress of a run of the person while it runs (view: todos, steps with key, tool, summary, state, result, text, usage with tokens_in, tokens_out, context_pct and, from the model calls the Host recorded, model and cost_usd; a step's summary is its first short argument, such as a command or a path); an empty view when the run is not running or reports none (ADR 0022); another person's run is 404 run.unknown
POST /v1/runs/{id}/cancelempty202 {state:"cancelling"}, or 200 {state} when the run already ended

A message sent to a conversation whose run is still going is steered into it by the Trigger (ADR 0006), as on every channel; there is no steer endpoint. runtime names one of the catalog's runtimes, the runtimes the person's @ routes reach. The message then goes there as @runtime text does in chat, and the conversation is pinned to that runtime. Any other value is 400 runtime.unknown, and no run starts. A model is chosen by the runtime, not by the request. role is user for the messages posted here and assistant for replies. The history lists this connection's conversations only; the person's runs elsewhere are read through /v1/runs/{id}.

3.3 Questions (P0)

Method and pathRequestResponse
GET /v1/questions?status=pending&conversation=200 {questions:[QuestionItem]}: QuestionView (with sign_in, and for the Host's approval of a tool call subject {tool, args_digest, preview {kind: command|diff|text, path?, body, truncated?}}: the command, an edit as a unified diff without line numbers, or else text such as a file's new content or the arguments as the prompt shows them, at most 8 KiB on a character boundary; TUI design G3) plus run_id, connection, conversation_id, can_answer, expires_at, for the person's runs and those the person may answer
POST /v1/questions/{id}/answer{version, value, choices?} (approval: approve, approve_conversation, reject; ask: text and option labels; sign-in: the secret)200 {accepted:true, message, question}; the question of an answer, of a 409 and of the question.* events names who settled it: by (the principal id), by_name (the display name, else the id in that channel) and by_connection (the connection's id); a settled or expired question is 409 question.already_resolved, an old version 409 question.stale, both with data.question; 403 question.not_allowed; 400 question.invalid_choice

A sign-in secret passes through to the Host and is never logged by the channel.

3.4 Uploads and artifacts (P0)

Method and pathRequestResponse
POST /v1/uploadsmultipart/form-data, field file; at most upload_max_mb (32 MiB by default)201 {upload_id, name, mime, size, expires_at}, the sender's for 24 hours; 413 upload.too_large
GET /v1/artifacts/{id}If-None-Match, Range (a download resumes: 206 with Content-Range, 416 past the end)200 stream with Content-Type, X-Content-Type-Options: nosniff, Content-Disposition: attachment, ETag; 304 when unchanged; any id not of the person's runs is 404 artifact.not_found

A message attaches only the sender's own uploads; another's upload_id is 404 upload.not_found.

A large file is sent as a resumable upload (media harness review M-12), at most upload_max_mb like a one-shot upload:

Method and pathRequestResponse
POST /v1/uploadsContent-Type: application/json, {user?, id?, name, size, mime?}; id is the client's own (8 to 64 of A-Z a-z 0-9 _ -), made when absent201 {id, upload_id, name, mime, size, received: 0, state: "open", expires_at}; the same user opening the same id and size again gets 200 with its state; another user's id, or another size, is 409 upload.id_taken; over the limit 413 upload.too_large
PATCH /v1/uploads/{id}header Upload-Offset, raw bytes200 with the state; a chunk wholly within the bytes received changes nothing (a replay); a chunk overlapping their end adds only its tail; an offset past them is 409 upload.offset_mismatch with received; bytes past size are 413 upload.too_large; neither stores anything; after completion only a replay is taken (409 upload.complete otherwise)
GET /v1/uploads/{id}200 {id, upload_id, size, received, state, …}
POST /v1/uploads/{id}/complete200 {state: "complete", upload_id, …}; a message attaches upload_id like a one-shot upload's, for 24 hours; before all bytes 409 upload.incomplete, the upload staying open; again after completion, the same reply

An unknown id or another user's upload is 404 upload.not_found. A chunk, a status or a complete need not name the user: under the static token a call that names none acts as the upload's own user, and a device call is always its own user's. Bytes are written to the instance's data directory as they arrive and counted in the upload's record after they are synced, so a connection cut mid-chunk keeps what arrived and a Host restart keeps the upload: the client asks GET for received and goes on from there. An upload not completed within upload_resume_hours (24 by default) of being opened is removed with its bytes by an hourly sweep (upload.expired in the log).

3.5 Catalog, workspaces, diffs and deliveries (P1a)

Method and pathResponse
GET /v1/catalog{directives:[{sigil, name, kind, owner, aliases, description}], runtimes, workspaces, default_runtime, models, connection}: the directive table the person sees in a direct chat here (P84), the runtimes the person's @ routes reach, the workspaces open to them, the connection's own runtime, and the vendor model each of these runtimes used last ({runtime: model}; a runtime without a recorded model call is left out), and the caller's own connection
GET /v1/workspaces{workspaces:[WorkspaceInfo]}
GET /v1/runs/{id}/diff{workspace, base, files:[{path, added, removed}], diff, truncated} for a run in a task worktree, committed or not (untracked new files left out, 1 MiB at most); otherwise 404 workspace.diff_unsupported
GET /v1/runs/{id}/traceThe run trace (plugin.Trace) of a run of the person, as /trace shows it in a direct chat: spans with model and tool calls, their times, results and approvals, findings and scores; another person's run is 404 run.unknown (TUI design G2)
POST /v1/runs/{id}/rating{value: up|down} rates a finished run of the person on any connection, with the checks a rating from its own channel has: 200 {accepted, message}; a value other than up or down is 400 rate.invalid, checked first; a run without a delivered final reply is 409 rate.refused with data.message; another person's run is 404 run.unknown (TUI design G4)
GET /v1/runs/{id}/deliveries{deliveries:[{id, run_id, connection, conversation_id, purpose, kind, state, attempts, ref, error}]}: every destination of the run
POST /v1/deliveries/{id}/retry202 with the delivery queued again; the runtime does not run again; one that is not failed is 409 delivery.not_failed

3.6 Memory, skill drafts, plugins and egress (P1b)

Memory, drafts and routes live in provider plugins (plugin.RecordProvider, ADR 0015 decision 6) in the uses of the connection's runtime: memory, skill-workshop and the egress provider mihomo. The Host passes the caller's trusted principal, and each provider applies the same rules as its tools.

Method and pathRequestResponse
GET /v1/memory?q=&scope=user|chat|shared&limit=200 {memories:[{kind, id, source, scope, text, updated_at, data:{kind, origin, version}}]}: what the person's own context may read
PATCH /v1/memory/{id}{text}200 with the next version; a shared memory needs an admin (403 record.not_allowed); another person's id is 404 record.unknown
DELETE /v1/memory/{id}none204, every version forgotten; 404 record.unknown
GET /v1/skills/draftsnone200 {drafts:[{id, title, text, state, data:{name, action, kind, digest, validation, version, note}}]}: the person's own, or every draft for an admin
POST /v1/skills/drafts/{id}/publish{digest} from the listadmin only; 200 with the published draft; 409 record.stale when the content changed since it was read; 501 record.unsupported without the workshop's manage grant
POST /v1/skills/drafts/{id}/discard{note?}admin only; 200 with the rejected draft
GET /v1/pluginsnone200 {plugins:[{id, plugin, version, roles, status, reason, enabled, name, description}]}, without options or secrets
PATCH /v1/plugins/{id}{enabled, allow_system?}admin only (403 auth.forbidden); needs the httpapi instance's manage grant (501 manage.not_granted); a configuration revision, as orquelo instance enable makes
PUT /v1/plugins/{id}/secrets/{key}{value}admin only, 204; the value is never returned or logged
GET /v1/egress/rulesnoneadmin only; 200 {routes:[{id, title, data:{instance, domain, via, revision}}]}
PUT /v1/egress/rules{revision?, routes:[{instance?, domain?, via}]}admin only; replaces every route with the checks of proxy_route_set; 409 egress.revision_conflict when revision is not the current one

An admin is a caller whose principal the Host made one (the operator's admins list); holding the static token is not enough.

3.7 Push (P1b)

Method and pathRequestResponse
POST /v1/push/register{platform: apns|fcm, token}201 {device_id, platform, relay}; the same token again returns the same registration; 400 for another platform or no token
DELETE /v1/push/register/{device_id}none204; 404 push.not_found for one that is not the caller's

The Host never calls Apple or Google. When a question opens that a registered person may answer, httpapi posts {question_id, kind, title_key, platform, token} to push_relay_url, with Authorization: Bearer <push_relay_token>. It never sends the prompt, a message or a command, and the app renders title_key (push.question.approval, push.question.ask, push.question.sign_in). Questions from before a registration are not pushed. A 5xx or network failure is retried every 3 seconds, and after an hour that notice is skipped and logged; a 4xx is logged and dropped. Revoking a paired device removes its registrations. The relay request goes through the egress routes (egress: in_process).

4. Event stream (GET /v1/stream)

  • ◆Without conversation, the stream carries all of the person's facts; with ?conversation=<id>, only that conversation's. An admin also gets the question frames of approvals addressed to admins in other people's runs.
  • ◆Frames:
text
  id: 1042
  event: run.finished
  data: {"seq":1042,"ts":"2026-11-27T00:10:01Z","conversation_id":"c1","run_id":"r9","payload":{"state":"succeeded","connection":"web","result":"…"}}

The id is the Host's fact seq, so Last-Event-ID (or ?last_event_id=) replays what the client missed. Clients ignore event types they do not know.

  • ◆Types: hello {server_seq, heartbeat_ms}, always first and without an id. stream.resync_required {oldest_seq, latest_seq} when the cursor is older than the oldest fact kept; the client reloads conversations, messages and questions and then follows from latest_seq. run.started {state, connection, attempt}. run.finished {state, connection, result}. question.opened, question.updated (a sign-in view changed, for example a new QR code) and question.resolved (settled on any channel), each with the full QuestionItem at that point. tool.started {tool, key} and tool.finished {tool, key, is_error}. subagent.updated. delivery.updated {delivery_id, purpose, state, connection, error}. message.created (the stored message, for a delivery to this channel). message.progress (the replaceable progress text, sent to open streams only, without an id). run.activity (a RunActivity of one of the person's running runs on any connection, at most every 100 ms per run, without an id and not replayed; ADR 0022).
  • ◆A : keepalive comment every 30 s. Replay reads the Host's fact log, kept as long as its retention says; nothing is held in memory beyond the open streams.

5. Traces

  1. Chat with a file: POST /v1/messages {id:"m1", conversation:"c1", text:"Review the architecture"} → 202. The stream then carries run.started → message.progress… → run.finished → delivery.updated + message.created (text) → delivery.updated + message.created (file). The client fetches GET /v1/artifacts/art_1.
  2. Reconnect: a phone loses the stream and reconnects with Last-Event-ID: 1042. Facts after 1042 are replayed. If they are gone, stream.resync_required comes first and the client reloads with GET /v1/conversations, GET /v1/conversations/c1/messages?after_seq=… and GET /v1/questions?status=pending. No run starts again.
  3. Approval race between Feishu and the app: question.opened(q1, version 1) is shown in Feishu and in the app. The person approves in Feishu, so the Host commits version 2 and the app's stream gets question.resolved. An app answer still sent with version 1 gets 409 question.already_resolved with data.question.version 2.
  4. Denial and drain: user B asks for user A's GET /v1/artifacts/art_a and gets 404 artifact.not_found. POST /v1/messages while the Host stops gets 503, Retry-After: 30, host.stopping; the client retries with the same id.
  5. Delivery retry: the Feishu delivery of a run fails while the app's succeeds. GET /v1/runs/r9/deliveries shows failed for Feishu. POST /v1/deliveries/d7/retry queues only that delivery, and the runtime is not run again.

6. Not in this version

Token-level message.delta and tool.progress are not built: the streamed text, the tool calls with their states and the usage come as run.activity (ADR 0022), and the progress text as message.progress. A separate steer endpoint is not built either (ADR 0006), nor are the WebSocket and gRPC adapters (section 2.4). ClientHost is offered to builtin transports only. The machine-readable contract is api/httpapi/v2/openapi.yaml.

7. Verification

  • ◆Unit tests: plugins/httpapi (pairing, single use, rate limit, revocation closing a stream, spoofed user, 409 with the question, sign-in secret not logged, uploads per sender and the size cap, resumable uploads (offsets, replay, gap, overflow, early completion, a cut chunk, a restart, expiry), replay and resync, history roles); internal/host/engine client_test.go (person scoping across linked accounts, cross-person denial of runs, questions, facts and artifacts, a racing answer, retrying one failed delivery without rerunning the runtime); plugins/localenv (Diff).
  • ◆veruqelo session client-protocol: interface cases on http-echo and one e2e case. A Feishu-and-app race needs a Feishu runner, which does not exist yet.