<!-- Source: https://console.uubright.com/docs/api/ -->
# HTTP API

The web app uses this API, and you can too: start tasks from scripts, follow their
events or answer approvals from other tools. The API is served by the control plane,
`http://127.0.0.1:8787` by default.

## Authentication

Send your owner token on every request:

```sh
curl -H "Authorization: Bearer $CCR_CLOUD_TOKEN" http://127.0.0.1:8787/api/sessions
```

The event streams (`…/events`) also accept `?token=`, for clients that read them with a browser's
`EventSource`, which can't set headers. The web app no longer does: it reads the board stream with `fetch`
and sends the header, so its token is never in an address. Prefer the header in your own clients too;
addresses end up in proxy and server logs. `GET /api/health`, the web app's static files and signed artifact URLs
need no bearer token.

Errors return JSON, `{"error": "..."}`, with a matching status code: `400` for invalid
input, `401` without a valid token, `404` for an unknown task or request, and `409`
when the request conflicts with the task's state.

In local mode, `POST /api/local/owner-token/handoff-complete` requires the raw
owner token over direct local access. It deletes the one-time `owner-token` file
after the desktop saves the token in Keychain. Paired devices and relay requests
receive `403`. `GET /api/relay/status` accepts owner or paired-device auth. With
the relay on, it has `{ "enabled": true, "connected": boolean, "registered": boolean }`,
which is all the desktop app reads, next to the fields under [Devices](#devices).
With the relay off it answers `503` `{"error": "Relay is disabled"}`. `registered` survives a
restart only for the same relay host key and relay origin. Changing
`CCR_CLOUD_RELAY_URL` requires registration at the new relay. If that relay later
forgets the host key, it closes the host with `4412` (registration required), which
resets `registered`; other refusals, including a managed relay's `4402` data cap,
leave it. `connected` is true once the relay has accepted the host: on its
acknowledgement, or, from a relay too old to send one, when the socket outlives the
relay's 5-second auth deadline.

## Computer identity

`GET /api/computer` accepts owner or paired-device authentication (including the encrypted relay)
and returns `{ "id": "h-…", "name": "My Mac" }`. `id` is the persistent console instance ID
stored under the data directory; it survives restarts and transport changes. `name` is the host
name, without a trailing `.local`, capped at 80 characters. Clients may keep a local display-name
override. Neither field contains a relay address. Copying or deleting the instance-ID file changes
these identity guarantees; preserve it alongside the host’s credentials when migrating.

## Workspaces

`GET /api/workspaces` lists workspaces; `GET /api/workspaces/:id` reads one.
Each record includes `mode`, the one the app uses.

| Route | |
|---|---|
| `POST /api/workspaces` | Create one: `{ "name": "Website", "kind": "coding", "identity": { "name": "Your Name", "email": "you@example.com" }, "plugins": ["/abs/path/to/plugin"] }`. Only `name` is required. `kind` `coding` sets mode `work`; without it the mode follows the default rule ([Chat mode](#chat-mode)). Chat workspaces are being retired: `kind` `non-coding` (mode `chat`) and `template` still work for now and will be removed. `identity` sets the Git author and committer, as `set-identity` does. Each plugin is checked as `enable-plugin` checks it. `template` (`teacher`, `writer`, `research` or `blank`, from `GET /api/workspace-templates`) makes a chat-mode workspace and copies in the template's `instructions`, `starters` and `examples`; it can't be combined with `kind` `coding`. Everything is checked before the workspace is made, so a `400` leaves nothing behind. Returns `201` with the record. |
| `GET /api/workspace-templates` | The New workspace templates, in order: `[{ id, name, icon, description, order, plugins, instructions?, starters, examples }]`. `plugins` are optional suggestions by name; the app never enables them automatically. `starters` use the [plugin starter](https://console.uubright.com/docs/plugins/#starters) format; `examples` are the three prompts New chat offers once. Open to paired devices. |
| `PATCH /api/workspaces/:id` | Any of `name` (renames), `mode` (`chat` or `work`), `identity` (`{name, email}`) and `defaultModels` (`{"claude": "sonnet", "codex": null}`: each agent's model for tasks that don't name one, where `null` clears it; see [Default models](https://console.uubright.com/docs/workspaces/#default-models)) and `chatPermissionMode` (`auto` or `default`: the permission mode new chats start in; owner token only, `403` otherwise; each workspace record's `canSetChatPermissionMode` says whether the caller may). A bad value is a `400` and changes nothing. |
| `GET /api/workspaces/:id/manager-limits` | The workspace Manager's limits and spend, for Workspace settings: `manager` (`{ id, title, agent, state, createdAt }`, or `null` without a lead as Manager), `lead` (`{ workersAuto, maxWorkers, budgetUsd, hardCap }` with defaults filled in; before a Manager starts, the limits it would start with), `max`, `month` (`{ key, label, resetsAt, timeZone }`, the server's local calendar month), `spend` (`month` and `lifetime`, each `{ manager, claudeWorkers, total }` in USD), `workers` (`{ live, codex }`), `budgetReached`, `billing` (`subscription` only for a confirmed subscription login, see [Monthly budget](https://console.uubright.com/docs/lead/#monthly-budget); `metered` when the billing is known to be otherwise; `null` when unknown), `budgetMode` (`warn` when the Manager and its Claude workers with spend this month are on a subscription and there's no hard cap, else `stop`) and `canChange` (the owner token). Paired devices may read it; changing a limit is `PATCH /api/sessions/:id` with the owner token. |
| `POST /api/workspaces/:id/plugins` | `{ "path": "/abs/path" }` enables a plugin directory, as `enable-plugin`. Named workspaces only. Returns `201` with the record. `409` when the host's Claude setup already loads it for this workspace's tasks (the same plugin enabled in `settings.json` or `settings.local.json`, or a skill of the same name in its `skills/`, or one that links to the add-on's own skill folder), with how to remove the host copy; `plugins` on create is refused the same way. Not checked with the workspace's own Claude login, which doesn't load the host setup. |
| `GET /api/workspaces/:id/capabilities` | What the workspace's tasks already have, for Workspace settings ([What your tasks already have](https://console.uubright.com/docs/workspaces/#what-your-tasks-already-have)): `builtin` (`{ version, seenAt, count }` from the last Claude task that started, or `null`; with the owner token also `names`, which leave out every name found in this computer's Claude homes, links included), `hostSetup` (`{ used: false, reason: "own" \| "docker" }`, or `{ used: true, mcp: "loaded" \| "skipped-local" \| "skipped-contract", skills, commands, plugins }` as counts), `addons` (`[{ path, name, description?, skills, contract, servers, needsSetup, duplicate? }]`), `recommended` (`{ template, plugins: [{ name, added }] }` or `null`) and `canChange`. With the owner token it also has `hostSetup.names` and `home`, and `available` (the plugin folders found, as `GET /api/plugins/available`, with `recommended`, `duplicate` and `duplicateMessage`). Paired devices get counts, never the names of the host's skills or plugins. Names come from folder listings (following links, as Claude Code does) and the `enabledPlugins` key of `settings.json` and `settings.local.json`; credential files and `~/.claude.json` aren't read. |
| `DELETE /api/workspaces/:id/plugins` | `{ "path": "/abs/path" }` disables it, as `disable-plugin`, and forgets its settings and secrets in that workspace; `404` if it isn't enabled. |
| `GET /api/plugins/available` | `{ plugins: [{ name, description?, path, contract, unavailable? }], truncated }`: folders with `.claude-plugin/plugin.json` under the repository roots and `~/.claude/plugins/marketplaces`, up to four levels down, excluding test and demo folders. Links aren't followed; `contract` marks a [contract plugin](https://console.uubright.com/docs/plugins/). `unavailable` is a safe reason the plugin cannot be enabled. A listed plugin is checked again when it is enabled. |

Creating, renaming, the mode and the Git identity are open to paired devices. Plugins need the owner token:
`plugins` on create, `POST …/plugins` and `GET /api/plugins/available` because a plugin runs code on this
computer, and `DELETE …/plugins` because it deletes the plugin's saved settings and secrets. Paired devices and
relay phones get `403`. These routes never accept Git or GitHub credentials, and there is no route to delete a workspace or
sign it in to Claude Code, Codex or GitHub: use the [server CLI](https://console.uubright.com/docs/cli/#workspaces).
A workspace's `managerTaskId` names its [Manager](https://console.uubright.com/docs/manager/).
`PUT /api/workspaces/:id/manager` with `{ "taskId": "s-..." }` sets it, and
`DELETE /api/workspaces/:id/manager` clears it. The task must be in that
workspace and not a worker or reviewer (`400` otherwise). Paired devices may set
it: it grants the task nothing.
Contract plugins' settings, write-only secrets and form answers have their own
routes: see [Plugin settings, secrets and forms](https://console.uubright.com/docs/plugins/#api).

`GET /api/workspaces/:id/projects` lists project links;
`POST /api/workspaces/:id/projects` with `{ "projectId": "p-..." }` links an
existing project. A project can be linked in several workspaces.
`GET /api/workspaces/:id/starters` lists the enabled plugins' starters. A plugin
with manifest starters gives `{ plugin, id, name, description, prompt, form?,
command?, body?, image?, accent?, icon? }`, where `image` is the URL of
`GET /api/workspaces/:id/plugins/:name/assets/<path>` ([Starters](https://console.uubright.com/docs/plugins/#starters)).
Otherwise each Markdown command is `{ plugin, command, name, description, body }`.
The app uses the slash command for Claude and the command body for Codex when a
starter is chosen.

`POST /api/sessions` and `POST /api/rooms` accept `workspaceId`. Omit it to use
`default`; an unknown ID returns 400. Task and room records include their
workspace ID. A task joining a room must use that room's workspace.

See [Workspaces](https://console.uubright.com/docs/workspaces/) for identity and current limitations.

## Chat mode

Chat workspaces are being retired; this stays for the ones that exist.

A workspace record's `mode` is how the app shows it: `chat` or `work` ([Chat mode](https://console.uubright.com/docs/chat-mode/)).
When the owner hasn't chosen, it is `chat` for a named workspace with plugins and no linked
projects, and `work` otherwise. `PUT /api/workspaces/:id/mode` with `{ "mode": "chat" }` (or
`"work"`) sets it. Paired devices may set it: it changes only the view.

A chat is a task started with `POST /api/sessions` and `"chat": {}`, or
`"chat": { "projectId": "cp-..." }` for one in a chat project. It has no repository: `repo`,
`projectId`, `room` and `lead` are refused with it (`400`). Its record keeps `chat`. It starts with `permissionMode` `auto` unless the request names one or the workspace's
`defaults.chatPermissionMode` says otherwise; the workspace's `defaults.permissionMode` applies to tasks only.
`GET /api/workspaces/:id/chats` lists the workspace's chats, newest activity first, as
`{ taskId, title, projectId?, activityAt, state, needsYou, pinnedAt?, archivedAt?, canDelete }`. `canDelete` is
true for the owner token only: deleting a chat is `DELETE /api/sessions/:id`, which a paired device can't do.
`?q=…` (2 to 200 characters) searches instead: chats whose title contains the words, then chats where your messages
or the answers do, case-insensitively and in this workspace only, at most 50. Each hit adds `match` (`title` or
`message`) and, for a message, a `snippet` around the words. `PATCH /api/workspaces/:id/chats/:task` with any of
`title`, `pinned` (true or false) and `archived` (true or false) renames, pins or archives a chat. A paired device
may, as it may rename a task.

Chat projects are per workspace:

| Route | |
|---|---|
| `GET /api/workspaces/:id/chat-projects` | List `{ id, workspaceId, name, instructions?, createdAt, notes }` |
| `POST /api/workspaces/:id/chat-projects` | `{ "name": "…", "instructions": "…" }` creates one |
| `GET`, `PATCH`, `DELETE /api/workspaces/:id/chat-projects/:project` | Read, rename or change `instructions`, delete. Its chats keep their history |
| `POST /api/workspaces/:id/chat-projects/:project/notes` | `{ "text": "…" }` adds the owner's own note |
| `PATCH`, `DELETE …/notes/:note` | Edit or forget a note |
| `POST …/chat-projects/:project/files/upload?name=…` | The file's bytes as the body: checked and scanned as an attachment. Answers `201` with `{ id, name, size, type, label }`, an upload not yet in the project |
| `POST …/chat-projects/:project/files` | `{ "upload": "a-…", "replace"?: "pf-…" }` adds the upload as a project file, or as a new version of `replace` |
| `DELETE …/chat-projects/:project/files/:file` | Removes a file from the project; chats keep their copies |
| `POST …/chat-projects/:project/files/save` | `{ "artifact": "a-…" }` or `{ "taskId": "…", "text": "…" }` copies a deliverable's file, or an answer as Markdown, into the project (with `from`). The same content again answers `200` with the existing file and `already: true` |

A note is one line of at most 300 characters, and a project keeps at most 50. A chat's agent
proposes notes with the `ccr-task` tool `propose_note`, offered only in a project chat. The
proposal is a decision (`memory: { projectId, note }` on it) whose one question is the note,
with options `Save` and `Don't save`. Only `Save` writes the note; any other answer or a
dismissal leaves memory unchanged. Each start of a chat passes the project's instructions and
notes to the agent's system prompt.

A project's `files` are `{ id, name, size, type, label, sha256, createdAt, updatedAt?, usedIn }`, where
`usedIn` counts the project's chats that have been sent the file. Each message to a project chat carries,
as extra attachments, the files the chat hasn't had in their current version, within what one message
may carry beside the owner's own files (20 files and the workspace's message size). They aren't listed on
the message's `user_message` event. A project holds at most 20 files, together no larger than one message
may carry. Over the relay, a file uploads as upload messages whose task is `project_<workspace>_<project>`,
then is added with `POST …/files`.

`GET /api/workspaces/:id/apps` lists the enabled plugins as
`{ name, description?, version?, status, error?, commands, skills, connectors }`, where
`connectors` names the plugin's MCP servers and never their commands or environment.

## Artifacts

`GET /api/sessions/:id/artifacts` lists published versions and current drafts for
one task. `GET /api/artifacts?workspace=<id>` lists the workspace's Deliverables; `kind` and `task`
are optional filters. `GET /api/artifacts/:id` reads one record. For a published
version, `POST /api/artifacts/:id/approve` changes its status to `approved`;
`POST /api/artifacts/:id/published` with an optional `{"url": "https://…"}` marks
an approved version published (409 otherwise). Each record carries a derived
`state` (`draft`, `needs-review`, `approved` or `published`; see
[Deliverable states](https://console.uubright.com/docs/artifacts/#deliverable-states)) and, once set,
`approvedAt`, `publishedAt` and `publishedUrl`. And
`POST /api/artifacts/:id/url` returns `{url, expiresAt}` for inline viewing or
download. Draft approval returns 409; drafts can mint preview URLs. These routes need an owner
or paired device token. The signed `/artifacts/<token>/<name>` URL is valid for
one artifact and one hour; GET and HEAD support a single byte range. Task summaries
include `artifacts: {count, latest, updatedAt}` for published versions only.
An HTML slides entry can serve its own directory subtree under the same token;
all other artifacts authorize one file.
If a published entry file's size, modification time or inode changes, its
capability URL returns 410 until the agent publishes a new version.
Over the relay, `GET /api/artifacts/:id/relay` replaces the signed URL: it answers
`{status: "uploading", sent, total}` while the server encrypts the file into the relay's
storage, then `{status: "ready", url, urlExpiresAt, key, size, hash, files}`
([format](https://console.uubright.com/docs/relay-protocol/#artifact-files)). It returns 404 outside the relay, 501 when the
relay has no file storage, 410 for a changed entry, and 413 above 256 MiB or past a quota.
See [Artifacts](https://console.uubright.com/docs/artifacts/) for publication and serving rules.

## Board and deploys

`GET /api/board?workspace=<id>` returns the workspace's board: `{workspaceId, asOf, cards, elsewhere?, stalled?, queue?}`. Each card has `id`,
`kind` (`task`, `pr`, `review` or `deploy`), `state` (`needs`, `working`, `ready` or `done`), `title`, `next` (one
line on what's next), `at`, `createdAt`, and where they apply `taskId`, `url`, `agent`, `badge`, `primary` (the card
carrying its task's own state, the one the task list shows), `status` (on that card, the task's status chip: one of
`needs`, `working`, `ready`, `done`, `paused` or `stopped`), `planned` (a worker its Manager started that hasn't begun its
first turn; the PWA files it under To do) and `seenState` (the state once a device has opened the
task; `hidden` when the task's PR cards tell the rest). When other workspaces have live tasks, the board also has
`elsewhere`: one `{workspaceId, counts}` per workspace, with no cards or session ids. `counts` maps each state to its
number of tasks (states with none are left out). `ready` is as the server sees it; a client that has opened some of
those tasks moves them itself, as the PWA does from the sessions it already lists. `stalled` is the Stalled row: one
`{taskId, title, kind, reason, at}` per idle worker nothing will wake (`worker`), runner stall (`runner`) and lead a
worker has waited on too long (`lead`). `queue` is the leads' review queue: `{taskId, title, url, leadTaskId?,
leadTitle?, note?, at}` per PR a worker reported ready. See [Worker states and stalls](https://console.uubright.com/docs/lead/#worker-states-and-stalls). `GET /api/board/events?workspace=<id>` with
`Accept: text/event-stream` sends the whole board on connect and again whenever it changes. Send the token in
the `Authorization` header, as the web app does; like task events it still accepts `?token=` for older clients.
Owner or paired device token.

`GET /api/cleanup?workspace=<id>` lists the workspace's stopped and exited tasks for **Clean up finished tasks…**:
`{retire, delete, tasks: [{id, title, state, activityAt, createdBy?, parentTaskId?, branch?, prs, retired?, disk}]}`, newest
first. `retire` and `delete` say what this caller may do (`delete` is true only for the owner token); `disk` is as in
`GET /api/sessions/:id/disk`, or `null` when the workspace is gone. `retired` is `{at, freedBytes, backup?, keptWorkspace?}`;
`backup.only` (`{commits, stashes?}`) counts what origin lacked when the task was retired; for a clone (`backup.allRefs`) only the
bundle Delete removes holds it. It is absent when origin didn't answer, and on older records. `?access=1` returns only `{retire, delete}`.

`GET /api/capacity` is the [capacity check](https://console.uubright.com/docs/operations/#capacity): `{checkedAt, recommended, limitedBy, perTask:
{memory, disk, memorySamples, diskSamples}, diskRoom, running, host: {cpus, load, totalMemory, availableMemory, swapTotal?,
swapFree?, disks: [{paths, available, total}], inotify: {maxInstances?, maxWatches?, inUse?}, tools: {docker, tmux,
systemd}, driver}, risks: [{level, key, text}]}`, with sizes in bytes. `limitedBy` is `memory`, `cpu`, `disk` or
`inotify`; `level` is `critical`, `warn` or `info`, critical first. Kept for a minute; `?fresh=1` measures again.
Owner or paired device token.

`POST /api/deploys` records a deploy for the board (owner token only). A deploy script posts
`{"id": "backend-v2.14", "status": "started", "service": "SciMigo backend", "version": "v2.14", "where": "prod"}` when it
starts, then the same `id` with `"status": "succeeded"` or `"failed"`.

`status` (`started`, `succeeded` or `failed`) is required, and `service` on a new deploy. `id`, `version`, `where`,
`url` (http or https) and `workspaceId` (default `default`) are optional; a later post with the same `id` updates that
deploy. A started deploy is Working, a succeeded one is Done this week, and a failed one, or one with no result 2 hours after it
started, Needs you for 24 hours. Deploys
are kept for a week in `deploys.json` in the data directory.

## Start a task

```sh
curl -X POST http://127.0.0.1:8787/api/sessions \
  -H "Authorization: Bearer $CCR_CLOUD_TOKEN" -H "Content-Type: application/json" \
  -d '{"prompt": "Reply OK", "permissionMode": "default", "outputStyle": "concise"}'
```

`POST /api/sessions` body (all fields optional):

| Field | Description |
|---|---|
| `prompt` | First message. Until the agent names the task, the title is a short form of its first sentence. |
| `title` | Task title, up to 80 characters. A given title is kept: the agent doesn't rename the task. |
| `projectId` | A saved project to work in. |
| `workspaceId` | Workspace for this task; defaults to `default`. |
| `repo` | Clone URL, when not using a project. Work happens on branch `ccr/SESSION_ID`. |
| `baseBranch` | Branch to start from. Overrides the project's base branch; without either, a task starts from `origin`'s default branch. See [Choose the base branch](https://console.uubright.com/docs/repositories/#choose-the-base-branch). |
| `model` | The model the agent runs: a Claude Code alias (`opus`, `fable`, `sonnet`, `haiku`) or full ID, or a Codex model. Omit to use the workspace's default for the agent, or else the agent's own. A model that doesn't suit the agent and `modelRoute` returns `400` with the reason. See [Choose the model](https://console.uubright.com/docs/tasks/#choose-the-model). |
| `permissionMode` | `default`, `acceptEdits`, `auto`, `plan`, `dontAsk` or `bypassPermissions`. Omit for the host default. See [Permissions](https://console.uubright.com/docs/tasks/#permissions). |
| `modelRoute` | `account` (the server user's Claude login) or `ccr` (the CCR gateway). Defaults to `account` in host mode and `ccr` in Docker mode. `ccr` needs a configured gateway; Docker mode has no `account`. See [Switch models with CCR](https://console.uubright.com/docs/switch-models/). |
| `outputStyle` | `default` or `concise`. Omit to use the server's own setting. See [Response style](https://console.uubright.com/docs/tasks/#response-style). |
| `room`, `handle` | Join this room as `@handle` (Claude Code tasks only). See [Rooms](https://console.uubright.com/docs/rooms/). |
| `lead` | Lead settings: `{"workersAuto"?: boolean}` from the owner or a paired device; the limits (`maxWorkers`, `budgetUsd`) are owner-only (`403` otherwise). Full shape: `{"workersAuto"?: boolean, "maxWorkers"?: number, "budgetUsd"?: number}`. See [Lead tasks](https://console.uubright.com/docs/lead/). |
| `parentTaskId` | The task that asked for this one, such as the workspace's [Manager](https://console.uubright.com/docs/manager/); it must be in the same workspace. The app nests the new task under it. Display only: it grants the parent nothing. |
| `holdPrompt` | `true` to name the task from `prompt` without sending it, so the client can upload files to the new task and send the prompt with them (`POST /api/sessions/:id/messages`). The New task form does this when files are attached. |
| `prRouting` | `"ask"` (default) or `"auto"`; inherits from the lead, then room when not set on the task. See [PR review routing](https://console.uubright.com/docs/lead/#pr-review-routing). |

It returns the task record with status `201`.

## Sessions

| Route | Description |
|---|---|
| `GET /api/sessions` | All tasks, each whole, newest started first. A host with hundreds of tasks answers with megabytes; a client that polls should ask for the list in parts, below. |
| `GET /api/sessions?window=N` | The list in parts, for polling: `{sessions, rest: {count, tag}}`. `sessions` holds, whole, the `N` (0–200) most recently active tasks, every other task that is at work, waits on you (an approval, a decision, a held message, a recovery, a merge card, a budget hold), has a job running or has a pull request still open, and each workspace's Manager; they come without the fields no list shows (`touched`, `declaredFiles`, `reviewVerdicts`, `costByMonth`), which `GET /api/sessions/:id` still has. `&include=ID,ID` (up to 64) adds tasks whole whatever their age, such as the one on screen. `rest` counts the tasks left out and names them with a `tag`. A task starting or ending a turn doesn't change the tag; a new task, a deleted one or a changed old one does. The web app asks with `window=50`. `window` and `rest` together are refused (400). |
| `GET /api/sessions?rest=N` | The tasks `?window=N` leaves out, as stubs: `{sessions, tag}`. A stub has `partial: true`, a version `v`, and what a row, a state and a count need: the task's record without usage, context, file lists, `updatedAt` (when it has `activityAt`) and the long fields of its nested records (`repo.localPath` and `repo.base`, a worker report's note, a review's focus and verdict); each PR is its `url`, `number`, `status`, `ready` and `readyAt`. Fetch it once. When `rest.tag` changes, `&versions=1` returns `{versions: {ID: v}, tag}` (a few kilobytes) and `&ids=ID,ID` (up to 100) returns just those stubs, so a client fetches only the ones it lacks or holds an old version of and drops the ones no longer named. The tag doesn't depend on `include`. |
| `GET /api/sessions/:id` | One task, including `state`, `openPermissions`, `uncertainMessages`, `jobs` (durable jobs still running: `[{id, command, startedAt}]`), `recovery` (a card waiting on the owner: `{id, reason: "stalled" \| "cut_off" \| "worktree" \| "start_failed", title, detail, fix?, actions}`), `waitingMessages` (ids of messages sent but not started yet; clients show Starting… instead of Ready while an idle task has one), `permissionMode`, `outputStyle`, `modelRoute`, `model` (what was asked for), `activeModel` (what the agent reports running), `pendingModel` (a change not taken yet), `context` (`{tokens, window}`: how full Claude Code's conversation is, and the window once a turn reports it), `modelSwitch` (`live`, `resume`, or `after-resume` for a runner too old to change it while it runs), `prs` (all tracked PR URLs, numbers, status, checks, readiness and pending notices), `workspacePath` (the task's worktree on a host-mode server, for **Open in editor**), and, once its agent reports it, `usage`: `{costUsd, input, output, cacheRead, cacheWrite, turns, lastTurnCostUsd, models, billing}` (Claude Code's estimate at API prices; `billing` is `subscription` or `api-key`). |
| `PATCH /api/sessions/:id` | Rename a task with `{"title":"…"}` (1–80 characters; the agent then keeps it, and `titleSource` becomes `owner`), or update `lead` and/or `prRouting`: `{"prRouting":"ask"}` or `{"prRouting":"auto"}`. `{"webResearch": false}` turns off web research for the task; it is turned on only from an approval. A paired device may only rename or turn web research off; the rest needs the owner token. A runner token cannot use this route. `lead` replaces the whole lead setting, so send `workersAuto`, `maxWorkers`, `budgetUsd` and `hardCap` together. Promoting an idle task restarts it; changing an existing lead's limits doesn't, and a budget raised above this month's spend clears the task's `budgetHold` ([Monthly budget](https://console.uubright.com/docs/lead/#monthly-budget)). |
| `GET /api/sessions/:id/events?from=N` | The task's event log from offset `N`. Send `Accept: text/event-stream` for live server-sent events; reconnects resume from `Last-Event-ID`. `?tail=N` opens a long task at its end: the last `N` events plus the *pinned* events from before them that a view still needs (open approvals and the latest `changes` summary). As JSON this returns `{before, pinned, events}`; as a stream, the pinned events come first without an SSE id, then a `history` event, `{"before": OFFSET}`, then the tail. Earlier events: `?before=OFFSET&limit=N` (JSON). Responses are gzipped when the client sends `Accept-Encoding: gzip`. |
| `GET /api/sessions/:id/view?tail=N` | The task's [session view](https://console.uubright.com/docs/how-it-works/#session-view): the last `N` items, with tool calls folded into groups and no tool input or output. Returns `{items, before, more, next, card, approvals, changes, background}`: `next` is the log offset to poll from, `card` the task card, `approvals` the open approval requests (as log events; the latest request for each open id), `changes` the latest changes summary without patches, `background` the background tasks still running (`{id, description, startedAt}`; the description may quote a command). `?from=OFFSET` returns the items changed by events at or after `OFFSET`, with the same fields; a tool group that gained steps comes again, so replace items by `offset` (and `part`, for a message's text blocks). Items are in feed order: a user item with a `position` sits there instead of at its `offset` (a queued follow-up held at the bottom, or a started one just before its turn), and comes again when it moves. `before` is a position. `?before=OFFSET&limit=N` pages back: `{items, before, more}`. `?message=ID` returns `{items}` with just that follow-up, wherever it sits. |
| `GET /api/sessions/:id/detail/:offset?call=ID` | One tool call's `{tool, input, output, error}`, where `offset` and `call` come from a step in the view. `output` is absent while the tool runs. |
| `GET /api/sessions/:id/changes` | The latest summary of what the task changed since it started: `{base, at, files: [{path, added, removed, binary, truncated?}], omittedFiles}`. Add `?file=PATH` for one file, including its `patch`. Available after the task stops. |
| `POST /api/sessions/:id/pr` | Push the task's branch and open a pull request: `{"title": "…", "body"?: "…", "draft"?: true, "commitAll"?: true, "base"?: "main"}`. Repository tasks only, while idle; returns `202`, and the result arrives as a `pull_request` or `pull_request_failed` event and in the task's `pullRequest`. |
| `POST /api/sessions/:id/prs` | Owner only: attach an existing open GitHub PR to this task with `{"url":"https://github.com/OWNER/REPO/pull/NUMBER"}`. Returns the task record. |
| `DELETE /api/sessions/:id/prs` | Owner only: stop tracking the PR in `{"url":"…"}`. Returns the task record. |
| `POST /api/reviews` | Owner only: start a [local PR review](https://console.uubright.com/docs/lead/#local-pr-review) with `{"repo":"OWNER/NAME","number":7,"focus"?:"…"}`. Returns `201` with `{reviewerTaskId, headSha, round, authorTaskId?, reviewer: "claude"|"codex", independence: "other-agent"|"same-agent", note?}` (the agent opposite to the author's when it can run, else a fresh session of the same agent, with `note` saying why), or `{alreadyReviewed: true, headSha, commentUrl}` when the head commit already has a review comment, or `{reviewing: true, reviewerTaskId, headSha}` while one runs. `409` with "No reviewer can run on this server…" (or "…on this Mac…") when neither a Codex reviewer with an enforced sandbox nor a Claude Code reviewer can run; `403` unless the repository is a project in the workspace, `400` unless that project is a local checkout; `409` if the PR isn't open; `429` when the host's reviewers are all busy. Host mode only. Each task's `prs[]` carries the PR's latest `verdict`: `{result: "pass"|"fail", head, stale, counts, agent, independence, note?, round, commentUrl, at}`. |
| `POST /api/sessions/:id/pr/route` | Send one pending PR feedback notice to its author task: `{"noticeId":"…"}`. The task's `pr` field lists `status`, `checks`, `failures`, `ready`, and pending notice IDs and titles. Returns `202`; `409` if the notice is gone. |
| `POST /api/sessions/:id/pr/merge` | You or your paired devices only (room, task, lead and reviewer tokens get `403`): merge a PR this task tracks on GitHub, as the workspace's GitHub login: `{"url":"…", "method"?: "merge"}` (`merge` or `squash`). Only a PR that shows Ready to merge, and only at the head commit it was ready at (sent to GitHub as `sha`). Returns the task record once GitHub has merged it; `409` with GitHub's reason when it can't, when the PR isn't tracked, open or ready, or when commits were pushed since it was ready (review it again). |
| `POST /api/sessions/:id/messages` | Send a follow-up: `{"text": "...", "attachments"?: ["a-…"]}`. With attachments, `text` may be empty. `"edits": "<message id>"` replaces your latest message (`409` for any other): the agent is told so, and the `user_message` event and view item keep the new text with `edits` and `edited: true`. `{"regenerate": true}` instead asks again for the last answer (`409` while a turn runs or before any message); its `user_message` has `auto: "regenerate"` and the view shows a `log` item with `action: "regenerate"`. The `user_message` event carries its command id and, with files, `attachments: [{id, name, size, type, scanned}]`; the view item has `queued`, `started`, `withdrawn`, or `uncertain` state. A stopped task is started and gets the message once it runs. Returns `409` if the task is a finished review, a file was already sent, or the task's runner is known to be too old for files (before its first connection a message with files waits), `413` if the files together pass the per-message limit (100 MB by default), `400` for more than 20 files. Withdrawing a message frees its files for another message. |
| `POST /api/sessions/:id/attachments?name=FILE` | Upload one file as the raw request body (any content type). Returns `201` with `{id, name, size, type, label, scanned, scanNote?}`: `name` is sanitized, `type` detected from the content. `413` past the per-file limit (25 MB by default; the server stops reading there), `422` for a refused type or a ClamAV hit (the file is quarantined), `413` when the task's unsent uploads would pass 200 MB, `503` if a configured ClamAV is down or can't scan the file, `507` while the server's data disk has less than 2 GB free, `400` as a relay request (a relay phone sends `up` messages instead, see [the relay protocol](https://console.uubright.com/docs/relay-protocol/#attachments)), `409` if the task is stopped. Limits come from the task's workspace (`attachmentLimits` in `GET /api/workspaces`) and change only with `ccr-cloud workspace set-attachment-limits`. |
| `GET /api/sessions/:id/attachments` | The task's uploads: `{attachments: [{id, name, size, type, label, scanned, sent, scanNote?}], limits: {fileBytes, messageBytes}, scanner}`. `scanner` says whether a ClamAV daemon is reachable. |
| `DELETE /api/sessions/:id/attachments/:attachmentId` | Remove an upload no message has taken; `409` once sent. |
| `POST /api/sessions/:id/messages/:messageId/withdraw` | Withdraw a queued follow-up. Returns `202` when accepted, `404` for an unknown id, or `409` when already started, finished, withdrawn, or withdrawal is pending. A runner may report `message_withdraw_refused` if the message starts between the request and delivery of the withdrawal command. |
| `POST /api/sessions/:id/jobs/:jobId/stop` | Stop one of the task's running durable jobs and its process group. The agent is told it was stopped. Returns `404` if the job isn't running. |
| `POST /api/sessions/:id/recovery/:recoveryId` | Answer a recovery card: `{"action": "nudge" \| "fresh" \| "retry" \| "dismiss"}`, one of the card's `actions`. `nudge` interrupts the stalled turn and sends a continue message; `fresh` saves uncommitted work as a WIP commit and starts a new agent session in the same worktree with a handoff note; `retry` starts the task again. Returns `404` if the card is already resolved, `409` if a nudged task isn't running. See [Failure and recovery](https://console.uubright.com/docs/reliability/). |
| `POST /api/sessions/:id/uncertain/:messageId` | Decide on a message the agent may not have seen after a crash: `{"action": "resend" \| "dismiss"}`. Messages after it wait for this. Returns `404` if it isn't waiting, `409` if a decision is already queued. An entry in `uncertainMessages` with a `reason` was held back by the server instead (files queued before the task started, for a runner too old for them): later messages don't wait, `resend` sends its text without the files, and a message that was only files returns `409`. |
| `POST /api/sessions/:id/permissions/:requestId` | Answer an approval: `{"behavior": "allow" \| "deny", "message"?: "...", "scope"?: "task"}`. `scope: "task"` allows the tool for the rest of the task, only for requests with `canAllowForTask: true` (Codex MCP tool calls). `scope: "web-research"` allows this request and, until it is turned off, every WebSearch and every WebFetch of a public http(s) page in the task; only requests the view marks `canAllowWebResearch: true` accept it. Requests allowed that way are logged as `permission_decision` with `auto: "web-research"`. For a question (`tool` is `AskUserQuestion`), `allow` is refused; `deny` skips it. |
| `POST /api/sessions/:id/questions/:requestId` | Answer a question: `{"answers": {"<question text>": "<answer>"}}`, one non-empty answer (at most 2,000 characters) per question in the request's `input.questions`. Join several picked options with `, `. 409 if the question's format isn't supported (skip it instead). |
| `GET /api/sessions/:id/screen` | Live view of the task's browser, as server-sent events: `status` (`{available, detail}`) and `frame` (`{data, width, height}`, a base64 JPEG and the page size in CSS pixels). Needs `CCR_CLOUD_BROWSER_BIN`. |
| `POST /api/sessions/:id/interventions/:helpId/control` | Take control of the browser while the agent waits for help (the task's `intervention`). Returns `{controller}`; send it back here every few seconds to keep control. `409` while someone else has control (`{"force": true}` takes it from them) or once the request is over. |
| `POST /api/sessions/:id/interventions/:helpId/input` | `{"controller": "…", "input": [...]}` with up to 50 of `{"type":"click","x","y"}`, `{"type":"scroll","x","y","dy"}`, `{"type":"text","text"}`, `{"type":"key","key":"Enter"\|"Backspace"\|"Tab"\|"Escape"}`, `{"type":"viewport","width","height"}` (lay the page out for your screen until the request ends; no size restores it), in the page's CSS pixels. `403` if you no longer have control. |
| `POST /api/sessions/:id/interventions/:helpId/done` | Hand the browser back: `{"controller": "…", "note"?: "…"}`. The agent continues and sees the note. |
| `POST /api/sessions/:id/model` | Change the model, like `/model`: `{"model": "opus"}`, or `{"model": null}` for the agent's own default. The change applies between turns only. Optional `interrupt: true` stops a running turn first, and `compact: true` runs Claude Code's `/compact` before switching. Returns `202` with `{applies, queued, afterTurn?}`: `applies` is `now` (Claude Code), `next_turn` (Codex) or `resume` (a stopped task); `afterTurn` means it waits for the stopped turn to end. The task log records a `model_changed` event once it applies. `400` for a model that doesn't suit the task, or on the CCR route one the gateway doesn't list. `409` with a `code`: `turn_running` (a turn is running and `interrupt` wasn't set), `context_too_large` (the conversation needs more than 80% of the new model's window; retry with `compact`), `provider_switch` (a model from another provider, or on the CCR route a provider it can't tell; use `/handoff`), or none while a task started before this version is running. |
| `POST /api/sessions/:id/handoff` | Move the work to a new task: `{"agent": "codex", "permissionMode": "auto"}` or `{"agent": "claude", "model": "deepseek,deepseek-chat"}`. `permissionMode` may be `auto` or `default` (Ask); a workspace Manager defaults to Auto when omitted. The new task's first message is a note built from this task's log (goal, branch, pull request, what is done, what is next). The server stops the old task, saves and pushes its branch when present, transfers its room handle and workers, and returns `201` with the new task. The old task keeps its history and its handoff can be undone. |
| `GET /api/models?agent=claude&modelRoute=account` | What the Model picker offers: `{models: [{value, label, note}], agentDefault?, note?}`. Claude Code on the account lists its aliases, on `ccr` what the gateway's `GET /v1/models` lists, and `agent=codex` what Codex's `model/list` returns. |
| `POST /api/sessions/:id/interrupt` | Interrupt the current turn. |
| `POST /api/sessions/:id/stop` | Stop the task, keeping its workspace. |
| `POST /api/sessions/:id/start` | Resume a stopped task. Optional body `{"modelRoute": "account" \| "ccr"}` moves it to that route first (host mode; `409` while the task is running). |
| `POST /api/sessions/:id/retire` | [Retire](https://console.uubright.com/docs/tasks/#retire-and-delete) a stopped or exited task: back up commits no remote has (to `backup/<id>` on origin, or a bundle on the server) after a WIP commit of uncommitted changes, then free its checkout, installed dependencies and scratch files. Returns the task record, whose `retired` is `{at, by, freedBytes, branch?, head?, wip?, backup?: {ref?, bundle?, allRefs?, commits}, ignored?: {archive, entries}, keptWorkspace?}` until it resumes. A task without a repository keeps its workspace and loses only installed dependencies. `409` while the task runs or a durable job is running, when it is already retired or a reviewer, when the backup fails, or when uncommitted work can't be saved by a WIP commit (a nested repository, a submodule with work its origin lacks, a changed file behind a clean filter, a task branch shared with or moved by another checkout) or is still there after it (nothing is freed; `error` says why). Owner or paired device token. |
| `GET /api/sessions/:id/disk` | The task's disk use and branch state: `{bytes, git, dirty?, unpushed?, stashes?, branch?, checkedAt}` (`unpushed` counts commits on HEAD, and for a clone on any local branch or tag, that remote-tracking refs don't have), `{}` when its workspace is gone. Counted when asked and cached for ten minutes; `?fresh=1` counts again. |
| `DELETE /api/sessions/:id` | Delete the task, its workspace, its attachments, its deliverables and its log. Owner token only; a paired device gets `403` and can retire instead. |

A task's `state` is one of `pending`, `cloning`, `idle`, `running`, `waiting`
(approval needed), `exited` or `failed`.

## Projects

| Route | Description |
|---|---|
| `GET /api/projects` | Saved projects. |
| `POST /api/projects` | Check a clone URL and save it: `{"name": "...", "repo": "URL"}`. Returns `422` with the check if the repository isn't readable. |
| `POST /api/projects/check` | Check a clone URL without saving: `{"repo": "URL"}`. |
| `GET /api/local-repositories?q=NAME` | Repositories discovered on the server (host mode). Optional case-insensitive name/path search, up to 200 characters; the 100-result limit applies after filtering. Pass the returned `snapshot` and `nextOffset` as `snapshot` and `offset` to load another page (decimal integers, 0–3000). Snapshots use five-minute idle expiry and LRU eviction; page-zero requests refresh expired tokens, while HTTP 410 on later pages tells the client to restart at page zero. The response includes `total` matches. |
| `POST /api/local-repositories/private-folders` | Allow discovery to read `~/Desktop` and `~/Documents` on a Mac (owner token only, host mode); remembered. `GET /api/local-repositories` reports `privateFolders: "ask"` or `"allowed"` on a Mac using the default folders. |
| `POST /api/projects/local` | Save a discovered checkout: `{"path": "...", "name"?: "..."}` (host mode). With `"byPath": true` (owner token only), `path` may start with `~/` and lie outside the discovery roots; see [Add a repository by path](https://console.uubright.com/docs/repositories/#add-a-repository-by-path). |
| `PUT /api/projects/:id/base-branch` | Set where a project's new tasks start: `{"baseBranch": "develop"}`. An empty value uses `origin`'s default branch. |
| `PUT /api/projects/:id/setup` | Set a project's setup: `{"script": "npm ci", "env": {"NAME": "value"}}`. An empty script and env remove it. Reserved variable names are refused with `400`. |
| `GET /api/setup` | Which execution mode is in use, how credentials are handled, and whether a CCR gateway is configured (`ccrGateway`). `localMode` is true in local mode; `sshHost` is `CCR_CLOUD_SSH_HOST` when set. `relayUploads` is true on hosts that take composer files over the relay; a relay app dims 📎 on hosts without it. |

## Notifications

| Route | Description |
|---|---|
| `GET /api/push/key` | The server's public push key. |
| `GET /api/push/subscriptions` | Registered devices. |
| `POST /api/push/subscriptions` | Register a device: `{"subscription": {...}, "label"?: "..."}`. |
| `DELETE /api/push/subscriptions` | Remove a device: `{"endpoint": "..."}`. |
| `POST /api/push/test` | Send a test notification to every device. |
| `POST /api/push/action` | A notification button's decision: `{"token": "…"}`. The signed token from the push payload is the authorization; no owner token. `403` for an invalid or expired token, or Allow for a tool that isn't read-only; `409` if the request is no longer open. |

## Activity

`GET /api/activity` (optional `?task=ID`): the app sends this while you're using it, meaning input in the last minute
on a focused window. For 15 seconds after it, decisions don't push; with `task`, that task's held-back decisions count as
seen. See [Notifications](https://console.uubright.com/docs/notifications/#what-youll-be-notified-about).

## Drafts and pins

What the app syncs between your devices ([details](https://console.uubright.com/docs/phone/#your-drafts-and-pins-follow-you)). The server stamps each
write with its own time; the last write wins.

| Route | Description |
|---|---|
| `GET /api/drafts` | `{drafts: {KEY: {text, at}}, pins?: {order, unpinned, at}}`: every draft with text, and the task pins. |
| `GET /api/drafts/:key` | One draft, `{text, at}`. A cleared draft has empty `text` and the time it was cleared; an unknown one has `at: 0`. |
| `PUT /api/drafts/:key` | Save `{"text": "…"}`; empty text clears it. Keys are `task:ID`, `new:WORKSPACE`, `manager:WORKSPACE` or `chat:WORKSPACE`. At most 32,000 characters (`413`); the server keeps the 500 most recent. |
| `PUT /api/pins` | Replace the task pins: `{"order": [ids], "unpinned": [ids]}`, at most 500 each. |

## Devices

| Route | Description |
|---|---|
| `POST /api/pairing` | Owner token or an [owner-grade device](https://console.uubright.com/docs/security/#who-can-do-what) (`403` for any other paired device). Create a single-use pairing code, valid for 10 minutes: `{code, shortCode, expiresAt}`. Open `/#pair=CODE` on the device. With the owner token on the [control socket](#control-socket), `{"ownerGrade": true}` makes the device that redeems it owner-grade (`shortCode` is then `null`); `403` over TCP, even with the owner token, and from any device. `managed-pair` uses it for the Mac app. Each such code is written to the activity log. |
| `POST /api/pair` | Exchange `{"code": "…", "label"?: "…"}` for a device token, without other authentication: `{token, device}`. `403` if the code is unknown, used or expired. |
| `GET /api/devices` | Paired devices; `current` marks the caller, `removable` says whether the caller may revoke that entry, and `ownerGrade: true` marks an owner-grade device. The web app reads what to offer from this list: on a direct connection a caller with no `current` entry is the owner token, and a device adds and removes devices only when its own entry has `ownerGrade`. It is display only; the routes below refuse whatever a client shows. `label` is what the device sent at pairing, without control and format characters (bidirectional overrides, zero-width marks, line breaks), at most 60 characters. |
| `DELETE /api/devices/:id` | Revoke a device and remove its push subscriptions. Owner token or an owner-grade device, except that any paired device may revoke itself (its own sign-out); `403` otherwise. |

A device token works where the owner token does, except for creating pairing codes,
revoking other devices, the [messaging settings](#messaging-settings-owner-only) routes
and the other owner-only routes listed under [Who can do what](https://console.uubright.com/docs/security/#who-can-do-what).

With the [encrypted relay](https://console.uubright.com/docs/phone-access/) on, these routes also exist:

| Route | Description |
|---|---|
| `POST /api/relay/pairing` | Owner token or an owner-grade device, over direct access (`403` for any other paired device or a relay phone). A ten-minute, one-use phone pairing payload. `409` when a [uuBright relay](https://console.uubright.com/docs/relay-managed/) plan's phone limit is reached. |
| `GET /api/relay/devices` | Relay phones, each with the `name` the phone sent when it paired; `current` marks the caller and `removable` says whether the caller may revoke that entry. Empty without the relay. |
| `DELETE /api/relay/devices/:id` | Revoke a relay phone and close its channel. Owner token or an owner-grade device, except that a relay phone may revoke itself; `403` otherwise. |
| `GET /api/relay/drift` | `{drift}`: `null`, or when the relay serves a different copy of the app than this computer, `{relay?, local, relayOlder, message, checkedAt}`. `relay` and `local` are build records `{cache, commit?, committedAt?, preparedAt?, dirty?}` (`relay` is missing for a relay deployed before build records, which is then compared by the `CACHE` in its `sw.js`); `message` names the redeploy command. Checked when the relay admits the host, every hour, every two minutes while a drift is shown, and on this request when the last check is over 30 seconds old (the answer may be the previous result while that check runs). |
| `GET /api/relay/status` | `{enabled, connected, registered, origin, hostId, mode, closeCode?, closeReason?, account?}`; `503` when the relay is off. `mode` is `managed` or `self-hosted`; `account` (managed only) is `{username, state, error?, plan?, registered}` with `state` `pending`, `ok`, `bound` (running without a token after registration), `token_needed` (bound, and the relay closed the host with `4412` (registration required), or, from a relay older than `4412`, refused admission with `4401` three times in a row; supply the token again. `closeReason` is `clock_skew` (`closeCode` 4425) when the relay turned this computer away because its clock is more than two minutes fast or four slow; that is never `token_needed`. An account-service outage closes with `4502` and never counts), `signed_out`, `refused` or `unreachable`. `registered` (top level, and the same value in `account`) is true once the relay has acknowledged this host key at this relay origin, and stays true across restarts and network drops until the relay closes the host with `4412` (registration required). `connected` is true once the relay has kept this host for six seconds or sent it a frame. |

## Rooms

See [Rooms](https://console.uubright.com/docs/rooms/) for how rooms work. Only the owner (or a paired device) can use these routes.

| Route | |
|---|---|
| `GET /api/rooms` | All rooms. |
| `POST /api/rooms` | Create a room: `{"name": "…", "goal"?: "…", "maxTurns"?: 50, "hours"?: 24, "autoPass"?: false, "prRouting"?: "ask" or "auto", "budgetUsd"?: 20}`. |
| `GET /api/rooms/:id` | One room: `state` (`open`, `paused` or `disbanded`), `members`, `tasks`, open `handoffs`, `questions` (agents' unanswered messages to you, each `{id, from, offset, at}`), `turns`, `maxTurns`, `deadline`, `autoPass` (absent when off), `costUsd` (its tasks' estimated cost so far) and `budgetUsd`. |
| `DELETE /api/rooms/:id` | Delete the room and its log. Member tasks keep running. |
| `GET /api/rooms/:id/events?from=N` | The room log from offset `N`. Send `Accept: text/event-stream` for live server-sent events; reconnects resume from `Last-Event-ID`. |
| `POST /api/rooms/:id/messages` | Post as the owner: `{"text": "…", "to"?: ["handle"]}`. Addressed tasks are woken. Returns `{offset, woken, notWoken}`. |
| `POST /api/rooms/:id/members` | Owner token only (paired devices, the relay and agents get `403`). Add an external member: `{"handle": "…"}`. Returns `{handle, token}`; the token is shown once. |
| `DELETE /api/rooms/:id/members/:handle` | Owner token only. Remove a member; an outside member's token stops working. |
| `POST /api/rooms/:id/invites` | Owner token only (paired devices, the relay and agents get `403`). A one-time invite code for an outside agent: `{"handle"?: "…", "host"?: "https://…"}`; `host` must be `https`, or `http` only for `localhost`, `127.0.0.1` or `[::1]`. Returns `{id, code, display, handle?, expiresAt, host, link, command}`; the code is shown once, works once and for ten minutes. `host` defaults to the address you used. At most 10 open per room. |
| `GET /api/rooms/:id/invites` | Open invites, as `{id, handle?, expiresAt}` (never the codes). |
| `DELETE /api/rooms/:id/invites/:inviteId` | Owner token only. Revoke an unused invite. |
| `POST /api/rooms/:id/handoffs/:handoffId/pass` | Wake the recipient with that hand-off. |
| `POST /api/rooms/:id/handoffs/pass` | Pass on every open hand-off, one prompt per recipient. |
| `POST /api/rooms/:id/handoffs/:handoffId/dismiss` | Drop a hand-off. |
| `POST /api/rooms/:id/questions/:questionId/dismiss` | Clear a question an agent asked you (`questions` in the room view). Posting to that agent through `messages` answers its questions too. |
| `POST /api/rooms/:id/auto-pass` | `{"on": true}` passes each new hand-off on as soon as an agent posts it; `{"on": false}` makes them wait for you again. Hand-offs already waiting are not passed. Each automatic pass counts against the turn limit. |
| `POST /api/rooms/:id/pr-routing` | Set inherited PR routing with `{"prRouting":"ask"}` or `{"prRouting":"auto"}`. |
| `POST /api/rooms/:id/tasks` | Add a task: `{"title": "…", "note"?, "assignee"?}`. |
| `PATCH /api/rooms/:id/tasks/:taskId` | Change a task: `title`, `note`, `assignee`, `state` or `branch`. |
| `POST /api/rooms/:id/pause` | Pause: no posts, task changes or wake-ups. |
| `POST /api/rooms/:id/resume` | Resume with a fresh time limit: optional `{"maxTurns": N, "hours": N, "budgetUsd": N or null}`. `409` if the turn limit or the budget is already used up. |
| `POST /api/rooms/:id/disband` | End the room: the log stays readable, external tokens stop working. |

`POST /api/rooms/rpc` is for external members and takes only a room token:
`{"id": "…", "method": "room_read", "params": {}}`. It returns `{result}` or `{error}`
with status `200`, and `401` for an unknown or revoked token. A repeated `id` returns
the first answer.

`POST /api/room-invites/redeem` takes no credential: the invite code is the authorization,
in the body only. `{"code": "ABCD-1234", "agent"?: "codex" or "claude", "handle"?: "…"}`
returns `201` with `{roomId, roomName, handle, token}`, the room token shown once. An
unknown, used or expired code gets `403`; five wrong codes from one network in ten minutes
get `429`, and ten across the server drop every open invite and pause new ones for ten
minutes. A refused handle (`400`, `409`) leaves the code usable. Not available through the relay.

## Share stats

`GET /api/share-stats` returns `{"days": 7, "tasksFinished": 3, "prsMerged": 2, "agentHours": 4.5}` for
the last seven days on this computer, for the [Share card](https://console.uubright.com/docs/sharing/). Counts only: no titles,
repositories, paths or ids. `tasksFinished` counts tasks that completed a turn in the window and aren't
running; `prsMerged`, tracked PRs GitHub reported merged in the window; `agentHours`, the agents'
reported turn durations (`result.duration_ms`). You and your paired devices.

## Health

`GET /api/health` returns `{"service": "ccr-cloud", "status": "ok", "apiVersion": 5, "instanceId": "h-…"}`
without authentication. `instanceId` is a random id kept in the data folder; an app showing
[several computers](https://console.uubright.com/docs/multi-host/) checks it before sending that computer's token. If `apiVersion` is missing or lower, an older control plane is
running; see [Troubleshooting](https://console.uubright.com/docs/troubleshooting/#the-app-and-server-dont-match).

### Control socket

A server in host mode also serves the same API on a Unix socket, `api.sock` in its data folder (mode 0700), and opens
it only after it has bound its TCP port. Only the owner's account can connect to it. Setup, `managed-pair` and the
Mac app's SSH tunnel (OpenSSH Unix-socket forwarding, `ssh -W <socket>`, OpenSSH 6.7 or newer) use it instead of the
TCP port, so a token never reaches another local user who took the port while the service was down. Over the socket,
`/api/health` also returns the service's `pid`. `setup --start --non-interactive --json` prints the socket's path as
`socket`.

## Model access (owner only)

Use the owner bearer token; paired-device tokens receive `403`. Saved secrets are
never returned, only whether each is set. See [Bring your own model](https://console.uubright.com/docs/bring-your-own-model/).

| Endpoint | Action |
|---|---|
| `GET /api/settings/model-access` | The active choice (`anthropic`, `bedrock` or `ccr`), each saved choice's settings without secrets, a saved Zhipu GLM key's base URL and model (never the key), the last check, and `gatewayFromEnv` |
| `POST /api/settings/model-access` | Check and save one choice, and make it active: `{"provider":"anthropic","key":"…"}`, `{"provider":"bedrock","region":"us-east-1","method":"profile","profile":"default"}`, `{"provider":"bedrock","region":"…","method":"keys","accessKeyId":"…","secretAccessKey":"…","sessionToken":"…"}` or `{"provider":"ccr","url":"http://127.0.0.1:3456","key":"…"}`. `{"provider":"glm","key":"…","baseUrl":"https://api.z.ai/api/anthropic","model":"glm-5.3-flash[1m]"}` saves GLM without making it active. A secret left out keeps its saved value. `"check": false` saves without the live check. Answers `{saved, check, status}`; a failed check is `200` with `saved: false` and saves nothing |
| `POST /api/settings/model-access/check` | Check the active choice again |
| `DELETE /api/settings/model-access/:provider` | Forget that choice's settings and secrets |

`GET /api/setup`, for any signed-in device, includes `modelAccess`: the active
choice's `active` and `label`, `claudeLogin`, `gatewayFromEnv`, `needsSetup`, true
when a host has no model access at all, and `glm` (`model` and `baseUrl`, no key)
when a GLM key is saved. A task's `modelRoute` may be `account`, `ccr` or `glm`.
`POST /api/sessions/:id/limit` accepts `choice: "glm"` when a key is saved; that
starts one new Claude Code task on GLM. `limitPolicy.fallback` may be `"glm"` and
is stored only: nothing switches on it automatically.

## Support bundle

`GET /api/support-bundle?task=<id>` returns the server's part of a problem report (see
[Report a problem](https://console.uubright.com/docs/troubleshooting/#report-a-problem)): the core's version, app build and
operating system, the task's id, title and state, the last 500 lines of the server log and of the
task's runner log, and its last 50 events. Without `task`, `?workspace=<id>` returns the server's
part alone. Secrets are redacted: the owner and device tokens, the CCR client key, the GitHub
token, every plugin secret, the task's environment, server environment variables named like a
token or key, known credential shapes (`sk-…`, `smgo_pat_…`, `ghp_…`, JWTs, private keys, URL
credentials, `password=`) and any long random-looking string. The response is at most 1 MB; long
logs lose their oldest lines first. You and your paired devices may call it; a task's own
credential gets `401`. `404` for an unknown task.

## Messaging settings (owner only)

Use the owner bearer token. Paired-device tokens receive `403`, even for status,
because status can contain a short-lived WeChat login link. Responses use
`Cache-Control: no-store`; saved bot tokens are never returned.

| Endpoint | Action |
|---|---|
| `GET /api/settings/messaging` | Discord and WeChat status and configuration source; no saved credentials |
| `POST /api/settings/messaging/discord/save` | Validate and save `{"token":"BOT_TOKEN"}`; does not connect yet |
| `POST /api/settings/messaging/discord/connect` | Return `202` with Connecting; poll status while the bot connects or reconnects |
| `POST /api/settings/messaging/discord/pair` | Issue a one-use five-minute account pairing code |
| `POST /api/settings/messaging/discord/test` | Send the paired owner a test DM |
| `POST /api/settings/messaging/discord/disconnect` | Stop and disable automatic startup; retain credentials |
| `POST /api/settings/messaging/discord/forget` | Stop and remove local bot credentials |
| `POST /api/settings/messaging/wechat/pair` | Begin Tencent pairing; poll status for its link and verification request |
| `POST /api/settings/messaging/wechat/verify` | Submit `{"code":"DIGITS"}` only when requested |
| `POST /api/settings/messaging/wechat/connect` | Reconnect using saved pairing |
| `POST /api/settings/messaging/wechat/test` | Send a test message using fresh WeChat conversation context |
| `POST /api/settings/messaging/wechat/disconnect` | Cancel pairing/stop the worker and disable startup |
| `POST /api/settings/messaging/wechat/forget` | Disconnect and remove local pairing credentials |

Environment-managed credentials cannot be replaced or forgotten through these APIs.
Disconnect/forget does not revoke the provider-side bot token or WeChat binding.

## Insights (owner only)

`GET /api/insights?range=7d|30d&tz=ZONE` returns [Insights](https://console.uubright.com/docs/insights/) for the last 7 or 30 days, with day
boundaries and the 2 am rule in the IANA time zone `tz` (default: the server's). Computed from the task records and
event logs on this computer; a result is reused for a minute. The response holds counts, seconds, dollars, bytes,
task ids and, in pattern cards and the cost check, the titles of the tasks they link to. It holds no message,
prompt, tool input or decision text. Fields: `outcomes`, `prompts` (`you`, `turns` by role, `fromAgents`,
`system`), `hours` (wall-clock and task-hour seconds for agent running and waiting on you, `elapsedOpenS`,
`unknownTaskS`, `quietGaps`), `days` (per local day, `[start, end]` seconds of running, waiting on you, unknown
and quiet), `spend` (`estimatedUsd`, `byBilling`, `byModel`, `tokens`, `codexTurns`, `disagree`), `disk`
(`freedBytes`, `freedBy`, `checkoutBytes` once measured) and `patterns`. Paired devices receive `403`.

`GET /api/weekly-report?workspace=ID&tz=ZONE` returns the [weekly report](https://console.uubright.com/docs/insights/#weekly-report) draft for one
workspace's last 7 days: `{ workspaceId, since, until, tz, markdown }`. The Markdown holds Insights' counts for the
workspace, merged PRs and reviewer verdicts with links, open decision titles and the Manager's open Workers by
title and state; no message, prompt, note or decision text. Paired devices receive `403`; an unknown workspace or
time zone `400`.

## Activity log (owner only)

`GET /api/activity-log` returns the [activity log](https://console.uubright.com/docs/security/#activity-log): `entries` (newest first, at most
`limit`, default 500), `total` matching, `actions` (every action in the log) and `chain` (`ok`, `count`, `pruned` with
`through`, `count` and `before` once retention has removed entries, and when it fails `brokenAt.seq` and `message`). Filters: `action` (exact, or a prefix ending in `.` such as `device.`),
`actor` (`owner`, `device`, `manager`, `worker`, `system`, or an actor id), `via` (`local`, `relay`, `push`,
`channel`, `internal`), `workspace`, `since` and `until` (ISO times). Each entry has `seq`, `at`, `action`, `actor`
(`kind`, `id`), `via`, `workspace`, `target`, `detail` (short labels only), `prev` and `hash`.
`GET /api/activity-log/export?format=json|csv` with the same filters downloads every matching entry in log order
and is itself recorded; `as=json` wraps the file as `{name, type, text}`. Paired devices and relay phones receive `403`.

## Setup check (owner only)

`GET /api/setup-check?workspaceId=ID` (`&refresh=1` to rediscover; otherwise a
result is reused for a minute) returns what first-run discovery found on the
server's computer: `items` (each `{id, title, status: "ok"|"action"|"skipped",
detail, fix?}`), `repos` (the ten most recently committed to, each with `path`,
`name`, `branch`, `remote`, `lastCommit`, `sources`, the `identity` Git would use
and its `scope`, `push` credential, `warnings` and `added`), `identities`,
`workspaceIdentity`, `ssh` (host aliases and key file names), `helpers`
(credential helper names), `gh` (`installed`, `accounts`, `setupGit`) and `ccr`
(`installed`, `configFiles`, `url`, `running`, `healthy`). No secret is read. Paired
devices and relay connections receive `403`. See [Setup check](https://console.uubright.com/docs/setup-check/).

`POST /api/setup-check/github-login` with `{"workspaceId": "ID"}` (optional)
starts `gh auth login --web` and answers `{id, state: "waiting", code, url, scope}`
once gh prints its one-time code (`502` with `error` if it can't). Poll
`GET /api/setup-check/github-login/:id` until `state` is `done`, `failed` or
`cancelled`; `DELETE` on it cancels. One sign-in runs at a time. A named workspace
needs its Git identity first and gets its own gh login. Owner only, like the check.
