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

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.
@@ -0,0 +1,583 @@
1
+ # Host API notes — verified against DeepSeek Harness 0.2.2-rc.1
2
+
3
+ Scope: the Host-side contract consumed by `bridge.js`. Everything here was read from the
4
+ installed Harness, not from memory:
5
+
6
+ - Install root: the Harness resources directory `…/resources/app.asar/dsh/`
7
+ (an asar archive; the `read` tool opens files inside it, native `glob`/`grep`/`ls` do not).
8
+ - Version: `package.json` → `@deepseek-ai/dsh-desktop-runtime` `0.2.2-rc.1`.
9
+ - **The shipped `.d.ts` files are absent from the install.** Every package's
10
+ `lib/types/**` contains only the compiled `.js` (which carries the JSDoc and the
11
+ real implementations). Package `package.json` `exports` still name
12
+ `lib/types/*.d.ts`, so type-only readers see through the archive; our research
13
+ used three sources instead:
14
+ 1. `node_modules/@deepseek-ai/<pkg>/lib/index.js` and `lib/types/*.js`
15
+ (implementation + JSDoc),
16
+ 2. `node_modules/@deepseek-ai/dsh-tool-cordis/lib/types/api-catalog.js`, a
17
+ generated declaration catalog (2347 entries) containing the public type
18
+ declarations as strings,
19
+ 3. focused runtime smoke tests against a fake Cordis context.
20
+ - Access path for a **profile-installed** plugin: no `@deepseek-ai/*` imports at
21
+ runtime (module resolution fails). Everything goes through the Cordis context:
22
+ `ctx.get(name)` for services and `ctx.on(name, fn, opts)` for events.
23
+
24
+ ---
25
+
26
+ ## 1. Services actually used
27
+
28
+ | Service name | Provider package | Shape |
29
+ |---|---|---|
30
+ | `sessionController` | `@deepseek-ai/dsh-api-session-controller` | class `SessionController`, `super(ctx, "sessionController", { namespace: "session" })` |
31
+ | `agents` | `@deepseek-ai/dsh-agent` | class `AgentRegistry`, `super(ctx, "agents")` |
32
+ | `agentPresets` | `@deepseek-ai/dsh-agent-preset-registry` | class `AgentPresetRegistry`, `super(ctx, "agentPresets")` |
33
+ | `agentDefaultModel` | `@deepseek-ai/dsh-agent-default-model` | injected dependency of the session controller; `currentSelection()` |
34
+ | `llm` | `@deepseek-ai/dsh-llm` | fallback catalog only |
35
+ | `approval` | `@deepseek-ai/dsh-user-approval` | not called directly; we listen on its waterfall |
36
+ | `workingDirectory` | (Host service) | `get(session)` → the session workspace root; used to contain uploads/previews |
37
+ | `workspaceRegistry` | (Host service) | `pinnedSessionIds` / `archivedSessionIds` getters, `pinSession`/`archiveSession`/… |
38
+ | `workspaceController` | (Host service) | same operations when the registry getters are absent |
39
+ | `workspaceChanges` | `dsh-workspace-changes` | `summary(sessionId, seq)` / `diff(sessionId, seq, index, signal)`; live-process only |
40
+ | `commands` | `dsh-commands` | `list(agent)` / `execute(agent, line, attachments, signal)`; live Agent required |
41
+ | `attachments` | (Host service) | `imageLimits` policy for inline images and previews |
42
+ | `userQuestions` | (Host service) | `answer(agent, callId, { answers })` for continued (timed-out) questions |
43
+
44
+ The v2 feature surface above is documented in detail in `docs/api-notes-v2.md`.
45
+
46
+ All lookups are defensive: `ctx.get(name)` returns `undefined` when the package is
47
+ not composed, and every bridge operation degrades instead of throwing.
48
+
49
+ `ctx.sessionController` is a Remote (Typert) service, but its business methods are
50
+ plain async functions and are callable from Host plugins. Two details matter:
51
+
52
+ - Several methods call `signal.throwIfAborted()` **unconditionally**, so callers
53
+ must pass an `AbortSignal`. `bridge.js` always creates one (`withSignal()`).
54
+ - Methods consult `ctx.remoteAccess.allows()`/`principalOf(ctx.invocation)`.
55
+ `remoteAccess.allows()` returns `true` "for the owner and outside a Remote
56
+ call" (`dsh-api-remote-access/lib/types/index.js`), so Host calls are never
57
+ filtered.
58
+
59
+ ---
60
+
61
+ ## 2. `ctx.sessionController` — exact signatures
62
+
63
+ From `lib/types/index.d.ts` (declaration catalog) + `lib/index.js` / `lib/types/*.js`:
64
+
65
+ ```ts
66
+ // list: cold-safe, no Agent activation, visible sessions ordered by activity
67
+ class SessionController {
68
+ async list(request: object, signal: AbortSignal): Promise<{ items: SessionSummary[] }>;
69
+ async create(request: SessionCreateRequest): Promise<{ sessionId: SessionId; agentPreset?: string }>;
70
+ async prompt(request: SessionPromptRequest, signal: AbortSignal): Promise<{ accepted: true }>;
71
+ cancel(request: { sessionId: SessionId }): Promise<{ accepted: true }>; // live agent only
72
+ async selectModel(request: { sessionId; provider; model; reasoningEffort? }): Promise<{ selected: ModelSelection }>;
73
+ modelCatalog(): Promise<ModelCatalog>;
74
+ async events(request: SessionPageRequest, signal: AbortSignal): Promise<{ cursor; records: SessionHistoryRecord[]; hasMore }>;
75
+ async state(request: { sessionId }, signal): Promise<{ cursor; active; running; queue; pendingInput }>;
76
+ async projections(request: { sessionId }, signal): Promise<{ kind; asOfSeq; values } | null>;
77
+ async resolveAgent(sessionId): Promise<{ agent: Agent } | { error: RemoteError }>;
78
+ }
79
+ ```
80
+
81
+ Key request/result types (declaration catalog):
82
+
83
+ ```ts
84
+ interface SessionCreateRequest {
85
+ readonly workspaceId?: WorkspaceId; readonly cwd?: string;
86
+ readonly sessionId?: SessionId; readonly agentPreset?: string;
87
+ }
88
+ interface SessionPromptRequest {
89
+ readonly requestId: SessionRequestId;
90
+ readonly sessionId: SessionId;
91
+ readonly mode: 'queue' | 'steer';
92
+ readonly content: readonly PromptContentPart[]; // { type:'text', text } is the text part
93
+ readonly clientTimeZone?: string;
94
+ }
95
+ interface SessionPageRequest {
96
+ readonly address: SessionAddress;
97
+ readonly throughSeq?: number; readonly beforeSeq?: number;
98
+ readonly maxMessages?: number; // default 50
99
+ readonly turnWindow?: { minMessages: number; minTurns: number };
100
+ }
101
+ ```
102
+
103
+ Notes verified in `lib/types/history/controller.js` and `lib/types/history.js`:
104
+
105
+ - `events()` returns the **newest** message-aligned page: `paginate()` walks the
106
+ log backwards from the end, cuts at `maxMessages` messages, returns
107
+ `events.slice(cut, end)` plus `hasMore = cut > 0`. This matches the mobile
108
+ "open the recent conversation" need; paging further back needs
109
+ `beforeSeq` (not exposed by PROTOCOL v1).
110
+ - `records` are `SessionHistoryRecord = { type: 'event', event: SessionWireEvent }`
111
+ where `SessionWireEvent = { type, seq, time, data, ignorable?, sourceEventSeqs?, surfaceOp? }`.
112
+ - `cancel()` reads the **attached** agent only (`ctx.agents.get`), so a cold
113
+ session rejects `session/not-found`; the bridge treats that as a no-op.
114
+ - `prompt()` deduplicates by `requestId` (checks inbox + durable log), resumes a
115
+ cold session, and returns `{ accepted: true }`. `mode` is required by the type
116
+ and defaults to queue behaviour in the implementation; the bridge sends `'queue'`.
117
+ - `create()` writes to `defaultCwd` (`process.cwd()` of the harness) when neither
118
+ `workspaceId` nor `cwd` is given. The bridge deliberately never sends `cwd`.
119
+
120
+ ---
121
+
122
+ ## 3. Session summaries and projections
123
+
124
+ `SessionSummary` (declaration catalog) — the list row:
125
+
126
+ ```ts
127
+ interface SessionSummary {
128
+ readonly agentAvailable: boolean;
129
+ readonly formatStatus?: 'current' | 'migration-required';
130
+ readonly sessionId: SessionId;
131
+ readonly updatedAt: number;
132
+ readonly running: boolean;
133
+ readonly blank: boolean;
134
+ readonly parentSessionId?: SessionId;
135
+ readonly origin?: 'subagent';
136
+ readonly cwd?: string; // never forwarded
137
+ readonly projections?: { kind: 'cached'|'sequenced'; asOfSeq: number;
138
+ values: Partial<SessionProjectionSummaryValues> };
139
+ }
140
+ ```
141
+
142
+ There is no `title`/`preset`/`model` field on the summary; they are projection
143
+ values (`@deepseek-ai/dsh-session-projection`), read from `projections.values`:
144
+
145
+ | Projection key | Wire value | Package |
146
+ |---|---|---|
147
+ | `title` | `string \| null` (latest `session/title`); `view: state => state` | `dsh-session-title` |
148
+ | `agentPreset` | `string \| null` (header preset + `agent-preset/selected`) | `dsh-agent-preset-registry` (`types/session.js`) |
149
+ | `modelSelection` | `{ lastUsed: ModelSelection\|null, next: ModelSelection\|null }` (view of pending/last-used) | `dsh-agent` (`types/model-selection.js`) |
150
+ | `titleInput`, `approvalState`, `turnBoundary`, `imageLimits` | not used; `imageLimits` is `summary: false` | — |
151
+
152
+ Cold sessions only carry projection hints when the projection cache has them, so
153
+ a cold session can legitimately have an empty `values` object. The bridge then
154
+ falls back to `projections()`/`state()` (and, for the title, the first
155
+ `user/message` in the read history page). **Title is best-effort for cold
156
+ sessions.**
157
+
158
+ `ModelSelection = { provider: string; model: string; reasoningEffort?: string }`.
159
+ The bridge sends `next ?? lastUsed`, and `{ provider, model }` only (PROTOCOL's
160
+ session frame has no effort field; the model picker frame has it).
161
+
162
+ Subagent sessions (`origin === 'subagent'`) are filtered out of `listSessions()`
163
+ and ignored by the live-event bridge: the phone must only drive ordinary
164
+ sessions. Prompt/tool events for subagents are therefore not streamed.
165
+
166
+ ---
167
+
168
+ ## 4. Durable Session events → HistoryItem
169
+
170
+ Event envelope and types come from `dsh-session/lib/types/index.js`, `surface.js`
171
+ and the declaration catalog (`SessionEventMap`); actual write sites in
172
+ `dsh-agent-loop/lib/index.js`:
173
+
174
+ ```ts
175
+ 'turn/start': { turn: number }
176
+ 'turn/end': { turn: number; reason: TurnEndReason } // {kind:'completed'|'blocked'|'error'|'aborted'|'max-tokens', error?, reason?}
177
+ 'step/start': { turn: number; step: number }
178
+ 'step/end': { turn: number; step: number }
179
+ 'user/message': UserMessage // data IS the message: {id, role:'user', content, source}
180
+ 'assistant/message': { turn; step; message: AssistantMessage;
181
+ stream: AssistantStreamRecord[]; usage?; interrupted?: true }
182
+ 'assistant/attempt': { turn; step; stream } // failed/aborted attempt, no message
183
+ 'tool/call': { turn; step; callId: ToolCallId; name: string; arguments: string /* raw JSON */ }
184
+ 'tool/result': { turn; step; message: ToolResultMessage; // message.toolCallId is the call id
185
+ error?: { name; code; reason? }; meta? }
186
+ 'session/title': { title: string; ... } // not needed: title is projected
187
+ ```
188
+
189
+ Message/content shapes (`dsh-llm/lib/types/message.js`, `assembler.js`):
190
+
191
+ ```ts
192
+ type ContentBlock =
193
+ | { type: 'text'; text: string }
194
+ | { type: 'reasoning'; text: string } // not rendered in history
195
+ | { type: 'tool-call'; id; name; arguments } // tool calls are protocol, not text
196
+ | { type: 'image' | ... }; // never forwarded
197
+
198
+ interface ToolResultMessage { role: 'tool'; source: {kind:'tool', callId};
199
+ toolCallId: ToolCallId; content: ContentBlock[];
200
+ isError?: boolean }
201
+ ```
202
+
203
+ `bridge.js` mapping (one chronological list, ids stable across reloads):
204
+
205
+ | Session event | HistoryItem |
206
+ |---|---|
207
+ | `user/message` with `data.source.kind === 'user'` | `{ id: 'seq:<seq>', kind: 'user', text: joinTextBlocks(content), ts: time }` |
208
+ | other `user/message` sinks | skipped (runtime context / model-selection notice / approval-policy notice are not human transcript) |
209
+ | `assistant/message` | `{ id: 'seq:<seq>', kind: 'assistant', text: joinTextBlocks(message.content), ts }` (empty content skipped, e.g. max-tokens step) |
210
+ | `tool/call` | `{ id: 'tool:<callId>', kind: 'tool', callId, name, title: name, argsPreview, ok: true, output: '', diff: null, durationMs: 0, ts }` |
211
+ | `tool/result` | fills the matching `tool:` item: `ok = !message.isError`, `output = joinTextBlocks(message.content) || error.message`, `durationMs = result.time - call.time`; a result with no call in the page (paging cut) creates a standalone `tool:` item |
212
+ | `turn/end` with `reason.kind === 'error'` | `{ id: 'seq:<seq>', kind: 'error', text: reason.error.message, ts }`; aborted/blocked/completed add nothing |
213
+ | `assistant/attempt`, boundaries, compaction, etc. | skipped |
214
+
215
+ Tool output and `argsPreview` are truncated (4000 / 200 chars by default).
216
+ `diff` is always `null`: no diff view is derived from session events.
217
+
218
+ ---
219
+
220
+ ## 5. Assistant token streaming
221
+
222
+ Event: `ctx.on('agent/assistant-stream', ({ agent, frame }) => …, { global: true })`.
223
+ Emitted by `AssistantStreamAttempt` in `dsh-agent-loop` via the agent's scoped
224
+ dispatcher (`this.dispatch.emit("agent/assistant-stream", { frame })`), so the
225
+ payload is `{ agent, frame }` and only a `{ global: true }` listener sees every
226
+ agent's frames.
227
+
228
+ ```ts
229
+ type AssistantStreamFrame =
230
+ | { type:'start'; attemptId; revision; turn: number; step: number }
231
+ | { type:'chunk'; attemptId; revision; index: number; time: number; chunk: StreamChunk }
232
+ | { type:'end'; attemptId; revision; index: number;
233
+ outcome: { kind:'committed'; eventType:'assistant/message'|'assistant/attempt'; seq }
234
+ | { kind:'abandoned' } };
235
+
236
+ type StreamChunk =
237
+ | { type:'text-delta'; index; text }
238
+ | { type:'reasoning-delta'; index; text }
239
+ | { type:'tool-call-delta'; index; id; name?; argumentsDelta }
240
+ | { type:'block-start'; index; blockType }
241
+ | { type:'block-end'; index; block }
242
+ | { type:'usage'; usage }
243
+ | { type:'finish'; reason; replayState? };
244
+ ```
245
+
246
+ Mapping to `onAssistant`:
247
+
248
+ - `start` → `{ sessionId, phase:'start', turn, step, text:'', reasoning:null }`
249
+ - `chunk` + `text-delta` → `{ phase:'delta', turn, step, text: chunk.text, reasoning:null }`
250
+ - `chunk` + `reasoning-delta` → `{ phase:'delta', turn, step, text:'', reasoning: chunk.text }`
251
+ - `end` → `{ phase:'end', turn, step, text:'', reasoning:null }`
252
+ - All other chunk types are ignored. `text`/`reasoning` are **incremental
253
+ fragments**, not cumulative text; the server may coalesce adjacent fragments
254
+ for the ~30 fps throttle. `turn`/`step` are taken from the `start` frame
255
+ because deltas do not carry them.
256
+
257
+ There is no Cordis event scoping surprise: `agent/assistant-stream` is an emit,
258
+ not a waterfall, so the first answer wins trivially.
259
+
260
+ ---
261
+
262
+ ## 6. Tool lifecycle
263
+
264
+ Chosen source: durable `session/event` `tool/call` / `tool/result`
265
+ (`dsh-tools/lib/types/batch.js` writes them; `dsh-agent-loop` recovery re-emits
266
+ missing results). This is preferred over `tools/pre-execute`/`tools/result`
267
+ because it carries `callId`, `name` and raw `arguments` durably and works for
268
+ every executor (native, PTC, transient tools), and it survives a reconnect
269
+ because history reproduces it.
270
+
271
+ - `tool/call` → `onTool({ sessionId, phase:'start', callId, name, title: name, argsPreview, detail })`
272
+ - `argsPreview`: compact single-line JSON (or the raw string) truncated to 200 chars.
273
+ - `detail`: shallow copy of the parsed arguments object (≤12 keys, strings
274
+ capped at 400 chars). `null` when the arguments are not a JSON object.
275
+ - `title`: there is **no tool-title service call in the durable event**. The
276
+ bridge uses the tool name as `title`; the mobile UI can localise known names.
277
+ (`ToolDefinition.presentCall`/`presentResult` produce view models for the
278
+ desktop, but they are not persisted with the event.)
279
+ - `tool/result` → `onTool({ sessionId, phase:'end', callId, ok: !message.isError,
280
+ output, durationMs, name, title })`
281
+ - `output` = text blocks of `data.message.content`, falling back to
282
+ `data.error.message`/`.reason`; truncated to 4000 chars.
283
+ - `durationMs` = result event time − call event time (both are durable
284
+ millisecond timestamps).
285
+
286
+ ---
287
+
288
+ ## 7. Approvals
289
+
290
+ Service: `@deepseek-ai/dsh-user-approval` (`super(ctx, "approval")`). The bridge
291
+ does **not** call `approval.request()`; it answers through the waterfall that the
292
+ service dispatches (`lib/types/index.js`, implementation `lib/index.js`):
293
+
294
+ ```ts
295
+ this.ctx.waterfall(scopeTarget(req.agent, req.agent), 'approval/request', req,
296
+ () => Promise.resolve('unavailable'))
297
+ ```
298
+
299
+ - Payload (`ApprovalRequestEvent`): `{ agent, toolName, callId?, reason?,
300
+ displayReason?: { en: string; [locale: string]: string }, signal? }`.
301
+ - Outcome vocabulary (`ApprovalOutcome`):
302
+ `'allowed-once' | 'rejected' | 'cancelled' | 'unavailable'`. The service
303
+ normalises rogue returns to `'unavailable'` and the **only grant is
304
+ `allowed-once`**.
305
+ - Policy: a session whose effective policy is `'never'` returns `'rejected'`
306
+ before any listener runs. A missing answerer fails closed with `'unavailable'`;
307
+ a throwing answerer is swallowed to `'unavailable'`.
308
+ - The service writes the durable `approval/asked` / `approval/decided` pair and
309
+ generates its own request id; that id is **not** in the waterfall payload, so
310
+ the bridge mints its own phone-facing `requestId` (UUID) and keeps it in a
311
+ pending map.
312
+ - Scope: the waterfall `this` is the agent scope, so the listener must be
313
+ registered as `{ global: true }` (plus `{ prepend: true }` to sit in front of
314
+ the gateway's forwarding listener). `ctx.on(...)` returns the disposer.
315
+ - Desktop answerer: `@deepseek-ai/dsh-api-remotes` forwards the `approval/request`
316
+ waterfall to connected Remote peers; `dsh-client-ui-approval` renders it in the
317
+ DSH web UI and answers `allowed-once`/`rejected`. Because the waterfall would otherwise
318
+ offer the request to both answerers, the bridge routes it **exclusively** while a phone is
319
+ connected (v15) and delegates with `next()` when no phone is connected.
320
+
321
+ Bridge behaviour (`onApprovalRequest`):
322
+
323
+ 1. If `options.hasApprovalPeers()` is supplied and returns false, delegate straight to
324
+ `next()` — an unpaired phone must never stall an approval.
325
+ 2. Otherwise emit `onApproval` and wait for the phone. The bridge does **not** call `next()`
326
+ in parallel: while a phone is connected it is the only answerer, so the desktop cannot be
327
+ left with a duplicate card whose request was already settled by the phone. The desktop
328
+ still sees the same pending list through the plugin's approval dock and can answer it.
329
+ 3. `answerApproval(requestId, 'allow'|'reject')` maps to `'allowed-once'`/`'rejected'` and
330
+ settles the promise; the first answer wins.
331
+ 4. `request.signal` abort settles `'cancelled'` and emits
332
+ `onApprovalResolved({ outcome:'cancelled' })`.
333
+ 5. `options.approvalWaitMs > 0` fails closed with `'unavailable'` after the deadline; `0`
334
+ (the default) waits indefinitely for a phone answer or turn abort.
335
+ 6. `dispose()` / last unsubscribe settles every pending approval with `'cancelled'`.
336
+
337
+ `expiresAt` is `0` in every frame: the Host has no approval deadline field, only
338
+ the tool's own timeout and the turn's abort signal.
339
+
340
+ Question requests (`user-questions/request`) use the same exclusive pattern with one extra
341
+ safety net: when **no** phone is connected at request time the bridge keeps the request
342
+ pending for `questionHandoffMs` (default 45 s) so a reconnecting phone can answer it, then
343
+ delegates to the next answerer. A connected phone is the exclusive answerer (no handoff
344
+ timer), matching approval routing.
345
+
346
+ ---
347
+
348
+ ## 8. Models
349
+
350
+ Preferred: `ctx.sessionController.modelCatalog()` (`lib/types/catalog.js`).
351
+
352
+ ```ts
353
+ interface ModelCatalog {
354
+ readonly default: ModelSelection;
355
+ readonly routableProviders: readonly string[];
356
+ readonly groups: readonly { id: string; name: string;
357
+ models: readonly { id; name; description?; reasoning?: { efforts; defaultEffort? }; badge? }[] }[];
358
+ readonly failures: readonly { id; name; message }[]; // per-provider isolation, not forwarded
359
+ }
360
+ ```
361
+
362
+ Bridge maps it to PROTOCOL:
363
+
364
+ - `catalog: groups.flatMap(g => g.models.map(m => ({ provider: g.id, model: m.id, label: m.name })))`
365
+ - `current: { provider: default.provider, model: default.model,
366
+ reasoningEffort: default.reasoningEffort ?? null }`
367
+
368
+ Fallback when no session controller: `ctx.llm.listProviders()`,
369
+ `await ctx.llm.listModels(providerId)`, `await ctx.llm.resolveModelInfo(provider, model)`
370
+ plus `ctx.agentDefaultModel.currentSelection()`.
371
+
372
+ `selectModel(sessionId, {provider, model, reasoningEffort?})` calls
373
+ `sessionController.selectModel`, which validates the model is currently routable
374
+ (`modelAvailable`), runs `resolveCallConfig`, calls `agent.model.select()` and
375
+ persists the default in the background. Unknown model → `session/model-unavailable`.
376
+
377
+ ---
378
+
379
+ ## 9. Agent presets
380
+
381
+ Service `agentPresets` (`@deepseek-ai/dsh-agent-preset-registry`), `super(ctx, "agentPresets")`.
382
+
383
+ ```ts
384
+ async list(): Promise<{ id; name?; description?; order?; broken? }[]> // sorted by order then id
385
+ get defaultId(): string // selectedDefault ?? default
386
+ presetForSession(session): string | null // 'agentPreset' projection
387
+ async select(agent: Agent, preset: string): Promise<{ id }> // blank session only
388
+ async resolve(id?): Promise<{ id; broken? }>
389
+ remoteExportList(): Promise<{ presets: (row & { isDefault: boolean })[] }>
390
+ ```
391
+
392
+ Bridge mapping: `{ presets: [{ id, title: name ?? id, description: description ?? '' }],
393
+ current: defaultId ?? null }`. `current` is the deployment default (the phone
394
+ shows the per-session preset from the session list; `preset.list` has no session
395
+ argument).
396
+
397
+ `selectPreset(sessionId, preset)` resolves the agent through
398
+ `sessionController.resolveAgent(sessionId)` (resuming a cold session) and calls
399
+ `presets.select(agent, preset)`. The registry rejects sessions whose first turn
400
+ started with `agent-preset/locked`; `not-found`/`invalid`/`locked` surface as the
401
+ protocol error envelope. A preset with a broken mount is still listed (with no
402
+ `broken` field in our wire shape).
403
+
404
+ ---
405
+
406
+ ## 10. Status
407
+
408
+ Two sources are used and both are forwarded as `onStatus({ sessionId, running })`:
409
+
410
+ - `ctx.on('session/event', (session, event))` `turn/start` → true, `turn/end` → false.
411
+ Durable and cold-safe (a resumed/replayed turn start shows running).
412
+ - `ctx.on('agent/status', ({ agent, status }))` with `AgentStatus = 'idle' | 'running'`.
413
+
414
+ A turn can run more than once per session; duplicate/coalescible frames are
415
+ expected. `server.js` should treat `session.status` as idempotent state, not as a
416
+ delta. The passive read `sessionController.state({sessionId})` gives the
417
+ authoritative snapshot (`{cursor, active, running, queue, pendingInput}`) if a
418
+ resync is ever needed.
419
+
420
+ ---
421
+
422
+ ## 11. Verified wire mapping (DSH → PROTOCOL.md)
423
+
424
+ | PROTOCOL frame | Source |
425
+ |---|---|
426
+ | `sessions` / session object | `sessionController.list()` summary + `title`/`agentPreset`/`modelSelection` projections |
427
+ | `session.opened` | session object above + `sessionController.events({maxMessages: limit})` history page |
428
+ | `history` | `events()` newest page, `mapHistory()` |
429
+ | `assistant.start/delta/end` | `agent/assistant-stream` frames |
430
+ | `tool.start/end` | `session/event` `tool/call` / `tool/result` |
431
+ | `approval.request` | `approval/request` waterfall payload (`displayReason`→`displayReason`, `callId`→`callId`, ours `requestId`, `expiresAt:0`) |
432
+ | `approval.resolved` | bridge settle path (`allowed-once`/`rejected`/`cancelled`/`unavailable`) |
433
+ | `session.status` | `turn/start`, `turn/end`, `agent/status` |
434
+ | `models` | `modelCatalog()` / `llm` fallback |
435
+ | `presets` | `agentPresets.list()` + `defaultId` |
436
+ | prompt / stop / model.select / preset.select / approval.answer | `sessionController.prompt/cancel/selectModel`, `agentPresets.select`, approval pending map |
437
+
438
+ The v2 frames (session management, queue, context, changes, commands, limits, questions and
439
+ attachments) are mapped from the sources in `docs/api-notes-v2.md`; this table covers only the
440
+ original v1 surface.
441
+
442
+ Wire-shape decisions:
443
+
444
+ - Session ids are the Harness `SessionId` (opaque `session-<uuid>` strings).
445
+ - `updatedAt`/`ts` are the Harness millisecond timestamps.
446
+ - History ids are `seq:<n>` for messages and `tool:<callId>` for tool cards, so
447
+ the SPA's list keys are stable across reconnects.
448
+ - The bridge strips `cwd` and any other filesystem field from every payload.
449
+ Error messages are path-redacted and capped at 600 chars. Tool arguments and
450
+ tool output are **not** path-redacted by default (the tool card needs them);
451
+ `createBridge(ctx, { redactPaths: true })` enables redaction for deployments
452
+ that require it.
453
+
454
+ ---
455
+
456
+ ## 12. Error / failure contract
457
+
458
+ All bridge methods resolve; none reject.
459
+
460
+ - Data operations return empty data on failure: `listSessions → []`,
461
+ `history → []`, `listModels → {catalog:[],current:null}`,
462
+ `listPresets → {presets:[],current:null}`.
463
+ - `openSession` returns either `{ session, history }` or
464
+ `{ ok: false, error: '<message>', errorCode: 'not-found'|'bad-request'|'internal' }`.
465
+ - `createSession` returns a session object with `id`, or the same error envelope.
466
+ - `prompt`/`cancel`/`selectModel`/`selectPreset` resolve `undefined` on success
467
+ and the error envelope on failure. `server.js`'s `callBridge()` already treats
468
+ any object with `ok === false` as a thrown failure (`new Error(value.error)`),
469
+ so `error` is a **string**; the protocol code rides beside it in `errorCode`.
470
+ - `answerApproval` returns `false` for unknown/expired ids.
471
+ - `answerQuestion` returns `true`/`false` for waterfall questions, an `{ ok:false }` envelope
472
+ on bad input, and delegates to `ctx.userQuestions.answer` for a continued question.
473
+ - Error `code` is one of the protocol codes: `bad-request`, `not-found`, `internal`,
474
+ `unavailable`, `forbidden`, `not-live` (mapped from RemoteError codes such as
475
+ `session/not-found`, `agent-preset/locked`, `session/model-unavailable`, and from bridge guards such as live-session command validation and cold-session checks).
476
+
477
+ ---
478
+
479
+ ## 13. Uncertainties / fallbacks (read before touching bridge.js)
480
+
481
+ 1. **`.d.ts` are not shipped** in this install (see header). Signatures above were
482
+ reconstructed from the compiled `lib/types/*.js` and the
483
+ `dsh-tool-cordis` declaration catalog; they match the code paths actually
484
+ executed in the smoke test, but a future Harness build may rename a method
485
+ without changing the packages list.
486
+ 2. **Approval routing is exclusive to the connected phone (v15).** Earlier v1 builds called
487
+ `next()` concurrently and raced the desktop answerer, which left a duplicate desktop
488
+ prompt that could only be dismissed by answering it again. The bridge now delegates
489
+ `next()` only when no phone is connected and otherwise waits for the phone; the desktop
490
+ plugin dock polls the same pending list, so either surface can answer and the first one
491
+ wins. There is still no Host API to cancel a specific pending Remote prompt in
492
+ 0.2.2-rc.1, which is why the exclusive routing matters.
493
+ 3. **Approval id mismatch.** The durable `approval/asked` id is generated inside
494
+ `ApprovalService.request` and is not part of the waterfall payload, so the
495
+ phone-facing `requestId` is bridge-owned. Nothing in the phone protocol
496
+ correlates to the durable audit id; this is intentional.
497
+ 4. **Approval timeout semantics.** `approvalWaitMs` defaults to 0 (wait). With no
498
+ desktop connected and the phone gone, an approval stays pending until the
499
+ turn is aborted. `server.js` should pass `hasApprovalPeers: () => <connected
500
+ device count> > 0` and may set `approvalWaitMs` to fail closed.
501
+ 5. **`onAssistant` delta text is incremental**, not cumulative. The server's
502
+ 30 fps coalescing must concatenate fragments. Reasoning arrives in
503
+ `reasoning`, text in `text`, never both in one frame.
504
+ 6. **Live turn errors are not a first-class event.** PROTOCOL v1 has no live
505
+ error frame. The bridge closes an open assistant bubble on `agent/error` and
506
+ relies on the next history read for the `kind:'error'` item (from
507
+ `turn/end.reason.kind === 'error'`).
508
+ 7. **Tool titles are the tool names.** The durable `tool/call` event has no
509
+ presentation title; deriving one would need the (non-persisted) tool
510
+ definition's `presentCall` view. The SPA is expected to localise known names.
511
+ 8. **Cold-session titles can be empty.** `list()` serves title from the
512
+ projection cache; a cold, uncached session may have no `values.title`. The
513
+ bridge leaves `title: ''` in the list and only recovers a title heuristic in
514
+ `openSession` (from projections or the first user message).
515
+ 9. **`selectPreset` may resume a cold session.** `resolveAgent()` activates an
516
+ agent to call `presets.select()`; selecting a preset on a started session
517
+ therefore fails with `agent-preset/locked` (mapped to `bad-request`). The
518
+ bridge does not pre-check blankness.
519
+ 10. **`cancel` cannot stop a cold session** (`session/not-found`), and a cold
520
+ session has no agent to cancel; the bridge returns success.
521
+ 11. **`modelCatalog()` can report per-provider failures** (`failures[]`). They
522
+ are swallowed: the phone only sees routable groups. If a provider's models
523
+ disappear from the picker, the cause is in `failures`, not in the bridge.
524
+ 12. **`redactPaths` is off by default.** If the deployment treats tool arguments
525
+ as secret, pass `redactPaths: true`; history error text and operation errors
526
+ are always path-redacted regardless.
527
+ 13. **Subagent sessions are hidden.** `listSessions` filters
528
+ `origin === 'subagent'`; prompt/tool/stream events for subagent agents are
529
+ ignored. Driving a subagent's own session from the phone is not supported by
530
+ v1.
531
+ 14. **Fallback paths are best-effort.** `prompt` via `agent.followup()` with a
532
+ hand-built message (no `@deepseek-ai/dsh-llm` `createUserMessage`) may be
533
+ rejected by the loop's frozen-message expectations; it only runs when
534
+ `sessionController` is absent. `listModels` falls back to `ctx.llm`.
535
+ 15. **No pagination beyond the newest page.** PROTOCOL v1's `history.load` is
536
+ `limit` only; `sessionController.events` supports `beforeSeq`/`throughSeq`
537
+ when v2 needs "load older".
538
+
539
+ ---
540
+
541
+ ## 14. What `server.js` must tolerate
542
+
543
+ - Handlers are optional and may be added/removed via `subscribe()` more than
544
+ once; multiple subscriptions all receive events. Unsubscribing the last one
545
+ removes the bridge's Cordis listeners and cancels pending approvals.
546
+ - `onStatus` may deliver the same `running` value twice (turn boundary +
547
+ agent status). Treat it as idempotent.
548
+ - `onAssistant` `phase:'end'` may arrive without a preceding `start` after a
549
+ reconnect; do not assume a strict start/end pairing.
550
+ - `onTool` `phase:'end'` can arrive without a matching `start` if the bridge was
551
+ created mid-turn (or after a server restart): `name`/`title` will be `''`.
552
+ - Approval `requestId` values are bridge-owned; never parse them.
553
+ - Calls to `prompt`/`selectModel`/etc. may return the `{ok:false,error}`
554
+ envelope; check it instead of assuming `undefined`/success.
555
+ - `dispose()` is final: after it, `subscribe()` is a no-op and every data call
556
+ still resolves (empty/error).
557
+
558
+ ---
559
+
560
+ ## 15. Method → Host mapping (quick reference)
561
+
562
+ | `createBridge()` method | Host calls |
563
+ |---|---|
564
+ | `listSessions()` | `sessionController.list({}, signal)`; fallback `agents.list()` |
565
+ | `openSession(id)` | `sessionController.events({address:{kind:'session',id},maxMessages:50})` + `list()` / `projections()` / `state()` |
566
+ | `createSession({preset})` | `sessionController.create({agentPreset?})` |
567
+ | `history(id,{limit})` | `sessionController.events({..., maxMessages:limit})` |
568
+ | `prompt(id,text,requestId)` | `sessionController.prompt({sessionId,requestId,mode:'queue',content:[{type:'text',text}]}, signal)` |
569
+ | `cancel(id)` | `sessionController.cancel({sessionId})`; fallback `agent.cancel({kind:'user'})` |
570
+ | `listModels()` | `sessionController.modelCatalog()`; fallback `llm.listProviders/listModels/resolveModelInfo` + `agentDefaultModel.currentSelection()` |
571
+ | `selectModel(id, sel)` | `sessionController.selectModel({sessionId,provider,model,reasoningEffort?})`; fallback `agent.model.select()` |
572
+ | `listPresets()` | `agentPresets.list()` + `agentPresets.defaultId` |
573
+ | `selectPreset(id,preset)` | `sessionController.resolveAgent(id)` then `agentPresets.select(agent,preset)` |
574
+ | `answerApproval(id,decision)` | pending map → waterfall answer (`allowed-once`/`rejected`) |
575
+ | `answerQuestion({requestId?,sessionId?,callId?,answers})` | pending question map, or `ctx.userQuestions.answer(agent, callId, {answers})` |
576
+ | `subscribe(handlers)` | `ctx.on('agent/assistant-stream'|'session/event'|'agent/status'|'agent/error'|'approval/request'|'user-questions/request', {global:true})` |
577
+ | `dispose()` | dispose listeners, settle pending approvals/questions, clear maps |
578
+
579
+ The v2 surface (`createSession`, `renameSession`, `forkSession`, `searchSessions`,
580
+ `setSessionPinned/Archived`, `listQueue`/`updateQueue`, `contextFor`, `changesList/Diff`,
581
+ `listCommands`/`executeCommand`, `saveUpload`/`readUpload`, `imageLimits`, `listModels`,
582
+ `selectModel`, `listPresets`, `selectPreset`) is documented method-by-method in
583
+ `docs/api-notes-v2.md`.
Binary file