@oar-sh/oar 0.9.13 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.github/extensions/web-relay/extension.mjs +9 -0
  2. package/.github/extensions/web-relay/server-lifecycle/managed-server.mjs +15 -1
  3. package/.github/extensions/web-relay/skills/question-bridge.mjs +4 -1
  4. package/CHANGELOG.md +396 -0
  5. package/README.md +12 -12
  6. package/bin/oar.js +677 -103
  7. package/package.json +7 -5
  8. package/server/claude-cloud-worker/claude-cloud-session-process.mjs +10 -4
  9. package/server/claude-worker/claude-session-process.mjs +39 -13
  10. package/server/claude-worker/claude-turn-publisher.mjs +20 -1
  11. package/server/claude-worker/subagent-timeline-recorder.mjs +75 -8
  12. package/server/copilot-worker/copilot-ask-user-tool.mjs +1 -1
  13. package/server/copilot-worker/copilot-prompt-context.mjs +3 -1
  14. package/server/copilot-worker/copilot-question-bridge.mjs +11 -6
  15. package/server/copilot-worker/copilot-sdk-adapter.mjs +11 -0
  16. package/server/copilot-worker/copilot-sdk-session-process.mjs +14 -1
  17. package/server/cursor-worker/cursor-ask-user-tool.mjs +1 -1
  18. package/server/cursor-worker/cursor-sdk-adapter.mjs +22 -7
  19. package/server/cursor-worker/cursor-session-worker.mjs +9 -2
  20. package/server/cursor-worker/cursor-turn-runner.mjs +18 -3
  21. package/server/grok-worker/grok-sdk-adapter.mjs +14 -0
  22. package/server/grok-worker/grok-turn-runner.mjs +13 -3
  23. package/server/public/app/api-client.js +3 -1
  24. package/server/public/app/ask-user-view.js +29 -4
  25. package/server/public/app/conversation-provider-indicator.mjs +18 -8
  26. package/server/public/app/question-answer-rule.mjs +15 -0
  27. package/server/public/app/question-multi-select.mjs +9 -2
  28. package/server/public/app/relay-event-view.mjs +5 -1
  29. package/server/public/app/settings-modal.js +17 -3
  30. package/server/public/index.html +9 -5
  31. package/server/relay-exit-codes.mjs +6 -0
  32. package/server/relay-self-restart.mjs +6 -1
  33. package/server/relay-tools.md +14 -11
  34. package/server/repositories/message-repository.mjs +29 -28
  35. package/server/repositories/subagent-timeline-statements.mjs +2 -0
  36. package/server/routes/ask-user-routes.mjs +41 -7
  37. package/server/routes/messages-routes.mjs +65 -10
  38. package/server/routes/preview-routes.mjs +73 -7
  39. package/server/routes/sessions-routes.mjs +49 -16
  40. package/server/server-runtime.mjs +156 -94
  41. package/server/services/cursor-session-root-service.mjs +70 -6
  42. package/server/services/data-dir-resolution.mjs +208 -19
  43. package/server/services/earlier-database-service.mjs +631 -0
  44. package/server/services/oar-cli-helpers.mjs +18 -5
  45. package/server/services/oar-state-layout.mjs +107 -0
  46. package/server/services/oar-state-migration-service.mjs +387 -96
  47. package/server/services/package-data-rescue-preinstall.mjs +22 -0
  48. package/server/services/package-data-rescue.mjs +137 -0
  49. package/server/services/preview-registry-service.mjs +3 -2
  50. package/server/services/push-dispatch-service.mjs +33 -6
  51. package/server/services/relay-event-service.mjs +183 -5
  52. package/server/services/relay-restart-queue.mjs +10 -3
  53. package/server/services/relay-singleton-guard.mjs +300 -36
  54. package/server/services/remote-relay-caller-context.mjs +7 -2
  55. package/server/services/remote-relay-dispatcher.mjs +30 -9
  56. package/server/services/session-activity-tracker.mjs +52 -15
  57. package/server/services/session-worker-launch-service.mjs +31 -1
  58. package/server/services/stale-turn-recovery.mjs +99 -0
  59. package/server/services/subagent-timeline-service.mjs +4 -1
  60. package/server/services/windows-autostart-service.mjs +415 -45
  61. package/server/services/windows-boot-autostart-service.mjs +962 -185
  62. package/shared/preview-instructions.mjs +17 -12
  63. package/shared/preview-tool-core.mjs +32 -14
  64. package/shared/question-answer-rule.mjs +63 -0
  65. package/shared/relay-events.mjs +54 -4
  66. package/shared/remote-relay-contract.mjs +20 -10
  67. package/shared/subagent-timeline.mjs +4 -0
  68. package/shared/windows-system-tools.mjs +25 -0
  69. package/shared/worker-runtime/config-loader.mjs +54 -8
  70. package/shared/worker-runtime/prompt-context.mjs +3 -1
  71. package/shared/worker-runtime/working-directory.mjs +65 -0
  72. package/.github/extensions/web-relay/README.md +0 -190
  73. package/server/README.md +0 -2187
  74. package/server/uploads/image_input.md +0 -540
package/server/README.md DELETED
@@ -1,2187 +0,0 @@
1
- # Copilot Web Proxy
2
-
3
- A Node.js web server that lets you chat with your local coding agents from any device via a browser.
4
-
5
- Three runtimes can serve a conversation, selected when the conversation is created:
6
-
7
- - **GitHub Copilot CLI** (default) — executed by the `web-relay` CLI extension and its session workers.
8
- - **OpenAI (BYOK)** — the Copilot CLI running in BYOK mode against an OpenAI-compatible endpoint, plus a direct Images API path for image conversations.
9
- - **Claude (Agent SDK)** — a dedicated Node worker in `server/claude-worker/` that speaks the same relay contracts.
10
-
11
- See [Claude Agent SDK provider](#claude-agent-sdk-provider) for the third runtime.
12
-
13
- ## Setup
14
-
15
- ```bash
16
- npm install
17
- ```
18
-
19
- This project now runs in package-wide ESM mode (`"type": "module"` in `package.json`).
20
-
21
- ## Starting the Server
22
-
23
- If you run `gh copilot` and the web-relay extension is loaded (project-local or user-global),
24
- the extension auto-starts `server.js` when needed and keeps the relay listener singleton
25
- while letting session-affine CLI workers run in parallel.
26
-
27
- If `tty-console` is installed as an optional dependency, the server starts it on an interactive
28
- terminal and stores its config/history files under `server/logs/`.
29
- When active, worker loop telemetry is summarized in the title bar (`Clients`, `Pen`, `Proc`,
30
- `parked`, running `CLIs`) and routine worker dequeue events are not printed as repeating logs.
31
-
32
- On Linux/macOS, session-affine worker launches prefer detached `tmux` sessions when `tmux`
33
- is available, using the worker SDK session id as the tmux session name so you can attach
34
- for debugging without changing the Windows launch path. Worker processes now launch from the
35
- relay repository root so the project-local `web-relay` extension is always discoverable; the
36
- session's actual target workspace is still passed via `COPILOT_WORKSPACE_ROOT` / `INIT_CWD`.
37
-
38
- The web client now includes a read-only **Inspect tmux console** action in the conversation
39
- three-dot menu. It streams only from active relay session workers and only while the viewer
40
- is actively watching that session.
41
-
42
- > **Single-owner rule:** Use either extension-managed relay transport **or** standalone `relay.mjs`, never both at the same time.
43
- > Agent/runtime restart policy is defined in `.github/copilot-instructions.md`.
44
-
45
- Launch Copilot CLI from the repository root with extensions enabled and no initial user prompt:
46
-
47
- ```bash
48
- npm run copilot:relay
49
- ```
50
-
51
- That runs `gh copilot -- --allow-all` from the repo root, so the
52
- extension is discovered and the relay starts immediately. If you installed the extension
53
- globally, plain `gh copilot` from any repository is enough.
54
-
55
- Or manually:
56
-
57
- ```bash
58
- node server/server.js
59
- ```
60
-
61
- This starts the web server and stays attached to the terminal, respawning its
62
- worker child across restarts. Ctrl+C (or closing the terminal) stops both.
63
- A Copilot CLI session with the extension attaches separately.
64
-
65
- If you install this repo locally with `npm link` or `npm install -g .`, the `copilot-remote`
66
- command starts the web relay server if needed and then launches `gh copilot` in the same shell
67
- from whatever folder you run it in. If a relay is already live, it reuses it instead of starting
68
- a second owner.
69
-
70
- `copilot-remote` also prepares a user-global `web-relay` extension wrapper by default. You can run
71
- `copilot-remote --install-extension` to install/update only the wrapper and exit.
72
-
73
- Relay server output is redirected to a logfile under `%LOCALAPPDATA%\copilot-remote\logs` by
74
- default (or `COPILOT_WEB_RELAY_LOG_DIR` if set), so the terminal stays reserved for the CLI.
75
-
76
- The global launcher no longer injects a bootstrap prompt; it just starts `gh copilot` directly
77
- after the relay is ready.
78
-
79
- If you need a specific `server/config.json` for token or tunnel settings, set
80
- `COPILOT_WEB_RELAY_CONFIG` to that file before launching. The global npm install does not include
81
- the repo-local gitignored config file by default.
82
-
83
- Mode summary — one entry point, role chosen by argv:
84
-
85
- - `node server/server.js` (= `npm start`): the process stays attached as a supervisor and runs
86
- `server-runtime.mjs` in a worker child it marks with `--relay-runtime`. Exit 75 relaunches the
87
- worker; other non-zero exits are retried 3 times before the supervisor gives up.
88
- - `node server/server.js --supervised`: runs the server in this process and exits 75 instead of
89
- restarting itself, leaving that to whoever spawned it. This is what the CLI extension passes.
90
- - `node server/relay.mjs`: the standalone Copilot relay, started by hand after the server is up.
91
- Manual escape hatch only — never alongside extension-managed transport.
92
-
93
- Role flags are argv, not env, on purpose: the server's environment is inherited by tmux worker
94
- sessions and by the Copilot CLI it launches, and the extension spawns the next server from that
95
- same environment — so an env flag would decide the role of unrelated servers down the tree.
96
-
97
- On Windows, the visible relay launcher path now targets a stable per-workspace Windows Terminal window name so later foreground launches reuse the same window instead of opening new desktop windows. Keep the hidden/stdio path as a fallback only.
98
-
99
- ### Runtime safety checklist (avoid duplicate relay workers)
100
-
101
- 1. Stop stale detached watchdog/relay processes before restart.
102
- 2. Keep exactly one listener on port `3333`.
103
- 3. The relay singleton lock is stored at `server/data/relay-server.lock` (stale locks are auto-recovered).
104
- 4. In extension-managed mode, do not start a second server or run `node relay.mjs`.
105
- 5. Verify `/api/status` shows `cliOnline: true` and queue counts are moving or zero.
106
- 6. Follow relay restart policy from `.github/copilot-instructions.md`.
107
- 7. In extension-managed mode, use `POST /api/relay/shutdown` for manual restart requests.
108
- - It is queued until the relay is idle, so it will not stop an in-flight turn immediately.
109
- - Send `{ "restart": true }` when you want a self-restart instead of a plain shutdown.
110
- 8. Do not run tests that spawn Copilot CLI clients unless the user explicitly permits it.
111
-
112
- Script necessity note:
113
-
114
- - Extension-managed relay does not call npm scripts directly; it starts `server.js --supervised` itself.
115
- - Extension-managed relay supervision includes bounded auto-restart while the CLI session is active,
116
- and is now the only supervisor in that mode.
117
- - `npm start` is a plain alias for `node server/server.js`; there is no other start script.
118
- - Manual restart policy is defined in `.github/copilot-instructions.md`.
119
-
120
- ## Global extension install (user-scoped)
121
-
122
- Copilot also scans a user extensions directory, so you can make this extension available
123
- across repositories:
124
-
125
- ```text
126
- C:\Users\<you>\.copilot\extensions\web-relay\extension.mjs
127
- ```
128
-
129
- With global install, starting `gh copilot` in any workspace will load this extension and keep
130
- the relay tied to that workspace CWD instead of forcing a fixed repo launcher.
131
-
132
- If you also keep a project-local copy, extension management can show two `web-relay` entries.
133
- Keep only one active to prevent duplicate loading.
134
-
135
- For global install, use `copilot-remote --install-extension` (recommended) or manually place a
136
- wrapper `extension.mjs` there that imports your repository extension entrypoint. Then set one of
137
- these environment variables so it can find your relay server files:
138
-
139
- - `COPILOT_WEB_RELAY_SERVER_DIR` (recommended) → absolute path to the `server` folder
140
- - `COPILOT_WEB_RELAY_ROOT` → repo root that contains `server\`
141
- - Optional overrides: `COPILOT_WEB_RELAY_CONFIG`, `COPILOT_WEB_RELAY_TOOLS`, `COPILOT_WEB_RELAY_LOG_DIR`
142
-
143
- Project-local extensions still take precedence if the same extension name exists in both locations.
144
-
145
- The startup banner shows your access URLs and token.
146
-
147
- ## Accessing the UI
148
-
149
- Open in any browser:
150
- ```
151
- http://<your-pc-ip>:3333/
152
- ```
153
-
154
- If `localhostOnly` is enabled in `config.json`, the server listens only on loopback and you must use:
155
-
156
- ```
157
- http://localhost:3333/
158
- ```
159
-
160
- `localhostOnly` affects only the local relay listener. SSH reverse tunnel exposure is configured separately with `sshTunnel.remoteBind`. The Cloudflare Tunnel mode (`cloudflaredTunnel`) needs no public bind at all: `cloudflared` connects outbound to Cloudflare and proxies back into `127.0.0.1`.
161
-
162
- Sign in once with the token prompt; the browser stores the session in an HttpOnly cookie.
163
- Each CLI session now tracks its own workspace root:
164
- - the running CLI keeps its learned runtime CWD
165
- - the **🗂️ Change CWD** menu updates that session's persisted next-launch CWD
166
- - the workspace browser follows the selected session's effective CWD instead of one relay-global root
167
-
168
- Startup CWD learning prefers explicit session/launcher hints such as `COPILOT_WORKSPACE_ROOT`,
169
- then other runtime cwd hints (`INIT_CWD`, `PWD`, session metadata). The extension startup sync
170
- deliberately skips `process.cwd()` so the relay host directory never silently masquerades as a
171
- project root. Sessions without an explicit configured CWD launch in the relay's working directory.
172
-
173
- A plain `cd <path>` chat command persists to that conversation's configured CWD only — it does not
174
- affect other sessions or the global relay root.
175
-
176
- Use the chat header **⋯** menu and choose **🗂️ Change CWD** to switch the selected session's next
177
- launch directory from the list of known directories. The CWD picker always stays available; the
178
- launch action is only enabled for the selected CLI when it is not running.
179
-
180
- ### Socket events for CWD changes
181
-
182
- | Event | Emitter | Meaning |
183
- |---|---|---|
184
- | `workspace_root_changed` | Admin CWD picker (`POST /api/workspace-root`) | Global relay root changed; affects all sessions that have no per-session root configured |
185
- | `conversation_workspace_root_updated` | Chat `/cd` command and conversation CWD API | Per-conversation configured root updated; only the referenced conversation is affected |
186
-
187
- ## Install as an app
188
-
189
- The UI is now a Progressive Web App. On Android Chrome, use the browser menu to choose
190
- **Install app** or **Add to Home screen**. Installed app mode now prefers fullscreen launch
191
- where supported (with standalone fallback), and hides install/fullscreen header buttons.
192
-
193
- When opened in a regular browser tab, the in-app **Install** button remains available
194
- in the chat header (shown as `⬇` on small screens).
195
-
196
- You can rename the installed app label from **⚙️ Settings → Relay name** (paired relays know this relay by the same name).
197
- The name is stored on the relay (app settings) and served in the web app manifest
198
- to every browser and origin (LAN and tunnel agree), so future installs pick it up
199
- immediately and already-installed Android apps receive it through Chrome's normal
200
- manifest-update flow — one confirmation prompt showing the new name, then the
201
- launcher label updates. A legacy per-browser name is adopted by the relay the
202
- first time that browser loads the app.
203
-
204
- **💤 Suspend host** (Windows relay hosts) puts the PC into suspend-to-RAM once
205
- nothing is running any more. The confirmation modal first lists what is still
206
- active — sessions with a running turn, sessions with live background agents, and
207
- open GitHub Actions runs in the workspaces of those sessions (read through the
208
- host's `gh` CLI; an unreadable CI state blocks for 15 minutes, then is ignored).
209
- Confirming queues the request: the relay polls every second and suspends after
210
- everything has been idle for 2 minutes (or 30 seconds when nothing was running
211
- at confirm time). While a suspend is queued every connected client shows a
212
- banner with the blockers or the countdown and a **Cancel** button, the menu entry
213
- reads **💤 Suspend pending…**, and reopening the modal offers to cancel. A relay
214
- restart drops the queued suspend; a push notification (event **Host suspend**)
215
- reports both the actual suspend and such a drop. For the first 45 seconds after
216
- a relay start the check lists one more blocker, "the relay just started,
217
- sessions are still reporting": the workers that outlived the previous runtime
218
- may not have reported their background work yet. A queued **🌄 Restart web relay**
219
- gets a banner of its own, with the sessions it waits for, **Restart now** and
220
- **Cancel restart** (see [Manual relay shutdown / self-restart](#manual-relay-shutdown--self-restart)).
221
-
222
- API: `GET /api/host/suspend` (state plus current blockers), `POST /api/host/suspend`,
223
- `POST /api/host/suspend/cancel`, and `POST /api/relay/shutdown/cancel`
224
- (token only, like the restart itself). Set `OAR_HOST_SUSPEND_DRY_RUN=1` to log instead of sleeping;
225
- `OAR_BOOT_REPORTING_WINDOW_MS` changes the 45 seconds (0 to 600000; test relays
226
- pin `0`, which switches the wait off; a negative value is ignored); an override in effect is
227
- logged at start.
228
-
229
- You can also hide the **💤 Suspend host** action from **⚙️ Settings** with the
230
- **Show Suspend host action** checkbox. This only controls the menu entry; the
231
- banner for an already queued suspend still shows on every device.
232
-
233
- The live thinking bubble's header carries three follow buttons on the right —
234
- **💭** thoughts, **📃** streamed answer, **🛠️** tool list. Arming one keeps that
235
- section's last line pinned just above the composer as the reply grows; scrolling
236
- the transcript by hand (wheel, touch, scroll keys) disarms it, typing in the
237
- composer does not. The armed mode is remembered per conversation for the life of
238
- the page. **Stop** now asks for confirmation before cancelling the turn.
239
-
240
- If you host the relay behind a subpath, set `remotePath` in `server/config.json` to that public path prefix and open the URL with a trailing slash so the PWA scope matches correctly for install prompts. The relay serves a path-relative manifest identity (`id`, `start_url`, `scope`) so each install stays bound to its own URL subtree and avoids cross-app collisions on shared origins.
241
-
242
- ## Model Selection
243
-
244
- The composer includes a model picker next to the Send button.
245
- Models are now populated dynamically from the active Copilot CLI runtime using
246
- raw model IDs (no relay-specific aliases). The selected model ID is sent as-is
247
- for each message.
248
-
249
- Behavior notes:
250
-
251
- - The picker refreshes from live CLI model discovery when relay status changes.
252
- - Selection is persisted in browser storage and reused if still available.
253
- - If live discovery is temporarily unavailable, the relay can use cached/current
254
- model state and shows a warning banner.
255
- - In extension-managed mode, the relay still switches model per message and
256
- reports the active model used in the response.
257
-
258
- ### A message without a model, an effort or a mode
259
-
260
- The composer always sends all three. A client that leaves one out of
261
- `POST /api/message` (a script, an agent on this relay) gets the conversation's
262
- own, never the relay-wide default:
263
-
264
- - **Model**, for an existing Copilot conversation: the conversation's saved
265
- `preferred_model`, then the runtime session's `provider_model`, then its
266
- `model`, then the model of the latest user message (`auto` skipped in each);
267
- only a conversation with none of these runs on the catalog's current model.
268
- A saved model the catalog no longer lists is refused with
269
- `409 CONVERSATION_MODEL_UNAVAILABLE` (`model`, `supportedModels`) instead of
270
- being replaced; the composer shows that text in its banner. An explicit
271
- `auto` is unchanged (new conversations only). Claude, Cursor, Grok, Claude
272
- Cloud and OpenAI conversations keep their pinned `provider_model`, as before.
273
- - **Effort**: for Copilot, an effort the model's variant id carries, else the
274
- conversation's `preferred_reasoning_effort`, clamped to the nearest level the
275
- model offers (`nearestSupportedReasoningEffort`, the composer's rule); with
276
- nothing to keep, the model's lowest level that is not `none`, so `none` is
277
- chosen only when the conversation asked for it or the model has no other
278
- level. OpenAI, Claude, Cursor and Grok conversations take the conversation's
279
- effort the same way; with no effort stored, or one that neither matches nor
280
- clamps (an `ultracode` on a model without it), they keep the provider's own
281
- default as before (`none`, which for Claude, Cursor and Grok means the
282
- model's default). A Claude Cloud conversation always runs with `none`: the
283
- cloud takes no effort. A board action's follow-up takes the conversation's
284
- effort as well.
285
- - **Mode**: a send that names no `relayMode`/`mode` runs in the
286
- conversation's saved `preferred_relay_mode`, not the relay default.
287
- - **Preferences**: a send to an existing conversation saves only what it named.
288
- A model it named is saved (with its effort only when that was named too, else
289
- the stored effort stays); an effort alone is saved against the stored model,
290
- and a conversation with no saved model runs with that effort but saves
291
- nothing; a send that named neither writes nothing. The mode saved with them
292
- is the one the turn runs in, so a send without a mode leaves the stored mode
293
- as it is. A send from another relay's agent never writes them, as before.
294
-
295
- A text repeat inside the duplicate window answers `200` with `duplicate: true`
296
- and `queued: false`, and nothing runs. A message whose turn **failed** no
297
- longer counts: sending it again queues it.
298
-
299
- ### OpenAI API key
300
-
301
- Open **Settings → OpenAI API key** to save an OpenAI key and exact model ID
302
- (`gpt-4o` by default). Use the provider toggle to switch new conversations
303
- between OpenAI and GitHub Copilot without re-entering the saved key. While
304
- enabled, newly created extension-managed conversation workers start with Copilot
305
- CLI BYOK environment variables pointing to `https://api.openai.com/v1`.
306
- Zero-message conversations follow provider changes; started conversations keep
307
- their original provider and lock the composer to their assigned model.
308
-
309
- GPT-5 and OpenAI reasoning-model sessions use the Responses API automatically;
310
- other OpenAI models retain the broader-compatible Chat Completions wire format.
311
- OpenAI BYOK sessions currently use reasoning effort `none`; GitHub Copilot
312
- reasoning choices remain separate even when both providers expose the same model
313
- ID.
314
-
315
- Saving or re-enabling the key refreshes OpenAI's `/v1/models` list and adds
316
- candidate OpenAI model IDs to the composer picker. The Settings model-variant
317
- refresh performs the same discovery while OpenAI is enabled and retains the
318
- cached list if discovery fails. Starting a conversation uses the cached list; it
319
- does not make another discovery request. The model selected when creating a
320
- conversation is persisted on that conversation and used as its `COPILOT_MODEL`;
321
- the Settings model is only the default. Starting a chat from a locked OpenAI
322
- conversation opens an independent model chooser without changing the active
323
- conversation.
324
-
325
- Disabling OpenAI retains the key and cached model list. Removing the key is a
326
- separate destructive action and makes subsequent conversations use GitHub
327
- Copilot.
328
- An existing OpenAI-assigned conversation can continue while its worker remains
329
- running, but cannot launch a replacement worker until an OpenAI key is configured.
330
-
331
- ### Claude models
332
-
333
- When the Claude provider is enabled, discovered `claude-*` IDs join the same catalog. The composer
334
- only offers models the active conversation's provider can serve, so Claude models are hidden in
335
- Copilot/OpenAI conversations and vice versa.
336
-
337
- **Select Models** has one tab per runtime — **Copilot**, **OpenAI**, **Claude SDK**, **Cursor SDK** —
338
- and each tab lists only rows contributed by that runtime. The Claude and Cursor tabs write their
339
- selection through `POST /api/settings/claude` / `POST /api/settings/cursor` (`enabledModels`) rather
340
- than the model-variant catalog; the configured default model is always enabled and cannot be
341
- deselected, since deselecting it would leave that provider's conversations without a model. An empty
342
- selection means "all available".
343
-
344
- `POST /api/model-variants/refresh` refreshes all enabled providers concurrently and reports
345
- `openAIModelDiscovery` and `claudeModelDiscovery` separately, so one provider's failed discovery does
346
- not hide another's success — the cached list is kept and a warning is surfaced in the UI.
347
-
348
- ## Claude Agent SDK provider
349
-
350
- Claude conversations are executed by `server/claude-worker/claude-session-worker.mjs`, a plain Node
351
- process spawned per conversation. It is not part of the Copilot CLI extension: it connects to the
352
- same worker WebSocket, sends the same heartbeats, and posts to the same activity/stream/thought/
353
- response endpoints, but runs turns through `@anthropic-ai/claude-agent-sdk` instead of the Copilot SDK.
354
-
355
- ### Enabling
356
-
357
- **Settings → Claude (Agent SDK) → Enable Claude for New Chat model selection.**
358
-
359
- Authentication uses the relay host's own logged-in Claude credentials (`~/.claude`) — the relay never
360
- stores an Anthropic API key. Run `claude` on the host and complete login before enabling. A turn that
361
- fails to authenticate is answered with a system note telling you to do exactly that, rather than
362
- being retried silently.
363
-
364
- Enabling (or changing the default model) triggers model discovery: a short-lived idle `query()` is
365
- opened purely to serve a `supportedModels()` control request, with a 20 s timeout. Discovered
366
- `claude-*` IDs — including bracketed capability variants such as `claude-opus-5[1m]` — are stored and
367
- added to the model catalog. Bare aliases (`default`, `sonnet`) are dropped in favour of the explicit IDs.
368
- In the composer, `[1m]` variants are folded into their base model: the base ID is the only dropdown
369
- entry, and the variant is selected through the context-size dropdown (`long_context` composes the
370
- `[1m]` ID on send and in the persisted per-conversation model preference).
371
-
372
- Disabling Claude rebinds conversations that have not yet sent a message back to the default provider,
373
- mirroring the OpenAI key-removal reconciliation. Conversations that have already started keep their
374
- provider, and other providers' bindings are never touched.
375
-
376
- ### Per-turn behavior
377
-
378
- | Relay mode | Claude mapping |
379
- | ----------- | --------------------------------------------------------------------------- |
380
- | `plan` | SDK `permissionMode: 'plan'`; `ExitPlanMode` publishes a **plan_ready** board, then the tool call is **denied** so the turn ends for review instead of rolling straight into implementation — the board's choice starts the next turn in the chosen mode |
381
- | `ask` | System prompt appended to prefer `AskUserQuestion` before implementing |
382
- | `agent` | Default permission mode, unmodified preset prompt |
383
- | `autopilot` | System prompt appended to keep moving unless input is truly blocking |
384
-
385
- - **Model and reasoning effort are per turn.** Each turn is a fresh `query()` with `resume`, so both
386
- can change between messages. Effort levels are `none` (SDK default) plus whatever the model reports
387
- (`low`, `medium`, `high`, `xhigh`, `max`), plus **Ultracode** — see below.
388
- - **Ultracode** is offered on every model whose discovered efforts include `xhigh`. It is not an SDK
389
- effort level but a session-scoped settings flag, so the relay carries `ultracode` as a sentinel on
390
- the ordinary effort ladder (`withClaudeUltracodeTier` in `services/provider-reasoning-effort.mjs`,
391
- the single source for all Claude effort lists) and only the worker translates it: a fresh session
392
- spawns with `effort: 'xhigh'` and `settings: { ultracode: true, enableWorkflows: true }`, and a
393
- live session is toggled in or out with `applyFlagSettings` (`claudeUltracodeFlagSettings`).
394
- `enableWorkflows` is passed explicitly because the worker loads no filesystem settings. It is never
395
- a silent default — the selectors label the rung "Ultracode" and warn about the token cost.
396
- - **Tools are auto-allowed**, matching the Copilot workers' `--allow-all` posture. Only two tools are
397
- intercepted: `AskUserQuestion` (bridged to relay question cards) and `ExitPlanMode` (plan board;
398
- denied after the board posts — the plan text comes from the tool input, or from the CLI's
399
- `planFilePath` when no inline plan is sent).
400
- - **Attachments** — images up to 5 MB are inlined as base64 content blocks; larger images and all
401
- non-image files are passed as absolute path references for Claude's `Read` tool.
402
- - **Subagents** — `forwardSubagentText` is on, so subagent text, thoughts, and activity stream into
403
- their own nested bubbles. `abort_subagent` maps to `query.stopTask()` for a backgrounded subagent;
404
- one running inside the current turn is still answered "not supported". Full-turn **Stop** works.
405
- - **Thinking** — the worker requests summarized thinking *display* without passing a `thinking`
406
- option, so it never switches thinking on for a session that has it off, and never changes a budget.
407
-
408
- ### Session continuity
409
-
410
- The native Agent SDK session id observed on the first turn is posted to
411
- `POST /api/claude-native-session` and stored in `runtime_sessions.claude_native_session_id`. Later
412
- turns pass it back as `resume`, so a Claude conversation survives worker restarts. The id is only
413
- cached in the worker after the server accepts it, so a failed persist is retried next turn.
414
-
415
- ### Background tasks and workflow progress
416
-
417
- The worker keeps one persistent CLI process per conversation, so background tasks survive the reply
418
- that started them. The live task set is posted to `POST /api/background-tasks` (REPLACE semantics)
419
- and broadcast as the `background_tasks` socket event; the composer's task panel renders it and can
420
- stop an individual task over a `worker.control` push. The conversation payload carries the set too
421
- (`backgroundTasks`, `endedBackgroundTasks`); the page's live poll and refresh leave it out when a
422
- `background_tasks` event for the conversation arrived while their request was on its way, as the
423
- event's set is at least as new.
424
-
425
- The relay holds the task sets in memory (`services/background-task-store.mjs`), so a relay restart
426
- starts without them while the workers and their tasks keep running (the console rows are stored;
427
- see below). The worker is the source of
428
- truth, and the relay asks:
429
-
430
- - **Digest and resync.** A worker's heartbeat carries `backgroundTasks: { count, digest }`, a digest
431
- of its sorted task ids (`shared/worker-runtime/background-task-digest.mjs`). When it differs from
432
- the set held for that worker (a restart, or a lost post either way round), the heartbeat answer
433
- says `resyncBackgroundTasks: true` and the worker posts its full set with `resync: true`; the
434
- request repeats on every beat until the two agree. A task restored this way keeps its start time
435
- and is not announced as started again. Every post of a set carries `order: { epoch, seq }` (the
436
- worker process and its count of set posts): two posts can overtake each other on the way, and the
437
- relay drops one that is older than the newest it applied from that process, or that comes from a
438
- process other than the one whose heartbeat came last for the session. A drop is logged and
439
- answered `stale: true` with a `reason`; a worker told so for its newest set asks for a heartbeat,
440
- on which the relay asks for the set again. `epoch` only names the process and is never compared
441
- as a time. A task that ended only because a set did not list it comes back, without a second
442
- start, when a later set lists it, unless a settle notice or its run's status has confirmed the
443
- end meanwhile. A worker that sends no digest (Cursor, Grok, Claude Cloud, or a worker on older
444
- code) has no opinion and is never asked.
445
- - **Placeholder.** A live Claude worker on older code cannot answer, but its heartbeat says whether
446
- background work holds its process (`steering.autoCompactWindow.backgroundWork`). While this
447
- runtime has not heard from that worker about its tasks, the session reads `background_only` with
448
- one task "background work, details not reported since the relay restarted (Kill session in its ⋯
449
- menu ends it)", the panel shows the
450
- same row without a Stop button, and a host suspend waits. It is derived on read
451
- (`services/background-work-view.mjs`), raises no event, and goes when the set arrives, the flag
452
- goes false or the worker is gone.
453
- - **Ends.** The Claude worker keeps a settle notice whose post failed (the newest 20, for 10
454
- minutes) and sends it again after the next heartbeat the relay answers; such a post is given up
455
- after 10 s without an answer.
456
- - **The console rows.** What the task console needs of a shell or Monitor task (its `outputPath`
457
- and `outputKind`, the ended row with status, exit code and `endedAt`, how a task ended when the
458
- settle came before the set dropped it) is kept in `background_task_rows` (migration 0018,
459
- `services/background-task-persistence.mjs`), written only when that part of a set changes, not on
460
- every progress post. At boot the store restores the ended rows still inside their hour, and holds
461
- the live ones (`restored`): the output route and the console's live room find a held task (the
462
- route answers it with `status: 'held'`, `held: true` and `stoppable: false`; the console says it
463
- waits for its worker), but `get()` and with it the panel, the session state and the suspend check
464
- do not count it as running, and the stop route only pushes the stop to the worker. The worker's next set settles it (a task in the set is live again, with the
465
- path it had; one not in it becomes an ended row, with the status the runtime before was told), a
466
- settle sent again for it ends it, and while a key has held tasks its heartbeat digest never
467
- counts as in step, so the relay asks for the set. Tasks of a worker that sends no set within twice
468
- the boot reporting window (at least 15 s; 90 s by default) are ended with status `unknown` and the
469
- pages get the `background_tasks` event (`endUnconfirmed`); a later set that lists one brings it
470
- back. A held task's end time is when the runtime before last knew it running: a stored live row's
471
- `updated_at` is written with the set and confirmed at most every 30 minutes while the worker's
472
- digest agrees, and a live row not confirmed for 6 hours (a worker that went away in an earlier
473
- runtime without an empty set) is deleted at boot instead of restored. Health readings are not
474
- stored: the poller reads the files again within 10 s, the ended rows once. A runner's counts come
475
- from the last 64 KB when its closing summary is there. A live log that outgrew that window is read
476
- whole by a per-task runner scan (`services/task-output-service.mjs`): it looks for a runner's
477
- header (a test run after a long install or build prints its header once) and counts from there,
478
- reads on from where it stopped as the file grows, and starts over on a new file under the path
479
- (shorter, another inode, an older mtime). The scans live in memory and share 4 MB per tick, each
480
- tick starting at another task, so after a restart a long log is caught up over a few ticks (the
481
- window's reading stands until then) and one busy log cannot keep the others waiting. An ended row
482
- never starts a scan, so the rows a restart brings back are read in their window only. What a
483
- worker says about a task (description, summary, last tool call, and a shell row's `command`, which
484
- the Claude worker takes from the Bash or Monitor call that started the task, Copilot from the
485
- shell tool's arguments or the task registry, Grok from the terminal) goes through `cleanTaskText`
486
- on the publish and settle routes: control codes and colours out, credentials scrubbed as in the
487
- output, then cut (a command at 2,000 characters; a Grok description is its command line). It is
488
- stored with the console rows, so a held or ended row keeps it; share links carry no task rows. The
489
- `none` answers of the output route use the page's texts (`TASK_OUTPUT_NONE_MESSAGES` in
490
- `public/app/task-console-render.mjs`). Rows go with their hour, the 20-per-key limit, a set that
491
- drops them or the conversation's delete. Without the table (a failed migration) the store works in
492
- memory as before.
493
- - **Run rows left `running`.** A background sub-agent's row whose end was never written would count
494
- as running work for a day. For a Claude worker that has reported its task set in this runtime, a
495
- `running` background row that the set does not list and that nothing has updated for 15 minutes
496
- is left out of the session state, `all_idle` and the suspend blockers.
497
-
498
- Tasks of type `local_workflow` carry an extra `workflowProgress` digest, because the SDK exposes no
499
- workflow-progress surface — the worker reads it off disk:
500
-
501
- - While the workflow runs, `subagents/workflows/<runId>/journal.jsonl` under the session directory
502
- gives the agent set and their running/done state; agent labels come from the first line of each
503
- `agent-<id>.jsonl`.
504
- - The run record `workflows/<runId>.json` is written **only at completion**, and takes over as the
505
- authoritative tree once it exists — it is the only source of phase titles, logs, token totals, and
506
- per-agent tool counts.
507
- - Parsing lives in `claude-worker/workflow-progress-digest.mjs` (`digestFromJournal`,
508
- `digestFromRunRecord`), polling in `claude-session-process.mjs` (`syncWorkflowPoller`, 2 s, only
509
- while such a task is live, published only when the digest actually changed). Reads are bounded by
510
- byte caps and a filename pattern, and the digest is clamped (≤100 agents, ≤50 phases, ≤5 log lines,
511
- per-field length caps). A run is joined to its task by the record's `taskId`, with a start-time
512
- mtime window as the mid-run fallback.
513
- - The relay never trusts the worker's JSON: `sanitizeWorkflowProgress` (`routes/messages-routes.mjs`)
514
- re-applies every clamp before storing or broadcasting, and drops a digest with no phases and no
515
- agents.
516
-
517
- When a workflow settles, the worker buffers its final digest (at most five, terminal status never
518
- downgraded) and attaches it to the next `POST /api/response` as `workflowRuns`. Runs that settled on
519
- a journal snapshot get one more run-record read at drain time, since the CLI often flushes the record
520
- a few seconds after the task disappears. The relay writes those rows into `workflow_runs` inside the
521
- same transaction that finalizes the assistant message, keyed on the response message id, and returns
522
- them with the message — so the transcript's collapsed **Finished background task** card (the same
523
- tree renderer as the live panel, `buildWorkflowRunCard` in `public/app/background-tasks-view.mjs`)
524
- survives a reload. A history rebuild deletes a conversation's `workflow_runs` alongside its
525
- `subagent_runs`, because both key on message ids the rebuild replaces.
526
-
527
- ### Sub-agent records (the sub-agent viewer)
528
-
529
- Every sub-agent run keeps its whole record in `subagent_timeline` (migration 0009): one row per
530
- thought, reply text, tool call (full input), tool result (cut at 4 KB, the original length kept in
531
- the entry's metadata), child agent or note, numbered per run by `seq` in the order the relay first
532
- saw it. A writer names each entry with its own `entry_key`; a second write under the same key
533
- updates the entry in place and keeps its `seq`, which is how a thought or a reply streams. A run
534
- keeps at most 2000 entries plus one note saying where it was cut (`subagent_runs.truncated`).
535
- `subagent_runs` also carries the run header the rows show: model, type, task id, tokens, whether it
536
- runs in the background, and who writes its timeline.
537
-
538
- - **Claude**: `claude-worker/subagent-timeline-recorder.mjs` reads every SDK message at process
539
- level, before any turn takes it, and posts entries to `POST /api/subagent-timeline` keyed by the
540
- run (coalesced every 500 ms; a run the relay does not know yet is retried). A background agent
541
- outlives the turn that spawned it, so its frames arrive between turns and during later turns;
542
- they go to its own record, never to a later turn's live lanes. A background launch's receipt
543
- (`tool_use_result.status: 'async_launched'`) leaves the run running; its `task_notification`
544
- ends it. Spawns carry `timelineOwner: 'worker'`.
545
- - **Copilot and Cursor** publish their sub-agents on the live lanes only (`/api/activity`,
546
- `/api/thought`, `/api/stream` with a `subagentRunId`); the relay copies each frame into the run's
547
- timeline, uncut. Fields they do not report (model, tokens) stay blank.
548
- - `POST /api/background-tasks` copies model, type, task id and tokens onto the run whose id is the
549
- task's `toolUseId`, so the row keeps them after the in-memory task set is cleared.
550
- - Every `subagent_status` event carries the whole header and the run's own turn (`messageId`). A
551
- turn that fails closes its foreground runs; background runs are closed by their worker, or by the
552
- relay when the worker dies.
553
-
554
- The browser draws one row per top-level run in the reply bubble (`public/app/subagent-row.mjs`, the
555
- panel's row grammar); a row's title, like a sub-agent task's title in the composer panel, opens
556
- `public/app/subagent-viewer.mjs`. The viewer reads `GET /api/conversation/:id/subagent/:runId`, grows
557
- with the `subagent_timeline` event, and fetches again from the last contiguous `seq` after a missed
558
- event or a reconnect. A run recorded before the timeline existed is served from its tagged
559
- activity, thought and stream rows (`legacy: true`).
560
-
561
- **Live delivery.** `subagent_timeline` goes only to the pages whose viewer shows that run. The viewer
562
- names its run with the socket message `subagent_viewer_watch { conversationId, subagentRunId }`
563
- (acknowledged with `{ ok: true }` or `{ ok: false, code }`: `missing-id`, `not-found`,
564
- `conversation-mismatch`) when it opens, moves to a child or its parent, and after every reconnect,
565
- and sends `subagent_viewer_unwatch` when it closes. The relay checks the run exists and belongs to
566
- the conversation and keeps each socket in at most one room, `subagent-viewer:<runId>`
567
- (`services/subagent-viewer-rooms.mjs`). Batches go to that room as volatile packets, so they are
568
- never kept for a reconnect replay and a backed-up connection drops them. socket.io also drops a
569
- volatile packet while the connection is still writing an earlier one, even from the same tick
570
- (a worker post that changes the header emits `subagent_status` first), so the relay holds batches
571
- one tick, merged per run, before sending. The viewer covers what is dropped: it waits for the
572
- watch's answer before its first read, fetches on a `seq` hole, after a reconnect, and once more when
573
- the run ends. A refused `not-found` watch is sent again on the run's next `subagent_status`. The lane
574
- events (`relay_activity`, `relay_thought`, `relay_stream`, `subagent_status`) go to every page as
575
- before.
576
-
577
- **Retention.** After `subagent_record_retention_days` (app setting, `0` = keep for good, otherwise 7,
578
- 14, 30 or 90; default 90; Settings → General → *Keep sub-agent tool output*) the relay strips a
579
- finished run's tool entries: a `tool_result` keeps its row with empty text, a `tool_call` keeps its
580
- one-line summary (`subagentToolCallSummary` in `shared/subagent-timeline.mjs`, the viewer's rule) in
581
- place of the input. Both get `pruned_at` (migration 0010) and metadata
582
- `{ pruned: true, prunedAt, originalChars, retentionDays }`; the viewer shows them as "Input removed
583
- after N days" / "output removed after N days". Thoughts, reply text, notes, child rows and the runs
584
- stay, and the age is the entry's `updated_at`; runs still `running` (or `pending`, `processing`) are
585
- never touched, nor are the lane rows. `services/subagent-record-retention.mjs` sweeps 30 s after
586
- start, once a day and 5 s after the setting changes, 2000 rows per transaction with the event loop
587
- free in between, through a partial index over the unstripped tool entries, and logs one
588
- `SUBAGENT RETENTION …` line. No VACUUM: SQLite reuses the freed pages.
589
-
590
- ### Context usage
591
-
592
- Claude sessions have no Copilot `events.jsonl` to tail. Instead the worker reads the live
593
- context-window breakdown with `getContextUsage()` while the turn's `Query` is still open, and posts it
594
- to `POST /api/claude-context-usage`; the relay stores it in `runtime_sessions.context_usage_json`.
595
- `GET /api/context/:id` then serves Claude and Copilot sessions through one normalized `contextUsage`
596
- view so a single renderer handles both. Claude supplies real per-category token counts; Copilot's
597
- coarse system/tools + messages + buffer split is synthesized into the same shape and flagged
598
- `isEstimate` when the runtime only reports a lower bound.
599
-
600
- ### Worker environment
601
-
602
- `applyClaudeProviderEnvironment` sets these on the worker launch environment:
603
-
604
- - `COPILOT_WEB_RELAY_WORKER_KIND=claude` — selects the Claude worker instead of the Copilot CLI
605
- - `CLAUDE_RELAY_MODEL` — the conversation's model, used when a turn carries none
606
-
607
- Also honored by the worker: `COPILOT_WORKSPACE_ROOT` (cwd), `COPILOT_WEB_RELAY_CONFIG` (relay config
608
- path), `CLAUDE_CODE_EXECUTABLE` (explicit Claude Code binary), and
609
- `COPILOT_WEB_RELAY_CLAUDE_WORKER_PATH` (override for the worker script location).
610
-
611
- On Linux/macOS the Claude worker still launches inside a `tmux` session named after the SDK session
612
- id, but without the `script`-based pseudo-TTY the Copilot workers need — it is a plain Node process.
613
- On Windows it opens a `Claude Worker <id>` terminal window.
614
-
615
- ### Provider-aware usage snapshots
616
-
617
- `fetchUsageSummary` reads GitHub Copilot plan quota, so it is skipped entirely for OpenAI and Claude
618
- turns. Those replies carry no usage line rather than displaying Copilot premium-request numbers under
619
- a reply that never touched Copilot.
620
-
621
- ### Plan usage for agents
622
-
623
- `remote_relay`'s `usage {relay}` (permission `read`, like `relay_info`; this relay too, as `this`)
624
- reads `GET /api/usage` and `GET /api/usage-limit` on the target and answers per provider card
625
- (Copilot, Claude, Claude Cloud, Cursor, Grok): `status` (`not-configured` and `unavailable` say why
626
- in `message`), `plan`, `source`, `capturedAt`, the meters (`used`, `allowance`, `remaining`,
627
- `utilization`, `unit`, `resetAt`, `severity`) and the card's detail rows and notes; plus
628
- `usageLimit` (`account`: the Claude window, its utilization, reset and overage; `pauses`: the turns
629
- held at a usage limit, by session). The dispatcher copies an allow-list of fields
630
- (`usageCard` in `services/remote-relay-dispatcher.mjs`), so a field the usage report gains later is
631
- not passed on; account labels and links are left out, and an e-mail address or a token-shaped
632
- string in a text is masked. A relay without `/api/usage` per provider answers
633
- `REMOTE_RELAY_UNSUPPORTED`; one without `/api/usage-limit` answers `usageLimit: null` with a note.
634
-
635
- ## Claude Cloud provider
636
-
637
- Provider type `claude-cloud`: a provider of its own, never an alias of `claude`. Its conversations
638
- run Claude Code in a sandbox at Anthropic, on a clone of a GitHub repository. The worker,
639
- `server/claude-cloud-worker/claude-cloud-session-worker.mjs`, is a plain Node process per
640
- conversation that speaks the usual worker contracts (WebSocket link, heartbeat, control poller,
641
- crash guard) but runs no agent: it sends the user's messages to the cloud session and follows the
642
- session's event stream (`claude-cloud-session-process.mjs`, `claude-cloud-event-normalizer.mjs`).
643
- The user-facing description, including what the provider does with the Claude CLI's login, is in
644
- the [providers guide](../docs/providers.md#claude-cloud); the tracker is
645
- [docs/feature-tracker/claude-cloud.md](../docs/feature-tracker/claude-cloud.md).
646
-
647
- ### The cloud client and the login
648
-
649
- `shared/claude-cloud/api-client.mjs` (`createClaudeCloudClient`) is the only code that knows the
650
- cloud API: paths, headers and bodies were measured from what the Claude CLI sends, not taken from
651
- a documented API, so every expectation about them lives in that one file. It is SDK-free (Node's
652
- `fetch`), turns every failure into a `ClaudeCloudError` with a `code` (`login_missing`,
653
- `login_expired`, `github_not_connected`, `repo_access_denied`, `environment_missing`, `not_found`,
654
- `rate_limited`, `bad_request`, `transient`), and never reconnects or retries on a timer by itself.
655
-
656
- `shared/claude-cloud/credentials.mjs` (`createClaudeCloudCredentials`) is the only code that reads
657
- the login: `CLAUDE_CODE_OAUTH_TOKEN` from the environment, else `claudeAiOauth.accessToken` in
658
- `<CLAUDE_CONFIG_DIR | ~/.claude>/.credentials.json`. The token is cached until a minute before it
659
- expires and then read again; the refresh token is never used. The relay process has one reader and
660
- one client (`server-runtime.mjs`), whose `nudge` lets the CLI look at its own status
661
- (`claudeAuthService.getStatus({ force: true })`) at most once in five minutes; each worker builds
662
- its own reader, without a nudge. `applyClaudeCloudProviderEnvironment` adds no credential to the
663
- launch environment (`COPILOT_WEB_RELAY_WORKER_KIND=claude-cloud` and `CLAUDE_CLOUD_RELAY_MODEL`,
664
- nothing else). Only a relay that itself runs on `CLAUDE_CODE_OAUTH_TOKEN` passes a login on: the
665
- variable is one of `WORKER_SECRET_ENV_VARS`, restricted to the `claude-cloud` worker kind
666
- (`workerSecretEnvVarsFor`), so under tmux it reaches a cloud worker through the owner-only secret
667
- env file, never as an `export` and never in the environment tmux is started with, and no other
668
- worker kind gets it that way. `redact()` takes the token out of every error text.
669
-
670
- The client's base URL is the Anthropic API. `shared/claude-cloud/base-url.mjs`
671
- (`resolveClaudeCloudBaseUrl`) lets `OAR_CLAUDE_CLOUD_API_BASE_URL` replace it for tests, and only
672
- with an `http(s)` URL of `127.0.0.1`, `[::1]` or `localhost` without credentials; any other value
673
- is ignored, because the client sends the login to whatever its base URL is. The relay's client and
674
- the worker's both resolve it there.
675
-
676
- ### Settings
677
-
678
- `services/claude-cloud-settings-service.mjs` keeps three `app_settings` rows:
679
- `claude_cloud_enabled` (default off), `claude_cloud_default_model` (default `claude-sonnet-5-5`)
680
- and `claude_cloud_environment_id`. Everything else the tab shows is read, not stored: the account
681
- from `claude auth status`, the login's source and expiry from `credentials.describe()`, the
682
- environments from the cloud (cached for a minute). **While the provider is off, nothing is asked of
683
- Anthropic**: the environments are listed only when it is on and a login exists. With no
684
- environment stored, `resolveEnvironmentId` takes the account's first active one and stores it.
685
- `models` is the Claude provider's model list with the `[…]` tier suffix dropped, deduplicated, the
686
- default first (`buildClaudeCloudModelList`). Every change is broadcast as the socket event
687
- `claude_cloud_settings_updated` with the GET body.
688
-
689
- Switching the provider off does not rebind anything: there is no reconciliation as for the other
690
- providers, and an existing cloud conversation still launches its worker.
691
-
692
- ### Creating a conversation
693
-
694
- `POST /api/conversation/bootstrap` takes `providerType: 'claude-cloud'` with
695
- `cloudSource: { repoUrl, branch? }`. The provider is only ever asked for by name (its model ids are
696
- the Claude provider's own, so a model never selects it). Refusals are `400` with a `code`:
697
- `claude_cloud_disabled`, `claude_cloud_repo_invalid`, `claude_cloud_branch_invalid`,
698
- `claude_cloud_environment_missing`, and `CLAUDE_CLOUD_MODEL_UNAVAILABLE` for a model outside the
699
- list. The repository is normalized to `https://github.com/<owner>/<repo>`
700
- (`shared/claude-cloud/repo-url.mjs` → `normalizeGitHubRepoUrl`; https, ssh and scp forms of
701
- github.com only), the branch is checked against git's ref rules (`isValidBranchName`; empty = the
702
- default branch), and the result is stored in `conversations.cloud_source_json` in the same
703
- transaction as the conversation. Nothing is created at Anthropic here. `POST /api/message` with
704
- `providerType: 'claude-cloud'` on a conversation of another provider is `409
705
- CLAUDE_CLOUD_REQUIRES_NEW_CONVERSATION`.
706
-
707
- `POST /api/message` accepts another model of the list until the first message has created the
708
- cloud session, and stores it on the runtime session; after that a different model is `409
709
- CLAUDE_CLOUD_MODEL_REQUIRES_NEW_CONVERSATION`. The worker, however, creates the session with the
710
- model it was launched with: `resolveModel` prefers `CLAUDE_CLOUD_RELAY_MODEL` over the delivered
711
- `providerModel`, so a change made after the worker started only takes effect if the worker is
712
- launched again before the first message. Reasoning effort is always `none` and the context tier
713
- always `default`, whatever the request says.
714
-
715
- ### Delivery, binding and resume
716
-
717
- `buildDequeuedRelayMessage` adds a `claudeCloud` field to every message delivered to a cloud
718
- worker (`buildClaudeCloudDelivery`): `{ sessionId, lastSequence, repoUrl, branch, environmentId,
719
- title }`. A restarted worker therefore needs nothing but the delivery. The worker reports the
720
- binding with `POST /api/claude-cloud-session` (`{ conversationId, cloudSessionId, sessionUrl?,
721
- lastSequence, pushedBranch?, costUsd?, model? }`) after it created the session, after every
722
- `result`, and on a push. `recordWorkerReport` (`services/claude-cloud-session-service.mjs`) stores
723
- the session id, the sequence (never moved back) and the cost on the runtime session row, keeps the
724
- session link and the list of pushed branches (the newest 20) in `cloud_source_json`, and emits the
725
- socket event `claude_cloud_session` with `{ conversationId, cloud }`. A report that names another
726
- cloud session than the stored one starts sequence, cost and pushed branches again.
727
-
728
- The conversation list, the conversation payload and the bootstrap answer carry the same `cloud`
729
- field: `{ repoUrl, slug, branch, sessionUrl, pushedBranches: [{ branch, at }], costUsd }`, or
730
- `null` for a conversation that is not a cloud one. There is no session root for a cloud
731
- conversation (`buildConversationSessionRootPayload` returns `null`).
732
-
733
- ### Usage
734
-
735
- The worker posts to the Claude worker's two usage routes. `POST /api/claude-context-usage` accepts
736
- a `claude-cloud` conversation and stores the session's context occupancy (used and maximum tokens,
737
- no categories) in `runtime_sessions.context_usage_json`, which `GET /api/context/:id` serves.
738
- `POST /api/claude-plan-usage` keeps a cloud worker's report under its own snapshot key
739
- (`claude-cloud`), so the Claude card stays what the Claude workers wrote.
740
-
741
- `GET /api/usage` builds two things from the cloud client while the provider is on
742
- (`services/claude-account-usage-service.mjs`: the usage body, the prepaid credits and the credit
743
- offer, read without a model turn, cached for 60 s, a failed read for 15 s; the route waits at most
744
- 3 s for them and falls back to the last turn's snapshot. Nothing is read and nothing cached is
745
- handed out while the provider is off):
746
-
747
- - the **Claude card's** live windows (`normalizeClaudeAccountUsage` in
748
- `services/plan-usage-claude.mjs`): the 5-hour, weekly and model-scoped windows with the
749
- account's own severity word, the week by product, and the organisation's prepaid credits;
750
- - the **Claude Cloud card** (`services/plan-usage-claude-cloud.mjs` → `buildClaudeCloudPlanCard`):
751
- one meter per top-level bucket of the usage body that carries a dollar limit (the cloud credit,
752
- with its expiry), the relay's own cloud spend (`readClaudeCloudSpend`: the sum of
753
- `runtime_sessions.claude_cloud_cost_usd` over the cloud conversations that still exist, plus the
754
- cost of the conversation named by `?conversationId=`), the latest cloud snapshot's session
755
- detail, and a note when a credit is offered but not claimed.
756
-
757
- ### Archive
758
-
759
- `DELETE /api/conversation/:id` and `POST /api/conversation/:id/archive` call
760
- `archiveSessionInBackground` for a cloud conversation: the cloud session is archived at Anthropic,
761
- best effort and not waited for, so neither action ever depends on Anthropic. Nothing is deleted
762
- there.
763
-
764
- ## Cursor Agent SDK provider
765
-
766
- Cursor conversations run through `server/cursor-worker/cursor-session-worker.mjs`, a per-conversation
767
- Node worker like the Claude one, backed by the Cursor Agent SDK. Authentication uses a Cursor API key
768
- saved via **Settings → Cursor SDK** (`POST /api/settings/cursor`); saving or replacing the key resets
769
- and re-runs model discovery, which also records each model's supported reasoning-effort tiers
770
- (`effortsByModel`).
771
-
772
- Per-turn behavior:
773
-
774
- | Relay mode | Cursor mapping |
775
- | ----------- | ---------------------------------------------------------------------------- |
776
- | `plan` | SDK native plan mode; a plan-shaped final message publishes a **plan_ready** board |
777
- | `ask` / `autopilot` | The SDK's send options carry no per-turn instruction channel, so a `[Relay mode: …]` nudge is prepended to the user message — injected only when the mode changes, and a change away from a nudged mode sends an explicit cancellation |
778
- | `agent` | Default behavior, no injection |
779
-
780
- - **Model and reasoning effort are per turn.** Effort is validated against the model's discovered
781
- tiers (`none` = model default); for `auto`/undiscovered models the request passes through and the
782
- worker validates it against the resolved model's live params.
783
- - **Stale agent handles are retried once.** A cached agent handle whose exchanged auth expired fails
784
- as a terminal error result even though the API key is still valid, so the worker recreates the
785
- handle and retries a single time; a second auth failure is treated as a real key problem.
786
- - **Session root** — the worker keeps its per-session agent store at
787
- `$CURSOR_AGENT_STORE_DIR` or `server/data/cursor-agents/<sdkSessionId>`, created on the first turn.
788
- The explorer's Session root resolves to it via `resolveCursorSessionRoot`.
789
- - Cursor turns are skipped by `fetchUsageSummary` like OpenAI and Claude turns — no Copilot usage
790
- line is attached.
791
-
792
- ## Turn recovery and the max turn duration
793
-
794
- A turn in `processing` is returned to the queue by two independent guards. **Both exempt a turn that
795
- is blocked on an unanswered relay question** — that turn is waiting on a human, and `relay_questions`
796
- carries its own expiry.
797
-
798
- 1. **Inactivity (`processingTimeoutMs`, default 10 min).** Measured from `owner_last_claimed_at`,
799
- which every worker heartbeat refreshes for the message it is working on — *not* from when the turn
800
- began. A turn that legitimately runs for hours of tool calls keeps pushing the cutoff forward.
801
- `processing_at` is only the fallback for rows with no owner (session-worker routing disabled).
802
- While the CLI is offline the window shrinks to 45 s.
803
- 2. **Absolute ceiling (Settings → Max turn duration, default 60 min).** Measured from `processing_at`.
804
- `0` disables it; the slider range is 0–600 minutes in 5-minute steps. This is a backstop for a
805
- worker that has hung while still heartbeating, and is stored in the DB app setting
806
- `turn_ceiling_minutes` — not in `config.json`. Shared bounds and formatting live in
807
- `shared/turn-ceiling.mjs`.
808
-
809
- ## Subagent runs and live streaming
810
-
811
- - `POST /api/stream` and `POST /api/activity` / `POST /api/thought` accept an optional
812
- `subagentRunId`. Frames carrying one are routed to that subagent's bubble instead of the parent.
813
- - The browser renders a **live reply preview**: main-thread stream text is markdown-rendered into the
814
- pending bubble while the turn runs, and replaced by the real message when it completes.
815
- - Subagent bubbles nest by `parentSubagentId`. A child event arriving before its parent's bubble
816
- exists builds the parent chain on demand, so nesting is preserved regardless of event order.
817
- - After the turn finishes, `subagentRuns` are returned with the assistant message and re-rendered as
818
- collapsible **🤖 <name>** sections containing that run's thoughts and activity.
819
- - Reloading mid-turn repaints both the reply preview and every subagent bubble from persisted stream
820
- rows (`deriveInFlightStreamTextByThread`).
821
- - The Copilot extension propagates the SDK `agentId` onto question/tool activity, so subagent-issued
822
- `ask_user` calls and tool results land in the right bubble. Re-discovering a known run no longer
823
- demotes it to a root or renames it.
824
-
825
- ## Conversation list active-turn flag
826
-
827
- `GET /api/conversations` returns `activeTurn` per conversation, derived from
828
- `listConversationIdsWithActiveQueue` (`pending` / `processing` / `parked`). Clients previously tracked
829
- this only from one-shot `message_status` socket events, which are lost if the socket drops between a
830
- turn finishing and delivery — leaving a permanent spinner. `activeTurn: false` now clears the
831
- client's optimistic state. Relay shutdown also waits 300 ms before disconnecting sockets so a terminal
832
- `message_status` emitted just before an idle-deferred restart still reaches the browser.
833
-
834
- ## Relay event subscriptions
835
-
836
- A session (the **watcher**) can ask to be told what happens in other sessions of this relay or of a
837
- paired relay, through `remote_relay`. The relay tells it by writing a short event message into the
838
- watcher's conversation; nothing reads transcripts on disk, and it works for every provider.
839
-
840
- **Actions** (`relay` may be left out and means `this`; on this relay the agent-sessions setting must
841
- be on, as for every local action; a paired relay: see [Across paired relays](#across-paired-relays)):
842
-
843
- - `subscribe {sessions: [ids] | ["all"], events?, once?, match?, stalled_minutes?, heartbeat_minutes?}`
844
- — `all` watches every session, ones created later too. The watcher's own conversation is never
845
- watched. The first subscribe of a conversation shows the user an approval card naming the
846
- sessions; a subscription to `all` is always named on a card (asked again after an Allow that did
847
- not cover it). The Allow is remembered as unlock rows `self:watch` / `self:watch-all`.
848
- - `unsubscribe {subscription_id | "all"}`, `list_subscriptions {watcher?}` (another conversation's
849
- subscriptions, to inspect before a transfer).
850
- - `transfer_subscriptions {from}` — moves every active subscription of another conversation, with
851
- its settings and its undelivered events, to the caller: a watcher is replaced without a moment
852
- where events go nowhere. Always an approval card (from where, how many, whether `all` is among
853
- them), also after the caller's first-subscribe Allow. The new watcher is dropped from moved
854
- session lists.
855
-
856
- **Events** (`shared/relay-events.mjs`): `question_asked` (prompt, options, question id; an approval
857
- card is marked as one only the user can answer), `error` (`turn_failed`, `usage_limit`,
858
- `worker_died`), `turn_end` (status `done` or `stopped`, reply preview), `task_finished` /
859
- `task_failed` (background sub-agents and shell tasks: kind, status, exit code where known; a
860
- non-zero exit is `task_failed`), `stalled` (no activity for `stalled_minutes`, default 15, while a
861
- turn or task runs and no question waits for an answer), `all_idle`
862
- (nothing runs in the watched set any more). `task_started` only when named in `events`.
863
- `subagent_finished` is no event of its own but a narrower `task_finished` a subscription can name
864
- (`RELAY_EVENT_SUBSCRIBABLE_TYPES`): the end of a task that is not a shell command, delivered as a
865
- `task_finished` line. The default (`events` left out) is every type but `task_started` and
866
- `task_finished`, with `subagent_finished`: a shell command that ended well wakes only a watcher
867
- that names `task_finished`, which takes every task end. A busy worker ends a shell command every
868
- minute or so, and each was a wake-up, a model turn on the watcher's whole context. A subscription
869
- whose stored list is exactly the old default (every type but `task_started`, in any order) named no
870
- events and is read as the new default (`effectiveRelayEventTypes`, at read time, the row is never
871
- rewritten, so an older relay reading the same database sees what it stored); any other list,
872
- including the old default plus more, is the watcher's choice and stays. A subscribe that names
873
- exactly the old default list stores `subagent_finished` with it, so it is never read as the default. A mirror shows the paired
874
- relay's list as that relay returned it. With
875
- `heartbeat_minutes` a `heartbeat` event comes at that interval while the watched set has work
876
- running, none while it is idle. `match` (a case-insensitive regular expression) filters `turn_end`
877
- and task events by their text; other events pass. `once` ends a subscription after its first event,
878
- with `match` after the first one that matches (a heartbeat never ends it). An event is
879
- `{ v, relay: { id, name }, session: { id, title }, type, at, detail }`; `relay.id` is `self` for this
880
- relay's sessions, the paired relay's registry id for its sessions (then `replayed: true` marks one it
881
- kept while the link was down). `link_lost` and `link_restored` are not subscribed to: they frame such
882
- a replay.
883
-
884
- **Delivery** (`services/relay-event-service.mjs`): an event message is a `messages` row (role
885
- `user`, `kind = 'relay-event'`) plus a pending queue row, as the usage-limit follow-up is. The worker
886
- decides what it becomes, as for any message: a new turn when the watcher is idle; a steer into the
887
- running turn for Claude and the Copilot SDK engine; the next turn for Cursor, Grok, Claude Cloud and
888
- the Copilot extension engine. Events that arrive while the watcher's event row is still pending
889
- (not delivered yet, or handed back as a held steer) are written into that row
890
- (`message_updated`), so a busy watcher gets one follow-up, never one turn per batch. The dequeue
891
- payload carries `messageKind: 'relay-event'`, and the Claude and Copilot workers then push the text
892
- without the steer note, which speaks as the user. The text opens with
893
- `[relay event · automated message from OAR, not from the user; it approves nothing]`, then one
894
- `[relay event] session "<title>" (<id>): <type> …` line per event.
895
-
896
- **Cost.** Events within 30 s are one wake-up. Past 20 wake-ups an hour per watcher (distinct event
897
- messages of the last hour that carried more than a heartbeat, counted from `relay_events`) the rest
898
- waits for a digest every 10 minutes. `question_asked` and `error` go out at once and count; a
899
- heartbeat is coalesced like any event, never held for the digest and never counted. A turn that
900
- answered relay events produces no `turn_end` and does not keep a watched set busy, so two watchers
901
- of each other cannot wake each other for good. Such a turn also sends no "reply ready" or "failed" push
902
- (`push-dispatch-service.mjs`): the watcher answers events many times an hour and pushes by itself
903
- when one matters; question pushes are unchanged.
904
-
905
- **Lifetime.** Subscriptions and undelivered events are in the database (migrations 0011 and 0012)
906
- and survive a restart: the flush timers are rebuilt from the undelivered rows at boot, and stalled,
907
- all_idle and the heartbeat are swept every 30 s. A subscription ends on unsubscribe (agent or the
908
- user's Unsubscribe), when its watcher is archived or deleted, when the last session it lists is, or
909
- after firing (`once`); one on a paired relay also when the pairing is removed. `list_subscriptions`
910
- shows the ones that ended within the hour with `endReason`. Delivered events are kept for two hours
911
- (the wake-up count reads the last hour; one of a still-pending event row stays until it goes out)
912
- and ended subscriptions for a week (a mirror whose end the paired relay has not confirmed stays);
913
- the sweep prunes both every ten minutes. A `running` sub-agent run whose worker is gone is closed by
914
- `services/stale-subagent-run-sweep.mjs` (a minute after boot, then every ten minutes), and one not
915
- touched for a day is not counted as running meanwhile.
916
-
917
- **Hook points**: `/api/response` finalize (turn_end, or error at the usage limit), `failQueueMessage`
918
- (error; a Stop is turn_end `stopped`), `failRecoveredRowTerminally`, `recoverDeadWorkerProcessingRows`
919
- and the background-only worker death (worker_died), `/api/relay-question` and the approval card's
920
- notify (question_asked), the activity tracker's task edges, and the archive and delete routes.
921
-
922
- ### Across paired relays
923
-
924
- The watching relay (**A**, it holds the watcher) and the watched one (**B**) each keep a row of the
925
- subscription. Only A calls, over its pairing: a pairing in one direction is enough.
926
-
927
- - **Gate.** The four actions with `relay: <paired relay>` pass the same checks as any `remote_relay`
928
- call there: the relay unlocked in the watcher's conversation (the user named it, or its agent wrote
929
- there), A's permission for it at least `read`, and B's inbound switch on (B refuses with
930
- `REMOTE_INBOUND_DISABLED`). `subscribe` first asks B with a dry run (sessions, limits, switch,
931
- version), then shows the watch card on A naming the relay (and `all`), remembered as
932
- `<registry id>:watch` / `:watch-all` and forgotten with the pairing, then subscribes on B and stores
933
- the mirror on A. No card on B. A relay that predates these routes answers Express's plain 404,
934
- which A reports as `REMOTE_RELAY_UNSUPPORTED` ("runs an OAR version without event subscriptions
935
- across relays").
936
- - **B's side** (`relay-event-routes.mjs`): `POST /api/relay-events/remote/subscribe` and
937
- `POST /api/relay-events/remote/pull` take only another relay's request (the `X-OAR-Remote-Origin`
938
- header names it; this relay's own agents and the browser get `403`) and only while the inbound
939
- switch is on. The subscription is an ordinary row whose watcher is the key
940
- `remote:<that relay's id>`, which names no conversation, so nothing a paired relay asks for is ever
941
- written into a conversation of B's; its events are recorded, swept (stalled, all_idle, heartbeat)
942
- and filtered like any, and wait for the fetch. Retention: per subscription the newest 500 undelivered
943
- events (questions and errors kept longest), none older than 7 days; a subscription not fetched for
944
- 7 days ends (`subscriber-gone`). What was dropped is counted and reported once.
945
- - **The fetch** (`services/relay-event-link-service.mjs` on A): every 5 s while A holds active
946
- subscriptions on B or an end B has not confirmed, every 30 s after a minute without an answer,
947
- nothing once none are left. The body is `{ after, subscriptions: [{ id, watcher }], ended: [ids] }`:
948
- B deletes what A stored up to `after`, applies the ends, updates the watcher names, and answers
949
- `{ events, cursor, more, subscriptions: [state], ended, dropped }` (at most 200 events a page).
950
- A writes the events into its watchers' undelivered events (only for subscriptions it holds, into the
951
- watcher it stored), ends or updates its mirrors from the states, clears confirmed ends and moves its
952
- cursor in one transaction, so a restart of either relay loses or repeats nothing. From there
953
- delivery is the same as for A's own sessions: coalescing, the cap and digest, the steer, the loop
954
- guard (an event turn on either relay is no `turn_end` for the other).
955
- - **Gaps.** A link without an answer for 60 s (failing fetches, or A down) is lost from its last
956
- answer on. The first fetch after that, every page of it, is held and written as one urgent row per
957
- watcher with subscriptions there: `link_lost` (no answer since …), `Replayed: N events …` with
958
- questions and errors first, `link_restored` (after how long, how many kept, how many dropped, which
959
- subscriptions ended there meanwhile). A shorter outage only delays. Nothing wakes the watcher when
960
- the link drops; `list_subscriptions` shows each paired subscription's `link` (`ok`, `failing`,
961
- `lost`), and a `heartbeat_minutes` subscription notices the silence.
962
- - **Ends.** Unsubscribe and an archived watcher end the mirror at once and mark it until B confirms
963
- (`list_subscriptions` shows `endPending`); `unsubscribe` waits up to 10 s for that and says so when B
964
- did not answer. An archived session on B, or B's user ending the subscription there, ends the mirror
965
- with the next fetch (`archived`, `ended-on-relay`). Removing the pairing sends one last fetch with
966
- every subscription as ended, then ends the mirrors (`pairing-removed`).
967
- - `unsubscribe "all"` and `transfer_subscriptions` act on the named relay's subscriptions; with `this`,
968
- `list_subscriptions` lists all of the watcher's (each with `relay`) and `transfer_subscriptions`
969
- moves all, its card naming the paired relays among them. A transfer reaches B as the new watcher's
970
- name with the next fetch.
971
-
972
- `/api/remote-relays/tool` refuses a call that carries another relay's origin: a paired relay never
973
- acts, or subscribes, for one of this relay's conversations.
974
-
975
- ### Session state and tasks
976
-
977
- `services/session-activity-tracker.mjs` knows what each session is doing, from the
978
- `/api/background-tasks` sets (a new task id is a start, a task gone from the set has ended, a
979
- changed one is activity), `POST /api/background-task-settled` (how a task ended; the Claude worker
980
- posts it from `task_notification`), the sub-agent run statuses and the activity, thought, stream and
981
- timeline posts (the activity clock). A task that leaves the set without word ends after 5 s with
982
- its run's status, else `completed` with `statusReported: false`; an exit code is read from the task
983
- summary when it names one (the SDK has no field for it). Memory only: a restart forgets the recently
984
- finished tasks and starts the clock at boot. Running tasks come back when the workers send their
985
- sets again (see [Background tasks and workflow progress](#background-tasks-and-workflow-progress)):
986
- a task that started before this runtime did is not announced as started a second time, and the end
987
- of a task this runtime never knew is still an event when the settle notice describes the task
988
- (`description`, `taskType`, `startedAt`). `all_idle` waits out the first 45 seconds after a relay
989
- start, like the suspend check.
990
-
991
- `GET /api/conversations` and `GET /api/conversation/:id` carry `sessionState` (`running_turn`: a
992
- turn processing, or queued and not held by a usage-limit pause; `background_only`: tasks running;
993
- `idle`), `sessionTasks` (running tasks, then up to five that ended within the hour: `kind`
994
- `subagent` | `shell`, `description`, `startedAt`, `lastActivityAt`, `status` `running` |
995
- `completed` | `failed` | `stopped`, `exitCode`, `summary`, `endedAt`) and `lastActivityAt`.
996
- `remote_relay`'s `list_sessions` and `read_session` pass them on as `state`, `tasks` and
997
- `lastActivityAt`; `active` stays and is true for background work too. `read_session` adds to each
998
- task its `taskId`, `output` (whether it has output to read), a shell task's `command` (its command
999
- line where the worker reports one, scrubbed of credentials and cut at 2,000 characters by the relay
1000
- when the worker posts it, shown to at most 500) and, for a task with an output file, `health`
1001
- (`minutesSinceOutput`, `quiet`, `quietAfterMinutes`, test-run `counts`);
1002
- `read_task_output {session, task_id, lines?}` (read permission; default 200 lines, at most 500 or
1003
- 32 KB) reads the end of that output through `GET /api/conversation/:id/background-task/:taskId/output`,
1004
- scrubbed of credentials.
1005
-
1006
- ### Browser
1007
-
1008
- An event message renders as a compact row (`relay-event-view.mjs`) folded to its summary
1009
- (`2 events · question, reply`); a row with a question or an error starts open, a replay carries a
1010
- **replayed** tag, and the user's fold is kept across re-renders. A watcher's header shows **👁 watching
1011
- N sessions** (or all; sessions on paired relays count, the chip's title names those relays), which
1012
- opens its subscriptions with an **Unsubscribe** button each (`lab-relay · Report builder`); a watched
1013
- session shows a **watched** badge in its header and, when watched by id, in the sidebar (a
1014
- subscription to all would badge every row; one on a paired relay badges none of this relay's
1015
- sessions). On the watched relay the badge names a paired relay's watcher with its relay.
1016
- The list comes from `GET /api/relay-events/subscriptions` and the `relay_event_subscriptions`
1017
- socket event (the whole active list after every change).
1018
-
1019
- ### Folded agent exchanges
1020
-
1021
- A prompt another agent sent the session (a paired relay's, or one of this relay's own: a user row
1022
- with `origin`) folds into one row, `note from <relay> · <session> · answered below` (`working…`,
1023
- `failed`, `stopped`, `no reply yet`), which opens to the prompt as it renders otherwise.
1024
- Presentation only (`agent-exchange-fold-view.mjs` decides, `syncAgentExchangeFolds` in
1025
- `conversation-view.js` applies it as one more idempotent pass after every render and update, beside
1026
- the separator and steering passes); the transcript data is unchanged. Nothing addressed to the user
1027
- folds away: the fold covers the agent's prompt alone. The session's reply to it can hold a line for
1028
- the user, so the reply, the live bubble of the running turn and the turn's question, approval and
1029
- plan cards always show, as for a message of the user's own; they are read for the row's status
1030
- only. One prompt is left unfolded: an agent's prompt that was itself steered into a running turn,
1031
- which renders as part of that turn's flow. A folded prompt shows open while its turn is `working…`
1032
- and closes by itself once it is replied, failed or stopped (`agentExchangeFoldOpen`); the user's
1033
- own toggle, kept by prompt id, always wins over that, and a jump to the prompt (search, pins, image
1034
- parent) opens it.
1035
-
1036
- ## Image conversations (OpenAI BYOK)
1037
-
1038
- Choosing **OpenAI Image (BYOK)** in New Chat creates a conversation whose replies are generated
1039
- images, calling the OpenAI Images API directly rather than going through a CLI worker.
1040
-
1041
- - The New Chat dialog swaps **Reasoning effort** for **Quality**, and adds a **Size** picker whose
1042
- options depend on the model (`dall-e-2`: 256/512/1024 squares; `dall-e-3`: 1024 plus the two
1043
- 1792 orientations; otherwise `auto` plus the 1024/1536 set). The chosen size is remembered per
1044
- browser and becomes the conversation's context tier.
1045
- - Generated images are stored per conversation and streamed from
1046
- `GET /api/generated-image/:conversationId/:messageId/:imageId/content`.
1047
- - **Edit this image** on a generated image sets it as the composer's image target (shown as an
1048
- *Editing …* chip); the next message is queued as an edit of that image instead of a fresh
1049
- generation. Image operations are recorded so a follow-up can continue from the right source image.
1050
- - Deleting a conversation garbage-collects its generated images.
1051
- - Continuity is gated by the `IMAGE_CONVERSATION_CONTINUITY_ENABLED` feature flag (on by default).
1052
-
1053
- ## Conversation sharing and per-message visibility
1054
-
1055
- - **Share** on a conversation issues a read-only token; shared viewers read through
1056
- `GET /api/shared/:token` and its scoped upload/generated-image content routes.
1057
- - `PATCH /api/conversation/:id/message/:messageId/share-visibility` toggles a single message's
1058
- `hidden_from_shares` flag. Hidden messages are filtered out of every shared view while staying
1059
- fully visible — and visibly marked as hidden — to the owner.
1060
- - The control appears on message hover; already-hidden messages keep their label visible so the state
1061
- is never silently lost.
1062
- - `POST /api/shared/:token/presence` tracks shared-viewer presence, surfaced as a watcher count.
1063
- `sharedPresenceMaxPerConversation` and `sharedPresenceMaxGlobal` cap how many viewers that count
1064
- tracks; they do not limit who can read a link.
1065
- - A revoked or renewed token answers a plain 404 on every shared route, the `/shared/:token` page
1066
- included, exactly like a token that never existed. An open shared page stops at its next poll.
1067
- - Settings → Sharing lists the active shares (`GET /api/shares`) with **Copy link**, **Renew link**
1068
- and **Stop sharing**, and each share's access log. Renewing adds a token to the share's lineage
1069
- (`conversation_shares.lineage_id`, migration 0016) and revokes the old one, so the log, keyed to
1070
- the lineage, carries over. Stopping a share or deleting the conversation deletes its log; nothing
1071
- else prunes it.
1072
- - The access log (`conversation_share_opens`) has one row per open, not per poll: the shared page's
1073
- first fetch carries `open=1` and counts unless the same viewer opened it in the last 10 s; a
1074
- fetch without the flag counts only when that viewer has not fetched the share for 30 minutes
1075
- (a page back from the background, a script). A row keeps the time, the IP address (unless
1076
- **Store viewer IP addresses** is off), the user agent, the country from `cf-ipcountry` (only when
1077
- the request came through a proxy the `trustProxy` setting trusts) and a viewer key: an HMAC of
1078
- address and user agent under a per-relay secret, which counts distinct viewers without the
1079
- address. The address is the one Express derives through `trustProxy`; a forwarded header from an
1080
- untrusted peer is ignored.
1081
-
1082
- ## Pinned messages
1083
-
1084
- - `PATCH /api/conversation/:id/message/:messageId/pin` with `{ pinned: boolean }` sets or clears
1085
- `messages.pinned_at`. A conversation holds at most 100 pins; the next one is refused with `409`
1086
- and `code: "pin-limit"`. The answer is
1087
- `{ ok, conversationId, messageId, pinned, pins, pinsRevision }`.
1088
- - `GET /api/conversation/:id` carries `pins`: every pinned message of the conversation in
1089
- conversation order, also those outside the requested history page, each as
1090
- `{ messageId, role, preview, timestamp, pinnedAt, attachmentCount, hiddenFromShares }`.
1091
- `preview` is plain text of at most 160 characters. Each message also carries `pinned`.
1092
- - Every change is broadcast as the socket event `conversation_pins_updated` with
1093
- `{ conversationId, pins, revision }`. `revision` (`pinsRevision` in the HTTP answers) grows with
1094
- every change. A conversation load that left the relay before a change can reach the browser
1095
- after the change's own event; the browser keeps the list with the higher revision.
1096
- - Shared views carry neither `pins` nor `pinned`: pins are the owner's bookmarks.
1097
- - Pins belong to message rows. `/compact` starts a new conversation without them (they stay with
1098
- the archived one); re-importing an imported session keeps them, matched like hidden marks.
1099
-
1100
- ## Relay Mode Selection
1101
-
1102
- The composer also includes a per-message mode picker:
1103
-
1104
- - `plan`
1105
- - `ask`
1106
- - `agent`
1107
- - `autopilot`
1108
-
1109
- Mode is stored with each queued message so the relay can change behavior per turn.
1110
- Clarification prompts from the CLI are forwarded back into the browser as question
1111
- cards with a reply box.
1112
-
1113
- `plan` mode behavior:
1114
- - Draft a concise implementation plan only (no implementation output).
1115
- - Read-only inspection is allowed when it materially improves plan quality (for example `glob`, `rg`, `view`).
1116
- - Do not edit repository files or run mutating commands unless implementation is explicitly requested.
1117
-
1118
- ## Conversation titles
1119
-
1120
- The active conversation header includes a `✍️` button for renaming the conversation inline.
1121
- Title edits are saved to the database and broadcast to other open clients immediately.
1122
-
1123
- ## Updates
1124
-
1125
- OAR never phones home by default. Automatic update checking is **opt-in**:
1126
- enable **Check for updates automatically** in ⚙️ Settings (stored in app
1127
- settings, off unless you turn it on) and the relay asks `oar.sh/latest.json`
1128
- for the newest version about twice a day (12 h ± 1 h jitter, ETag-aware, 5 s
1129
- timeout, failures silent). A manual **Check for updates** button works without
1130
- opting in — that single request is the only traffic it creates. Set
1131
- `OAR_NO_UPDATE_CHECK=1` in the relay's environment to disable even manual
1132
- checks; `OAR_UPDATE_MANIFEST_URL` points the check at a different manifest
1133
- (used by tests and staging).
1134
-
1135
- When a newer version is available, Settings shows a dismissible-per-version
1136
- card (not dismissible if the release is marked critical — it still never
1137
- auto-applies). On npm-global installs, **Update** runs
1138
- `npm i -g @oar-sh/oar@<version>` with the log streamed into the card, then the
1139
- relay restarts once the running turns finish (queued messages wait for it). After the restart the relay
1140
- verifies the running version actually changed; if not, the npm log is surfaced
1141
- as a failure. Git checkouts are detect-only — the card shows a "pull to
1142
- update" hint instead of the button. `oar update [--beta] [--to X.Y.Z]` does
1143
- the same from a terminal, and rollback is `oar update --to <previous>`.
1144
-
1145
- ## Feature flags
1146
-
1147
- Feature flags are declared in one registry (`server/features.mjs`) and managed
1148
- from the web UI's Settings → Features tab, which renders each flag with its
1149
- user-facing description. Current flags and defaults:
1150
-
1151
- - `SESSION_WORKER_ROUTING_ENABLED` — ON by default; per-conversation worker
1152
- processes with ownership and crash recovery (off = legacy shared polling).
1153
- - `SESSION_WORKER_CONTINUATION_ROUTING_ENABLED` — ON by default; strict
1154
- ownership validation when routing clarification answers back to the asking
1155
- worker.
1156
- - `SESSION_WORKER_FALLBACK_RESTART_ENABLED` — OFF by default; reserved rollout
1157
- gate, no effect yet.
1158
- - `IMAGE_CONVERSATION_CONTINUITY_ENABLED` — ON by default; keeps
1159
- generated-image context across turns so *Edit this image* can continue from
1160
- the right source image.
1161
-
1162
- Resolution happens once at relay startup, with this precedence:
1163
-
1164
- 1. Registry defaults
1165
- 2. Stored settings (`app_settings` rows, written by the Features tab via
1166
- `GET/POST /api/settings/features`)
1167
- 3. Environment override: `COPILOT_REMOTE_{FLAG_NAME}` (`true/false`, `1/0`,
1168
- `yes/no`, `on/off`)
1169
-
1170
- Changes saved in the Features tab take effect after a relay restart; the tab
1171
- shows a restart notice and offers the queue-idle-deferred restart. A legacy
1172
- `features` key in `config.json` is migrated into `app_settings` once at boot
1173
- and stripped from the file. Unknown flag names and invalid values are ignored
1174
- safely.
1175
-
1176
- Question bridge rule:
1177
-
1178
- - User-facing questions/clarifications must use `ask_user` so they flow through
1179
- the relay question bridge and render as web question cards/buttons.
1180
- - This applies in `autopilot` too: still call `ask_user` for clarification, and
1181
- the relay layer will surface the question card even if the direct question hook
1182
- is bypassed.
1183
- - Plain-text assistant questions are not considered bridge-backed questions, and there is
1184
- **no fallback that converts them into question cards**. Every relay question originates from an
1185
- explicit request — `onUserInputRequest`, `onElicitationRequest`, or Claude's `AskUserQuestion`.
1186
- A turn that merely ends with a plain-text question simply completes, and the user answers it as
1187
- the next message.
1188
-
1189
- ## Session Worker Management
1190
-
1191
- Session workers are long-running CLI processes that execute turns for Copilot agent sessions. The relay manages a pool of workers to enable:
1192
- - Parallel execution (multiple sessions can run simultaneously)
1193
- - Session persistence (a worker stays alive across turns for a given session)
1194
- - Graceful restarts (degraded workers are replaced without losing queued work)
1195
-
1196
- ### Worker Lifecycle States
1197
-
1198
- 1. **Spawned** — Worker process created, initializing CLI connection
1199
- 2. **Ready** — Worker opened WebSocket to relay, registered in worker pool, ready to accept turns
1200
- 3. **Processing** — Worker actively executing a turn (streaming activity to browser)
1201
- 4. **Degraded** — Worker failed heartbeat or reported errors; relay moves pending work to other workers or restarts
1202
- 5. **Dead/Exited** — Worker process terminated; polling loop will spawn replacement if turns still pending
1203
-
1204
- ### Worker Heartbeat & Health Check
1205
-
1206
- - Workers send keep-alive pings every 30 seconds (default) to `/api/workers/{id}/heartbeat`
1207
- - Relay tracks last heartbeat time for each worker
1208
- - If a worker misses 2+ consecutive heartbeats (~60 seconds), it's marked "degraded"
1209
- - Degraded workers don't receive new turns; existing work is reassigned
1210
- - Polling loop detects degraded workers and respawns them if they're still needed
1211
-
1212
- ### Supervisor Service
1213
-
1214
- The **session-worker-supervisor-service** tracks all active workers:
1215
-
1216
- - Maintains registry: `workers[sdkSessionId] = { id, process, sdkSessionId, status, lastHeartbeat }`
1217
- - Monitors process health: checks if process is still running, collects exit codes
1218
- - Handles restarts: when a worker fails, spawns a replacement with exponential backoff
1219
- - Cleans up: removes dead workers from registry after TTL (default 5 minutes)
1220
-
1221
- ### Environment & Workspace
1222
-
1223
- Session workers inherit:
1224
-
1225
- - `COPILOT_WORKSPACE_ROOT` — Target workspace directory (from turn metadata or session config)
1226
- - `INIT_CWD` — Initial working directory (fallback for workspace resolution)
1227
- - `COPILOT_REMOTE_*` — All relay config via environment variables
1228
- - CLI session state from the last known good checkpoint
1229
-
1230
- ### Restart Orchestration
1231
-
1232
- When a worker needs restart:
1233
-
1234
- 1. **Graceful shutdown** — Send SIGTERM, wait up to 5 seconds for clean exit
1235
- 2. **Kill if needed** — Force SIGKILL if SIGTERM timeout
1236
- 3. **Backoff** — Wait before respawn (start at 1s, double up to 30s max)
1237
- 4. **Reassign work** — Any pending turns for that session are placed back in queue for the new worker
1238
- 5. **Report status** — Relay broadcasts worker status to browser UI (shows "reconnecting..." briefly)
1239
-
1240
- ### Platform-Specific Behavior
1241
-
1242
- - **macOS/Linux:** Workers prefer `tmux` sessions for better isolation and debugging (can attach with `tmux attach -t {sessionId}`)
1243
- - **Windows:** Workers launch in a new Terminal window (TTY-Console if available, otherwise cmd)
1244
- - Both: Worker inherits relay's environment and runs from relay repo root so project-local extensions are discoverable
1245
-
1246
- ## How It Works
1247
-
1248
- ```
1249
- [Browser] ←── WebSocket ──→ [server.js :3333] ←── WebSocket-first relay ──→ [Copilot CLI session]
1250
- ```
1251
-
1252
- 1. Browser sends a message → stored in server queue
1253
- 2. The relay worker socket delivers queued turns to the bound CLI session immediately
1254
- 3. The CLI processes the turn and posts the response to `POST /api/response`
1255
- 4. Server broadcasts response via Socket.io → appears in browser instantly
1256
-
1257
- ## Monitoring Mode (CLI)
1258
-
1259
- After launching the server, the CLI opens a worker WebSocket link:
1260
- - Identifies itself with the bound SDK session id and worker pid
1261
- - Receives queued turns over `ws(s)://.../api/session-worker/ws`
1262
- - Reconnects starting at 1 second, with exponential backoff capped at 8 seconds
1263
- (see [Worker link reconnects](#worker-link-reconnects))
1264
- - Falls back to `GET /api/pending` only while the worker socket is unavailable
1265
- - Processes any message with full PC access (file system, commands, etc.)
1266
- - Posts the response back
1267
- - CLI appears **online** (green dot) in the web UI while the relay is connected
1268
- - While working, relay tool activity is streamed into the pending assistant bubble
1269
- (for example `Search (glob)` and `Search (grep)`).
1270
- - Assistant reply text is streamed into the pending assistant bubble while the turn is running.
1271
- - Tool activity is now also kept with the assistant message as a collapsible
1272
- **Tool activity** section after the response arrives.
1273
- - Clarification prompts from `ask_user`/user-input requests are forwarded as
1274
- question cards in the conversation; answering the card resumes the waiting turn.
1275
- - Answered relay question cards stay visible in the conversation journal, including
1276
- the answer you submitted.
1277
-
1278
- ### Worker link reconnects
1279
-
1280
- Every session worker (Copilot SDK, Claude, Claude Cloud, Cursor, Grok) and the Copilot CLI extension
1281
- use the same link, `shared/worker-runtime/worker-websocket-link.mjs`. Its reconnect rules:
1282
-
1283
- - A connection counts as made at the relay's first `server.hello`, which the relay sends as soon as it
1284
- accepts the socket. A socket still connecting, or open without that hello, after 15 seconds
1285
- (`connectTimeoutMs`) is given up and retried: a relay hung in its shutdown can hold a socket in
1286
- either state without ever ending it.
1287
- - The link ends a socket on whichever comes first of an error, a close, that deadline, a stale
1288
- connection (30 seconds without a server frame) and the relay's `server.draining`, and schedules
1289
- the next attempt from there; later events from the same socket are ignored. It never waits for a
1290
- close event, which Node 22 does not fire for a socket closed while connecting, and a socket whose
1291
- constructor throws is retried too.
1292
- - There is at most one pending reconnect and one socket at a time. The delay starts at 1 second and
1293
- doubles up to 8 seconds, plus up to 250 ms of jitter; it starts over only after a completed
1294
- handshake, so a relay that accepts and drops the socket is not retried every second.
1295
- - Each failed attempt logs one `worker ws disconnected <reason> attempt=<n> retryInMs=<ms>` line in
1296
- the worker log for the first three, then at most one a minute, with `notLogged=<n>` counting the
1297
- ones in between.
1298
- - `stop()` (worker shutdown) clears the pending reconnect and the deadline and closes the socket
1299
- without scheduling another attempt.
1300
-
1301
- The relay's detached-worker watch (`services/detached-worker-watch-service.mjs`) is the safety net
1302
- behind this: it replaces a worker that has had no socket for 60 seconds while a message waits, but
1303
- never while a turn or background work of that session runs, so the link has to reconnect by itself.
1304
-
1305
- ### Session activation behavior (important)
1306
-
1307
- In extension-managed mode, the web server can already be running while the CLI is still
1308
- shown as offline. The worker socket starts when the Copilot session becomes active
1309
- (`onSessionStart`), which usually happens after your first prompt in the CLI.
1310
-
1311
- This means the following startup sequence is expected:
1312
- 1. Open `http://localhost:3333` and briefly see "CLI is offline"
1313
- 2. Send one message in the CLI
1314
- 3. Extension opens the worker socket and queued web messages begin processing
1315
-
1316
- If a conversation is still unbound when the CLI first sees it, the extension now claims it through `/api/session-sync` before processing so the browser can send back to the same SDK session. A separate startup sync to `/api/session-workspace-root` reports the CLI working directory for the already-bound session; it no longer creates a placeholder conversation on its own.
1317
-
1318
- | Symptom | Check |
1319
- |---|---|
1320
- | UI says "CLI is offline" | Verify `/api/status` works with the auth cookie or `Authorization: Bearer <token>` and shows `cliOnline: true` |
1321
- | UI flaps online/offline after restart | Ensure you are not mixing extension-managed mode with standalone `relay.mjs`, and confirm only one relay process owns port `3333` |
1322
- | "Web relay connected" banner repeats too often | Ensure only one extension instance is active; banner dedupe now persists across extension restarts for the same CLI session and reprints only when relay details change |
1323
- | No response after sending | Tail `server\ext-debug.log` and confirm `onSessionStart fired` + `startPolling called` |
1324
- | Wrong model used | Check logs for `Model selected: requested=... active=...` |
1325
- | Question card stuck | Answer in the card UI; logs should show `relay question created` and `relay question answered` |
1326
- | Tunnel not connecting | Check server console for `[ssh-tunnel]` lines; confirm SSH key auth works without password |
1327
- | Tunnel keeps reconnecting | VPS `sshd_config` needs `GatewayPorts no` (default) — Caddy handles the public port |
1328
-
1329
- ## Windows-Specific Runtime Behavior
1330
-
1331
- ### Worker Launcher
1332
-
1333
- - Workers on Windows launch via a **stable Terminal window** (when available).
1334
- - If TTY-Console (optional dependency) is installed, workers use an interactive terminal for debugging.
1335
- - Otherwise, workers spawn in a new `cmd` or PowerShell window.
1336
- - Window name is workspace-based so repeated worker restarts reuse the same window instead of opening duplicates.
1337
- - Claude workers open a `Claude Worker <id>` window running `node claude-session-worker.mjs` directly, instead of the `gh copilot` launch path.
1338
-
1339
- ### Path Handling
1340
-
1341
- - **Drives API** — `/api/drives/roots` returns fixed/removable drive letters (`C:`, `D:`, etc.) instead of mount points.
1342
- - **Path format** — `C:/Users/alice/project/file.txt` (forward slashes, drive letter prefix).
1343
- - **Directory listing** — Uses PowerShell via `Get-ChildItem` for recursive listings (faster than fs.readdir on large directories).
1344
- - **Workspace root** — Must be an absolute Windows path; relative paths or UNC paths (`\\server\share`) are handled but may behave unexpectedly.
1345
-
1346
- ### Model Refresh
1347
-
1348
- - Model discovery on Windows invokes `copilot.ps1` via PowerShell with `-ExecutionPolicy Bypass` to bypass execution policy restrictions.
1349
- - Command: `powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "copilot help config | Select-String -Pattern 'gpt'"`.
1350
- - If PowerShell is not available, falls back to direct `copilot help config` (may fail due to execution policy).
1351
-
1352
- ### Environment Variables
1353
-
1354
- - Workers inherit all relay server environment, including `COPILOT_WORKSPACE_ROOT` and `INIT_CWD`.
1355
- - On Windows, these paths use backslash or forward-slash format; CLI normalize paths automatically.
1356
- - `PYTHONUNBUFFERED=1` and `NODE_OPTIONS` should be set before relay startup for worker inheritance.
1357
-
1358
- ### SSH Tunnel on Windows
1359
-
1360
- - SSH tunnel uses `ssh.exe` (assumes `git-bash` or OpenSSH is in PATH).
1361
- - If SSH is not available, tunnel mode cannot be "managed"; stays in "disabled" mode.
1362
- - Windows Firewall may require inbound rule for local relay port (default 3333) if browser is on another machine.
1363
-
1364
- ## API Reference
1365
-
1366
- All authenticated routes accept an HttpOnly auth cookie or an `Authorization: Bearer <token>` header.
1367
-
1368
- `GET /api/status` now also includes `readyBanner`, a preformatted relay-info payload used by the CLI extension to print the access window directly in the Copilot CLI client when relay connectivity is established.
1369
- It also includes `restartOrchestrator` with the current relay-side restart transaction state.
1370
- It also includes `relayShutdown`, which reports queued manual relay shutdown/restart state separately from the worker restart orchestrator.
1371
- Queue metrics include `parkedCount` for turns deferred behind restart/rebind gates.
1372
-
1373
- | Method | Path | Description |
1374
- |--------|------|-------------|
1375
- | POST | `/api/message` | Send a message from the browser |
1376
- | POST | `/api/upload` | Upload binary file content (deduped by SHA-256) |
1377
- | GET | `/api/upload/:sha256/content` | Stream stored upload content by hash |
1378
- | PATCH | `/api/conversation/:id/draft` | Save composer draft text and optional `draftAttachments` |
1379
- | GET | `/api/files/*` | Stream a workspace file by repo-relative path (token required) |
1380
- | GET | `/api/files-preview/*` | Return structured preview JSON for markdown/code/text/image/video files |
1381
- | GET | `/api/repo/tree` | Return repository root + first-level entries for lazy workspace browsing |
1382
- | GET | `/api/repo/list` | Lazy-load workspace directory entries (`path`, `includeHidden`, `includeHeavy`) |
1383
- | GET | `/api/drives/roots` | Return browsable root(s) for explorer drive mode — on Windows returns fixed/removable drive letters; on Linux returns a single `/` root node |
1384
- | GET | `/api/drives/list` | Lazy-load directory entries (`path`, optional `includeHidden`) — on Windows `path` is a drive-letter path (e.g. `C:/foo`); on Linux `path` is an absolute POSIX path (e.g. `/home/user`) |
1385
- | GET | `/api/session-root/list` | List the explorer's Session root (`path`, optional `includeHidden`) — like `/api/drives/list`, but a not-yet-created root returns an empty folder (`exists: false`) instead of 404, and the sibling `<path>.jsonl` transcript is appended as a child |
1386
- | POST | `/api/repo/mkdir` | Create a folder in the workspace: `{ path, name, conversationId? }` where `path` is the repo-relative parent (`''` for the root); the target is resolved like `/api/files/*` (no `..`, no symlink escape). Answers `{ ok, path }`; 409 when the name is taken |
1387
- | POST | `/api/repo/rename` | Rename a workspace entry in place: `{ path, newName, conversationId? }`. The root cannot be renamed; symlinks are refused. Answers `{ ok, path }` |
1388
- | POST | `/api/repo/delete` | Delete a workspace entry, folders recursively: `{ path, conversationId?, dryRun? }`. `dryRun: true` answers `{ ok, kind, files, dirs, capped }` (counted below the folder, capped at 10 000) and removes nothing |
1389
- | POST | `/api/drives/mkdir` | As `/api/repo/mkdir` for an absolute path (also the explorer's Session root), checked like `/api/drives/list`: `{ path, name }`. Missing parents are created with the folder |
1390
- | POST | `/api/drives/rename` | As `/api/repo/rename` for an absolute path: `{ path, newName }`. `/` and drive roots are refused |
1391
- | POST | `/api/drives/delete` | As `/api/repo/delete` for an absolute path: `{ path, dryRun? }`. `/` and drive roots are refused |
1392
- | GET | `/api/drives/file` | Stream a file by path — Windows drive path or Linux absolute path depending on server platform |
1393
- | GET | `/api/drives/files-preview` | Return structured preview JSON for a file — Windows drive path or Linux absolute path depending on server platform |
1394
- | GET | `/api/git/status` | Git status for the conversation's workspace root (`branch`, `upstream`, `ahead`, `behind`, `files[]` incl. untracked); a non-repo root returns `isRepo: false` rather than an error |
1395
- | GET | `/api/git/diff` | Full-context unified diff for one changed file (`path`, optional `untracked=1`); the client renders both "changes only" and "full file" views from this single patch |
1396
- | POST | `/api/git/pull` | Run `git pull` in the conversation's workspace root and return the combined output |
1397
- | GET | `/api/git/remote` | Where a folder lives on GitHub, for the New Chat modal of a Claude Cloud chat: `?root=<absolute path>` → `{ ok, root, hasGit, remoteUrl, repoUrl, slug, branch, upstream, ahead, behind, dirty }`. The one git route that takes a path from the client; it passes the same policy as a requested CWD (`403` outside `workspaceRootAllowList`, `400` otherwise). Read-only (`git status`, `git remote get-url`) |
1398
- | GET | `/api/conversations` | List all conversations |
1399
- | GET | `/api/sessions` | List runtime sessions bound 1:1 to conversations |
1400
- | GET | `/api/conversation/:id` | Get conversation message windows (`before*`, `after*`, or `aroundMessageId`) plus session-root metadata |
1401
- | GET | `/api/search/messages` | Search message text across all conversations (`q`, `limit`, `offset`) |
1402
- | PATCH | `/api/conversation/:id` | Update a conversation title |
1403
- | POST | `/api/conversation/:id/compact` | Compact a conversation into a new one with carry-over summary seed |
1404
- | DELETE | `/api/conversation/:id` | Delete a conversation: stops its session worker, deletes its CLI session, removes its rows. A Claude Cloud conversation's cloud session is archived at Anthropic in the background (never waited for). A Copilot session the relay only imported and never ran is hidden and tombstoned instead: nothing is stopped and its CLI session is kept. `409 conversation-active` (`reason: turn-running` / `background-tasks`) while it is still working; `409 worker-stop-failed` when its worker survives the stop (nothing deleted) |
1405
- | GET | `/api/sdk-session-delete/pending` | (CLI relay) Fetch next pending SDK session delete request |
1406
- | POST | `/api/sdk-session-delete/result` | (CLI relay) Report SDK session delete result |
1407
- | POST | `/api/session-sync` | (CLI relay) Sync conversation↔SDK binding and optionally confirm orchestrator rebind completion |
1408
- | POST | `/api/session-workspace-root` | (CLI relay) Report the startup workspace CWD for a session once it is known |
1409
- | GET | `/api/pending` | (CLI) Fetch next pending message |
1410
- | POST | `/api/response` | (CLI) Submit response for a message |
1411
- | GET | `/api/restart-orchestrator` | Read relay restart orchestrator state |
1412
- | POST | `/api/restart-orchestrator/request` | Queue a restart transaction for a target SDK session |
1413
- | POST | `/api/activity` | (CLI) Push in-flight tool activity for current message; web search/fetch entries may include bounded queries, URLs, and output previews, while `store_memory`/`vote_memory` entries include available memory metadata |
1414
- | POST | `/api/stream` | (CLI) Push in-flight assistant text stream for current pending message |
1415
- | POST | `/api/relay/pause` | Pause dequeueing and drop currently queued messages |
1416
- | POST | `/api/relay/resume` | Resume dequeueing after pause |
1417
- | POST | `/api/relay/shutdown` | Queue an authenticated relay shutdown or self-restart |
1418
- | GET | `/api/relay/shutdown` | The queued request's state (as `relay_shutdown_state`), plus `preview`: what a restart asked now would wait for and leave running (`?action=shutdown` for a shutdown). See [Manual relay shutdown / self-restart](#manual-relay-shutdown--self-restart) |
1419
- | POST | `/api/relay/shutdown/keep-waiting` | Answer to the max-wait question: the queued request waits another full period, counted from now → `{ ok, extended, …state }` |
1420
- | POST | `/api/relay/shutdown/cancel` | Withdraw a queued (not yet started) shutdown or restart; held messages go out at once |
1421
- | GET | `/api/relay-questions` | (CLI/UI) List relay questions by `status` (for example `pending` or `answered`) |
1422
- | GET | `/api/relay-question/:id` | (CLI) Fetch a single relay question |
1423
- | POST | `/api/relay-question` | (CLI) Create a relay question for the browser |
1424
- | POST | `/api/relay-question/:id/answer` | (UI) Submit an answer for a relay question |
1425
- | POST | `/api/relay-question/:id/timeout` | (CLI/UI) Mark a relay question timed out |
1426
- | POST | `/api/heartbeat` | (CLI) Keep CLI status alive. A session worker may send `backgroundTasks: { count, digest }`; the answer carries `resyncBackgroundTasks: true` when the relay's set for that worker differs |
1427
- | GET | `/api/status` | Overall status |
1428
- | GET | `/api/about` | The About OAR modal: `version`, `commit` (the checkout's HEAD read from `.git`, else a `gitHead` stamp in package.json, else `null`), `startedAt` and `uptimeSeconds` of the relay process; `providers[]` (enabled ones only: `cliVersion` from the CLI probe cache, never a new probe, `sdkVersion` from node_modules, `state` `online`/`offline` for the relay CLI that runs Copilot's extension engine and OpenAI, `online`/`idle` with `runningWorkers` for the others); `stats` (conversations, messages, turns = replies, `turnsByProvider`, `firstConversationAt`); `usage` (only what is stored: Copilot premium requests, Cursor and Grok tokens and cost, Claude Cloud cost); `relay` (`dbBytes` = database + WAL, `runningWorkers`); `update` (latest version only while the opt-in check is on). The totals are read in rowid ranges of 10 000 messages with the event loop free in between, and kept for 60 s |
1429
- | GET | `/api/models` | Live/cached model catalog used by the UI picker |
1430
- | POST | `/api/models/snapshot` | (CLI/relay) Publish discovered model snapshot |
1431
- | POST | `/api/conversation/:id/refresh-history` | Re-import an existing conversation's history through the local Copilot SDK |
1432
- | GET | `/api/context/:conversationId` | Context metrics for a conversation or `sdk_session_id`. Copilot sessions are parsed from session-state events (falling back to a labeled lower-bound completion-token estimate when full legacy buckets are missing); Claude sessions are served from the breakdown their worker stored, and so are Cursor, Grok and Claude Cloud sessions. All return the same normalized `contextUsage` view alongside `providerType` and the runtime's own `text` dump |
1433
- | GET | `/api/context` | Same payload when a `conversationId` query is provided; otherwise returns a missing-selection response |
1434
- | GET | `/api/usage` | Unified plan usage: one card per configured provider (`providers[]` with `meters`, `details`, `links`) built from the live Copilot quota, the Claude worker's latest stored snapshot, and the derived Cursor cycle totals. A provider that cannot be read yields an unavailable card rather than failing the response, so the modal always renders. While Claude Cloud is on, the Claude card's windows are read live from the account, and a Claude Cloud card is added (credit meters, the relay's cloud spend, and the cost of the conversation named by `?conversationId=` when it is a cloud one); a card may carry `notes[]` (a line of text with an optional https link), and a meter `severity` and `resetKind: 'expiry'`. Legacy top-level Copilot quota fields are spread alongside `providers` for cached clients; `?legacy=1` returns the Copilot-only snapshot on its own |
1435
- | GET | `/api/settings/cursor-allowance` | Read the manual Cursor plan allowances (`cursorModelsUsd`, `otherModelsUsd`, `resetDay`) |
1436
- | POST | `/api/settings/cursor-allowance` | Set the Cursor pool allowances and billing reset day; `null` clears an allowance, and `resetAccounting: true` re-baselines the derived spend tracking |
1437
- | GET | `/api/settings/claude` | Read Claude provider settings (`enabled`, `model`, `models`, `availableModels`, `attributionMode`, `backgroundCommandLimitMinutes` with the slider bounds `backgroundCommandLimitMinMinutes`, `backgroundCommandLimitMaxMinutes`, `backgroundCommandLimitStepMinutes`, `backgroundCommandLimitDefaultMinutes`) |
1438
- | POST | `/api/settings/claude` | Enable/disable Claude, set the default model, the enabled model subset, the attribution mode or `backgroundCommandLimitMinutes` (clamped to 30…480 and snapped to 30-minute steps; not a number is `400`; read by Claude sessions spawned afterwards); triggers discovery and unstarted-conversation reconciliation |
1439
- | GET | `/api/settings/claude-cloud` | Read Claude Cloud settings: `{ enabled, defaultModel, environmentId, environments: [{ id, name }] \| null, environmentsError, account: { loggedIn, email, orgName, subscriptionType } \| null, token: { source, hasToken, expiresAt }, models }`. `token` says where the login is read from (`env`, `file`, `none`) and when it runs out, never the token. `environments` is `null` while the provider is off or the host has no login: nothing is asked of Anthropic then |
1440
- | POST | `/api/settings/claude-cloud` | `{ enabled?, defaultModel?, environmentId? }` → `{ ok: true, …the GET body }`. Enabling without a Claude login on the host is `400` with `code: 'claude_cloud_login_missing'`; an empty `environmentId` clears the stored one. Emits `claude_cloud_settings_updated` |
1441
- | GET | `/api/settings/cursor` | Read Cursor provider settings — same shape as Claude's: `models` is the enabled subset, `availableModels` the full discovered list, plus per-model `efforts` |
1442
- | POST | `/api/settings/cursor` | Set/remove the Cursor API key, default model, or enabled model subset; key changes reset discovered models and effort tiers |
1443
- | GET | `/api/settings/turn-ceiling` | Read the max turn duration plus slider bounds (`minMinutes`, `maxMinutes`, `stepMinutes`, `defaultMinutes`) |
1444
- | POST | `/api/settings/turn-ceiling` | Set the max turn duration in minutes (`0` = no limit) |
1445
- | GET | `/api/settings/relay-restart-max-wait` | How long a queued relay restart waits before it asks: `{ maxWaitMinutes, choices: [5, 10, 15, 30, 60, 120, 240, 0], defaultMinutes: 30, overrideMs }`; `0` = no limit; `overrideMs` is `OAR_RELAY_RESTART_MAX_WAIT_MS` when set |
1446
- | POST | `/api/settings/relay-restart-max-wait` | `{ maxWaitMinutes }` → the GET body; anything but one of `choices` is `400`. A queued request measures its current period against the new value at once |
1447
- | GET | `/api/settings/subagent-record-retention` | How long sub-agent records keep tool inputs and output: `{ retentionDays, choices: [0, 7, 14, 30, 90], defaultDays: 90 }`; `0` = keep for good |
1448
- | POST | `/api/settings/subagent-record-retention` | `{ retentionDays }` → the GET body; anything but one of `choices` is `400`. Runs a retention sweep 5 s later |
1449
- | POST | `/api/claude-native-session` | (Claude worker) Persist the native Agent SDK session id for resume |
1450
- | POST | `/api/claude-context-usage` | (Claude and Claude Cloud workers) Report the session's context-window breakdown after a turn; `409` for a conversation of any other provider |
1451
- | POST | `/api/claude-plan-usage` | (Claude and Claude Cloud workers) Report the session's structured `/usage` data — plan rate-limit windows plus session cost totals — falling back to the stable `modelUsage`/`totalCostUsd` result fields. Stored as the latest Claude snapshot; a Claude Cloud conversation's report is stored under its own snapshot key, `claude-cloud` |
1452
- | POST | `/api/claude-cloud-session` | (Claude Cloud worker) Report the cloud session a conversation is bound to: `{ conversationId, cloudSessionId, sessionUrl?, lastSequence, pushedBranch?, costUsd?, model? }` → `{ ok, cloud }`. Sent after the session was created, after every `result` and on a push; emits `claude_cloud_session`. `404` without a runtime session, `409` for a conversation that is not a cloud one |
1453
- | POST | `/api/cursor-plan-usage` | (Cursor worker) Report the agent's cumulative billed usage; the relay diffs it against a per-agent checkpoint and books the increase into the current billing cycle under the pool implied by the turn's model |
1454
- | POST | `/api/subagent-run` | (Worker) Register/update a subagent run. A new run needs the spawning turn's `messageId`; an update to a known run may omit it (a background agent's end arrives between turns). Optional header fields: `subagentType`, `model`, `modelInherited`, `taskId`, `background`, `timelineOwner`; a post without `status` leaves the run's state alone. Emits `subagent_status` with the whole header |
1455
- | POST | `/api/subagent-timeline` | (Worker) `{ conversationId, subagentRunId, entries: [{ key, kind, text, done?, toolName?, toolUseId?, metadata? }], header? }` → `{ ok, stored, truncated }`. Kinds: `thought`, `tool_call`, `tool_result`, `text`, `child`, `note`. Fenced by the run row, not by an open turn; an unknown run whose `header.parentSubagentId` is known is created under the parent's turn, anything else is `404 unknown_run`. Sends `subagent_timeline` `{ conversationId, messageId, subagentRunId, entries, truncated }`, volatile, only to the pages watching the run (`subagent_viewer_watch`) |
1456
- | GET | `/api/conversation/:conversationId/subagent/:subagentRunId` | One run's record for the viewer: `?after=<seq>&limit=<n>` (default 500, max 2000) → `{ run, entries, children, nextAfter, complete }`. `entries` are those after `after` plus any still open; `run.legacy` marks a record rebuilt from the lane rows |
1457
- | POST | `/api/conversation/:conversationId/subagent/:subagentRunId/cancel` | Request cancellation of one subagent run (unsupported by the Claude runtime) |
1458
- | PATCH | `/api/conversation/:id/message/:messageId/share-visibility` | Hide or unhide a single message from shared views |
1459
- | PATCH | `/api/conversation/:id/message/:messageId/pin` | `{ pinned }` → pin or unpin a single message; answers with the conversation's pin list and broadcasts `conversation_pins_updated` |
1460
- | POST | `/api/conversation/:id/share` | The conversation's read-only share link, made if it has none (one active share per conversation): `{ token, shareUrl, path, created }`; a new one sends `share_created` |
1461
- | POST | `/api/conversation/:id/share/renew` | A new token for the active share; the old one answers 404 from then on and the access log carries over. Sends `share_renewed`; 404 without an active share |
1462
- | DELETE | `/api/conversation/:id/share` | Stop sharing: revokes every token of the conversation and deletes its access log → `{ revokedAt, revokedCount, opensDeleted }`. Sends `share_revoked`; 404 without an active share |
1463
- | GET | `/api/shares` | Every active share: `{ shares: [{ conversationId, title, archived, token, shareUrl, path, sharedSince, renewedAt, lastOpenedAt, openCount, viewerCount }], storeViewerIp, accessLog }` |
1464
- | GET | `/api/conversation/:id/share/opens` | The active share's access log, newest first: `?limit=<n>` (default 200, max 1000) → `{ opens: [{ openedAt, ip, country, userAgent, viewer }], total, limit }` |
1465
- | GET/POST | `/api/settings/shares` | `{ storeViewerIp }`: whether new access log entries (and the status events of shared reads) keep the viewer's IP address; on by default. A change sends `share_settings_changed` |
1466
- | GET | `/api/shared/:token` | (No auth) Read-only shared conversation view (hidden messages filtered out). `?open=1` marks the page's first fetch, which the access log counts as an open |
1467
- | POST | `/api/shared/:token/presence` | (No auth) Report shared-viewer presence for the watcher count |
1468
- | POST | `/api/openai/images/generate` | Generate images for an OpenAI Image conversation |
1469
- | POST | `/api/image-operations/:operationId/execute` | Execute a queued image generation/edit operation |
1470
- | GET | `/api/generated-image/:conversationId/:messageId/:imageId/content` | Stream a generated image blob |
1471
- | GET | `/api/relay/identity` | This relay's identity for paired relays: `relayId`, `name` (the PWA app name, else the hostname), `version`, `platform`, `publicUrl`, `remoteRelays.{protocol, inbound}` |
1472
- | GET | `/api/remote-relays` | Paired remote relays with their status (`relays[]`, never a token) plus `self` |
1473
- | POST | `/api/remote-relays` | Pair a relay from a pasted web address (`url`, optional `token`, `pairBack`, `selfUrl`); `{ needsToken: true }` when neither token works |
1474
- | PATCH | `/api/remote-relays/:id` | Change a paired relay's `permission` (`read` / `prompt` / `full`), URL or token |
1475
- | DELETE | `/api/remote-relays/:id` | Remove a paired relay here (the other side keeps its entry) |
1476
- | POST | `/api/remote-relays/:id/check` | Probe a paired relay now |
1477
- | POST | `/api/remote-relays/pair` | (Relay to relay) Another relay introduces itself after the user paired it there |
1478
- | GET | `/api/remote-relays/summary` | (Worker) `{ count, online, localEnabled }`: the number of paired relays, how many of them are online, and whether agent sessions are switched on. Workers register `remote_relay` when `count` is above zero or `localEnabled` is `true` |
1479
- | POST | `/api/remote-relays/tool` | (Worker) One `remote_relay` tool call: `{ conversationId, action, args }`. For a paired relay the relay checks the mention unlock, the permission, the hop limit and (ask/plan mode) the user's approval, then forwards the call to the remote. For this relay itself (named by its name or `this`; refused with `REMOTE_RELAY_LOCAL_DISABLED` while agent sessions are off) it checks instead that the call does not aim at the caller's own conversation (`REMOTE_RELAY_OWN_SESSION`) and, for `create_session`, that the caller was not created by an agent (`REMOTE_RELAY_NESTED_SESSION`), that fewer than 4 sessions it created have a turn queued or running (`REMOTE_RELAY_SESSION_LIMIT`) and that the user allowed it once for the conversation; the call then runs against this relay's own routes in-process. A `model` in `create_session` or `send` is checked first, before any approval card, against the list New Chat offers for the provider on the target (`/api/models` for Copilot and OpenAI, the provider settings routes for Claude, Cursor, Grok and Claude Cloud): one it does not list is refused with `REMOTE_RELAY_UNKNOWN_MODEL`, `suggestions` (the close matches) and `models`, and nothing is created or sent. Casing follows the list; a Claude alias (`opus`, `sonnet`, `haiku`, with an optional `[1m]`) resolves to the newest listed model of its family by version number (a date suffix ignored, the undated id first, `[1m]` ids only when the alias asks and they are listed); a `[1m]` id with only its base listed runs as the base, with a note; a Copilot id with its effort (`gpt-5.4-high`) goes to the bootstrap and the first prompt as the listed id plus `reasoningEffort` (an explicit `effort` wins, and a note says so), but only when the catalogue lists that effort for the id (`reasoningByModel`): `gpt-5.1-codex-max` with only `gpt-5.1-codex` listed is unknown, with the base suggested; `auto` passes. `send` also takes the provider's whole discovered list (`availableModels`) and the session's own model, as the message route does. Without a list (discovery has not run, the route did not answer; `auto` alone is no list) the model goes on unchecked and `modelNote` says so, as it does when the bootstrap binds another model than the one asked. A provider not set up there answers `REMOTE_RELAY_PROVIDER_UNAVAILABLE` before its model is looked at. The bootstrap route itself checks a Copilot model from an agent against Copilot's own models: an unknown one is refused (`COPILOT_MODEL_UNAVAILABLE`, with `supportedModels` and `suggestedModels`; another provider's model gets that provider's answer), a listed one is bound in the list's casing, an effort-suffixed one as the listed id plus that effort when `reasoningByModel` lists it; the browser's New Chat keeps its fallback to the current model. `wait_seconds` is cut to the `maxWaitSeconds` setting for every target |
1480
- | GET | `/api/relay-events/subscriptions` | Every active [relay event subscription](#relay-event-subscriptions) (`{ available, subscriptions }`); refused to other relays' agents |
1481
- | DELETE | `/api/relay-events/subscriptions/:id` | The user's Unsubscribe (a paired relay's subscription too: it learns with its next fetch); refused to other relays' agents |
1482
- | POST | `/api/relay-events/remote/subscribe` | (Relay to relay) A paired relay's agent subscribes to sessions here: `{ watcher: { conversationId, title }, subscriber: { name }, scope, sessions, events?, once?, match?, stalled_minutes?, heartbeat_minutes?, dry_run? }` → `{ ok, subscription }`. Another relay's request only, inbound switch on; see [Across paired relays](#across-paired-relays) |
1483
- | POST | `/api/relay-events/remote/pull` | (Relay to relay) That relay fetches its events: `{ after, subscriptions: [{ id, watcher }], ended: [ids] }` → `{ ok, events, cursor, more, subscriptions, ended, dropped }` |
1484
- | POST | `/api/background-task-settled` | (Worker) How a background task ended: `{ conversationId, taskId, toolUseId?, status, summary?, reason?, description?, taskType?, startedAt? }` (Claude worker, from `task_notification`; the last three describe a task that was in its published set) |
1485
- | GET | `/api/remote-relays/inflight` | (Worker) Number of `remote_relay` calls running for `conversationId` |
1486
- | GET/POST | `/api/settings/remote-relays` | This relay's `publicUrl` and `inboundEnabled` (accept prompts from other relays' agents) |
1487
- | GET | `/api/settings/agent-sessions` | Agent sessions: `{ enabled, maxWaitSeconds, limits: { minWaitSeconds: 120, maxWaitSeconds: 3600, stepSeconds: 60 }, maxActiveSessions: 4 }`. `enabled` (default `false`) lets this relay's agents start and use sessions on it through `remote_relay`; `maxWaitSeconds` (default `600`) is the longest wait of one `remote_relay` call, for this relay and paired ones |
1488
- | POST | `/api/settings/agent-sessions` | `{ enabled?, maxWaitSeconds? }` → `{ ok: true, …the GET body }`, and the socket event `agent_sessions_settings_updated` with the GET body. `enabled` must be a boolean and `maxWaitSeconds` a whole number of seconds inside `limits` and on its step; anything else is `400` with `{ ok: false, error }` and nothing is stored |
1489
-
1490
- ### Manual relay shutdown / self-restart
1491
-
1492
- - `POST /api/relay/shutdown`, `POST /api/relay/shutdown/cancel` and `POST /api/queue/empty` need the
1493
- token and nothing else: the browser app calls them from a phone, over a tunnel and over the LAN.
1494
- - The request body accepts:
1495
- - `reason` (optional string)
1496
- - `requestedBy` (optional string)
1497
- - `restart` (optional boolean-ish flag; `true` queues self-restart instead of plain shutdown)
1498
- - `immediate` (optional boolean-ish flag; `true` does not wait for the running turns)
1499
- - Example restart request:
1500
-
1501
- ```json
1502
- {
1503
- "reason": "manual-restart",
1504
- "requestedBy": "localhost-api",
1505
- "restart": true
1506
- }
1507
- ```
1508
-
1509
- - Response payload includes:
1510
- - `status`: `queued` or `shutting_down`
1511
- - `action`: `shutdown` or `restart`
1512
- - `restart`: boolean mirror of the action
1513
- - `requestedAt`, `reason`, `requestedBy`
1514
- - `queue`: current `pendingCount` / `processingCount` / `parkedCount`
1515
- - `waitingFor`, `held`, `backgroundTasks`, `survival`, `maxWaitMs`, `deadlineAt`, `immediate` (below)
1516
- - The relay waits until no turn is processing before acting. While the request is queued no pending message is handed to a worker (a turn started meanwhile would postpone the restart again); pending and parked rows stay in the database and run after the restart.
1517
- - `immediate: true` (boolean-ish, like `restart`) starts it at once, running turns or not: the banner's **Restart now**. The answer still names what it did not wait for.
1518
- - Maximum wait (`services/relay-restart-queue.mjs`): after **Ask after a queued relay restart has waited** (`relay_restart_max_wait_minutes`, 30 by default, 5–240 or `0` = no limit; `OAR_RELAY_RESTART_MAX_WAIT_MS` overrides it in ms, for test relays) the request stays queued and sets `question: { askedAt }`; the relay pushes one notification (titled *Relay restart waiting*; switch **Queued relay restart waited its maximum time**, `relayRestart`) and never restarts while turns run; it still goes ahead as soon as the last turn ends, question or not. A raised maximum (or none) that moves the deadline into the future withdraws the question; `/keep-waiting` without a question does nothing (`extended: false`). An `immediate` request may name the queued request it was shown (`expectRequestedAt`, its `requestedAt`); when that request is gone the answer is `accepted: false, stale: true` and nothing starts. Agents are told never to send `immediate` (`relay-tools.md`). The user answers with `immediate`, `/keep-waiting` (another full period from now; counted in `keptWaiting`) or `/cancel`. With no limit the request, and the messages it holds, wait until the turns end or someone decides.
1519
- - What it waits for, holds and leaves running (`services/relay-restart-picture.mjs`), in the answer, in `GET /api/relay/shutdown`, in `/api/status` → `relayShutdown` and in the `relay_shutdown_state` socket event (sent on every change and on connect):
1520
- - `waitingFor`: `[{ conversationId, title, turns }]`, the sessions with a processing turn
1521
- - `held`: `{ count, conversations: [{ conversationId, title, count }] }`, pending and parked messages
1522
- - `backgroundTasks`: `[{ conversationId, title, count, detail, survives, why }]`, sessions with running background work of a live worker (the task panel's sets and running sub-agent runs, through `background-work-view.mjs`), then sessions with console tasks held since the last restart (`background-task-store.mjs` `listRestored`), which no worker has confirmed yet: `survives: null`
1523
- - `survival`: `{ action, workersSurvive, summary }`. Workers are separate processes (tmux, detached, a console window) and outlive a restart, which the relay's supervisor or the CLI extension takes; they outlive a shutdown too, except under a systemd service (detected from `INVOCATION_ID` and a `.service` cgroup), whose stop may take the workers with it (`survives: false`, shown as "may stop"; a worker in a tmux session the service did not start survives, which the relay cannot tell). A Claude Cloud session runs at Anthropic and always survives
1524
- - while queued also `holdsNewTurns`, `maxWaitMs`, `waitingSince` (start of the current period), `deadlineAt` (`null` without a limit), `question`, `keptWaiting`
1525
- - Ownership after an intentional restart follows the argv role, so exactly one supervisor acts on exit 75:
1526
- - `server.js --supervised` exits 75 and relaunches under `.github/extensions/web-relay/server-lifecycle/managed-server.mjs`
1527
- - bare `node server/server.js` keeps its supervisor attached, respawns the `--relay-runtime` child, and keeps the same terminal session alive
1528
-
1529
- ### Interrupted turns after a restart
1530
-
1531
- `services/restart-resume-service.mjs` implements **After a relay restart, tell interrupted sessions
1532
- to carry on** (`app_settings` `restart_resume_notes`, `'1'` on, off when absent; `GET/POST
1533
- /api/settings/restart-resume` `{ enabled }`, a boolean, 400 otherwise). At boot it notes the queue
1534
- rows that are `processing` (the turns the runtime before left) and follows them through the
1535
- recovery paths, which report each outcome (`noteRestartTurnOutcome`):
1536
-
1537
- | Path | `cut` (cannot run again) | `requeued` | `failed` |
1538
- | --- | --- | --- | --- |
1539
- | stale sweep (`recoverProcessingOlderThan`) | stale continuation dropped; consumed row failed | requeued | over the retry budget |
1540
- | dead worker (`recoverDeadWorkerProcessingRows`) | continuation dropped; consumed row failed | requeued | over the retry budget |
1541
- | owner heartbeat idle (`recoverOwnedProcessingRowsForSession`) | continuation dropped; consumed row failed; a started turn failed as `turn-replay-blocked` | requeued | |
1542
-
1543
- A heartbeat that lists a row (`activeQueueMessageId(s)`) claims it: its worker lived through the
1544
- restart and has the turn, so whatever ends it later is not put down to the restart, and the
1545
- session gets no note. A row that leaves `processing` another way is read from the queue: back in `pending` or `parked` is
1546
- `requeued`, anything else (a reply from a worker that lived through the restart) is settled. Once
1547
- none of a conversation's rows of the boot is processing, it gets a note when one was `cut` and none
1548
- was `requeued`, `claimed` or `failed`; the stale sweep's 15 s tick decides the ones that settled on their own,
1549
- and the watch ends 30 minutes after the boot. The note is a message of the relay's (role `user`,
1550
- `kind = 'relay-restart-resume'`) with a pending queue row on the interrupted turn's model, mode and
1551
- owner, queued at the time it is written (behind a message the user queued meanwhile), as the
1552
- usage-limit follow-up is; the primer then starts the worker. No note when the setting is off at
1553
- that moment, for a deleted or archived conversation, while the conversation holds a usage-limit
1554
- follow-up, or a second time in the same runtime. The browser renders it as a compact relay row
1555
- (`relay-restart-note-view.mjs`).
1556
-
1557
- ### Upload storage model
1558
-
1559
- - Physical blobs are stored in `server/uploads/<sha256>` (content-addressed).
1560
- - Metadata (`original_name`, `mime_type`, `size_bytes`) is stored in SQLite.
1561
- - Message/conversation references are tracked in SQLite; when a conversation is deleted,
1562
- unreferenced blobs are garbage-collected from disk automatically.
1563
- - Image attachments are forwarded to the Copilot SDK as multimodal attachments
1564
- (`file` when a disk path is available, otherwise inline `blob`).
1565
- - Non-image uploads continue to be exposed as file references.
1566
- - `POST /api/upload` sniffs the payload's magic bytes and reconciles them against the
1567
- client-supplied `X-File-Type` header. The detected type wins on disagreement, so a
1568
- disguised executable is stored as what it actually is. Unrecognised bytes (plain text,
1569
- CSV, source files) keep the claimed type. The response reports `mimeTypeCorrected`.
1570
-
1571
- ### Composer attachments: paste, drag-and-drop and eager upload
1572
-
1573
- - Files reach the composer through three paths, all sharing one ingestion function:
1574
- the 📎 picker, `Ctrl+V` paste, and drag-and-drop onto the input area.
1575
- - **Paste attaches, it never sends.** When the clipboard holds both an image and text,
1576
- the image wins and the text is discarded. When it holds only text, the handler does
1577
- nothing so the browser's native paste is untouched.
1578
- - Clipboard bitmaps arrive unnamed (or as a generic `image.png`) and are renamed
1579
- `pasted-<ISO-timestamp>.<ext>`.
1580
- - Images over ~2 MB are downscaled client-side to a 2560 px longest edge and re-encoded
1581
- to **JPEG** before upload. GIF and SVG are never re-encoded, and a re-encode that fails,
1582
- grows the file, or yields anything other than JPEG/PNG falls back to the original bytes.
1583
- - The output format is deliberately restricted to JPEG/PNG: Copilot's image-input docs call
1584
- these "the most widely supported formats". WebP compresses better and previews correctly
1585
- in the browser, but arrives at the model unreadable.
1586
- - Re-encoding therefore has two triggers, tracked by `reencodeReason()`:
1587
- - `'size'` — the image is over the byte threshold. Abandoned if the result is no smaller.
1588
- - `'format'` — the source is not PNG/JPEG/GIF (e.g. WebP, AVIF, HEIC), so it is converted
1589
- at its original dimensions **regardless of size**, and kept even if the result is larger:
1590
- a bigger image the model can read beats a smaller one it cannot.
1591
- - Without the `'format'` trigger a WebP small enough to skip the size threshold would reach
1592
- the model invisible.
1593
- - Attachments upload **eagerly** on selection rather than on Send. Chips show an
1594
- uploading spinner, and a failed upload becomes a clickable retry.
1595
- - Send is disabled while any upload is in flight. Failed uploads are deliberately not
1596
- counted as in-flight, so a failure can never wedge the button.
1597
- - Exceeding the 6-attachment cap keeps the first 6 and reports the overflow in a toast
1598
- (previously the overflow was dropped silently).
1599
- - Shared read-only viewers cannot paste or drop.
1600
-
1601
- ### Composer attachment cache
1602
-
1603
- - Pending attachments persist **per conversation**, mirroring how text drafts already work.
1604
- Switching conversations and returning restores them, as does reloading the page.
1605
- - Storage is `conversations.draft_attachments`: a JSON array of `{sha256, name, type, size}`.
1606
- Only already-uploaded attachments are persisted — never file bytes.
1607
- - `PATCH /api/conversation/:id/draft` accepts an optional `draftAttachments` array.
1608
- Omitting the field leaves the stored attachments untouched; passing `null` or `[]` clears
1609
- them. Every entry must reference a blob the server already holds, otherwise the request
1610
- is rejected with a 400.
1611
- - Removing an attachment is expressed as a draft save carrying the remaining list, so it is
1612
- ordered against in-flight draft writes rather than racing them. The server diffs the list
1613
- and releases the reference itself; there is deliberately no delete-by-hash endpoint, since
1614
- blobs are content-addressed and shared, and such a route would let one caller destroy
1615
- another conversation's freshly uploaded blob.
1616
- - Draft blobs are kept alive by an `upload_refs` row using the sentinel
1617
- `message_id = '__draft__'`. On send, the real message reference is inserted and the
1618
- sentinel row is dropped. Reference release only reclaims blobs whose sentinel row this
1619
- conversation actually held.
1620
- - Conversation deletion needs no special handling: the existing foreign-key cascade and
1621
- orphan sweep already collect draft blobs.
1622
- - Because uploads are eager, a blob can exist before anything references it (pasting into a
1623
- conversation that is then abandoned, or switching conversations mid-upload). A sweep runs
1624
- at startup and every 6 hours to reclaim unreferenced blobs older than 24 hours; the age
1625
- floor guarantees an in-flight upload is never collected.
1626
- - Attachments added before a conversation exists stay in the composer (already uploaded) and
1627
- are adopted by the conversation created on first send.
1628
-
1629
- ### Chat file reference tokens
1630
-
1631
- - The web explorer/file preview can copy references as backticked tokens:
1632
- - ``@file:<path>``
1633
- - ``@folder:<path>``
1634
- - Folder tokens use the full folder path.
1635
- - File tokens use the full file path shown by the preview/browser context.
1636
- - Tokens are root-agnostic: workspace paths are repo-relative, drive paths keep `C:/...` form.
1637
-
1638
- ### Reference-driven inspection helper
1639
-
1640
- - Messages containing `@file:` tokens are parsed server-side before queueing.
1641
- - Text/markdown references stay as plain references (no binary payload attached).
1642
- - Small image references (up to ~1 MB) are attached to the pending turn so vision-capable
1643
- models receive real image input.
1644
- - Oversized image references are left as plain text references to avoid oversized request payloads.
1645
-
1646
- ### Workspace file bridge
1647
-
1648
- - Use `/api/files/<repo-relative-path>` to open workspace files in a new tab. The browser sends the auth cookie automatically.
1649
- - Use `/api/files-preview/<repo-relative-path>` for structured preview JSON (`kind`, `language`, `content`, `truncated`, `size`).
1650
- - Use `/api/repo/tree?includeHidden=0&includeHeavy=0` to load workspace root and first-level entries.
1651
- - Use `/api/repo/list?path=<repo-relative-dir>&includeHidden=0|1&includeHeavy=0|1` for lazy-loaded workspace directory browsing.
1652
- - Use `/api/drives/roots` + `/api/drives/list?path=<path>&includeHidden=0|1` for lazy-loaded drive/root browsing (separate from workspace heavy mode).
1653
- - Use `/api/drives/file?path=<path>` and `/api/drives/files-preview?path=<path>` for drive/root file raw/preview access.
1654
- - Use `/api/session-root/list?path=<sessionRootPath>&includeHidden=0|1` for the explorer's Session root. Child directories below it lazy-load through `/api/drives/list` as usual. The Claude Agent SDK creates a session's directory lazily — only once the session writes `subagents/` or `tool-results/` files — so the root is served as an empty folder until then rather than 404ing, and the transcript that lives one level up in the project directory is listed as a child of it. Cursor sessions resolve their Session root the same lazy way: the worker's per-session agent store (`$CURSOR_AGENT_STORE_DIR` or `server/data/cursor-agents/<sdkSessionId>`) exists only after the session's first turn, and the Session button stays disabled until it does.
1655
- - Requests are auth-protected and restricted to files inside the workspace root.
1656
- - **Platform split** — the drives API adapts automatically based on the server OS:
1657
- - **Windows:** drive roots are discovered via `fsutil.exe`; paths use Windows drive-letter format (`C:/foo/bar`); directory listing uses PowerShell.
1658
- - **Linux:** a single `/` root is returned; paths are absolute POSIX paths (`/home/user/file.txt`); directory listing uses `fs.readdir` + `fs.stat`.
1659
- - The `/api/status` response includes a `platform` field (`win32`, `linux`, `darwin`, etc.) so the browser UI can adapt path handling accordingly.
1660
- - Drive browsing is auth-protected; path traversal attacks and non-absolute paths are rejected on both platforms.
1661
- - Traversal or non-file paths are rejected.
1662
- - **Linux access scope** — on Linux the drives API currently allows any authenticated user to browse and read any path that the server process has OS-level read access to (i.e. the same permissions as the user running the relay). There is no additional allowlist restriction beyond requiring an absolute path.
1663
- > **TODO:** add an optional `drivesAllowList` config key (array of absolute path prefixes) so operators can restrict drive access to a set of directories (e.g. home folder or workspace root). When the list is non-empty, requests whose resolved path does not start with one of the listed prefixes should be rejected with `403`.
1664
- >
1665
- > When implementing it, reuse `isWithinAllowedPrefix()` from `services/workspace-root-path-policy.mjs` rather than writing a second `startsWith` check — a bare prefix match would let `C:\work` admit `C:\work-secrets`. See `workspaceRootAllowList` below, which already follows this pattern.
1666
-
1667
- ### Git changes modal
1668
-
1669
- The **🌿 Git changes** entry in the conversation `⋯` menu opens a modal over the conversation's
1670
- workspace root, backed by `services/git-changes-service.mjs` and `routes/git-routes.mjs`:
1671
-
1672
- - `GET /api/git/status?conversationId=…` — branch, upstream, ahead/behind, and every changed file
1673
- (staged, unstaged, and untracked; porcelain v1 parsing). The root is resolved server-side from the
1674
- conversation scope exactly like the file-preview routes — the client never sends a path — and a
1675
- workspace root that is not a git repository returns `isRepo: false` rather than an error.
1676
- - `GET /api/git/diff?path=…&untracked=0|1&conversationId=…` — one full-context unified diff
1677
- (`-U999999`, untracked files via `git diff --no-index /dev/null`). The client renders both the
1678
- **Changes only** view (context collapsed to gap markers) and the **Full file** view from this
1679
- single patch; the parsing lives in `public/app/git-diff-model.mjs`.
1680
- - `POST /api/git/pull?conversationId=…` — runs `git pull` in the workspace root and returns the
1681
- combined output.
1682
-
1683
- File paths passed to `/api/git/diff` go through the same `resolveWorkspaceFilePath` containment
1684
- check as the file bridge, so traversal outside the workspace root is rejected.
1685
-
1686
- `GET /api/git/remote?root=…` belongs to the New Chat modal, not to this one: it reads the `origin`
1687
- remote (else the remote of the upstream branch), the current branch, ahead/behind and whether the
1688
- checkout is dirty, for the Repository and Branch fields of a Claude Cloud chat
1689
- (`services/git-remote-service.mjs`). There is no conversation yet at that point, so it is the one
1690
- git route that takes a path from the client, validated like a requested CWD
1691
- (`validateRequestedWorkspaceRoot`). Credentials in a remote URL are dropped before it is returned,
1692
- and a remote that is not a github.com repository comes back with `repoUrl: null`.
1693
-
1694
- ### Changing the launch CWD
1695
-
1696
- Two endpoints set a conversation's launch directory. Both accept the same aliases —
1697
- `rootPath`, `workspaceRootPath`, `workspace_root_path`, `cwd` — and both validate the
1698
- path before touching the database.
1699
-
1700
- | Endpoint | Effect |
1701
- | --- | --- |
1702
- | `POST /api/conversation/:id/workspace-root` | Saves the next-launch CWD. Does not touch the running CLI. |
1703
- | `POST /api/conversation/:id/relaunch-with-workspace-root` | Saves the CWD, stops the CLI, and relaunches it in the new directory. |
1704
-
1705
- **Validation** (`services/workspace-root-path-policy.mjs`): the path must be absolute
1706
- (drive-relative `C:foo` and extended-length `\\?\` forms are rejected), must not contain
1707
- `; & | \0 \r \n` — the same characters the chat `cd` command already rejects — and must
1708
- resolve, via `realpath`, to an existing directory. The resolved real path is what gets
1709
- persisted and spawned, so a symlink cannot smuggle a request past the allow list.
1710
- Failures return `400` with a `code` of `missing-root-path`, `invalid-root-path`,
1711
- `relative-root-path`, or `root-path-not-found`.
1712
-
1713
- **`workspaceRootAllowList`** (optional, `server/config.json`, or the
1714
- `COPILOT_WORKSPACE_ROOT_ALLOW_LIST` env var using the platform path delimiter): an array of
1715
- absolute path prefixes. **Absent, `null`, `[]`, or not an array disables the check entirely**,
1716
- which is the default and matches the historical "any existing directory" behaviour. When it is
1717
- non-empty, a request outside every prefix is rejected with `403` and
1718
- `code: "root-path-not-allowed"`. Matching is on segment boundaries and is case-insensitive on
1719
- Windows. Entries that do not resolve to a directory are logged and dropped rather than failing
1720
- closed, so a typo cannot brick the relay.
1721
-
1722
- **Concurrency.** All three endpoints that reach the session-worker launch path — the relaunch
1723
- route, the save route, and `POST /api/session-worker/:sdkSessionId/launch` — share one mutex
1724
- keyed by `sdkSessionId`. On top of that, the relaunch route coalesces duplicate requests
1725
- (a mobile double-tap, a second tab, a retried fetch) within a 5 s window:
1726
-
1727
- - same request in flight → awaits it and returns the same body plus `coalesced: true`
1728
- - same request just settled → replays the cached body with `coalesced: true, cached: true`
1729
- - a *different* request in flight → `409` with `code: "relaunch_in_progress"`
1730
-
1731
- Request identity is `conversationId` + the normalized path, or an explicit `Idempotency-Key`
1732
- header / `idempotencyKey` body field, which the web UI mints once per user gesture.
1733
- Both endpoints are additionally rate limited to 6 requests per 10 s per session and client IP,
1734
- returning `429` with `Retry-After`.
1735
-
1736
- **Stop semantics.** The relaunch stops every process in the session's tree, waits for them to
1737
- exit, and escalates once (`SIGKILL` on POSIX; a re-enumerated forced pass on Windows, which
1738
- catches children spawned after the first snapshot). If anything survives, the relay **does not
1739
- launch** — it returns `409` with `code: "worker-stop-timeout"` and `remainingPids`, having still
1740
- saved the CWD for the next clean launch. Launching on top of a survivor is what previously left
1741
- two CLIs claiming one session.
1742
-
1743
- **Response fields.** A successful relaunch reports what actually happened rather than a bare
1744
- `ok: true`:
1745
-
1746
- | Field | Meaning |
1747
- | --- | --- |
1748
- | `relaunched` | A fresh process was started in the requested directory. |
1749
- | `workspaceRootApplied` | The running CLI is actually in the requested directory. |
1750
- | `reusedExistingProcess` | An existing process was reused, so the new CWD did **not** take effect. |
1751
- | `warning: "cwd-not-applied"` | Present with `activeWorkspaceRootPath` and a human-readable `message` whenever `workspaceRootApplied` is `false`. |
1752
- | `stoppedPids` / `launchedPid` | Which processes were killed and which was started. |
1753
- | `coalesced` / `cached` | This response was replayed from a duplicate request. |
1754
-
1755
- **Recent CWD history.** `recent_workspace_roots` is keyed by `path_key`, a case-normalized form
1756
- of the path (lower-cased in full on Windows, untouched on POSIX), so `C:\Git\Repo` and
1757
- `c:\git\repo` occupy one row and the 12-entry cap counts distinct directories. The runtime
1758
- rebuilds an older table in place at startup; `server/migrations/0002-recent-workspace-roots-path-key.mjs`
1759
- performs the same rebuild offline.
1760
- - The web UI opens workspace mentions in an in-app preview dialog with **Preview / Raw** mode buttons.
1761
- - Markdown preview supports optional embedded-HTML mode with script/event-handler stripping and a visible warning.
1762
- - The floating **📁 Browse files** button opens the explorer with **Workspace**, **Drives**, and (when available) **Session** roots, tree navigation, list/icon folder views, and image thumbnails.
1763
-
1764
- ### Browser filter persistence and refresh behavior
1765
-
1766
- - The **Hidden** and **Heavy** toolbar toggles are persisted in `localStorage`, under separate keys
1767
- for the workspace root and the drives/session roots (the toolbar labels them differently:
1768
- "Hidden" vs "Hidden/System"). Every filter defaults to off, so a fresh browser profile behaves
1769
- exactly as it did before persistence existed.
1770
- - Refreshing the browser — via the Refresh button or a filter toggle — refetches the lazy tree and
1771
- then re-opens the folders that were expanded, rather than collapsing back to the root. A rapid
1772
- double-toggle is safe: the restore is applied against the tree that actually arrived last.
1773
- - Switching root, or a session root changing underneath the browser, discards a parked restore
1774
- because the saved path belongs to the tree being left.
1775
-
1776
- ### External link handling
1777
-
1778
- Links in chat bubbles, question cards, and subagent bubbles are opened in a new tab with
1779
- `noopener`/`noreferrer` applied, including links added to the DOM after page load. Workspace file
1780
- links (`@file:` mentions and file-preview markdown) are exempt so they continue to open the in-app
1781
- preview.
1782
-
1783
- ## Structured Answers and Multi-Field Elicitation
1784
-
1785
- The relay supports **structured answer forms** that extend beyond simple text `ask_user` questions. When a Copilot agent or tool needs multi-field input (e.g., confirmation with multiple checkboxes, form data with validation), the relay bridges the question into a web form.
1786
-
1787
- ### Database Schema
1788
-
1789
- Structured answers are stored in the `relay_questions` table:
1790
-
1791
- - `id` (primary key, UUID)
1792
- - `request_schema` (JSON schema defining form fields: types, validation, constraints)
1793
- - `structured_answer` (JSON object containing user's multi-field response)
1794
-
1795
- The migration `server/migrations/0001-add-structured-answer.mjs` creates the `structured_answer` and `request_schema` columns.
1796
-
1797
- ### Elicitation Flow
1798
-
1799
- 1. **Agent sends multi-field question** → Copilot SDK sends `ElicitationRequest` with `requestSchema` (JSON schema).
1800
- 2. **Extension bridges question** → `.github/extensions/web-relay/skills/question-routing-hooks.mjs` detects structured schema and registers it in the relay.
1801
- 3. **Browser renders form** → `server/public/app/question-schema-view.mjs` generates UI from the JSON schema (text inputs, checkboxes, dropdowns, etc.).
1802
- 4. **User submits form** → `ask-user-view.js` validates and POSTs to `/api/ask-user` with `structuredAnswer` payload.
1803
- 5. **Relay stores + returns** → Answer stored in `structured_answer` column; extension retrieves via `/api/pending` and returns `ElicitationResponse` to SDK.
1804
-
1805
- ### Schema Example
1806
-
1807
- ```json
1808
- {
1809
- "type": "object",
1810
- "properties": {
1811
- "confirmation": {
1812
- "type": "boolean",
1813
- "title": "Do you want to proceed?"
1814
- },
1815
- "environment": {
1816
- "type": "string",
1817
- "enum": ["dev", "staging", "prod"],
1818
- "title": "Select environment"
1819
- },
1820
- "tags": {
1821
- "type": "array",
1822
- "items": { "type": "string" },
1823
- "title": "Enter tags"
1824
- }
1825
- },
1826
- "required": ["confirmation", "environment"]
1827
- }
1828
- ```
1829
-
1830
- ### Browser Behavior
1831
-
1832
- - Multi-field forms render form controls for each schema property.
1833
- - Validation happens client-side (required fields, type checking) and server-side.
1834
- - Single-field simple `ask_user` (legacy) still renders as a single text input or button group.
1835
-
1836
- ## Relay Tool Guidance
1837
-
1838
- The CLI extension (`.github/extensions/web-relay/extension.mjs`) loads `relay-tools.md`
1839
- for shared tool guidance.
1840
-
1841
- The browser UI keeps the usage button in the sidebar header, and that button continues to
1842
- call `/api/usage` directly. It now renders the unified plan-usage report — one card per
1843
- provider with meters, reset countdowns and collapsible cost detail — via
1844
- `public/app/plan-usage-view.mjs`, falling back to the old Copilot-only text summary when
1845
- the response carries no `providers` array (an older relay, or one without the plan-usage
1846
- service).
1847
-
1848
- ## Config (`config.json`)
1849
-
1850
- ```json
1851
- {
1852
- "authToken": "<your-token>",
1853
- "port": 3333,
1854
- "localhostOnly": true,
1855
- "pollIntervalMs": 3000,
1856
- "processingTimeoutMs": 600000,
1857
- "conversationSessionMode": "isolated",
1858
- "contextIndicatorMode": "default",
1859
- "sdkVersion": "1.0.63",
1860
- "sdkPath": "/absolute/path/to/copilot-sdk/index.js",
1861
- "cliPath": "/absolute/path/to/app.js",
1862
- "sshTunnel": {
1863
- "mode": "disabled",
1864
- "required": false,
1865
- "remoteBind": "loopback",
1866
- "command": "ssh",
1867
- "user": "ubuntu",
1868
- "host": "relay.example.com",
1869
- "remotePort": 4444,
1870
- "identityFile": "~/.ssh/id_rsa",
1871
- "autoReclaimPort": true
1872
- },
1873
- "cloudflaredTunnel": {
1874
- "mode": "disabled",
1875
- "required": false,
1876
- "token": "",
1877
- "binary": "",
1878
- "extraArgs": []
1879
- }
1880
- }
1881
- ```
1882
-
1883
- | Key | Default | Description |
1884
- |---|---|---|
1885
- | `authToken` | *(required)* | Token for all API / UI access |
1886
- | `port` | `3333` | HTTP/WebSocket listen port |
1887
- | `localhostOnly` | `true` | Bind only to loopback (`127.0.0.1`) and block LAN/WAN access |
1888
- | `pollIntervalMs` | `3000` | CLI poll interval (ms) |
1889
- | `processingTimeoutMs` | `600000` | Worker-inactivity window before a turn is treated as stale (ms) — see [Turn recovery](#turn-recovery-and-the-max-turn-duration) |
1890
- | `conversationSessionMode` | `isolated` | SDK session strategy (`isolated` or `shared`) |
1891
- | `contextIndicatorMode` | `default` | Input context indicator style (`default` shimmer line or `bar` fill indicator) |
1892
- | `sdkVersion` | *(latest detected)* | Optional semver pin (for example `1.0.63`) used by relay SDK auto-detection |
1893
- | `sdkPath` | *(auto-detected)* | Optional absolute override for Copilot SDK entry path (`.../copilot-sdk/index.js`) |
1894
- | `cliPath` | *(auto-detected)* | Optional absolute override for Copilot CLI app path (`.../app.js`) |
1895
- | `restartGracefulTimeoutMs` | `8000` | Graceful shutdown wait before force fallback |
1896
- | `restartShutdownTimeoutMs` | `45000` | Drain timeout while waiting for active queue jobs |
1897
- | `restartSpawnTimeoutMs` | `18000` | Max wait for resume process to leave online state |
1898
- | `restartRebindTimeoutMs` | `20000` | Max wait for session-sync rebind confirmation |
1899
- | `restartMaxAttempts` | `3` | Max restart attempts before terminal exhaustion |
1900
- | `restartRetryBackoffMs` | `[1000,3000,7000]` | Deterministic retry backoff schedule |
1901
- | `sshTunnel.mode` | `disabled` | Tunnel mode (`disabled` or `managed`) |
1902
- | `sshTunnel.enabled` | `false` | Legacy alias for mode (`true` => `managed`, `false` => `disabled`) |
1903
- | `sshTunnel.required` | `false` | Pause dequeue when tunnel is disconnected in managed mode |
1904
- | `sshTunnel.remoteBind` | `loopback` | Remote bind mode for SSH `-R` (`loopback` or `public`) |
1905
- | `sshTunnel.command` | `ssh` | SSH executable path or command name |
1906
- | `sshTunnel.user` | — | SSH user on VPS |
1907
- | `sshTunnel.host` | — | VPS hostname / IP |
1908
- | `sshTunnel.remotePort` | — | Port opened on the VPS |
1909
- | `sshTunnel.identityFile` | *(optional)* | SSH private key path (`~` expanded); uses ssh-agent if omitted |
1910
- | `sshTunnel.autoReclaimPort` | `true` | When remote bind fails, run a remote reclaim step before retrying |
1911
- | `sshTunnel.reclaimStaleSshSessions` | `false` | Also kill your own childless `@notty` SSH sessions when the port stays held (see caveat below) |
1912
- | `sshTunnel.remoteCleanupCommand` | *(optional)* | Override reclaim command (`ssh user@host <command>`) for custom VPS cleanup |
1913
- | `cloudflaredTunnel.mode` | `disabled` | Cloudflare tunnel mode (`disabled` or `managed`) |
1914
- | `cloudflaredTunnel.enabled` | `false` | Legacy alias for mode (`true` => `managed`) |
1915
- | `cloudflaredTunnel.required` | `false` | Pause dequeue when the Cloudflare tunnel is disconnected in managed mode |
1916
- | `cloudflaredTunnel.token` | — | Tunnel token from the router panel (never logged) |
1917
- | `cloudflaredTunnel.binary` | `cloudflared` | Path or command name of the `cloudflared` you installed (OAR ships none); defaults to `cloudflared` on `PATH`. Without one the tunnel stays off and the status says how to install it |
1918
- | `cloudflaredTunnel.extraArgs` | `[]` | Extra arguments appended to `cloudflared tunnel run` |
1919
- | `tunnelMarkerHeaders` | `[]` | Extra edge-injected header names that mark tunnel traffic; merged with `COPILOT_TUNNEL_MARKER_HEADERS` and `cf-ray` (an empty list does not switch the env value off). A request carrying one is never "from this machine" (session-worker path guard, image-operation run, sign-in lockout exemption) |
1920
- | `allowedOrigins` | `[]` | Extra browser origins the Socket.IO channel accepts besides the relay's own origin |
1921
-
1922
- ### SDK auto-detection behavior
1923
-
1924
- - Relay first honors explicit `sdkPath` + `cliPath` from `config.json` when both are set.
1925
- - Otherwise it auto-detects the highest available semver under platform-specific install roots:
1926
- - **Windows:** `%LOCALAPPDATA%\copilot\pkg`
1927
- - **Linux:** `$XDG_CACHE_HOME/copilot/pkg` (default `~/.cache/copilot/pkg`), then `$XDG_DATA_HOME/copilot/pkg` (default `~/.local/share/copilot/pkg`)
1928
- - **macOS:** `~/Library/Application Support/copilot/pkg`
1929
- - Within each root it checks platform subdirs (`<platform>-<arch>`, then `universal`) and picks the highest version containing both:
1930
- - `copilot-sdk/index.js`
1931
- - `app.js`
1932
- - Optional environment override: set `COPILOT_PKG_DIR` to force a specific pkg base directory.
1933
- - Optional config pin: set `sdkVersion` to require an exact version during auto-detection.
1934
-
1935
- ## SSH Reverse Tunnel
1936
-
1937
- When `sshTunnel.mode` is `managed` (or legacy `sshTunnel.enabled=true`), `server.js` spawns:
1938
-
1939
- ```
1940
- ssh -N -o ServerAliveInterval=30 -o ServerAliveCountMax=3 \
1941
- -o StrictHostKeyChecking=accept-new -o BatchMode=yes \
1942
- -o ExitOnForwardFailure=yes \
1943
- -R <remoteSpec> <user>@<host>
1944
- ```
1945
-
1946
- `sshTunnel.remoteBind` controls `<remoteSpec>`:
1947
- - `loopback` => `<remotePort>:127.0.0.1:<port>` (loopback bind, best with Caddy `reverse_proxy localhost:<remotePort>`)
1948
- - `public` => `*:<remotePort>:127.0.0.1:<port>`
1949
- `ExitOnForwardFailure=yes` ensures the tunnel process exits immediately if remote port forwarding fails, allowing clean auto-retry instead of a false "connected" state.
1950
-
1951
- **Auto-reconnect** — if the tunnel exits for any reason it is rescheduled with
1952
- exponential backoff (5 s → 10 s → 20 s → 40 s → 60 s cap, no retry limit).
1953
- The counter resets after a connection is stable for >30 s.
1954
-
1955
- **Remote stale-forward reclaim** — on `remote port forwarding failed for listen port`,
1956
- the relay runs a one-shot remote cleanup over SSH and retries quickly on the same
1957
- fixed port. Set `sshTunnel.autoReclaimPort` to `false` to disable, or provide
1958
- `sshTunnel.remoteCleanupCommand` for your own server-specific cleanup command.
1959
-
1960
- The reclaim reads the port state from `ss` / `/proc/net/tcp` rather than trusting
1961
- `lsof`. This matters: when the port is held by a stale `ssh -R` forward, the owning
1962
- `sshd` session has dropped privileges, so `/proc/<pid>/fd` is root-owned and both
1963
- `lsof` and `fuser` report nothing even though the socket belongs to your own uid.
1964
- The cleanup exits non-zero while the port is still bound, so a port that cannot be
1965
- freed falls back to exponential backoff instead of respawning `ssh` every second.
1966
-
1967
- Killing such a forward requires killing the `sshd` session that owns it. That is
1968
- off by default because the session cannot be identified precisely without root.
1969
- Enabling `sshTunnel.reclaimStaleSshSessions` sweeps your own `sshd` sessions that
1970
- have no child processes — the shape `ssh -N -R` leaves behind. Interactive shells,
1971
- IDE remote servers (VS Code / Cursor) and the reclaim command itself all have
1972
- children and are skipped, but any *other* `-N` forward you rely on for a different
1973
- port would also be killed, so leave it off unless the relay owns the account.
1974
-
1975
- **Caddy VPS config:**
1976
-
1977
- ```
1978
- relay.example.com {
1979
- reverse_proxy localhost:4444
1980
- }
1981
- ```
1982
-
1983
- **`/api/status`** now includes:
1984
-
1985
- ```json
1986
- "contextIndicatorMode": "default",
1987
- "sshTunnel": {
1988
- "mode": "managed",
1989
- "required": false,
1990
- "enabled": true,
1991
- "blocking": false,
1992
- "connected": true,
1993
- "host": "relay.example.com",
1994
- "remotePort": 4444,
1995
- "remoteBindMode": "loopback",
1996
- "reconnectAttempts": 0,
1997
- "connectedSince": "2026-05-18T01:00:00.000Z",
1998
- "lastError": null,
1999
- "valid": true
2000
- }
2001
- ```
2002
-
2003
- ### Managed vs. Disabled Mode
2004
-
2005
- | Setting | Behavior |
2006
- |---------|----------|
2007
- | `mode: "disabled"` | No SSH tunnel; relay is only accessible locally (localhost). Suitable for development or internal network access. |
2008
- | `mode: "managed"` | SSH tunnel enabled; relay opens reverse port forward to VPS. Suitable for remote access or internet-facing deployments. |
2009
-
2010
- ### Tunnel Connection & Queueing
2011
-
2012
- - **Tunnel required = false** (default): Queue continues to process even if tunnel is disconnected. Browser can still interact via localhost.
2013
- - **Tunnel required = true**: Queue is paused (returns `paused: true` with reason `ssh_tunnel_required`) when tunnel is disconnected. Used when relay **must** be accessible via VPS (e.g., mobile browser always connects through VPS).
2014
-
2015
- When `required=true` and tunnel is down:
2016
- - Relay stays running internally
2017
- - `/api/pending` returns `{ paused: true, reason: "ssh_tunnel_required" }`
2018
- - Extension stops dequeuing turns
2019
- - Browser sees "waiting for tunnel to reconnect..." status
2020
- - Once tunnel reconnects, queue resumes automatically
2021
-
2022
- ### SSH Tunnel Configuration Precedence
2023
-
2024
- 1. `server/config.json` → `sshTunnel` object
2025
- 2. Environment variables → `COPILOT_REMOTE_SSH_TUNNEL_*` prefixed keys
2026
-
2027
- Example environment overrides:
2028
- ```bash
2029
- COPILOT_REMOTE_SSH_TUNNEL_MODE=managed \
2030
- COPILOT_REMOTE_SSH_TUNNEL_USER=deployer \
2031
- COPILOT_REMOTE_SSH_TUNNEL_HOST=vps.example.com \
2032
- COPILOT_REMOTE_SSH_TUNNEL_REMOTE_PORT=4444 \
2033
- npm start
2034
- ```
2035
-
2036
- ### SSH tunnel migration notes
2037
-
2038
- - `sshTunnel.mode` is now the canonical switch. Use `disabled` for direct relay deployments and `managed` for reverse SSH.
2039
- - `sshTunnel.enabled` still works for compatibility and maps to `mode`.
2040
- - Add `sshTunnel.required: true` only when queue dequeue must stop until the tunnel reconnects.
2041
-
2042
- `restartOrchestrator` in `/api/status` and `/api/restart-orchestrator` now exposes
2043
- attempt/retry/timeout fields (`attempts`, `maxAttempts`, `retryAt`, `retryBackoffMs`,
2044
- `spawnDeadlineAt`, `rebindDeadlineAt`) plus terminal outcomes
2045
- (`terminalOutcomeCode`, `terminalOutcomeMessage`, `terminalOutcomeAttempts`).
2046
- Failure classes are deterministic: transient timeouts (`spawn-timeout`, `rebind-timeout`)
2047
- retry with bounded backoff; session mismatch conflicts (`transaction-mismatch`, `target-mismatch`)
2048
- are terminal and stop retrying.
2049
- `POST /api/session-sync` accepts optional orchestrator correlation/target/rebind fields:
2050
- `orchestrator_correlation_id`, `orchestrator_target_session_id`, and `rebind_completed`
2051
- (or `rebind_state=completed`). Rebind mismatches return `409` with `retryable`/`terminal`.
2052
- The extension dequeue/send path treats this restart-orchestrator flow as authoritative and
2053
- does not attempt in-process runtime session switch calls.
2054
-
2055
- This worker restart-orchestrator flow is separate from the manual relay self-restart state
2056
- reported as `relayShutdown`.
2057
-
2058
-
2059
-
2060
- ## Database Migrations
2061
-
2062
- The relay uses a simple SQL migration system to evolve the SQLite schema over time.
2063
-
2064
- **Migration File Location:** `server/migrations/`
2065
-
2066
- **Migration Lifecycle:**
2067
-
2068
- 1. On server startup, relay checks the database for applied migrations
2069
- 2. Unapplied migrations (in filename order) are executed automatically
2070
- 3. Each migration file exports a `up()` function that creates/alters tables
2071
- 4. After successful execution, migration is recorded in the database metadata
2072
- 5. Migrations are idempotent: re-running a migration is safe (no duplicates)
2073
-
2074
- **Currently Deployed Migration:**
2075
-
2076
- - **`0001-add-structured-answer.mjs`** — Adds `structured_answer` and `request_schema` columns to the `relay_questions` table to support multi-field elicitation forms (see [Structured Answers and Multi-Field Elicitation](#structured-answers-and-multi-field-elicitation) section).
2077
- - `request_schema` (TEXT/JSON) — JSON schema defining form fields and validation
2078
- - `structured_answer` (TEXT/JSON) — User's submitted multi-field response object
2079
-
2080
- **In-place column additions:**
2081
-
2082
- Some columns are added directly at startup with guarded `ALTER TABLE` statements rather than
2083
- migration files. Recent additions on `runtime_sessions`:
2084
-
2085
- - `claude_native_session_id` (TEXT) — native Claude Agent SDK session id, replayed as `resume`
2086
- - `context_usage_json` (TEXT/JSON) — latest context-window breakdown reported by a Claude worker
2087
- - `context_usage_captured_at` (TEXT) — when that breakdown was captured
2088
-
2089
- and on `messages`:
2090
-
2091
- - `hidden_from_shares` / `share_hidden_at` — per-message share visibility (see
2092
- [Conversation sharing](#conversation-sharing-and-per-message-visibility))
2093
-
2094
- `0005-remote-relays.mjs` adds `origin_json` to `messages` and `conversations` (provenance of
2095
- prompts and sessions another relay's agent created) and the table
2096
- `conversation_remote_relay_unlocks` (the remote relays the user mentioned per conversation).
2097
- Agent sessions reuse both without a migration of their own: a conversation an agent of this relay
2098
- created stores an origin with `local: true` that names the conversation it was created from, and
2099
- the user's **Allow** for a conversation's agent to start sessions here is a row of that table
2100
- under the relay id `self` (`remote-relay-repository.mjs`).
2101
-
2102
- `0011-relay-event-subscriptions.mjs` adds `relay_event_subscriptions` (what each watcher asked for,
2103
- kept after it ended with `ended_at` / `end_reason`, for a week) and `relay_events` (events per watcher, with
2104
- `delivered_at` and the message they went into, kept for two hours once delivered). See
2105
- [Relay event subscriptions](#relay-event-subscriptions).
2106
-
2107
- `0012-cross-relay-event-subscriptions.mjs` adds the columns both sides of a subscription across
2108
- relays need (on the watching relay `remote_subscription_id`, `remote_meta_json`, `remote_sync`; on
2109
- the watched one `subscriber_relay_id`, `subscriber_relay_name`, `subscriber_watcher_id`,
2110
- `subscriber_watcher_title`, `last_pull_at`, `dropped_count`) and `relay_event_links` (per paired
2111
- relay the fetch cursor and the link's health). See [Across paired relays](#across-paired-relays).
2112
-
2113
- `0017-conversation-history-indexes.mjs` adds two indexes and nothing else:
2114
- `queue(response_message_id)` for the sub-agent records of each reply on a history page, and
2115
- `messages(conversation_id, timestamp, id)` for selecting the page itself. `GET
2116
- /api/conversation/:id` and the shared view select the requested page in SQL in conversation order
2117
- (timestamp, then id) and hydrate only its replies, so a page costs the same in a conversation of
2118
- any length. A conversation with a row whose timestamp is not the relay's ISO form
2119
- (`YYYY-MM-DDTHH:MM:SS.mmmZ`) or whose id is not lowercase letters, digits and dashes is paged the
2120
- old way: every row loaded, the page cut afterwards.
2121
-
2122
- `0018-background-task-rows.mjs` adds `background_task_rows` (`store_key`, `task_id`, `state`
2123
- `live` | `ended`, `row_json`, `ended_at`, `updated_at`; one row per key and task): the task
2124
- console's rows across a relay restart (see
2125
- [Background tasks and workflow progress](#background-tasks-and-workflow-progress)). Additive and
2126
- idempotent; a failure is logged and retried on the next boot, and the store keeps its rows in
2127
- memory meanwhile. An older build ignores the table.
2128
-
2129
- `0007-claude-cloud.mjs` adds the storage of [Claude Cloud](#claude-cloud-provider) conversations.
2130
- It is additive and idempotent, runs on every boot, and a failure is logged and retried on the next
2131
- one:
2132
-
2133
- - `runtime_sessions.claude_cloud_session_id` (TEXT) — the cloud session the conversation runs in,
2134
- reported by its worker after the first message
2135
- - `runtime_sessions.claude_cloud_last_sequence` (TEXT) — the event sequence number of the last
2136
- finished turn's `result`: where a restarted worker reads the session's event log on from
2137
- - `runtime_sessions.claude_cloud_cost_usd` (REAL) — what the session has cost so far, as the cloud
2138
- reports it
2139
- - `conversations.cloud_source_json` (TEXT/JSON) — `{ repoUrl, branch, environmentId, sessionUrl,
2140
- pushedBranches: [{ branch, at }] }`
2141
-
2142
- New tables are likewise created at startup with `CREATE TABLE IF NOT EXISTS` in both the fresh-schema
2143
- and migration blocks — most recently `workflow_runs` (final workflow digest per assistant message,
2144
- keyed on `response_message_id`, cascade-deleted with the conversation; see
2145
- [Background tasks and workflow progress](#background-tasks-and-workflow-progress)).
2146
-
2147
- Statements that depend on these columns are prepared conditionally, so an older database keeps
2148
- working with the corresponding feature inert rather than crashing at startup.
2149
-
2150
- **To Deploy New Migrations:**
2151
-
2152
- 1. Create file `server/migrations/000N-description.mjs` (increment the number)
2153
- 2. Export an async `up()` function that receives the database connection
2154
- 3. Write SQL alterations:
2155
- ```javascript
2156
- export async function up(db) {
2157
- await db.exec(`ALTER TABLE some_table ADD COLUMN new_col TEXT;`);
2158
- }
2159
- ```
2160
- 4. Restart the relay; migration runs automatically
2161
- 5. Verify: check relay logs for `[migrations] Applying 000N-description`
2162
-
2163
- ## Files
2164
-
2165
- | File | Description |
2166
- |------|-------------|
2167
- | `server.js` | Main server |
2168
- | `public/index.html` | Web chat UI |
2169
- | `config.json` | Auth token and settings (gitignored) |
2170
- | `data/copilot.db` | Persisted conversations, settings, and queue storage (gitignored) |
2171
- | `relay-tools.md` | Markdown tool guidance loaded by the relay extension |
2172
- | `claude-worker/` | Claude Agent SDK session worker (turn runner, ask-user bridge, attachments, SDK message normalizer) |
2173
- | `claude-cloud-worker/` | Claude Cloud session worker (turn runner over the cloud session's event stream, event normalizer) |
2174
- | `../shared/claude-cloud/` | Claude Cloud API client, the reader of the Claude CLI's login, repository/branch/model string rules |
2175
- | `services/claude-cloud-settings-service.mjs` | Claude Cloud switch, default model and environment |
2176
- | `services/claude-cloud-session-service.mjs` | What the relay keeps per cloud conversation: worker reports, the `cloud` payload field, archiving |
2177
- | `services/claude-account-usage-service.mjs` | Live Claude account usage for Check Usage (only while Claude Cloud is on) |
2178
- | `services/git-remote-service.mjs` | GitHub remote and branch of a folder, for the New Chat modal |
2179
- | `services/relay-event-service.mjs` | Relay event subscriptions: subscribe / transfer, recording, coalescing, the hourly cap and digest, delivery into the watcher's conversation, stalled / all_idle / heartbeat sweeps |
2180
- | `services/session-activity-tracker.mjs` | What each session is doing: `state`, tasks, task edges and the activity clock |
2181
- | `../shared/relay-events.mjs` | Relay event types, limits and the text of an event message |
2182
- | `services/remote-relay-loopback.mjs` | The `remote_relay` client for this relay itself (agent sessions): hands the dispatcher's requests to the relay's own HTTP handler in-process instead of opening a connection |
2183
- | `services/claude-session-root-service.mjs` | Resolves the browsable session folder for Claude conversations |
2184
- | `services/context-usage-view.mjs` | Normalizes Copilot and Claude context data into one payload |
2185
- | `services/cloudflared-tunnel-service.mjs` | Supervises the `cloudflared` child process for the Cloudflare Tunnel mode |
2186
- | `services/tunnel-worker-path-guard.mjs` | Rejects session-worker WebSocket paths that arrive through a public tunnel |
2187
- | `../shared/turn-ceiling.mjs` | Shared bounds/formatting for the max turn duration setting |