# HTTP API behavior This guide describes ordering, retries, recovery, and caller obligations for daemon protocol 3. [OpenAPI](openapi.yaml) owns exact routes, methods, request fields, response fields, variants, and limits. Its document-format version is separate from the daemon protocol version. [API architecture](http-api-architecture.md) owns implementation and persistence boundaries. [Client API ownership](client-api.md) describes the Go adapter. Follow [Change the HTTP API](contributing-api.md) when editing a contract or adding an operation. ## Contract boundaries Resources group domain operations, rather than matching individual screens. JSON reads and SSE watches use the same resource URL with different `Accept` headers. Ordinary HTTP requests perform changes. SSE delivers updates. An input ID identifies submitted intent across retries. A stream cursor identifies an actor lifetime and position. A transcript checkpoint identifies durable history. Those identities are not interchangeable. The daemon owns execution, argument parsing, storage inspection, and bounded progress. Clients own navigation, drafts, rendering, and confirmations. Local discovery and process replacement remain application policy outside the API connection. Bounds apply before subscriber mailboxes. Model execution does not wait for a client socket to drain. [Session streams](http-streams.md) describe replay and overflow behavior. ### Reading and changing the wire contract OpenAPI defines required, optional, and nullable fields. `DynamicJSON` marks provider-private or extension-specific data inside typed envelopes. A client may ignore unknown response fields, but it must validate required fields and known variants. An SSE event's `data` is a string containing JSON. Decode it before validating the declared `contentSchema`. Validating the outer string does not validate its contents. OpenAPI's byte-limit annotations also require runtime checks. JSON Schema `maxLength` counts Unicode code points, not encoded bytes. The [contribution guide](contributing-api.md) separates required validation work from the [existing verification evidence](#verification). ## Resource map This table is a navigation guide, not an exhaustive route or method inventory. The `paths` section of [OpenAPI](openapi.yaml) defines supported operations, including routes not shown here. [`server.gleam`](../src/albedo/daemon/server.gleam) dispatches core requests. Extensions dispatch their own services. | Resource family | Behavior in this guide | | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `/server`, `/server/shutdown` | [Readiness and instance-targeted shutdown](#server-identity-and-shutdown). | | `/settings`, `/storage`, `/usage` | [Shared settings and accounting](#server-settings-and-storage). | | `/sessions` and `/sessions/{session_id}` | [Browsing, creation, configuration, deletion, and input](http-sessions.md). | | `/sessions/{session_id}/shell-commands/{command_id}` | [Human shell commands](http-sessions.md#human-shell-commands), stop, and output reads. | | `/sessions/{session_id}/side-questions/{question_id}` | [Side questions](http-sessions.md#side-questions) and cancellation. | | Session history and active-output resources | [Durable content](#durable-history) and [unfinished-output recovery](http-streams.md#session-watch). | | Session context, catalog, reload, kernel, and compaction resources | [Observation and runtime changes](#history-context-catalogs-and-runtime). | | `/models`, `/workspaces`, `/hosts`, and session file and checkout-change resources | [Models and workspace observations](#models-workspaces-hosts-and-provider-login). | | `/auth` and its login and account resources | [Provider login](#models-workspaces-hosts-and-provider-login). | | `/extensions/{extension_name}` | [Extension-owned operations](http-extensions.md). | Session creation uses the `SessionCreationRequest` union in OpenAPI. History kinds come from `HistoryEntry`, and published event variants come from `SessionEvent`. This guide explains their semantics without maintaining parallel enum lists. ### Opening a chat 1. Use the supplied base URL and bearer token to read `/server`. Check protocol and required capabilities before opening a screen. 2. Read `/sessions` for the picker or family graph. Each row includes its metadata and bounded live state. 3. Read the selected session. Install its history, pending inputs, status, progress, and cursor together. Count a deliberate opening with one identified visit. Background reads do not count. 4. Watch that same session URL as SSE, passing the installed cursor pair. Apply subsequent events, or replace the daemon-derived view on reset. 5. Send a message with an identified input PUT. Keep its local handle until the returned decision or matching stream event resolves it. Cancellation targets that input identity. 6. Fetch older history by durable position. Open context, catalog, or extension resources when the user needs them. Use the validator already displayed with a resource when editing it. ## HTTP rules ### Addressing and authentication A client receives a base URL and daemon bearer token. Native local clients may read the protected discovery record. Other clients receive both values through explicit connection setup. No API method reads client installation files, launches a daemon, or replaces one. Every platform request, including SSE, uses `Authorization: Bearer `. The token grants operator access to this daemon. This protocol has no user accounts, tenant isolation, or session ACLs. Provider OAuth accounts are model-provider credentials, not daemon identities. Browser OPTIONS preflights are the exception to bearer presentation. They return only allowed request metadata and cannot read or mutate resources. The default listener remains loopback. Connections across an untrusted network require HTTPS or an encrypted tunnel. Tokens never appear in URLs, response bodies, diagnostic logs, or stream events. Browser clients use `fetch` for JSON and SSE so they can send the authorization header. Native `EventSource` does not expose arbitrary request headers. [The SSE specification](https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface) defines its constructor and stream format. Browser access uses an operator-configured list of exact allowed origins. The daemon validates `Origin` before routing or reading a body. Allowed preflights advertise the supported method and headers, including `Authorization`, `Content-Type`, `If-Match`, and `If-None-Match`. Responses vary by `Origin` and expose `ETag`, `Location`, and `Retry-After`. There are no authentication cookies or wildcard origins. Origin approval does not replace the bearer check. This follows the [Fetch CORS protocol](https://fetch.spec.whatwg.org/#http-cors-protocol). The daemon validates the requested host against its listener and configured public addresses. A supplied origin or host never grants additional permission. Optional extension intake routes declare their own authentication policy. ### Encoding, limits, and pagination The SDK [`http_api.gleam`](../src/albedo/harness/sdk/http_api.gleam) owns the response limit, strict JSON decoding, and paging tokens. The daemon [`http_api.gleam`](../src/albedo/daemon/http_api.gleam) owns request body limits. [`http_coding.gleam`](../src/albedo/daemon/http_coding.gleam) owns content-coding negotiation. JSON uses UTF-8, `snake_case` field names, and tagged objects for variants. IDs are opaque strings. Paths and query values use ordinary percent encoding. Core timestamps are UTC RFC 3339 strings. Unknown historical timestamps are null. Durations use explicitly named units. Counters and sequence numbers are integers from zero through `2^53 - 1`. Unknown request fields, duplicate JSON keys, invalid enum values, malformed query values, and unknown query parameters return `400 invalid_request`. Requests do not silently substitute defaults for invalid values. Unknown response fields may be ignored. Missing required fields and invalid known variants fail decoding. `PATCH` uses `application/merge-patch+json`. Omission keeps a value, `null` removes an override or optional value, and `false` remains a real value. Arrays replace the complete array. Writable fields are listed for each resource. [JSON Merge Patch](https://www.rfc-editor.org/rfc/rfc7396.html) defines these rules. Ordinary JSON request bodies have a 64 KiB limit. Input admission has a 100,200,000-byte limit, room for ten encoded images and 20 MiB of decoded generic files. JSON responses and SSE data frames have a 1 MiB limit. The limits on each OpenAPI operation apply as well. HTTP body framing accepts valid fixed-length and chunked requests, enforcing the same byte limit while reading. Ambiguous framing, unsupported content encoding, and incomplete bodies fail without executing the operation. zstd is the one content coding. A JSON or text response of at least 1 KiB is compressed when `Accept-Encoding` admits `zstd`, and so is a session or collection event stream, flushed after every frame. Limits and `ETag` values describe the decoded representation, and these responses add `Vary: Accept-Encoding`. Image resources are never coded. The daemon needs OTP 29, whose `zstd` can flush a stream between frames. Frames use a 64 KiB window (`windowLog 16` in `albedo_http_api`), not level 1's 512 KiB default: the window is the memory a client's decoder must hold, and an event stream keeps one decoder for the client's whole life. When `GET /server` lists the `zstd_requests` capability, a request body may use `Content-Encoding: zstd`. It must be one frame that declares its decoded size, which must fit the route's limit. Anything else is `400`. The CLI compresses bodies of 16 KiB or more. Lists return `{ "items": [], "next": null }`. `next` is an opaque continuation token tied to the query and representation, including `limit`. Follow-up requests retain the original query and add `next`. Default `limit` is 50. Maximum is 200. Each page also respects its encoded byte limit, including JSON escaping. Catalog entries, glances, input outcomes, and reset snapshots obey that bound even when their item counts fit. Large content uses its documented paging path. Summary text is shortened explicitly. A single catalog entry is at most 64 KiB. Session glances include at most 16 entries of 8 KiB each. Tokens never contain credentials and cannot authorize access. A token for another query returns `400`. Missing singleton resources return `404`. An empty collection returns `200`. Collection traversal uses a stable sort key and ID as its tie breaker. Sessions use most recent activity first. A traversal is not a frozen global snapshot: concurrent edits can move rows. Clients key rows by ID and refresh on invalidation. History traversals use immutable transcript positions and do not have this limitation. ### Revisions and errors The [SDK HTTP contract](../src/albedo/harness/sdk/http_api.gleam) encodes problems and validators for the daemon and extension services. The domain owner checks the validator at its commit boundary. An `ETag` validates the complete selected JSON representation. Configuration has a separate representation from volatile session state. Session reads expose the URL and validator for `view=configuration`. Settings reads expose the URL and validator for each `group`. Editing those representations uses `If-Match` without conflicting with unrelated progress or another settings group. Extension item reads likewise expose the item's observed URL and validator. `PATCH` and conditional `DELETE` require the observed `If-Match`. Missing preconditions return `428`. Stale ones return `412`. Checks and the corresponding commit occur under the owning resource's serialization or transaction boundary. Validators are opaque. Clients never derive them from an integer revision. Mutation envelopes carry new resource validators explicitly and are not cached as canonical read representations. Errors use `application/problem+json`, with `type: "about:blank"`, `title`, `status`, `detail`, and a stable Albedo `code`. An optional `fields` array contains JSON pointers and safe explanations. Identified operation decisions can add a typed `decision` field. Clients branch on status and code, never wording. Raw request bodies, secrets, and provider responses do not appear in errors. [Problem Details](https://www.rfc-editor.org/rfc/rfc9457.html) defines the common envelope. | Status | Meaning | | ------ | ------------------------------------------------------------------------------------ | | 200 | A read or synchronous operation returned its documented result | | 201 | A resource was created. `Location` identifies it | | 202 | Input is durably accepted, or an explicitly identified action is underway | | 204 | A deletion or cancellation needs no response body | | 400 | Invalid syntax, fields, query, or identity timestamp | | 401 | Missing or invalid daemon token. Includes `WWW-Authenticate: Bearer` | | 403 | Disallowed browser origin or caller permission | | 404 | Unknown current resource or disabled extension route | | 405 | Known path, unsupported method. Includes `Allow` | | 406 | Unsupported response media type | | 409 | Busy state, identity conflict, stale catalog, or incompatible operation | | 410 | Retained deletion, expired identity, or obsolete prepared context | | 412 | The observed representation or creation precondition no longer holds | | 413 | Body exceeds its limit | | 415 | Unsupported request media type | | 428 | Required precondition is missing | | 429 | Admission or rate limit. Includes `Retry-After` where a later new intent can succeed | | 503 | Owner, storage, or upstream preparation is unavailable | All authenticated data responses use `Cache-Control: no-store`. Clients may keep in-memory resource state and validators. Errors after SSE headers use the stream failure contract rather than pretending to change the HTTP status. ### Retries and cancellation Reads can retry transient connection failures with capped backoff and jitter. They remain subject to the caller's deadline. Authentication and protocol errors are actionable failures, not evidence that a daemon is absent. Session creation, input admission, visits, and login creation retain the original ID and encoded intent during recovery. Other changes have no automatic replay after a lost response. A precondition or a resource-specific identity can make an explicit retry safe. The [session contract](http-sessions.md) defines identified-operation recovery. Canceling a client context stops its requests and subscriptions. It does not undo an accepted input, interrupt a shared turn, stop a detached daemon, or authorize replacing one. Those are separate operations. Transport cancellation after a mutation was sent can leave its outcome uncertain. ## Server, settings, and storage ### Server identity and shutdown `GET /server` reports readiness, daemon instance identity, protocol, capabilities, build information, and observations. `instance_id` changes at each startup. Build labels and digests are update information, not proof of API compatibility. Capabilities map feature names to contract versions. Attachment checks the required versions in [`daemon/server.go`](../cli/internal/daemon/server.go). Optional operations check their advertised capability before invocation. [Daemon attachment](daemon-lifecycle.md#client-development) explains the connection boundary. Quota readings retain their account, observation time, source, and safe failure details. An unknown percentage remains unknown. The optional history view is paged. See [quota observations](../robot-docs/quota.md) and the parameters on the OpenAPI operation. Reading a notice does not dismiss it. Dismissal is a shared UI setting. `POST /server/shutdown` accepts `instance_id` and `timeout_ms`, default 5,000 and maximum 30,000. A different instance returns `409 instance_changed`. The daemon marks itself draining, refuses new admissions, stops active turns, flushes durable state, and closes. Accepted waiting inputs remain durable for the replacement daemon. Kernels keep running for it unless `stop_kernels` is true. Then sessions save their variables and their kernels end. `202` reports `instance_id` and `state: "draining"`. The client observes closure with a bounded wait. It cannot use this endpoint to start the replacement. The interactive CLI still offers to keep or restart a discovered daemon. Keeping it is the default. Its approved instance identifies the shutdown target. [Daemon attachment and local startup](daemon-lifecycle.md) owns this user flow and deliberate operator overrides. ### Shared settings The [settings operations in OpenAPI](openapi.yaml) define group names, fields, secret-presence metadata, and patch schemas. [Persisted settings](../robot-docs/settings.md) links the implementation owners. A group read supplies its canonical URL and validator. A patch changes one group under its observed `If-Match`. It cannot partially apply a multi-group request. Validation covers the complete candidate before publication. The [settings recovery boundary](http-api-architecture.md#settings-crash-recovery) coordinates participating readers and writers. Provider keys and MCP secrets are write-only. Omission retains a secret, a replacement string changes it, and null removes it. Reads expose presence and names, not values. Response-only presence fields are invalid on writes. Deleting a profile or MCP definition also removes its associated secrets. MCP candidate validation runs before persistence. A failed probe keeps the previous definition and secrets. The write-only `validate_connection` control can deliberately skip that probe. It is not a saved definition field. Public and secret environment or header maps cannot declare the same name. Header names compare without case. A definition cannot combine multiple bearer sources. Switching sources requires removing the old one in the same patch. Environment references resolve on the daemon host, and the probe uses the candidate's resolved values. Changing a provider profile does not select it. Changing the default profile explicitly affects new sessions. Removing the selected default requires a replacement or an explicit removal in the same patch. Per-model raised-cap and compact-at choices affect subsequent prepared requests. Clients use the returned `cap_key` rather than constructing one. A compact-at choice can lower a model window, not raise it. Existing requests retain their captured settings. Capability selection uses candidate IDs and the observed catalog revision. The daemon resolves IDs to persisted preference keys. This prevents stale discovery from changing a different file. Configured MCP enablement is separate from capability selection: a disabled definition remains unavailable even if selected. A successful patch distinguishes the saved resource from application state. `composition_changed` describes a change to desired composition, not proof that open sessions reloaded. The caller can list sessions with `needs_reload=true` and explicitly reload them. Global services use new desired settings on subsequent requests. The exact group and mutation envelopes remain in OpenAPI. The [settings tests](../test/e2e/settings_test.py) exercise conditional edits, secret retention and removal, candidate validation failure, and persistence failure. ### Usage totals `GET /usage` (capability `usage_summary: 1`) answers what the provider calls used over the last 1-90 days (seven by default), ending with the client's today. `utc_offset_minutes` (-720 to 840, default zero) sets the client's midnight. That one offset applies to every day, so days before a daylight-saving change are an hour out, and an hour that straddles a fractional-offset midnight counts in the earlier day. Optional `provider` and `account` (which needs `provider`. Empty selects rows without an account) narrow the days and model lines, never `scopes`. The read is one snapshot of hourly totals kept beside the request ledger. [provider requests](../robot-docs/provider-requests.md#usage-totals) owns how they are kept. ### Storage accounting `GET /storage` reports database, session, shared-image, and daemon-file accounting. OpenAPI defines the report fields and section continuations. [Storage reads in the Go adapter](../cli/internal/daemon/storage.go) page those sections without filesystem access. Session estimates count pinned context, transcript content, cell sources, payloads, and traces. Shared images count once outside session estimates. Estimates do not claim allocated disk space per session. Database measurements share one read boundary. Filesystem measurements describe the inspection period. Session and file lists use separate `next` tokens within this response, with each token identifying its section. A session token resumes after the last session ID shown, so sessions written, added or removed between pages never void it. Totals always cover the complete store. An online client needs no filesystem or Python access. Returned paths describe the daemon's files and never authorize local deletion. Offline diagnosis and approved cleanup remain explicit local operations under the ownership lock. ## History, context, catalogs, and runtime ### Durable history [`http_history.gleam`](../src/albedo/daemon/http_history.gleam) and [`http_transcript.gleam`](../src/albedo/daemon/http_transcript.gleam) own history projections and content paging. `GET /sessions/{session_id}/history` accepts `view=entries|checkpoints`, default entries, and one of `before`, `after`, or `next`. Positions are durable transcript positions, unrelated to the actor cursor. Pages retain ascending display order and include `older`, `newer`, and `high_water`. Default entry count is 100, maximum 200, with a 256 KiB content budget. Each entry has stable `id`, `position`, `kind`, `turn_id`, `input_id`, `created_at`, `content`, nullable `checkpoint_id`, and `content_complete`. User entries, assistant answers, and tool calls expose checkpoints for their inclusive durable transcript row. Calls packed into one row share a checkpoint. A fork cannot split that row. Checkpoint view lists user turns for the TUI fork picker. Recorded thinking duration is exposed as `thinking_duration_ms`. Live thinking completion can report `elapsed_ms`. These measure thinking, not the whole turn. `HistoryEntry` in [OpenAPI](openapi.yaml) defines the complete kind and content unions, including human `shell_command` outcomes. Content can contain text, JSON, image metadata, and execution traces. Tagged daemon notes retain their native origin as a JSON part with `field: "origin"`. Tool names, native call IDs, normalized progress-call IDs, activity summaries, and file diffs remain available. Provider-private fields are explicit opaque data. Clients do not reinterpret them as execution instructions. The daemon pages on complete display groups when they fit. A large group uses content references rather than growing a response past its bound. Preview truncation is explicit and never changes the stored content. Checkpoint view contains position, valid checkpoint ID, title, turn type, and bounded preview. It provides the TUI tree and fork picker without a separate tree route. `GET /sessions/{session_id}/history/{entry_id}` returns the full entry content as pages of `parts`, each with `field`, `offset_bytes`, `text`, and `complete`. Text and JSON fields use their exact stored UTF-8 encoding. Offsets are bytes, and pieces end on UTF-8 boundaries. Opaque `next` identifies the next piece. The decoded content budget is 256 KiB per page. The daemon shortens a page further when JSON escaping would reach the common encoded response bound. Image fields are not paged. An image's metadata gives its MIME type, dimensions, byte count, and a reference to `GET /sessions/{session_id}/history/{entry_id}/{field}`, which returns the stored bytes with the image's own `Content-Type`. Clients can reconstruct full arguments, results, and images without filesystem access. `GET /sessions/{session_id}/history/content?entries=a,b,c` reads those parts for up to 200 entries in one walk, in the order `entries` names them, so a page whose entries are mostly references costs one request per byte budget instead of one per entry. Each part carries the `entry_id` it belongs to, because a page can stop in the middle of an entry. Offsets, the per-piece and per-page budgets, and the exclusion of image fields are the single-entry route's. A `next` continuation is bound to that request's path and its exact set of entries, so it cannot be replayed against another set. Entry IDs are at most 128 characters. Clients that need one entry's content keep using the single-entry route. ### Prepared context and request records `GET /sessions/{session_id}/context` defaults to `view=summary`. It describes the latest actual prepared request, never prepares a new one. The summary has `state: "pending"|"ready"`, nullable `snapshot_id`, capture time, provider, model, protocol, context-window tokens, compaction observations, and sections. Each section contains ID, label, kind, source, item count, UTF-8 byte count, page count, and bounded preview. Pending state contains a reason. `view=section` requires `snapshot_id`, `section_id`, and a zero-based `page`. A page has `text`, omitted-content explanation, page index, and page count. Text has a 32 KiB UTF-8 limit and ends on a character boundary. Only the latest snapshot is retained. If it changes during navigation, the old identity returns `410 context_changed`. The client refreshes the summary. A page never silently comes from another prepared request. `view=requests` pages provider request records by durable sequence. It exposes attempt identity, attribution, outcome, usage observations, and links to transcript positions. Full provider request bodies and credentials are absent. Unknown historical identities remain null. Estimated and observed token counts have separate fields and sources. See [provider request recording](../robot-docs/provider-requests.md). `GET /models?view=cache-policy` reads the cache-policy table and its layer diagnostics. Entries retain matching patterns, clock, tiers, prices, survival, evidence, sources, and notes. `limit` and `next` page entries. Optional `extension`, `host`, and `model` selectors return the first matching entry in `matched`, independent of the displayed page. This view does not require a provider profile and never connects to a provider. Catalogue view remains the default. ### Discovery and loaded composition `GET /sessions/{session_id}/catalog` returns `discovery` and `loaded` as separate fields. Optional `kind=extensions|skills|instructions|mcp|commands` filters entries without changing these identities. Discovery contains `revision`, workspace, candidates, and diagnostics. It reflects current local files and preferences. Remote files come from the last observed mirror. Preparation refreshes stale mirrors. Loaded contains its composition revision and prepared command definitions. Reading discovery does not reload the prompt or start a kernel. Before a composition exists, `native_commands` supplies static HTTP declarations from selected extensions. Clients use these declarations only while the loaded revision is null. Observing them does not prepare an extension or start a kernel. If desired discovery fails, `discovery` is null and `discovery_failure` contains a safe reason. Retained loaded commands remain readable. Successful discovery sets `discovery_failure` to null. Clients need a discovery revision to edit selection. Candidates retain source, resolved-source identity, enablement, shadowing, dependencies, and diagnostics. OpenAPI defines their exact fields and the plugin metadata available for extension inspection. Selections use candidate IDs and the observed discovery revision. Paths are daemon metadata, not client filesystem instructions. Diagnostics survive missing, invalid, shadowed, and quarantined entries. Command definitions contain ID, slash name, description, typed argument declarations, caller permissions, and `delivery: "read"|"mutation"|"input"`. They identify either a canonical HTTP operation or a durable input variant. There is no public endpoint that accepts an arbitrary slash command string. The CLI parses slash syntax into the named operation. Python bindings call the same domain owner with trusted model caller context. Page descriptors declare display and form data together with typed HTTP actions. The [command contract](../robot-docs/commands.md) and OpenAPI own their field definitions. An action resolves bindings from literals, the displayed row, submitted form values, or the installed session snapshot. An edit binds `If-Match` to the row's observed validator. The adapter does not fetch a newer validator just to overwrite a stale screen. Descriptors cannot change retry policy or authorization. The adapter rejects foreign origins and undeclared extension routes. Result schemas are local JSON Schema fragments without remote schema retrieval. Extension response bodies remain explicit dynamic JSON values. ### Reload, kernel upgrade, and compaction `POST /sessions/{session_id}/reload` accepts `target: "session"|"models"|"both"`, default both. Session reload requires idle, builds the candidate composition before swapping it, and retains the previous composition on failure. Success preserves the Python namespace and pinned prompt prefix, except where an extension's declared lifecycle requires restart. The result includes loaded revision, restart requirements, and warnings. Model reload reports success or failure per provider and keeps old catalog data where refresh failed. It also reloads cache policy, reported separately as `cache_policy` with state and failure. Session-only reload returns null there. `both` returns these outcomes explicitly. One confirmed refresh is not hidden by failure of the other. `POST /sessions/{session_id}/kernel/upgrade` accepts an empty object and requires idle. It stages the new kernel, reports the fate of live jobs, copies supported namespace state, and swaps only after validation. Failure keeps the previous kernel usable where the existing upgrade boundary permits it. Stopped external jobs are reported as stopped and cannot be claimed restored. The response contains old and new identities, upgrade state, stopped jobs, and warnings. `POST /sessions/{session_id}/kernel/restart` accepts an empty object and does not require idle: it cancels queued inputs and the running turn as an interrupt does, discards the saved variables, and stops the kernel and its jobs without asking the kernel anything. The response waits for the stop and reports the old kernel id (null when none ran), the stopped jobs, and the cells that ended. A stop that fails answers 503 `kernel_restart_failed`. `POST /sessions/{session_id}/compaction` accepts an optional `strategy`. It requires idle and compacts the model-facing projection without deleting transcript history. A supplied strategy first becomes the session override. The response reports `selection_applied`, the effective strategy, compaction state, before and after counts, and safe failure details. A failed compaction can retain a successfully selected strategy. The response preserves that fact. Neither runtime action automatically retries an uncertain external effect. ## Models, workspaces, hosts, and provider login `GET /models` reads metadata for a saved provider profile or an explicitly supplied provider and endpoint. It returns model objects even when the provider cannot enumerate every ID. A manual model ID can still be selected. Unknown limits remain null, and metadata retains its source and freshness. [Model selection](../robot-docs/models.md) links the owning provider and catalog code. `GET /workspaces` without `location` lists recent canonical workspaces with use counts and last activity. With `location`, it browses that directory. Optional preview data includes VCS facts, language shares, and a bounded file tree. The exact representation and limits are in [OpenAPI](openapi.yaml). `include=files` (alone or as `preview,files`) lists the directory's files after its directories, each by name under the same pagination, and gives every item `kind`, `size` (null for a directory) and `ignored` (whether git, or a colocated jj, ignores it. Null outside a repository or in jj without git). Git and jj facts retain their distinct typed variants. A missing optional VCS fact is null with a diagnostic, rather than loss of the entire directory. The tree has at most 12 top-level entries and four children per directory. `more` counts omissions. Local and SSH locations share this representation. Paths are interpreted and canonicalized on the daemon's host. `GET /sessions/{session_id}/files?path=` reads one file for a client to show, on the machine the session's workspace is on, local or over the same SSH gather as browsing. `path` is absolute there, relative to the workspace, `~/...` in a local workspace, or the host-prefixed spelling the answer uses. The answer carries the canonical `path` (host-prefixed when remote), `size` in bytes, `modified_at`, and `text`. Only regular UTF-8 files without NUL are read: over 1 MiB, or too large to answer within the response limit, is 413 `file_too_large`. Binary or invalid UTF-8 is 415 `file_not_text`. Missing, a directory, or not a regular file is 404 `file_not_found`. A host that is not ready is 503 `workspace_unavailable`, as for browsing. `GET /sessions/{session_id}/changes?base=uncommitted|upstream` reads every change of the checkout enclosing the session's workspace, on the machine the workspace is on. It answers the checkout (kind, root, head, branch), the base it compared with (spec, label such as `HEAD`, `@-`, `origin/main` or `trunk()`, and short commit), and the files sorted by path, each with status, the path a rename came from, line counts, a binary flag, and a unified diff or the reason it was omitted (`binary`, `too_large` past 256 KiB, `budget` once 768 KiB of encoded diffs is spent, in order). At most 1000 files are listed, then `truncated`. It never writes: no index refresh, no jj snapshot or operation. Each answer has an ETag over its body, and `If-None-Match` with it answers 304, so a client polls it while a session works. A workspace outside any checkout is 409 `not_a_repository`, an upstream base with nothing to compare with 409 `no_upstream`, a host that is not ready 503 `workspace_unavailable`, a failing git or jj 502 `vcs_failed`, and commands past their 15 s deadline 504 `vcs_timeout`. Capability `checkout_changes: 1` covers it and `include=files`. `GET /hosts` reads known SSH targets and cached probe state. `POST /hosts/{host}/probe` starts or joins a bounded probe. Repeated probes coalesce. A read does not start SSH sign-in. [Workspace and host ownership](../robot-docs/workspaces.md) links the daemon implementation. SSH sign-in remains an explicit operator action. A local CLI can perform the existing terminal handoff using daemon-supplied target and control-path metadata after confirmation. A client on another machine displays instructions for signing in on the daemon host. This API does not promise a browser terminal. Filesystem failure codes distinguish missing workspace, needs-auth, unreachable host, unsupported host, and permission denied. `GET /auth` returns login providers, their form fields and supported flows, redacted accounts, and account selection metadata. It does not duplicate credential values from settings. `PUT /auth/logins/{login_id}` uses UUIDv7, with provider and declared typed form values. The server records immutable login intent and returns URL, expiry, `state`, and manual-input instructions. First creation returns `201`. An identical PUT returns the existing flow with `200`. Changed intent returns `409 login_conflict`. Same-ID comparison stays inside the daemon and includes the private form values. A duplicate never starts a second flow. Login secrets never appear in the read representation or its fingerprint provenance fields. Fingerprints are server-created and are not exposed for low-entropy login secrets. GET inspects that flow. `PATCH` supplies `response`, such as a pasted callback URL or provider code, under `If-Match`. DELETE cancels it idempotently. States are `waiting`, `exchanging`, `complete`, `failed`, `cancelled`, and `expired`. Flow reads include bounded safe progress and globally unique opaque account IDs that also identify their provider. Completed flows return account metadata. Terminal flow metadata remains for 15 minutes, uncompleted flows expire after their advertised provider deadline, and at most eight flows are active. Duplicate creation never opens a second flow. An expired or evicted ID cannot restart a flow. Unknown IDs older than the 15-minute flow recovery window return `410`. Login admission intent and terminal decisions survive daemon restart within their retention window. A restart marks an unfinished flow `failed` with `code: "daemon_restarted"`. It does not reuse a lost listener or exchange. Repeating its PUT returns that retained failure. Starting again requires a new login ID. The daemon retains only the protected secret material needed for immutable-intent comparison and removes it when the record expires. OAuth callbacks stay on provider-required daemon-owned loopback listeners. They validate provider state and PKCE where the provider supports it. Manual callback input preserves remote-client usability. Secrets and callback codes stay out of logs and SSE. Selecting an account updates a provider profile through `/settings`. `DELETE /auth/accounts/{account_id}` refuses removal while a saved profile still references it. It does not interrupt a running request using captured credentials. ## File path completion `GET /sessions/{session_id}/file-paths?query=&limit=8` is an advisory, session-scoped resource (`file_path_completion: 1`), not an attachment operation. Bare queries enumerate the stored workspace on its own host, without opening file contents. Starting `~` or `~/` anchors at that host's home, `./` at the workspace, and `/` at that host's filesystem root. The directory through the last slash is literal; only the tail fuzzy-matches descendant relative paths. Results preserve the entered directory prefix (`~` becomes `~/`); bare results stay workspace-relative. There is no `~user` expansion or fallback when a typed directory does not exist. Explicit `./../` paths may leave the workspace; this is completion, not a sandbox. Ignore-aware ripgrep enumeration is deadline/output bounded; unavailable ripgrep, directory, or host fails with `workspace_unavailable`, never a local fallback. Timeouts always fail. An anchored scan with filesystem errors and some emitted paths returns that subset with `truncated: true`; errors without paths still fail. Results use stable case-insensitive subsequence ranking and lexical tie-breaking. `truncated` also means more matches exist or an enumeration cap was reached. Clients insert the selected path as ordinary draft text; the input submission contract is unchanged. See [workspace path completion](../robot-docs/workspaces.md#path-completion) for enumeration limits and ownership. ## Client responsibilities API operations are independent of UI shortcuts. Client-owned drafts, editors, clipboard operations, animation, navigation, confirmations, and quit behavior do not need daemon routes. Human graph messages use ordinary user inputs addressed to the selected session. Agent-originated mail uses trusted family permissions. A client cannot forge an agent sender by adding a role or caller field. The daemon exposes bounded live state and full durable content separately. A screen can show a preview without reconstructing tool arguments, but must use content reads when the user requests the complete result. A reset replaces daemon-derived state while preserving local drafts and unresolved operation handles. [Client API ownership](client-api.md) describes adaptation. [API architecture](http-api-architecture.md) names persistence and lifecycle owners. [Change the HTTP API](contributing-api.md) states contribution requirements. ## Verification These are examples of checked behavior, not an exhaustive coverage claim: | Behavior | Evidence | | ------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | | An ordinary HTTP consumer creates a session, admits input, reconnects, and reads history. | [`http_consumer_test.py`](../test/e2e/http_consumer_test.py). | | Identified input keeps its intent, queue decision, and delivery state across retries and restart. | [`operations_test.py`](../test/e2e/operations_test.py) and [`operations_lifecycle_test.py`](../test/e2e/operations_lifecycle_test.py). | | Old actor cursors reset, replay retains order, and stalled readers cannot retain unbounded queues. | [`stream_replay_test.py`](../test/e2e/stream_replay_test.py) and [`stream_pressure_test.py`](../test/e2e/stream_pressure_test.py). | | Unicode preview offsets and interleaved tool identities stay consistent with durable arguments. | [`tool_progress_test.py`](../test/e2e/tool_progress_test.py). | | Conditional settings edits preserve secrets, and a blocked committed recovery reports failure until recovery can finish. | [`settings_test.py`](../test/e2e/settings_test.py). This does not establish coverage of every storage crash point. | | Shell command retries and side-question continuation preserve identity without replaying external effects. | [`shell_commands_test.py`](../test/e2e/shell_commands_test.py) and [`side_questions_test.py`](../test/e2e/side_questions_test.py). | Controlled [session stream tests](../cli/internal/daemon/session_stream_test.go) cover malformed batches and callback failure before cursor commit. The [real-daemon contract transport](../cli/test/e2e/contract_test.go) validates responses encountered by Go end-to-end scenarios. Neither establishes coverage of operations a scenario never invokes. [Change the HTTP API](contributing-api.md#verify-the-change) states the checks required for a new change. A requirement to test a failure boundary is not a claim that every such test already exists. ## Related guides - [Documentation index](readme.md) - [Session lifecycle and recovery](http-sessions.md) - [HTTP streams and recovery](http-streams.md) - [Extension HTTP behavior](http-extensions.md) - [API architecture](http-api-architecture.md) - [Change the HTTP API](contributing-api.md)