@deep-podder/dsh-remote-mobile 0.0.0-stage → 0.0.6

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.
package/PROTOCOL.md ADDED
@@ -0,0 +1,627 @@
1
+ # dsh-remote-mobile — wire protocol
2
+
3
+ This file is the contract between the three halves of the plugin:
4
+
5
+ | Half | Files | Responsibility |
6
+ |---|---|---|
7
+ | Host Cordis plugin + HTTP/WS server | `index.js`, `server.js`, `auth.js`, `push.js`, `qr.js` | pairing, static SPA, WebSocket hub, desktop routes, Web Push |
8
+ | Host bridge to the DSH runtime | `bridge.js` | sessions, prompts, streaming, approvals, questions, uploads |
9
+ | Mobile SPA (phone browser) | `mobile/index.html`, `mobile/app.js`, `mobile/styles.css` | the phone UI |
10
+ | Desktop pairing UI + dock (DSH web client) | `client.js` | the Settings panel and the synced approval dock |
11
+
12
+ No external npm dependencies anywhere. Plain ESM on the Host, plain browser JS in the SPA.
13
+
14
+ ## Ports and origins
15
+
16
+ - Standalone server: `http://<bind-host>:<port>` — default `0.0.0.0:3456` (`0` picks a free port).
17
+ - The DSH Web UI keeps its own origin (for example `http://127.0.0.1:56770`) and is where
18
+ `client.js` runs; it never loads the phone SPA.
19
+ - The mobile SPA is served **only** by the standalone server.
20
+
21
+ ## Auth model
22
+
23
+ 1. On enable, the Host creates an ephemeral **pairing token** (random bytes, base64url) and a
24
+ 4-digit **PIN** (`crypto.randomInt(0, 10000)`). PIN lives 5 minutes, token 10 minutes.
25
+ 2. QR URL: `<public-url>/?t=<token>` — `public-url` is the selected interface (Tailscale
26
+ Serve, tailnet IP, Wi-Fi), so the QR honours the chip selected in the desktop panel.
27
+ 3. A valid `?t=` link makes the SPA `POST /api/pair` with `{ "token": "<token>" }`. The server
28
+ consumes the token and replies `200 { "paired": true, "device": {...}, "version": "..." }`
29
+ with `Set-Cookie: dsh_rm_session=<signed>; Path=/; HttpOnly; SameSite=Lax;
30
+ Max-Age=<30 days>`, adding `Secure` when the request arrived over TLS.
31
+ 4. Manual entry (`<public-url>/`) shows a PIN screen and calls `POST /api/pair` with
32
+ `{ "pin": "1234" }`. Wrong PIN → `401 { "error": "invalid-pin" }`; more than 5 failures
33
+ per address in 5 minutes → `429 { "error": "rate-limited", "retryAfterMs": n }`.
34
+ 5. Cookie-protected routes are `POST /api/rotate-pin`, `POST /api/unpair`, `POST /api/upload`,
35
+ `GET /api/preview`, the WebSocket upgrade and the `/api/push/subscribe`,
36
+ `/api/push/unsubscribe`, `/api/push/test`, `/api/push/report` routes. `GET /api/health`,
37
+ `GET /api/state`, `GET /api/push/key` and `POST /api/pair` are unauthenticated by design, as
38
+ is the desktop-panel `/api/desktop/*` family (loopback/desk key instead of a phone cookie,
39
+ see below). An unauthenticated upgrade is refused with `401` before any frame; a revoked
40
+ device's socket is closed immediately.
41
+ 6. `POST /api/unpair` and the desktop **revoke** both rotate every token and PIN, so a stale
42
+ QR link or a cleared browser cannot silently re-pair.
43
+
44
+ ### HTTP endpoints (standalone server)
45
+
46
+ | Method | Path | Auth | Request / response |
47
+ |---|---|---|---|
48
+ | GET | `/` | no | SPA `index.html` (CSP, `no-store`) |
49
+ | GET | `/app.js`, `/styles.css` | no | static assets, versioned by the page (`?v=<n>`), `no-store` |
50
+ | GET | `/api/health` | no | `{ ok: true, version }` |
51
+ | GET | `/api/state` | no | `{ paired, device: { id, name, createdAt, canApprove } \| null, version, pinTtlMs }` |
52
+ | POST | `/api/pair` | no | `{ token? }` or `{ pin? }` → `200 { paired, device, version }`, `401`, `429` |
53
+ | POST | `/api/rotate-pin` | cookie | `{}` → `{ pin, pinExpiresAt }` |
54
+ | POST | `/api/unpair` | cookie | `{}` → `{ ok: true }`, revokes this device and clears the cookie |
55
+ | POST | `/api/upload` | cookie | raw bytes, up to 32 MiB; headers `x-dsh-session` (required), `x-dsh-filename`, `x-dsh-media-type` → `{ ok, name, path, relativePath, size, mediaType }` (`path` is the absolute Host path, used by the phone only as an opaque attachment reference) |
56
+ | GET | `/api/preview?session=<id>&path=<path>` | cookie | the stored image bytes (`content-type`, `nosniff`, `private, max-age=300`); 404 when missing or not a previewable image |
57
+ | GET | `/api/push/key` | no | `{ enabled: true, publicKey }` — VAPID `applicationServerKey` (base64url raw P-256 point); `{ enabled: false, publicKey: null }` before the server starts |
58
+ | POST | `/api/push/subscribe` | cookie | `{ subscription: { endpoint, keys: { p256dh, auth } } }` → `{ ok: true, deviceId }`; `400 invalid-subscription` (bad shape, insecure scheme, or a host that is not a known push provider — see below), `429 too-many-subscriptions` (per device and global caps) |
59
+ | POST | `/api/push/unsubscribe` | cookie | `{ endpoint }` → `{ ok: true }` (removes only this device's endpoint) |
60
+ | POST | `/api/push/test` | cookie | `{}` → `{ ok, sent, gone, failed }` (status/counts only — never the push service's response body); `429 { error: "rate-limited", retryAfterMs }` above 6 sends/minute per device; no-op without subscriptions |
61
+ | POST | `/api/push/report` | cookie | bounded diagnostics from the service worker / SPA: `{ kind, detail, scope, permission? }` → `{ ok: true }`; each field is collapsed to one bounded line before it is appended to the Host debug log (no endpoints, keys or notification content) |
62
+
63
+ Request bodies are bounded: JSON bodies 64 KiB, `/api/pair` 8 KiB, uploads 32 MiB. The
64
+ desktop `/api/desktop/*` family additionally answers `OPTIONS` with `204` and CORS headers
65
+ for a loopback page (and the private-network preflight header).
66
+
67
+ ### Desktop endpoints (loopback / desk key)
68
+
69
+ `client.js` runs on the DSH web origin, so it uses the same-origin routes the Host registers
70
+ on `ctx.webServer`:
71
+
72
+ | Method | Path |
73
+ |---|---|
74
+ | GET | `/remote-mobile/pairing` |
75
+ | POST | `/remote-mobile/pairing/rotate` |
76
+ | POST | `/remote-mobile/pairing/revoke` |
77
+ | POST | `/remote-mobile/pairing/enable` |
78
+ | POST | `/remote-mobile/pairing/disable` |
79
+ | GET | `/remote-mobile/pairing/pending` |
80
+ | POST | `/remote-mobile/pairing/answer` |
81
+ | POST | `/remote-mobile/pairing/device` |
82
+
83
+ `POST /remote-mobile/pairing/device` (same-origin) and `POST /api/desktop/device`
84
+ (body `{ deviceId, canApprove }` → `{ ok: true, device }`, 404 `missing-device` for an
85
+ unknown id) flip one paired device's approval permission. Both obey the same
86
+ loopback/desk-key policy as the other desktop routes.
87
+
88
+ The standalone server exposes the same data on `/api/desktop/status`, `/rotate`, `/revoke`,
89
+ `/enable`, `/disable`, `/pending`, `/answer`, `/device`. Those accept a loopback TCP peer
90
+ (the panel's keyed bootstrap path passes `?key=<desk-key>`); a remote origin gets 403 even
91
+ from this machine's browser. The desk key is written once per process to
92
+ `$DSH_HOME/remote-mobile-state.json.desk-key` (0600) and grants nothing over the network.
93
+ Each device row in `/api/desktop/status` carries `canApprove`.
94
+
95
+ ### Static app surface (installable PWA + share target)
96
+
97
+ | Method | Path | Notes |
98
+ |---|---|---|
99
+ | GET | `/manifest.webmanifest` | `application/manifest+json`; standalone app, icons, share target |
100
+ | GET | `/sw.js` | root-scope service worker, `Service-Worker-Allowed: /`, `no-cache` |
101
+ | GET | `/icons/icon-192.png`, `/icons/icon-512.png`, `/icons/icon-maskable-512.png`, `/icons/apple-touch-icon.png` | PNG icons |
102
+ | GET | `/favicon.svg` | SVG favicon |
103
+ | GET | `/share-target?title=&text=&url=` | Web Share Target: `302` to `/?share=<urlencoded JSON {title,text,url}>` |
104
+
105
+ The service worker caches the shell (`/`, the versioned `/app.js` and `/styles.css`) so the
106
+ installed app opens offline, and never caches `/api/*`, `/ws`, `/remote-mobile/*` or the share
107
+ target. Installation requires a secure context (HTTPS, e.g. Tailscale Serve); on plain HTTP
108
+ the SPA works but no service worker is registered. The share redirect is handled entirely
109
+ client-side: the SPA reads `?share=`, pre-fills the composer, strips the query and never
110
+ auto-sends.
111
+
112
+ ### Web Push (real background notifications)
113
+
114
+ Approvals, questions and finished replies are delivered through the browser Push API, so a
115
+ notification arrives while the phone page is frozen, the app is backgrounded or the screen is
116
+ off. The Host implements RFC 8291 (`aes128gcm` payload encryption) and RFC 8292 (VAPID) itself
117
+ with `node:crypto` and the global `fetch` (`push.js`, no npm dependency); the only third party
118
+ is the browser's own push service endpoint.
119
+
120
+ **Requirements.** Push needs a secure context: HTTPS (Tailscale Serve or a trusted TLS proxy)
121
+ or `http://localhost`/`127.0.0.1`. Plain HTTP over the LAN has no service worker and therefore
122
+ no push. The user must have granted notification permission to the installed app/tab.
123
+
124
+ **VAPID key.** `GET /api/push/key` is unauthenticated (the public key is public by design) and
125
+ returns:
126
+
127
+ ```jsonc
128
+ { "enabled": true, "publicKey": "<base64url, raw uncompressed P-256 point (65 bytes)>" }
129
+ ```
130
+
131
+ `publicKey` is **base64url without padding**. Decode it to bytes before
132
+ `pushManager.subscribe({ userVisibleOnly: true, applicationServerKey })` (browsers also accept
133
+ the base64url string; passing the decoded bytes is unambiguous). `enabled: false` with a `null`
134
+ key means the server is still starting.
135
+
136
+ **Subscribing.** After pairing, `POST /api/push/subscribe` with the cookie and
137
+ `{ "subscription": { "endpoint": "https://...", "keys": { "p256dh": "...", "auth": "..." } } }`
138
+ (any `PushSubscription.toJSON()`-shaped object; `keys.p256dh` must decode to 65 bytes and
139
+ `keys.auth` to 16). Success is `{ "ok": true, "deviceId": "<the cookie's device id>" }`. The
140
+ server keeps at most **4** subscriptions per device and **16** total; re-subscribing the same
141
+ endpoint refreshes it instead of growing the store; a full store answers
142
+ `429 { "error": "too-many-subscriptions" }` and a malformed shape
143
+ `400 { "error": "invalid-subscription" }`. Endpoints must be `https:` URLs whose host is a
144
+ known browser push service (FCM, Mozilla autopush, Windows WNS, Apple push) or a suffix the
145
+ operator configured with `PA_REMOTE_MOBILE_PUSH_HOSTS`; an arbitrary host is refused so the
146
+ Host cannot be used as an HTTPS request proxy (only the deterministic dev harness accepts
147
+ loopback `http:` endpoints).
148
+
149
+ **Unsubscribing.** `POST /api/push/unsubscribe` with `{ "endpoint": "..." }` →
150
+ `{ "ok": true }`. Only the calling device's own endpoint can be removed; an unknown endpoint is
151
+ an idempotent no-op. Unpairing, desktop revoke and device eviction also delete that device's
152
+ subscriptions.
153
+
154
+ **Test.** `POST /api/push/test` (cookie, empty body) sends one `kind: "test"` notification to
155
+ the calling device's subscriptions and answers `{ "ok": <at least one accepted>, "sent": n,
156
+ "gone": n, "failed": n }` (counts only; the push service's response body never reaches the
157
+ phone). Above 6 sends/minute for one device it answers
158
+ `429 { "error": "rate-limited", "retryAfterMs": n }`. With no subscriptions it is a no-op
159
+ (`{ "ok": false, "sent": 0, "gone": 0 }`) and touches no network. Unlike the automatic
160
+ notifications, this explicit action is not foreground-gated.
161
+
162
+ **Diagnostics.** The service worker and SPA may `POST /api/push/report` with a bounded
163
+ `{ kind, detail, scope, permission? }` body (`sw-activated`, `push-shown`, `push-error`,
164
+ `notification-click`, `push-enabled`). Each field is collapsed to one bounded log line before
165
+ it is appended to the Host debug log; it never includes endpoints/keys/notification content,
166
+ and exists so a delivery failure can be distinguished from an OS-level notification block.
167
+
168
+ **Encryption detail.** `aes128gcm` is RFC 8291 with the **empty AEAD AAD** used by
169
+ single-record pushes; authenticating the header instead produces a tag that the push service
170
+ accepts and the browser silently drops. `dev/push-check.mjs` pins the RFC 8291 Appendix A
171
+ wire body byte-for-byte next to the VAPID signature and decrypt round-trip.
172
+
173
+ **Push message payload.** The service worker's `push` event delivers JSON (`event.data.json()`):
174
+
175
+ ```jsonc
176
+ {
177
+ "kind": "approval" | "question" | "reply" | "test",
178
+ "title": "Approval needed" | "Question from Harness" | "Reply ready" | "Test notification",
179
+ "body": "short bounded text",
180
+ "tag": "approval:<requestId>" | "question:<requestId>" | "reply:<sessionId>:<minute>" | "test:<deviceId>:<ts>",
181
+ "sessionId": "..." | null,
182
+ "url": "/?session=<sessionId>" | "/"
183
+ }
184
+ ```
185
+
186
+ - `kind: "approval"` — `body` is `<toolName>: <bounded reason>` (or just the tool name); open
187
+ `url` to answer with the pending approval card.
188
+ - `kind: "question"` — `body` is the first question's text, bounded to 160 characters.
189
+ - `kind: "reply"` — title is `Reply ready · <session title>` (title alone when unknown) and
190
+ `body` is a bounded plain-text excerpt (≤150 chars) of the assistant's actual reply with
191
+ fenced code dropped and markdown flattened; at most one per session per 60 s.
192
+ - `kind: "test"` — from `POST /api/push/test`.
193
+
194
+ Use the payload `tag` as `showNotification({ tag })` so a repeat for the same request replaces
195
+ the old notification instead of stacking. The payload never contains tool output, tool
196
+ arguments or secrets; the body is the bounded text described above (control characters are
197
+ stripped and secret-looking `key=value` pairs are redacted). A finished-reply notification is
198
+ conversation content on the lock screen by design — see SECURITY.md.
199
+
200
+ **Service worker expectations.**
201
+
202
+ - `push`: `const data = event.data ? event.data.json() : {}`; `event.waitUntil(self.registration
203
+ .showNotification(data.title, { body: data.body, tag: data.tag, icon: '/icons/icon-192.png',
204
+ badge: '/icons/icon-192.png', data: { url: data.url, sessionId: data.sessionId } }))`.
205
+ - `notificationclick`: `event.notification.close()`; focus a matching client or
206
+ `clients.openWindow(event.notification.data.url)` (same-origin URL from the payload).
207
+ - `pushsubscriptionchange`: re-run `GET /api/push/key` → `pushManager.subscribe(...)` →
208
+ `POST /api/push/subscribe` (same-origin, so the cookie rides along). If that fails, retry on
209
+ the next app start.
210
+
211
+ **Gating, limits and expiry.** The SPA reports whether its page is visible with the
212
+ `client.visibility` frame below (on `visibilitychange` and once after `ready`). While **any**
213
+ connected phone page reports `visible: true` the server sends no push; when none is visible it
214
+ fans out to every stored subscription, capped at ~30 notifications/minute process-wide and
215
+ deduplicated by `tag` for 5 minutes. The desktop **Remote access** switch being off also
216
+ suppresses delivery (the subscriptions are kept and delivery resumes when it is switched back
217
+ on). Push services that answer `404`/`410` are pruned automatically. Browser/push-service
218
+ subscriptions can expire at any time, so the SPA should re-subscribe on start when
219
+ `Notification.permission === "granted"`.
220
+
221
+ ## WebSocket
222
+
223
+ `ws://<host>:<port>/ws` (or `wss://` behind Tailscale Serve) — cookie required. JSON text
224
+ frames, one object per frame. Unknown types are ignored with an `error` frame. Every frame
225
+ carries `type`; data frames additionally carry `sessionId`.
226
+
227
+ ### Client → Server
228
+
229
+ ```jsonc
230
+ { "type": "sessions.list" }
231
+ { "type": "sessions.open", "sessionId": "..." }
232
+ { "type": "sessions.create", "preset": "standard", "cwd": "/path/to/dir" } // both optional
233
+ { "type": "sessions.search", "query": "literal message text" } // cold-safe, max 20 sessions
234
+ { "type": "session.rename", "sessionId": "...", "title": "New title" }
235
+ { "type": "session.fork", "sessionId": "...", "atSeq": 123 } // atSeq optional
236
+ { "type": "session.pin", "sessionId": "..." }
237
+ { "type": "session.unpin", "sessionId": "..." }
238
+ { "type": "session.archive", "sessionId": "...", "stopActivity": false } // stopActivity optional
239
+ { "type": "session.unarchive","sessionId": "..." }
240
+ { "type": "queue.list", "sessionId": "..." } // live sessions only
241
+ { "type": "queue.update", "sessionId": "...", "itemId": "...",
242
+ "action": "edit" | "remove" | "steer", "text": "edited text" } // text only for edit
243
+ { "type": "history.load", "sessionId": "...", "limit": 50 } // limit 1..200, default 50
244
+ { "type": "prompt", "sessionId": "...", "text": "...", "requestId": "uuid",
245
+ "mode": "queue" | "steer", // default "queue"
246
+ "attachments": [{ "path": "...", "name": "photo.jpg", "mediaType": "image/jpeg", "size": 1234 }] }
247
+ { "type": "stop", "sessionId": "..." }
248
+ { "type": "approval.answer", "requestId": "...", "decision": "allow" | "reject" }
249
+ { "type": "question.answer", "sessionId": "...", "requestId": "...", "callId": "...",
250
+ "answers": [{ "id": "color", "selected": ["Blue"], "custom": null }] }
251
+ { "type": "model.list" }
252
+ { "type": "model.select", "sessionId": "...", "provider": "...", "model": "...", "reasoningEffort": null }
253
+ { "type": "preset.list" }
254
+ { "type": "preset.select", "sessionId": "...", "preset": "standard" }
255
+ { "type": "limits" } // image limits (additive)
256
+ { "type": "context.get", "sessionId": "..." } // context-window meter
257
+ { "type": "changes.list", "sessionId": "...", "limit": 10 } // changed-file events (live only)
258
+ { "type": "changes.diff", "sessionId": "...", "seq": 0, "index": 0 }
259
+ { "type": "commands.list", "sessionId": "..." } // every Host command (export/permission hidden)
260
+ { "type": "commands.execute", "sessionId": "...", "line": "goal ship it" } // "/" optional; args kept
261
+ { "type": "client.visibility", "visible": true } // page foreground state (Web Push gating)
262
+ { "type": "ping", "t": 0 }
263
+ ```
264
+
265
+ `commands.execute.line` may be sent with or without the leading slash (`"/goal ship it"` or
266
+ `"goal ship it"`); the command name is validated against the live Agent's current command
267
+ registry, and the full trimmed line (arguments preserved) reaches that registry. Two commands
268
+ are hidden from the phone: `/export` (its Host command only records a lifecycle, and the desktop
269
+ browser then downloads the ZIP from a Host-only route the phone server cannot proxy) and
270
+ `/permission` (it switches the session's sandbox/approval preset, including
271
+ `danger-full-access`; sandbox policy must not be changed from a device that may itself be
272
+ restricted from answering approvals). Hiding is by name and by first-party definition id, so a
273
+ renamed alias cannot re-expose the policy switch.
274
+
275
+ Model selection: `model.list` returns the flattened Host catalog. Models that expose a
276
+ reasoning control carry `reasoning.efforts[]` (`id`, `name`, optional `description`) and an
277
+ optional `defaultEffort`; models without it have no `reasoning` field. `model.select` takes
278
+ the same `reasoningEffort` the catalog advertised (raw effort id). Omit it to fall back to
279
+ `defaultEffort`, and when the model has neither, the effective behaviour is the provider
280
+ default. The selected effort is echoed back in the `model` object of `sessions` rows and
281
+ `session.opened.session`, and `model.list.current.reasoningEffort` is the deployment default's
282
+ effort.
283
+
284
+ `prompt` accepts text, attachments, or both. Attachments are first POSTed to `/api/upload`
285
+ and the returned descriptors are forwarded here. The bridge now delivers uploads whose
286
+ `mediaType` starts with `image/` as **real inline image content parts**
287
+ (`{ type: "image", mediaType, data: <base64> }`) built from the stored bytes, so the model
288
+ sees the photo without a tool call. Every attachment still keeps a path reference in the
289
+ prompt text: non-images in the existing
290
+ `Attached files from the user's phone (read them with your file tools; images can be opened
291
+ with read_image):` block, inline images in an
292
+ `Attached images from the user's phone (shown inline in this message; already visible to you
293
+ — no tool call needed):` block. If the Host rejects the image parts for any reason (validation,
294
+ size, unsupported type), the bridge retries the same prompt once as text-only path
295
+ references, so a phone send never fails because of its images. Non-image files are never
296
+ inlined.
297
+
298
+ `prompt.mode`: `"queue"` (default) targets the session's next turn. `"steer"` injects into the
299
+ nearest step of a **running** turn; when the agent is idle (or after its turn ended) the Host
300
+ rejects it and the server answers with an `error` frame (`code: "bad-request"`). Steering does
301
+ not replace queued prompts and is best-effort by design.
302
+
303
+ `session.rename` is cold-safe: the Host resumes the session to append `session/title`,
304
+ normalizes the text (control sequences/whitespace) and truncates it to its configured UTF-8
305
+ byte budget (80 bytes in the shipped desktop composition). A title with no visible characters
306
+ is refused with an `error` frame (`code: "bad-request"`), not persisted.
307
+
308
+ `session.fork` is cold-safe. `atSeq` is an inclusive event boundary; omitted, the Host forks
309
+ the latest completed turn. The fork is a **new independent session** (not a subagent child)
310
+ and appears in the next `sessions` refresh. Sources that still need a desktop-side migration
311
+ answer with `code: "bad-request"` and a message asking to open the session on the desktop.
312
+
313
+ `sessions.search` searches literal message **content** (not titles), cold-safe. The Host caps
314
+ results at 20 sessions and 240 code points per snippet; there is no pagination in v1 (a
315
+ `hasMore` flag says the cap was hit). An empty query is `code: "bad-request"`.
316
+
317
+ Pin/archive are registry-global flags:
318
+ - `session.pin` prepends the session to the pinned set; pinning an archived session fails
319
+ (`code: "bad-request"`, unarchive first).
320
+ - `session.archive` requires an inactive session unless `stopActivity: true` is sent, which
321
+ stops a running turn/job first. Archiving drops the pin. Archived sessions stay visible in
322
+ `sessions` (with `archived: true`) but cannot run a model step until unarchived.
323
+ - These calls acknowledge with `session.pinned` / `session.archived` and are followed by a
324
+ `sessions` refresh.
325
+
326
+ Project workspaces: every `ready` and `sessions` frame carries `workspaces`, the registered
327
+ project workspaces in Host display order as `{ id, title, path, sessionIds }`. Every session
328
+ row (list/open/create) also carries `workspaceId`: the owning workspace id, or `null` when the
329
+ session belongs to no registered workspace (for example one created with a plain `cwd`). The
330
+ `sessionIds` membership mirrors the desktop sidebar grouping, so the SPA groups rows by
331
+ `workspaceId` and shows ungrouped sessions separately. Names, ids and project root paths only —
332
+ never session content.
333
+
334
+ `context.get` returns the context-window meter for one session. It is cold-safe (read from
335
+ the Host's `contextPressure` / `tokenUsage` projections): `usedTokens` prefers
336
+ `projectedTokens` (the size the next request would send) and falls back to
337
+ `pressureTokens`; `basis` is `"usage"` when a provider usage sample exists, `"estimated"`
338
+ when only the projection's estimate exists, and `"unknown"` for a session that never ran a
339
+ turn. `contextWindow` is the model's window when the Host recorded it. The same object is
340
+ included in `session.opened` as `context`.
341
+
342
+ Changed files: `changes.list` scans recent session events for `workspace/changes` and returns
343
+ one item per event (`seq`, `turn`, counts and files). File summaries are kept in Host memory
344
+ for live sessions only; an event whose summary is gone (cold session, another process, Host
345
+ restart) comes back as `{ available: false }` instead of an error. `changes.diff` takes the
346
+ event `seq` and the **original index in that summary's `files` array** and answers with either
347
+ text hunks (`kind: "text"`, unified-style lines without `@@` headers, `coarse` when the Host's
348
+ diff timeout forced a whole-file hunk), or `kind: "binary"` / `"oversized"` refusals. Paths are
349
+ relativised to the session directory or reduced to a short tail — the phone never receives
350
+ `cwd`, drive letters or home paths. Diff data is live-process only: unknown coordinates answer
351
+ `code: "unavailable"`.
352
+
353
+ Commands: `commands.list` requires a live Agent, so a cold session answers
354
+ `available: false` (the phone never activates a session just to list commands). For a live
355
+ Agent the bridge returns every descriptor from the Agent's Host command registry — including
356
+ commands mounted by the Agent preset (goal/plan/compact/feedback, …) — sorted by name, minus
357
+ the desktop-only `/export` and the policy-changing `/permission`. The phone therefore shows the
358
+ same benign command surface the desktop palette offers. `commands.execute` resolves the name
359
+ against that same live registry (never a static list), runs the full trimmed line on that Agent
360
+ (arguments preserved) and reports `command.result`; the Host logs durable `command/run` +
361
+ `command/done` events, so the phone should reload history afterwards to show the command node.
362
+ A cold session answers `code: "not-live"`, an unknown or hidden command `code: "forbidden"`.
363
+
364
+ ### Server → Client
365
+
366
+ ```jsonc
367
+ { "type": "ready", "version": "0.0.6", "server": { "name", "port" },
368
+ "device": { "id", "name", "canApprove": true }, "sessions": [], "workspaces": [],
369
+ "activeSessionId": null, "queue": [],
370
+ "limits": { "image": { "maxBytes", "maxDimension", "maxImages",
371
+ "maxMessageBytes", "mediaTypes": ["image/png", "..."] } } | null }
372
+
373
+ { "type": "limits", "image": { "maxBytes", "maxDimension", "maxImages",
374
+ "maxMessageBytes", "mediaTypes": ["image/png", "..."] } | null }
375
+
376
+ { "type": "sessions", "sessions": [
377
+ { "id", "title", "running": false, "updatedAt": 0,
378
+ "preset": "standard|null", "model": { "provider", "model", "reasoningEffort": "..." | null } | null,
379
+ "agentAvailable": true, "pinned": false, "archived": false, "workspaceId": "ws-id|null" }
380
+ ], "workspaces": [{ "id": "ws-id", "title": "Project", "path": "/projects/x",
381
+ "sessionIds": ["..."] }], "activeSessionId": "..." | null }
382
+
383
+ { "type": "session.opened",
384
+ "session": { "id", "title", "running", "preset", "model",
385
+ "agentAvailable", "pinned", "archived", "workspaceId" },
386
+ "history": [HistoryItem],
387
+ "queue": [{ "id", "placement": "queued|steering|context", "rpcId": "..."?, "text": "..." }],
388
+ "context": { "usedTokens": 0, "pressureTokens": 0, "projectedTokens": 0,
389
+ "contextWindow": 0, "basis": "usage|estimated|unknown",
390
+ "tokenUsage": { "inputTokens", "outputTokens", "totalTokens",
391
+ "reasoningTokens" } | null } | null }
392
+
393
+ { "type": "session.updated", "sessionId": "...", "title": "New title",
394
+ "session": { same shape as a `sessions` row } | null }
395
+
396
+ { "type": "sessions.found", "query": "...", "hasMore": false,
397
+ "results": [{ "id", "title", "snippet", "updatedAt", "running", "pinned", "archived",
398
+ "agentAvailable", "workspaceId" }] }
399
+
400
+ { "type": "session.pinned", "sessionId": "...", "pinned": true, "archived": false }
401
+ { "type": "session.archived", "sessionId": "...", "archived": true, "pinned": false }
402
+
403
+ { "type": "queue", "sessionId": "...",
404
+ "items": [{ "id", "placement": "queued|steering|context", "rpcId": "..."?, "text": "..." }],
405
+ "pendingInput": ["approval"|"question"|"other"], "running": true, "active": true }
406
+ { "type": "queue.changed", "sessionId": "...",
407
+ "items": [{ "id", "placement", "rpcId": "...", "text": "..." }] }
408
+
409
+ { "type": "history", "sessionId": "...", "items": [HistoryItem], "hasMore": false }
410
+
411
+ { "type": "context", "sessionId": "...",
412
+ "usedTokens": 0, "pressureTokens": 0, "projectedTokens": 0, "contextWindow": 0,
413
+ "basis": "usage|estimated|unknown",
414
+ "tokenUsage": { "inputTokens", "outputTokens", "totalTokens", "reasoningTokens" } | null }
415
+
416
+ { "type": "changes", "sessionId": "...",
417
+ "items": [{ "seq": 0, "available": true, "turn": 1, "total": 2, "added": 10, "deleted": 3,
418
+ "files": [{ "index": 0, "path": "src/app.ts", "display": "src/app.ts",
419
+ "added": 8, "deleted": 1, "binary": false, "oversized": false }] }
420
+ ] } // unavailable items: { "seq": 0, "available": false, "files": [] }
421
+ { "type": "changes.diff", "sessionId": "...", "seq": 0, "index": 0,
422
+ "kind": "text" | "binary" | "oversized", "path": "src/app.ts", "coarse": false,
423
+ "hunks": [{ "oldStart": 1, "oldLines": 2, "newStart": 1, "newLines": 3,
424
+ "lines": [" context", "-removed", "+added"] }] }
425
+
426
+ { "type": "commands", "sessionId": "...", "available": true,
427
+ "items": [{ "name": "goal", "description": "...", "hint": "[<objective>|clear]",
428
+ "attachments": true },
429
+ { "name": "plan", "description": "...", "hint": "[off|message]", "attachments": true },
430
+ { "name": "compact", "description": "...", "hint": null, "attachments": false }],
431
+ "reason": null } // available:false with reason "not-live" | "unavailable";
432
+ // /export and /permission are hidden from the phone
433
+ { "type": "command.result", "sessionId": "...", "commandId": "..." | null,
434
+ "name": "goal", "kind": "success" | "error", "text": "..." | null,
435
+ "sourceEventSeq": 0 | null }
436
+
437
+ { "type": "assistant.start", "sessionId": "...", "turn": 1, "step": 1 }
438
+ { "type": "assistant.delta", "sessionId": "...", "text": "...", "reasoning": null }
439
+ { "type": "assistant.end", "sessionId": "...", "turn": 1, "step": 1 }
440
+
441
+ { "type": "tool.start", "sessionId": "...", "callId": "...", "name": "pwsh",
442
+ "title": "Run command", "argsPreview": "...", "detail": { "command": "..." } | null,
443
+ "question": null } // question payload when this call asks the user
444
+ { "type": "tool.end", "sessionId": "...", "callId": "...", "ok": true,
445
+ "output": "...", "durationMs": 120, "detail": null }
446
+
447
+ { "type": "approval.request", "sessionId": "...", "requestId": "...", "toolName": "pwsh",
448
+ "title": "Approval required", "reason": "...", "displayReason": "..." | null,
449
+ "callId": null, "expiresAt": 0,
450
+ // Additive card context, present only when the bridge already correlated the
451
+ // tool call (callId); absent otherwise. Never contains secret-looking values.
452
+ "argsPreview": "bounded, scrubbed preview (≤600 chars)",
453
+ "argsKind": "command" | "write" | "edit" | "other",
454
+ "detail": { "kind": "command" | "write" | "edit" | "other", "path": "..."? } }
455
+ { "type": "approval.resolved", "sessionId": "...", "requestId": "...",
456
+ "outcome": "allowed-once" | "rejected" | "cancelled" | "unavailable",
457
+ "by": "phone" | "desktop" | null }
458
+
459
+ { "type": "question.request", "sessionId": "...", "requestId": "...", "callId": "..." | null,
460
+ "questions": [
461
+ { "id": "color", "question": "Which colour?", "header": "Colour",
462
+ "detail": null, "multiSelect": false,
463
+ "options": [{ "label": "Red", "description": "Warm" }, { "label": "Blue" }] }
464
+ ] }
465
+ { "type": "question.resolved", "sessionId": "...", "requestId": "..." | null, "callId": "..." | null,
466
+ "answers": [{ "id": "color", "selected": ["Blue"], "custom": null }] | null,
467
+ "outcome": "answered" | "declined" | "unavailable",
468
+ "by": "phone" | "desktop" | null }
469
+
470
+ { "type": "session.status", "sessionId": "...", "running": true }
471
+ { "type": "models",
472
+ "catalog": [{ "provider", "model", "label",
473
+ // Only when the model exposes a reasoning control:
474
+ "reasoning": { "efforts": [{ "id", "name", "description": "..." | null }],
475
+ "defaultEffort": "..." | null } }],
476
+ "current": { "provider", "model", "reasoningEffort": null } | null }
477
+ { "type": "presets", "presets": [{ "id", "title", "description" }], "current": "standard" | null }
478
+
479
+ { "type": "visibility", "visible": true } // ack for client.visibility; not required for Web Push
480
+ { "type": "error", "code": "bad-request|not-found|internal|not-live|unavailable|forbidden", "message": "..." }
481
+ { "type": "pong", "t": 0 }
482
+ ```
483
+
484
+ ### Welcome replay
485
+
486
+ After `ready`, the server immediately replays every open interaction as its original frame —
487
+ each pending `approval.request`, then each pending `question.request`. A phone that reconnects
488
+ therefore sees the same cards again without asking the Host to re-emit them; answering from
489
+ either device settles the request once.
490
+
491
+ ### HistoryItem
492
+
493
+ The SPA renders a flat, already-ordered stream. `kind` is one of `user`, `assistant`,
494
+ `tool`, `error`, `system`. Assistant message text is markdown and the SPA sanitises it.
495
+
496
+ ```jsonc
497
+ { "id": "seq:12", "kind": "user", "text": "...", "ts": 0 }
498
+ { "id": "seq:13", "kind": "assistant", "text": "markdown...", "ts": 0 }
499
+ { "id": "tool:call-1", "kind": "tool", "callId": "call-1", "name": "read",
500
+ "title": "Read file", "argsPreview": "src/index.ts", "ok": true,
501
+ "output": "…", "diff": null, "durationMs": 42, "ts": 0 }
502
+ { "id": "seq:14", "kind": "error", "text": "...", "ts": 0 }
503
+ ```
504
+
505
+ A `user` history item that was sent with phone uploads carries an `attachments` array in
506
+ addition to its clean text, so the SPA can render thumbnails through `/api/preview`:
507
+
508
+ ```jsonc
509
+ { "id": "seq:11", "kind": "user", "text": "what is this?", "ts": 0,
510
+ "attachments": [{ "path": "...", "name": "photo.jpg", "mediaType": "image/jpeg" }] }
511
+ ```
512
+
513
+ ## Behaviour rules
514
+
515
+ - **Live vs cold sessions.** Every session row and `session.opened.session` carries
516
+ `agentAvailable`: true only while the Host has an attached Agent. `queue.list`,
517
+ `queue.update` and `prompt.mode: "steer"` are live-only; a cold session answers
518
+ `code: "not-live"` (queue/steer) or the Host's busy/steer error, and the SPA must hide or
519
+ disable those controls when `agentAvailable` is false. `sessions.list`, `sessions.open`,
520
+ `history.load`, `sessions.search`, `session.rename` and `session.fork` are cold-safe.
521
+ - **Queue is the live inbox, not history.** `queue` items (`queued`/`steering`/`context`)
522
+ live in the running agent's inbox; they become `user` history items only when the loop
523
+ claims them at the next turn/step. `queue.update` supports `edit` (text only, non-empty),
524
+ `remove`, and `steer` (only for a `queued` item of a running turn). There is **no
525
+ reordering**. After any queue mutation the server pushes `queue.changed` (coalesced to at
526
+ most one frame per session per ~120 ms) and `queue.update` also acks with a `queue` frame
527
+ to the requesting device.
528
+ - **Pending queue replay.** `session.opened` includes the current queue (empty for a cold
529
+ session), so a reconnect that re-opens its active session restores the queue; `ready`
530
+ carries `queue: []` because no session is active on a fresh socket.
531
+ - **Inline images are best-effort.** The bridge inlines at most 4 images per prompt and at
532
+ most the smaller of 5 MiB and the deployment's `maxImageBytes`/`maxMessageImageBytes`
533
+ (plus `maxImagesPerMessage`); a stored upload larger than that, of an unsupported type, or
534
+ otherwise unreadable is kept as a path reference instead of being inlined. The effective
535
+ caps are advertised in `ready.limits.image` and on demand via `{ "type": "limits" }`
536
+ (`null` when the Host cannot discover the attachment store). If the Host rejects the
537
+ inline parts, the bridge retries once with a text-only prompt and logs a warning (counts
538
+ only, no content). History rows are unchanged: user items still carry
539
+ `attachments: [{ path, name, mediaType }]`, now parsed from both attachment blocks.
540
+ - **Search may be disabled.** `sessions.search` answers `code: "unavailable"` with a clear
541
+ message when this deployment turns off the session-query index; the SPA should hide or
542
+ disable search in that case rather than retrying.
543
+ - **Session metadata.** `agentAvailable`, `pinned`, `archived` and `workspaceId` are
544
+ annotated by the Host from the live Agent registry and the workspace registry; missing
545
+ workspace services degrade to `false`/`null`. Archived sessions remain in `sessions` (so the
546
+ SPA can group them) but cannot run until unarchived.
547
+ - **Projects come from the workspace registry.** `ready`/`sessions` carry the registered
548
+ `workspaces` in display order and each session row names its owning `workspaceId`; the SPA
549
+ can reproduce the desktop's project grouping without extra round-trips. Workspaces are
550
+ listed even when empty, and a session in no workspace is `workspaceId: null`.
551
+ - **The phone command palette mirrors the Host registry.** `commands.list` returns every
552
+ command the live Agent's registry offers (host-plane and preset-mounted), sorted by name,
553
+ minus `/export` (Host-only download route) and `/permission` (sandbox/approval policy switch).
554
+ `commands.execute` validates against the same live registry and preserves arguments.
555
+ - **Approval cards carry bounded call context.** When a tool call was seen before the ask,
556
+ `approval.request` adds `argsPreview` (≤600 chars), `argsKind`
557
+ (`command`/`write`/`edit`/`other`) and `detail` (`{kind, path?}`, path only). Values whose
558
+ argument key looks like a password/secret/token/key/credential are never cached or shown;
559
+ the bridge keeps at most 200 call contexts and evicts oldest first. A card without a seen
560
+ `callId` (or before the bridge observed the call) simply omits all three fields.
561
+ - **Per-device approval permission.** Every paired device has `canApprove` (default `true`,
562
+ persisted, absent means `true`). A device with `canApprove:false` gets
563
+ `{ "type": "error", "code": "forbidden", "message": "this device is not allowed to answer
564
+ approvals" }` for `approval.answer`; the frame never reaches the bridge. Questions are not
565
+ gated in this pass. The same device cannot widen its own sandbox: `/permission` is refused
566
+ for every phone, so a restricted device cannot disable the approval gate it may not answer.
567
+ The desktop panel flips the flag through
568
+ `POST /api/desktop/device` or the same-origin `POST /remote-mobile/pairing/device`.
569
+ - **One answerer, first answer wins.** While a phone client is connected the bridge answers
570
+ `approval/request` from the phone only (the desktop dock polls the same list, so either
571
+ device can answer); the first answer clears both surfaces. With no phone connected the
572
+ request goes straight to the shipped desktop answerer.
573
+ - **Questions follow the same exclusive routing, with a reconnect grace.** While a phone is
574
+ connected it is the answerer. If **no** phone is connected when the question is asked, the
575
+ bridge keeps the request pending for up to 45 seconds (`questionHandoffMs`) so a
576
+ (re)connecting phone can still receive it; if no phone connects in that window it hands the
577
+ request to the desktop chain and reports `outcome: "unavailable"` to the phone. A phone that
578
+ disconnects after receiving a question does not start a new handoff timer.
579
+ - **Resolution frames name the answering surface.** `approval.resolved` and
580
+ `question.resolved` carry `by: 'phone' | 'desktop' | null`; the SPA uses it to say
581
+ "Approved on desktop" when the other device settled a card it was still showing. A
582
+ question handed off to the desktop reports `outcome: "unavailable"`, which the SPA shows
583
+ as "Moved to the desktop to answer."
584
+ - **Cards are session-scoped.** The SPA renders an approval or question card only inside the
585
+ session it belongs to. Pending interactions for another session appear in the notice bar
586
+ (`Approval needed in <title> (+N)`) with **Open**, which switches session and re-attaches
587
+ the card. The server never needs to know which session the phone is viewing.
588
+ - **Session list refreshes are pushed.** A new approval, a status change, a create, a
589
+ rename, a fork, or a pin/archive mutation makes the server re-list sessions and broadcast
590
+ `sessions` (together with the current `workspaces`); clients must tolerate a `sessions`
591
+ frame at any time (the SPA uses it for the notice bar, sidebar badges, project grouping and
592
+ pin/archive grouping).
593
+ - **Web Push is per device and foreground-aware.** `client.visibility` (default unknown =
594
+ not visible) gates every push: no push while a phone page reports itself visible, otherwise
595
+ all stored subscriptions receive the JSON payload from the Web Push section. Pushes are
596
+ best-effort and detached from the WebSocket path; a full store, a duplicate `tag`, the
597
+ process-wide ~30/min cap, a visible page or an empty store all skip silently. Dead
598
+ subscriptions (404/410) are pruned; the VAPID key pair and subscriptions live in the same
599
+ state file as pairing under `push`, and revoking/unpairing a device deletes its
600
+ subscriptions.
601
+ - Token and PIN are one-shot/rotating as described above; `revoke` drops one device
602
+ immediately and closes its socket, and rotates all pairing material.
603
+ - The server keeps at most 8 paired devices; state lives in `$DSH_HOME/remote-mobile-state.json`
604
+ (0600) so phones survive a Host restart. The same file's `push` field holds the VAPID key
605
+ pair and the subscription store (absent in files written by older versions; the server then
606
+ generates a fresh key pair).
607
+ - WS reconnect is the SPA's job: exponential backoff 0.5 s → 8 s, then `sessions.list` plus
608
+ `history.load` for the active session; pending interactions are replayed by the server.
609
+ - Streaming deltas are throttled server-side to about 30 fps; the SPA may coalesce.
610
+ - Uploads are size-capped (32 MiB) and only previewable image types are served back by
611
+ `/api/preview`; everything else is a normal attachment path in the transcript.
612
+ - Transport limits: WebSocket messages are capped at 1 MiB (oversize closes with `1009`),
613
+ JSON request bodies at 64 KiB and `/api/pair` bodies at 8 KiB. Upload filenames are
614
+ sanitised and previews are resolved and confined to the session's
615
+ `var/remote-mobile-uploads` directory.
616
+ - PINs, tokens, cookies, the desk key and the VAPID private key are never written to any log.
617
+ The optional request trails record method, path, origin, Host header, peer address, user
618
+ agent and allowed/denied only; the debug trail additionally records pairing method/device
619
+ name and `approval.request` / `approval.answer` ids and decisions. Push delivery logs only
620
+ aggregate/wire outcomes — never the endpoint, subscription keys or payload body.
621
+
622
+ - **Client-only features.** The install prompt, service-worker registration, notification
623
+ permission/subscription, voice input, camera capture, Android share target and the WebAuthn
624
+ app-lock gate are local to the SPA; they degrade silently when the browser or secure context
625
+ does not support them and never change the wire protocol (delivery itself is server-side Web
626
+ Push, above). The app lock is a privacy gate over the same authenticated session, not a
627
+ server rule.