@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.
package/bridge.js ADDED
@@ -0,0 +1,3167 @@
1
+ import { mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises'
2
+ import { basename, extname, join, resolve, sep } from 'node:path'
3
+
4
+ const PREVIEW_MEDIA_TYPES = {
5
+ '.png': 'image/png',
6
+ '.jpg': 'image/jpeg',
7
+ '.jpeg': 'image/jpeg',
8
+ '.webp': 'image/webp',
9
+ '.gif': 'image/gif',
10
+ }
11
+ const MAX_PREVIEW_BYTES = 25 * 1024 * 1024
12
+ /** Path-reference block for non-image uploads (and legacy messages). */
13
+ const ATTACHMENT_BLOCK_MARKER = "\n\nAttached files from the user's phone (read them with your file tools; images can be opened with read_image):\n"
14
+ /** Block listing images that are also sent as real inline image parts. */
15
+ const IMAGE_ATTACHMENT_BLOCK_MARKER = "\n\nAttached images from the user's phone (shown inline in this message; already visible to you — no tool call needed):\n"
16
+ /** One attachment line inside either block: `- path (name) [mediaType]`. */
17
+ const ATTACHMENT_LINE = /^- (.*?)(?: \(([^()]*)\))? \[([^\]]+)\](?: — .*)?$/
18
+ /** Media types we can inline as image parts (must match a previewable extension). */
19
+ const INLINE_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
20
+ /** Defensive per-message cap, independent of the deployment's attachment limits. */
21
+ const MAX_INLINE_IMAGES = 4
22
+ /** Defensive per-image cap (5 MiB), further clamped by the attachment service. */
23
+ const MAX_INLINE_IMAGE_BYTES = 5 * 1024 * 1024
24
+ /** Bounded memory for approval-card call context (oldest evicted first). */
25
+ const MAX_APPROVAL_CONTEXTS = 200
26
+ /** Bound for the approval card's argument preview. */
27
+ const MAX_APPROVAL_PREVIEW_CHARS = 600
28
+ /** Keys whose values are never cached or shown on an approval card. */
29
+ const SECRET_ARG_KEY = /(pass(word|phrase)?|secret|token|api[-_]?key|credential|authorization|cookie|private[-_]?key|session[-_]?key|access[-_]?key|bearer)/i
30
+ /** Tools whose primary argument is a shell command. */
31
+ const SHELL_TOOL_NAMES = new Set(['pwsh', 'powershell', 'bash', 'sh', 'shell', 'terminal', 'exec', 'run_command', 'command', 'process'])
32
+ /** Tools that create or overwrite a file. */
33
+ const WRITE_TOOL_NAMES = new Set(['write', 'write_file', 'create_file', 'fs_write', 'file_write', 'save_file'])
34
+ /** Tools that patch/edit an existing file. */
35
+ const EDIT_TOOL_NAMES = new Set(['edit', 'edit_file', 'apply_patch', 'str_replace_editor', 'patch', 'replace', 'replace_string'])
36
+ /** Argument keys that may name a file path. */
37
+ const PATH_ARG_KEYS = ['path', 'file_path', 'filePath', 'filename', 'file', 'target', 'notebook_path']
38
+ /** Argument keys that carry a shell command. */
39
+ const COMMAND_ARG_KEYS = ['command', 'cmd', 'script', 'input', 'code', 'commandLine']
40
+ /** Argument key pairs that carry an edit's before/after text. */
41
+ const EDIT_ARG_PAIRS = [
42
+ ['old_string', 'new_string'],
43
+ ['oldString', 'newString'],
44
+ ['old_str', 'new_str'],
45
+ ['oldText', 'newText'],
46
+ ['old_text', 'new_text'],
47
+ ['old', 'new'],
48
+ ]
49
+ /**
50
+ * Host commands the phone must not offer even though the agent's registry lists
51
+ * them.
52
+ *
53
+ * - `export`: only records a lifecycle on the Host; the desktop browser then
54
+ * downloads the ZIP from a Host-only route the phone server cannot proxy.
55
+ * - `permission`: switches the session's sandbox/approval preset. One preset is
56
+ * `danger-full-access` (no sandbox, approvals never asked), so offering this
57
+ * from the phone would let a paired device disable the approval gate it is
58
+ * supposed to answer — including a device the desktop marked as not allowed to
59
+ * answer approvals. Sandbox policy stays a desktop decision.
60
+ */
61
+ const PHONE_HIDDEN_COMMANDS = new Set(['export', 'permission'])
62
+ /**
63
+ * First-party definitions hidden by identity as well, so renaming the command
64
+ * (or a localized alias) cannot re-expose a policy-changing surface.
65
+ */
66
+ const PHONE_HIDDEN_COMMAND_DEFINITION_IDS = new Set(['@deepseek-ai/dsh-permission-presets'])
67
+ /** Maximum changed-file entries the phone renders per change event. */
68
+ const MAX_CHANGE_FILES = 200
69
+ /** Maximum diff lines returned to the phone (the Host's own cap is larger). */
70
+ const MAX_DIFF_LINES = 800
71
+ /** Commands can run a compaction/model pass; give them enough time. */
72
+ const COMMAND_TIMEOUT_MS = 300000
73
+
74
+ /** Return a finite number or null (projections omit fields instead of zeroing them). */
75
+ function finiteOrNull(value) {
76
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
77
+ }
78
+
79
+ /** Object check usable at module scope (the bridge's own helper lives inside the factory). */
80
+ function asPlainObject(value) {
81
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
82
+ }
83
+
84
+ /**
85
+ * Map the Host's `contextPressure` / `tokenUsage` projections to the phone's
86
+ * context-meter shape. `usedTokens` prefers the projected prompt size because
87
+ * `pressureTokens` only advances after the next request reports usage.
88
+ */
89
+ function summarizeContextValues(values) {
90
+ const pressure = asPlainObject(values?.contextPressure) ? values.contextPressure : {}
91
+ const usage = asPlainObject(values?.tokenUsage) ? values.tokenUsage : null
92
+ const pressureTokens = finiteOrNull(pressure.pressureTokens)
93
+ const projectedTokens = finiteOrNull(pressure.projectedTokens)
94
+ const contextWindow = finiteOrNull(pressure.contextWindow)
95
+ const usedTokens = projectedTokens ?? pressureTokens ?? null
96
+ return {
97
+ usedTokens,
98
+ pressureTokens,
99
+ projectedTokens,
100
+ contextWindow,
101
+ basis: usedTokens === null ? 'unknown' : pressureTokens === null ? 'estimated' : 'usage',
102
+ tokenUsage: usage === null ? null : {
103
+ inputTokens: finiteOrNull(usage.inputTokens),
104
+ outputTokens: finiteOrNull(usage.outputTokens),
105
+ totalTokens: finiteOrNull(usage.totalTokens),
106
+ reasoningTokens: finiteOrNull(usage.reasoningTokens),
107
+ },
108
+ }
109
+ }
110
+
111
+
112
+ /**
113
+ * Turn a Host file path into something safe to show on the phone: relative to the
114
+ * session directory when possible, otherwise just the basename. Never a drive
115
+ * letter, absolute path or home-directory prefix.
116
+ */
117
+ function phonePath(value, cwd) {
118
+ if (typeof value !== 'string' || value.length === 0) return ''
119
+ let path = value.replace(/\\/g, '/')
120
+ const base = typeof cwd === 'string' ? cwd.replace(/\\/g, '/').replace(/\/+$/, '') : ''
121
+ if (base.length > 0) {
122
+ if (path === base) return ''
123
+ if (path.startsWith(`${base}/`)) return path.slice(base.length + 1)
124
+ }
125
+ if (path.startsWith('~/')) return path.slice(2)
126
+ if (path === '~') return ''
127
+ if (/^[A-Za-z]:\//.test(path) || path.startsWith('/')) {
128
+ const parts = path.split('/').filter((part) => part.length > 0)
129
+ return parts.length <= 2 ? parts.join('/') : parts.slice(-2).join('/')
130
+ }
131
+ return path
132
+ }
133
+
134
+ /**
135
+ * dsh-remote-mobile — Host bridge to the DeepSeek Harness runtime.
136
+ *
137
+ * The bridge is the only place that knows DSH's Host vocabulary. It maps the
138
+ * Harness services and Cordis events onto the small, transport-agnostic surface
139
+ * declared in `PROTOCOL.md`; `server.js` owns HTTP/WS and never touches DSH.
140
+ *
141
+ * Design constraints (see `docs/api-notes.md` for the verified details):
142
+ * - Plain ESM, zero dependencies, no `@deepseek-ai/*` imports. The plugin is
143
+ * profile-installed and cannot resolve Harness packages at runtime, so every
144
+ * capability is reached through the Cordis context (`ctx.get(name)`) and the
145
+ * event bus (`ctx.on(name, fn, opts)`).
146
+ * - No top-level side effects: everything happens inside `createBridge()`.
147
+ * - Every returned method resolves and never rejects. Operations that return
148
+ * data degrade to empty data on failure; operations that would normally be
149
+ * `void` resolve `undefined` on success and `{ ok: false, error }` on
150
+ * failure. `answerApproval()` returns a boolean. `server.js` can therefore
151
+ * treat any object carrying `ok === false` as an error envelope.
152
+ * - Nothing Host-internal leaks to the phone: session payloads omit `cwd`,
153
+ * absolute paths are redacted from error text, and tool output is truncated.
154
+ *
155
+ * Verified against DeepSeek Harness 0.2.2-rc.1.
156
+ */
157
+
158
+ /** Default bound for a tool output string sent to the phone. */
159
+ const MAX_OUTPUT_CHARS = 4000;
160
+ /** Default bound for `argsPreview`. */
161
+ const MAX_ARGS_PREVIEW_CHARS = 200;
162
+ /** Default bound for a tool `detail` string value. */
163
+ const MAX_DETAIL_STRING_CHARS = 400;
164
+ /** Default history page size (in assistant/user messages). */
165
+ const DEFAULT_HISTORY_LIMIT = 50;
166
+ /** Default per-operation timeout for Host service calls. */
167
+ const DEFAULT_TIMEOUT_MS = 15000;
168
+ /** Timeout used for cold history reads, which may hit the persistence layer. */
169
+ const HISTORY_TIMEOUT_MS = 30000;
170
+ /** Timeout used for prompt admission (attachment scan, agent resume). */
171
+ const PROMPT_TIMEOUT_MS = 30000;
172
+ /** Bounded memory for tool cards waiting for their result (oldest evicted first). */
173
+ const MAX_TOOL_STARTS = 500;
174
+ /** Recognised approval outcomes, matching dsh-user-approval. */
175
+ const APPROVAL_OUTCOMES = new Set(['allowed-once', 'rejected', 'cancelled', 'unavailable']);
176
+
177
+ /**
178
+ * Create the Host bridge.
179
+ *
180
+ * @param {object} ctx - Cordis Host context of the owning plugin.
181
+ * @param {object} [options] - bridge tuning, all optional.
182
+ * @param {() => boolean} [options.hasApprovalPeers] - return true when at least
183
+ * one mobile client is connected. When supplied and false, approval requests
184
+ * are passed straight to the next waterfall listener (the desktop answerer),
185
+ * so an unpaired/closed phone never stalls an approval.
186
+ * @param {() => boolean} [options.hasQuestionPeers] - same signal for question
187
+ * requests; falls back to `hasApprovalPeers` when omitted.
188
+ * @param {number} [options.questionHandoffMs=45000] - how long a question waits
189
+ * for a phone to (re)connect before it is handed to the desktop chain; 0
190
+ * disables the handoff.
191
+ * @param {number} [options.approvalWaitMs=0] - 0 waits for a phone answer (or
192
+ * turn abort) indefinitely; > 0 fails closed with `unavailable` after the
193
+ * deadline.
194
+ * @param {number} [options.timeoutMs] - per-operation Host-call timeout.
195
+ * @param {number} [options.maxOutputChars] - tool output truncation.
196
+ * @param {number} [options.maxArgsPreviewChars] - arguments preview truncation.
197
+ * @param {boolean} [options.redactPaths=false] - also mask absolute paths in
198
+ * tool arguments/output. Off by default: the phone is a paired device of the
199
+ * same user and the tool card is useless without its arguments.
200
+ * @returns {object} the bridge surface documented in `PROTOCOL.md`.
201
+ */
202
+ export function createBridge(ctx, options = {}) {
203
+ const opts = options && typeof options === 'object' ? options : {};
204
+ const log = createLogger(ctx);
205
+ const handlers = new Set();
206
+ const attempts = new Map(); // sessionId -> { attemptId, turn, step }
207
+ const toolStarts = new Map(); // callId -> { sessionId, name, time }
208
+ // Bounded approval-card context, keyed by tool call id. Populated when the
209
+ // bridge sees `tool/call`, consumed (or not) when an approval asks for it.
210
+ const approvalContexts = new Map(); // callId -> { argsPreview, argsKind, detail }
211
+ const pendingApprovals = new Map(); // bridge requestId -> { sessionId, settle }
212
+ const pendingQuestions = new Map(); // bridge requestId -> { sessionId, callId, questions, answer }
213
+ let listenerDisposers = null;
214
+ let disposed = false;
215
+ let fallbackIdCounter = 0;
216
+
217
+ const timeoutMs = positiveNumber(opts.timeoutMs, DEFAULT_TIMEOUT_MS);
218
+ const maxOutputChars = positiveNumber(opts.maxOutputChars, MAX_OUTPUT_CHARS);
219
+ const maxArgsPreviewChars = positiveNumber(opts.maxArgsPreviewChars, MAX_ARGS_PREVIEW_CHARS);
220
+ const redactPaths = opts.redactPaths === true;
221
+
222
+ // ---------------------------------------------------------------------------
223
+ // Infrastructure helpers
224
+ // ---------------------------------------------------------------------------
225
+
226
+ /** Look up an optional Cordis service without throwing. */
227
+ function service(name) {
228
+ try {
229
+ if (typeof ctx?.get === 'function') return ctx.get(name);
230
+ return ctx?.[name];
231
+ } catch (error) {
232
+ log.warn(`service lookup for "${name}" failed: ${errorMessage(error)}`);
233
+ return undefined;
234
+ }
235
+ }
236
+
237
+ /** Return the current time in ms; never throws. */
238
+ function now() {
239
+ return Date.now();
240
+ }
241
+
242
+ /** Generate an opaque id for bridge-owned request ids. */
243
+ function newId() {
244
+ try {
245
+ const crypto = globalThis.crypto;
246
+ if (crypto && typeof crypto.randomUUID === 'function') return crypto.randomUUID();
247
+ } catch {
248
+ // fall through to the counter
249
+ }
250
+ fallbackIdCounter += 1;
251
+ return `rm-${now().toString(36)}-${fallbackIdCounter}`;
252
+ }
253
+
254
+ /**
255
+ * Run one Host operation with a short-lived AbortSignal.
256
+ *
257
+ * Several `sessionController` methods call `signal.throwIfAborted()`
258
+ * unconditionally, so a real (or signal-shaped) value is required. The
259
+ * signal is never aborted on success; the timer only guards a wedged read.
260
+ */
261
+ async function withSignal(operation, timeout) {
262
+ let controller;
263
+ let timer = null;
264
+ let signal;
265
+ try {
266
+ controller = typeof AbortController === 'function' ? new AbortController() : undefined;
267
+ } catch {
268
+ controller = undefined;
269
+ }
270
+ if (controller !== undefined) {
271
+ signal = controller.signal;
272
+ const limit = positiveNumber(timeout, timeoutMs);
273
+ if (limit > 0) {
274
+ timer = setTimeout(() => {
275
+ try {
276
+ controller.abort(new Error('bridge operation timed out'));
277
+ } catch {
278
+ // abort() rarely throws; ignore
279
+ }
280
+ }, limit);
281
+ }
282
+ } else {
283
+ // Minimal duck-typed signal for exotic embeddings.
284
+ signal = {
285
+ aborted: false,
286
+ reason: undefined,
287
+ throwIfAborted() {},
288
+ addEventListener() {},
289
+ removeEventListener() {},
290
+ };
291
+ }
292
+ try {
293
+ return await operation(signal);
294
+ } finally {
295
+ if (timer !== null) clearTimeout(timer);
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Build the `{ ok: false, error }` envelope understood by server.js.
301
+ *
302
+ * `server.js` does `throw new Error(value.error)`, so `error` is the human
303
+ * message string; the protocol code travels beside it in `errorCode`.
304
+ */
305
+ function failure(error, fallbackCode) {
306
+ const described = describeError(error, fallbackCode);
307
+ return { ok: false, error: described.message, errorCode: described.code };
308
+ }
309
+
310
+ /** Map a thrown value onto the protocol's small error vocabulary. */
311
+ function describeError(error, fallbackCode) {
312
+ const code = errorCode(error);
313
+ let mapped = typeof fallbackCode === 'string' ? fallbackCode : 'internal';
314
+ if (code !== undefined) {
315
+ if (code.endsWith('not-found') || code === 'SESSION_QUERY_SESSION_NOT_FOUND') mapped = 'not-found';
316
+ else if (/(bad-request|invalid|locked|conflict|unavailable|required|unsupported|busy|steer|migration|fork|title)/.test(code)) mapped = 'bad-request';
317
+ else if (code === 'gateway/cancelled') mapped = 'bad-request';
318
+ else mapped = 'internal';
319
+ } else if (error instanceof Error && /not found/i.test(error.message)) {
320
+ mapped = 'not-found';
321
+ }
322
+ return { code: mapped, message: sanitize(errorMessage(error)) };
323
+ }
324
+
325
+ function errorCode(error) {
326
+ if (error && typeof error === 'object' && typeof error.code === 'string') return error.code;
327
+ const nested = error && typeof error === 'object' ? error.cause : undefined;
328
+ if (nested && typeof nested === 'object' && typeof nested.code === 'string') return nested.code;
329
+ return undefined;
330
+ }
331
+
332
+ function errorMessage(error) {
333
+ if (typeof error === 'string') return error;
334
+ if (error instanceof Error) return error.message || error.name || 'error';
335
+ if (error && typeof error === 'object' && typeof error.message === 'string') return error.message;
336
+ const text = String(error ?? 'unknown error');
337
+ return text === '[object Object]' ? 'unknown error' : text;
338
+ }
339
+
340
+ /**
341
+ * Remove anything that looks like a Host filesystem path and bound the text.
342
+ * Errors from Harness services routinely embed absolute paths.
343
+ */
344
+ function sanitize(value) {
345
+ let text = String(value ?? '');
346
+ try {
347
+ text = text.replace(/[A-Za-z]:\\[^\s"'`<>|]+/g, '<path>');
348
+ text = text.replace(/(^|[\s("'`])\/(?:[^\s"'`<>|/]+\/)+[^\s"'`<>|)]+/g, '$1<path>');
349
+ } catch {
350
+ // pathological input: keep the original text
351
+ }
352
+ if (text.length > 600) text = `${text.slice(0, 599)}…`;
353
+ return text;
354
+ }
355
+
356
+ function truncate(value, maximum) {
357
+ const text = typeof value === 'string' ? value : String(value ?? '');
358
+ if (text.length <= maximum) return text;
359
+ return `${text.slice(0, Math.max(0, maximum - 1))}…`;
360
+ }
361
+
362
+ function positiveNumber(value, fallback) {
363
+ const parsed = Number(value);
364
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
365
+ }
366
+
367
+ function clampLimit(value) {
368
+ const parsed = Number(value);
369
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) return DEFAULT_HISTORY_LIMIT;
370
+ return Math.min(parsed, 500);
371
+ }
372
+
373
+ function isSessionId(value) {
374
+ return typeof value === 'string' && value.length > 0 && value.length <= 512;
375
+ }
376
+
377
+ function isPlainObject(value) {
378
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
379
+ }
380
+
381
+ /** Best-effort JSON parse for tool arguments. */
382
+ function parseJson(raw) {
383
+ if (typeof raw !== 'string' || raw.length === 0) return undefined;
384
+ try {
385
+ return JSON.parse(raw);
386
+ } catch {
387
+ return undefined;
388
+ }
389
+ }
390
+
391
+ /** Join the text blocks of a message content array. */
392
+ function joinTextBlocks(content) {
393
+ if (!Array.isArray(content)) return '';
394
+ const parts = [];
395
+ for (const block of content) {
396
+ if (!isPlainObject(block)) continue;
397
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text);
398
+ }
399
+ return parts.join('');
400
+ }
401
+
402
+ /** Build a short, single-line preview of raw/parsed tool arguments. */
403
+ function previewArgs(raw, parsed) {
404
+ let text = raw;
405
+ if (parsed !== undefined) {
406
+ try {
407
+ text = JSON.stringify(parsed);
408
+ } catch {
409
+ text = raw;
410
+ }
411
+ }
412
+ text = typeof text === 'string' ? text : '';
413
+ if (redactPaths) text = sanitize(text);
414
+ return truncate(text.replace(/\s+/g, ' ').trim(), maxArgsPreviewChars);
415
+ }
416
+
417
+ /** Build the bounded `detail` object for a tool card. */
418
+ function detailFromArgs(parsed) {
419
+ if (!isPlainObject(parsed)) return null;
420
+ const out = {};
421
+ let count = 0;
422
+ for (const key of Object.keys(parsed)) {
423
+ if (count >= 12) break;
424
+ const value = parsed[key];
425
+ if (typeof value === 'string') {
426
+ out[key] = truncate(redactPaths ? sanitize(value) : value, MAX_DETAIL_STRING_CHARS);
427
+ } else if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
428
+ out[key] = value;
429
+ } else if (Array.isArray(value)) {
430
+ out[key] = value.slice(0, 8).map((item) => {
431
+ if (typeof item === 'string') return truncate(redactPaths ? sanitize(item) : item, 120);
432
+ if (typeof item === 'number' || typeof item === 'boolean' || item === null) return item;
433
+ return null;
434
+ });
435
+ } else if (isPlainObject(value)) {
436
+ try {
437
+ const text = JSON.stringify(value);
438
+ out[key] = truncate(redactPaths ? sanitize(text) : text, 300);
439
+ } catch {
440
+ out[key] = null;
441
+ }
442
+ }
443
+ count += 1;
444
+ }
445
+ return out;
446
+ }
447
+
448
+ /** Scrub secret-looking values from parsed tool arguments (never logged). */
449
+ function scrubArgumentValue(value, depth = 0) {
450
+ if (depth > 3 || value === undefined) return undefined;
451
+ if (Array.isArray(value)) return value.slice(0, 20).map((item) => scrubArgumentValue(item, depth + 1));
452
+ if (isPlainObject(value)) {
453
+ const out = {};
454
+ for (const [key, child] of Object.entries(value)) {
455
+ // Refuse to cache values whose key looks like a credential.
456
+ if (SECRET_ARG_KEY.test(key)) continue;
457
+ const scrubbed = scrubArgumentValue(child, depth + 1);
458
+ if (scrubbed !== undefined) out[key] = scrubbed;
459
+ }
460
+ return out;
461
+ }
462
+ if (typeof value === 'string') return truncate(value, 300);
463
+ if (typeof value === 'number' || typeof value === 'boolean' || value === null) return value;
464
+ return undefined;
465
+ }
466
+
467
+ /** Redact secret-looking JSON values when the raw argument string did not parse. */
468
+ function scrubRawArguments(raw) {
469
+ return String(raw ?? '').replace(/("([^"\\]*)"\s*:\s*)"([^"\\]*)"/g, (match, prefix, key) => (
470
+ SECRET_ARG_KEY.test(key) ? `${prefix}"…"` : match
471
+ ));
472
+ }
473
+
474
+ /** Read the first non-empty string value for one of the given argument keys. */
475
+ function firstStringArg(source, keys) {
476
+ if (!isPlainObject(source)) return undefined;
477
+ for (const key of keys) {
478
+ const value = source[key];
479
+ if (typeof value === 'string' && value.length > 0) return value;
480
+ }
481
+ return undefined;
482
+ }
483
+
484
+ /** Map one tool call to its bounded approval-card context (or null). */
485
+ function describeApprovalContext(name, rawArgs, parsed) {
486
+ const toolName = typeof name === 'string' ? name.toLowerCase() : '';
487
+ const source = isPlainObject(parsed) ? parsed : undefined;
488
+ const path = firstStringArg(source, PATH_ARG_KEYS);
489
+ const isEdit = EDIT_TOOL_NAMES.has(toolName)
490
+ || EDIT_ARG_PAIRS.some(([oldKey, newKey]) => (
491
+ firstStringArg(source, [oldKey]) !== undefined && firstStringArg(source, [newKey]) !== undefined
492
+ ));
493
+ if (isEdit) {
494
+ const pair = EDIT_ARG_PAIRS.find(([oldKey, newKey]) => (
495
+ firstStringArg(source, [oldKey]) !== undefined && firstStringArg(source, [newKey]) !== undefined
496
+ ));
497
+ const oldText = pair === undefined ? '' : firstStringArg(source, [pair[0]]) ?? '';
498
+ const newText = pair === undefined ? '' : firstStringArg(source, [pair[1]]) ?? '';
499
+ const diffHead = [
500
+ oldText.length > 0 ? `- ${truncate(oldText.replace(/\s+/g, ' ').trim(), 200)}` : '',
501
+ newText.length > 0 ? `+ ${truncate(newText.replace(/\s+/g, ' ').trim(), 200)}` : '',
502
+ ].filter(Boolean).join('\n');
503
+ const previewParts = [path ?? 'edit', diffHead].filter((part) => part.length > 0);
504
+ return {
505
+ argsPreview: truncate(previewParts.join('\n'), MAX_APPROVAL_PREVIEW_CHARS),
506
+ argsKind: 'edit',
507
+ detail: { kind: 'edit', ...(path === undefined ? {} : { path }) },
508
+ };
509
+ }
510
+ if (WRITE_TOOL_NAMES.has(toolName)) {
511
+ if (path === undefined) return null;
512
+ return {
513
+ argsPreview: truncate(path, MAX_APPROVAL_PREVIEW_CHARS),
514
+ argsKind: 'write',
515
+ detail: { kind: 'write', path },
516
+ };
517
+ }
518
+ const isShell = SHELL_TOOL_NAMES.has(toolName) || firstStringArg(source, COMMAND_ARG_KEYS) !== undefined;
519
+ if (isShell) {
520
+ const command = firstStringArg(source, COMMAND_ARG_KEYS);
521
+ if (command !== undefined) {
522
+ return {
523
+ argsPreview: truncate(command.replace(/\r\n?/g, '\n'), MAX_APPROVAL_PREVIEW_CHARS),
524
+ argsKind: 'command',
525
+ detail: { kind: 'command' },
526
+ };
527
+ }
528
+ }
529
+ // Generic fallback: scrubbed argument JSON, never the raw secret-bearing blob.
530
+ let argsPreview = '';
531
+ if (source !== undefined) {
532
+ const scrubbed = scrubArgumentValue(source);
533
+ if (isPlainObject(scrubbed) && Object.keys(scrubbed).length > 0) {
534
+ try {
535
+ argsPreview = JSON.stringify(scrubbed);
536
+ } catch {
537
+ argsPreview = '';
538
+ }
539
+ }
540
+ }
541
+ if (argsPreview.length === 0 && typeof rawArgs === 'string' && rawArgs.length > 0) {
542
+ argsPreview = scrubRawArguments(rawArgs);
543
+ }
544
+ if (argsPreview.length === 0) return null;
545
+ return {
546
+ argsPreview: truncate(argsPreview, MAX_APPROVAL_PREVIEW_CHARS),
547
+ argsKind: 'other',
548
+ detail: { kind: 'other', ...(path === undefined ? {} : { path }) },
549
+ };
550
+ }
551
+
552
+ /** Cache one approval-card context under its call id (bounded, never logged). */
553
+ function rememberApprovalContext(callId, name, rawArgs, parsed) {
554
+ if (typeof callId !== 'string' || callId.length === 0) return;
555
+ let context = null;
556
+ try {
557
+ context = describeApprovalContext(name, rawArgs, parsed);
558
+ } catch {
559
+ context = null;
560
+ }
561
+ if (context === null) {
562
+ approvalContexts.delete(callId);
563
+ return;
564
+ }
565
+ approvalContexts.set(callId, context);
566
+ while (approvalContexts.size > MAX_APPROVAL_CONTEXTS) {
567
+ const oldest = approvalContexts.keys().next().value;
568
+ if (oldest === undefined) break;
569
+ approvalContexts.delete(oldest);
570
+ }
571
+ }
572
+
573
+ /** Look up the cached approval context for one call id. */
574
+ function approvalContextFor(callId) {
575
+ if (typeof callId !== 'string' || callId.length === 0) return undefined;
576
+ return approvalContexts.get(callId);
577
+ }
578
+
579
+ /** Normalize one question from tool arguments or the service request shape. */
580
+ function wireQuestion(question) {
581
+ if (!isPlainObject(question)) return null;
582
+ const id = typeof question.id === 'string' ? question.id : '';
583
+ const text = typeof question.question === 'string' ? question.question : '';
584
+ if (!id || !text) return null;
585
+ const out = { id, question: text };
586
+ if (typeof question.header === 'string' && question.header.length > 0) out.header = question.header;
587
+ if (typeof question.detail === 'string' && question.detail.length > 0) out.detail = question.detail;
588
+ if (question.multiSelect === true || question.multi_select === true) out.multiSelect = true;
589
+ if (Array.isArray(question.options)) {
590
+ out.options = question.options
591
+ .filter((option) => isPlainObject(option) && typeof option.label === 'string')
592
+ .map((option) => ({
593
+ label: option.label,
594
+ ...(typeof option.description === 'string' ? { description: option.description } : {}),
595
+ }));
596
+ }
597
+ if (isPlainObject(question.intent)) {
598
+ out.intent = {
599
+ kind: question.intent.kind,
600
+ approve: question.intent.approve,
601
+ ...(typeof question.intent.reject === 'string' ? { reject: question.intent.reject } : {}),
602
+ ...(typeof question.intent.always === 'string' ? { always: question.intent.always } : {}),
603
+ };
604
+ }
605
+ return out;
606
+ }
607
+
608
+ /** Normalize a question batch (drops malformed entries). */
609
+ function wireQuestions(list) {
610
+ if (!Array.isArray(list)) return [];
611
+ return list.map(wireQuestion).filter((question) => question !== null);
612
+ }
613
+
614
+ /** The `question` payload attached to an `ask_user_question` tool row. */
615
+ function questionToolPayload(callId, parsed) {
616
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.questions)) return null;
617
+ const questions = wireQuestions(parsed.questions);
618
+ if (questions.length === 0) return null;
619
+ return { callId, questions };
620
+ }
621
+
622
+ /**
623
+ * Validate an answer batch against its questions and fill skipped items with
624
+ * the documented blank answer `{ id, selected: [] }` (desktop Skip semantics).
625
+ */
626
+ function normalizeAnswerBatch(answers, questions) {
627
+ if (!Array.isArray(answers)) throw new Error('answers must be an array');
628
+ const known = new Set(questions.map((question) => question.id));
629
+ const byId = new Map();
630
+ for (const item of answers) {
631
+ if (!isPlainObject(item) || typeof item.id !== 'string') throw new Error('every answer needs an id');
632
+ if (!known.has(item.id)) throw new Error(`unknown answer id ${item.id}`);
633
+ const selected = Array.isArray(item.selected)
634
+ ? item.selected.filter((label) => typeof label === 'string')
635
+ : [];
636
+ const entry = { id: item.id, selected };
637
+ if (typeof item.custom === 'string' && item.custom.length > 0) entry.custom = item.custom;
638
+ byId.set(item.id, entry);
639
+ }
640
+ if (byId.size !== answers.length) throw new Error('duplicate answer ids');
641
+ return { answers: questions.map((question) => byId.get(question.id) ?? { id: question.id, selected: [] }) };
642
+ }
643
+
644
+ /** Read the `answers` array out of a downstream answer object. */
645
+ /**
646
+ * Split the attachment blocks appended by `prompt()` out of a user message,
647
+ * so the phone can show clean text plus structured attachment metadata.
648
+ *
649
+ * Supports both the legacy file-path marker and the Batch D image marker, in
650
+ * either order; history rows keep the exact `{path,name,mediaType}` shape.
651
+ * @returns {{ text: string, attachments: Array<{ path: string, name: string, mediaType: string }> }}
652
+ */
653
+ function splitAttachmentBlock(text) {
654
+ if (typeof text !== 'string' || text.length === 0) return { text: text ?? '', attachments: [] };
655
+ let cut = -1;
656
+ for (const marker of [ATTACHMENT_BLOCK_MARKER, IMAGE_ATTACHMENT_BLOCK_MARKER]) {
657
+ const index = text.indexOf(marker);
658
+ if (index !== -1 && (cut === -1 || index < cut)) cut = index;
659
+ }
660
+ if (cut === -1) return { text, attachments: [] };
661
+ const attachments = [];
662
+ for (const line of text.slice(cut).split('\n')) {
663
+ const entry = ATTACHMENT_LINE.exec(line.trim());
664
+ if (entry === null) continue;
665
+ attachments.push({
666
+ path: entry[1],
667
+ name: entry[2] ?? '',
668
+ mediaType: entry[3],
669
+ });
670
+ }
671
+ return { text: text.slice(0, cut).trimEnd(), attachments };
672
+ }
673
+
674
+ /** One path-reference block (marker plus `- path (name) [mediaType]` lines). */
675
+ function attachmentBlock(marker, items) {
676
+ if (items.length === 0) return '';
677
+ const lines = items.map((item) => {
678
+ const label = typeof item.name === 'string' && item.name.length > 0 ? ` (${item.name})` : '';
679
+ const type = typeof item.mediaType === 'string' && item.mediaType.length > 0 ? item.mediaType : 'file';
680
+ return `- ${item.path}${label} [${type}]`;
681
+ });
682
+ return `${marker}${lines.join('\n')}`;
683
+ }
684
+
685
+ /** Read the deployment's image limits, or `null` when the store is absent. */
686
+ function attachmentImageLimits() {
687
+ try {
688
+ const attachments = service('attachments');
689
+ const limits = attachments?.imageLimits;
690
+ return isPlainObject(limits) ? limits : null;
691
+ } catch (error) {
692
+ log.warn(`attachments.imageLimits failed: ${errorMessage(error)}`);
693
+ return null;
694
+ }
695
+ }
696
+
697
+ /**
698
+ * Effective inline-image policy: our defensive caps clamped by the
699
+ * deployment's attachment limits when the store is available.
700
+ */
701
+ function inlineImagePolicy() {
702
+ const limits = attachmentImageLimits();
703
+ const maxBytesCandidates = [MAX_INLINE_IMAGE_BYTES];
704
+ if (Number.isFinite(limits?.maxImageBytes) && limits.maxImageBytes > 0) {
705
+ maxBytesCandidates.push(limits.maxImageBytes);
706
+ }
707
+ if (Number.isFinite(limits?.maxMessageImageBytes) && limits.maxMessageImageBytes > 0) {
708
+ maxBytesCandidates.push(limits.maxMessageImageBytes);
709
+ }
710
+ const maxImagesCandidates = [MAX_INLINE_IMAGES];
711
+ if (Number.isFinite(limits?.maxImagesPerMessage) && limits.maxImagesPerMessage > 0) {
712
+ maxImagesCandidates.push(limits.maxImagesPerMessage);
713
+ }
714
+ const declaredTypes = Array.isArray(limits?.mediaTypes)
715
+ ? limits.mediaTypes.filter((type) => typeof type === 'string')
716
+ : [];
717
+ const mediaTypes = new Set(
718
+ declaredTypes.length > 0
719
+ ? declaredTypes.filter((type) => INLINE_IMAGE_MEDIA_TYPES.has(type))
720
+ : [...INLINE_IMAGE_MEDIA_TYPES],
721
+ );
722
+ const messageBytes = Number.isFinite(limits?.maxMessageImageBytes) && limits.maxMessageImageBytes > 0
723
+ ? limits.maxMessageImageBytes
724
+ : MAX_INLINE_IMAGE_BYTES * MAX_INLINE_IMAGES;
725
+ return {
726
+ maxBytes: Math.min(...maxBytesCandidates),
727
+ maxImages: Math.min(...maxImagesCandidates),
728
+ maxMessageBytes: messageBytes,
729
+ maxDimension: Number.isFinite(limits?.maxImageDimension) && limits.maxImageDimension > 0
730
+ ? limits.maxImageDimension
731
+ : null,
732
+ mediaTypes,
733
+ };
734
+ }
735
+
736
+ /** Wire-facing image limits for the SPA, or `null` when undiscoverable. */
737
+ function imageLimitsWire() {
738
+ const limits = attachmentImageLimits();
739
+ if (limits === null) return null;
740
+ const policy = inlineImagePolicy();
741
+ return {
742
+ image: {
743
+ maxBytes: policy.maxBytes,
744
+ maxDimension: policy.maxDimension,
745
+ maxImages: policy.maxImages,
746
+ maxMessageBytes: policy.maxMessageBytes,
747
+ mediaTypes: [...policy.mediaTypes],
748
+ },
749
+ };
750
+ }
751
+
752
+ /** Normalize a declared media type; only image/* types are candidates. */
753
+ function normalizeImageMediaType(value) {
754
+ if (typeof value !== 'string') return null;
755
+ const mediaType = value.trim().toLowerCase();
756
+ if (!mediaType.startsWith('image/')) return null;
757
+ return mediaType;
758
+ }
759
+
760
+ /**
761
+ * Read one saved phone upload as inline image bytes.
762
+ *
763
+ * Containment is re-checked exactly like `readUpload()`: only files under this
764
+ * session's `var/remote-mobile-uploads` directory with a matching previewable
765
+ * extension are read. Any failure returns `null` and the caller falls back to
766
+ * a path reference for that attachment.
767
+ */
768
+ async function readInlineImage(base, attachment, policy) {
769
+ const mediaType = normalizeImageMediaType(attachment.mediaType);
770
+ if (mediaType === null || !policy.mediaTypes.has(mediaType)) return null;
771
+ if (typeof attachment.path !== 'string' || attachment.path.length === 0) return null;
772
+ const directory = join(base, 'var', 'remote-mobile-uploads');
773
+ let absolutePath;
774
+ try {
775
+ absolutePath = resolve(attachment.path);
776
+ } catch {
777
+ return null;
778
+ }
779
+ if (absolutePath !== directory && !absolutePath.startsWith(directory + sep)) return null;
780
+ const expected = PREVIEW_MEDIA_TYPES[extname(absolutePath).toLowerCase()];
781
+ if (expected === undefined || expected !== mediaType) return null;
782
+ try {
783
+ // Resolve symlinks before reading: a link created inside the upload
784
+ // directory must not escape it.
785
+ const realDirectory = await realpath(directory);
786
+ const realPath = await realpath(absolutePath);
787
+ if (realPath !== realDirectory && !realPath.startsWith(realDirectory + sep)) return null;
788
+ const info = await stat(realPath);
789
+ if (!info.isFile() || info.size <= 0 || info.size > policy.maxBytes) return null;
790
+ const data = await readFile(realPath);
791
+ if (data.length === 0 || data.length > policy.maxBytes) return null;
792
+ const name = typeof attachment.name === 'string' && attachment.name.length > 0
793
+ ? attachment.name
794
+ : basename(realPath);
795
+ return {
796
+ path: attachment.path,
797
+ name,
798
+ mediaType,
799
+ bytes: data.length,
800
+ data: data.toString('base64'),
801
+ };
802
+ } catch (error) {
803
+ log.warn(`image upload could not be read for inline delivery: ${sanitize(errorMessage(error))}`);
804
+ return null;
805
+ }
806
+ }
807
+
808
+ /** The workspace root for one session (used by uploads and preview validation). */
809
+ async function resolveSessionBase(sessionId) {
810
+ const workingDirectory = service('workingDirectory');
811
+ if (workingDirectory && typeof workingDirectory.get === 'function') {
812
+ let agent = getLiveAgent(sessionId);
813
+ if (!agent) agent = await resolveAgentForSession(sessionId);
814
+ if (agent) {
815
+ try {
816
+ const base = workingDirectory.get(agent.session);
817
+ if (typeof base === 'string' && base.length > 0) return base;
818
+ } catch (error) {
819
+ log.warn(`workingDirectory.get failed: ${errorMessage(error)}`);
820
+ }
821
+ }
822
+ }
823
+ return process.cwd();
824
+ }
825
+
826
+ /** Map a ModelSelection-ish value onto the wire route. */
827
+ function selectionRoute(selection) {
828
+ if (!isPlainObject(selection)) return null;
829
+ if (typeof selection.provider !== 'string' || selection.provider.length === 0) return null;
830
+ if (typeof selection.model !== 'string' || selection.model.length === 0) return null;
831
+ const effort = typeof selection.reasoningEffort === 'string' && selection.reasoningEffort.length > 0
832
+ ? selection.reasoningEffort
833
+ : null;
834
+ return { provider: selection.provider, model: selection.model, reasoningEffort: effort };
835
+ }
836
+
837
+ /** Map a ModelSelection onto the wire `current` shape. */
838
+ function selectionWire(selection) {
839
+ return selectionRoute(selection);
840
+ }
841
+
842
+ /** Read the deployment default model without requiring any session. */
843
+ function defaultSelection() {
844
+ try {
845
+ const defaults = service('agentDefaultModel');
846
+ if (defaults && typeof defaults.currentSelection === 'function') return defaults.currentSelection();
847
+ } catch (error) {
848
+ log.warn(`agentDefaultModel.currentSelection failed: ${errorMessage(error)}`);
849
+ }
850
+ return undefined;
851
+ }
852
+
853
+ // ---------------------------------------------------------------------------
854
+ // Session summaries → wire sessions
855
+ // ---------------------------------------------------------------------------
856
+
857
+ /**
858
+ * The `SessionSummary` shape from dsh-api-session-controller:
859
+ * `{ sessionId, updatedAt, running, blank, origin?, projections?: { values } }`.
860
+ * Title/preset/model live in `projections.values` (keys `title`,
861
+ * `agentPreset`, `modelSelection`).
862
+ */
863
+ function wireSession(summary, workspace) {
864
+ const values = isPlainObject(summary?.projections?.values) ? summary.projections.values : {};
865
+ const title = typeof values.title === 'string' ? values.title : '';
866
+ const preset = typeof values.agentPreset === 'string' && values.agentPreset.length > 0
867
+ ? values.agentPreset
868
+ : null;
869
+ const selectionState = isPlainObject(values.modelSelection) ? values.modelSelection : undefined;
870
+ const modelSelection = selectionState?.next ?? selectionState?.lastUsed;
871
+ const id = typeof summary?.sessionId === 'string' ? summary.sessionId : '';
872
+ return decorateSession({
873
+ id,
874
+ title,
875
+ running: summary?.running === true,
876
+ updatedAt: Number.isFinite(summary?.updatedAt) ? summary.updatedAt : 0,
877
+ preset,
878
+ model: selectionRoute(modelSelection),
879
+ agentAvailable: typeof summary?.agentAvailable === 'boolean' ? summary.agentAvailable : agentIsLive(id),
880
+ }, workspace);
881
+ }
882
+
883
+ /** Build a wire session for a live agent (fallback path). */
884
+ function wireSessionFromAgent(agent, workspace) {
885
+ const session = agent?.session;
886
+ const id = typeof session?.id === 'string' ? session.id : (typeof agent?.id === 'string' ? agent.id : '');
887
+ let preset = null;
888
+ try {
889
+ const presets = service('agentPresets');
890
+ if (presets && typeof presets.presetForSession === 'function' && session) {
891
+ const recorded = presets.presetForSession(session);
892
+ if (typeof recorded === 'string' && recorded.length > 0) preset = recorded;
893
+ }
894
+ } catch (error) {
895
+ log.warn(`presetForSession failed: ${errorMessage(error)}`);
896
+ }
897
+ let model = null;
898
+ try {
899
+ if (agent && agent.model && typeof agent.model.current === 'function') {
900
+ model = selectionRoute(agent.model.current());
901
+ }
902
+ } catch (error) {
903
+ log.warn(`agent.model.current failed: ${errorMessage(error)}`);
904
+ }
905
+ return decorateSession({
906
+ id,
907
+ title: '',
908
+ running: agent?.status === 'running',
909
+ updatedAt: 0,
910
+ preset,
911
+ model,
912
+ agentAvailable: true,
913
+ }, workspace);
914
+ }
915
+
916
+ /** Whether a summary/agent describes a subagent session (not shown on the phone). */
917
+ function isSubagentSummary(summary) {
918
+ return summary?.origin === 'subagent';
919
+ }
920
+
921
+ function isSubagentAgent(agent) {
922
+ return agent?.session?.header?.origin === 'subagent';
923
+ }
924
+
925
+ /**
926
+ * The registry-global pin/archive sets plus each session's owning workspace id.
927
+ *
928
+ * `bySession` is built from `workspaceRegistry.list()` membership (registry
929
+ * order is display order). Degrades to empty sets/map when the workspace
930
+ * feature is not composed, so session frames stay well-formed.
931
+ */
932
+ function workspaceIndex() {
933
+ const empty = { pinned: new Set(), archived: new Set(), bySession: new Map(), available: false };
934
+ try {
935
+ const registry = service('workspaceRegistry');
936
+ if (!registry) return empty;
937
+ const pinned = Array.isArray(registry.pinnedSessionIds) ? registry.pinnedSessionIds : [];
938
+ const archived = Array.isArray(registry.archivedSessionIds) ? registry.archivedSessionIds : [];
939
+ const bySession = new Map();
940
+ if (typeof registry.list === 'function') {
941
+ const workspaces = registry.list();
942
+ for (const workspace of Array.isArray(workspaces) ? workspaces : []) {
943
+ const workspaceId = workspace === null || workspace === undefined ? '' : String(workspace.id ?? '');
944
+ if (workspaceId.length === 0) continue;
945
+ for (const sessionId of Array.isArray(workspace.sessionIds) ? workspace.sessionIds : []) {
946
+ if (typeof sessionId === 'string' && sessionId.length > 0 && !bySession.has(sessionId)) {
947
+ bySession.set(sessionId, workspaceId);
948
+ }
949
+ }
950
+ }
951
+ }
952
+ return {
953
+ pinned: new Set(pinned.filter((id) => typeof id === 'string')),
954
+ archived: new Set(archived.filter((id) => typeof id === 'string')),
955
+ bySession,
956
+ available: true,
957
+ };
958
+ } catch (error) {
959
+ log.warn(`workspace state unavailable: ${errorMessage(error)}`);
960
+ return empty;
961
+ }
962
+ }
963
+
964
+ /** Whether the Host currently has a live Agent attached for this session. */
965
+ function agentIsLive(sessionId) {
966
+ return getLiveAgent(sessionId) !== undefined;
967
+ }
968
+
969
+ /** Flatten one queue snapshot (`SessionQueuedItem[]`) to the wire shape. */
970
+ function queueItems(queue) {
971
+ if (!Array.isArray(queue)) return [];
972
+ const out = [];
973
+ for (const item of queue) {
974
+ if (!isPlainObject(item)) continue;
975
+ const id = typeof item.id === 'string' ? item.id : '';
976
+ if (!id) continue;
977
+ const placement = item.placement === 'steering'
978
+ ? 'steering'
979
+ : item.placement === 'context' ? 'context' : 'queued';
980
+ out.push({
981
+ id,
982
+ placement,
983
+ ...(typeof item.rpcId === 'string' && item.rpcId.length > 0 ? { rpcId: item.rpcId } : {}),
984
+ text: joinTextBlocks(item.content),
985
+ });
986
+ }
987
+ return out;
988
+ }
989
+
990
+ /** Synchronous queue snapshot from a live Agent's inbox (no Host await). */
991
+ function queueItemsFromAgent(agent) {
992
+ const inbox = agent?.inbox;
993
+ if (!isPlainObject(inbox)) return [];
994
+ const out = [];
995
+ const push = (message, placement) => {
996
+ if (!isPlainObject(message) || typeof message.id !== 'string' || message.id.length === 0) return;
997
+ const rpcId = message.source?.rpcId;
998
+ out.push({
999
+ id: message.id,
1000
+ placement,
1001
+ ...(typeof rpcId === 'string' && rpcId.length > 0 ? { rpcId } : {}),
1002
+ text: joinTextBlocks(message.content),
1003
+ });
1004
+ };
1005
+ for (const message of Array.isArray(inbox.nextTurn) ? inbox.nextTurn : []) push(message, 'queued');
1006
+ for (const message of Array.isArray(inbox.nextStep) ? inbox.nextStep : []) {
1007
+ push(message, message?.source?.kind === 'user' ? 'steering' : 'context');
1008
+ }
1009
+ return out;
1010
+ }
1011
+
1012
+ /** Emit a conservative queue snapshot for one live session (`onQueue`). */
1013
+ function emitQueue(sessionId) {
1014
+ const agent = getLiveAgent(sessionId);
1015
+ if (!agent) return;
1016
+ emit('onQueue', {
1017
+ sessionId,
1018
+ items: queueItemsFromAgent(agent),
1019
+ running: agent.status === 'running',
1020
+ });
1021
+ }
1022
+
1023
+ /** Add the pin/archive/workspace/live fields every wire session carries. */
1024
+ function decorateSession(session, workspace, live) {
1025
+ if (!isPlainObject(session)) return session;
1026
+ const id = session.id;
1027
+ session.pinned = workspace?.pinned?.has?.(id) === true;
1028
+ session.archived = workspace?.archived?.has?.(id) === true;
1029
+ session.workspaceId = workspace?.bySession?.get?.(id) ?? null;
1030
+ if (typeof live === 'boolean') session.agentAvailable = live;
1031
+ else if (typeof session.agentAvailable !== 'boolean') session.agentAvailable = agentIsLive(id);
1032
+ return session;
1033
+ }
1034
+
1035
+ /** Map workspace-registry failures onto friendly protocol errors. */
1036
+ function mapWorkspaceFailure(error, action) {
1037
+ const name = error && typeof error === 'object' && typeof error.name === 'string' ? error.name : '';
1038
+ if (name === 'WorkspaceActiveSessionError') {
1039
+ return failure('the session is running; stop it first or retry with stopActivity', 'bad-request');
1040
+ }
1041
+ if (name === 'WorkspaceArchivedSessionPinError') {
1042
+ return failure('unarchive the session before pinning it', 'bad-request');
1043
+ }
1044
+ if (name === 'WorkspaceUnknownSessionError') {
1045
+ return failure('the session does not exist', 'not-found');
1046
+ }
1047
+ if (action === 'archive' && /active/i.test(errorMessage(error))) {
1048
+ return failure('the session is running; stop it first or retry with stopActivity', 'bad-request');
1049
+ }
1050
+ return failure(error);
1051
+ }
1052
+
1053
+ /** Read all visible sessions; `null` means the controller is unavailable. */
1054
+ async function readSummaries() {
1055
+ const controller = service('sessionController');
1056
+ if (!controller || typeof controller.list !== 'function') return null;
1057
+ const result = await withSignal((signal) => controller.list({}, signal), timeoutMs);
1058
+ if (!isPlainObject(result) || !Array.isArray(result.items)) return [];
1059
+ return result.items;
1060
+ }
1061
+
1062
+ /** Find one summary, or `undefined` when the controller has no such row. */
1063
+ async function findSummary(sessionId) {
1064
+ const items = await readSummaries();
1065
+ if (!items) return undefined;
1066
+ return items.find((item) => item && item.sessionId === sessionId);
1067
+ }
1068
+
1069
+ /**
1070
+ * Read live execution state (`{ cursor, active, running, queue, pendingInput }`)
1071
+ * from the passive state controller. No agent is resumed.
1072
+ */
1073
+ async function readState(sessionId) {
1074
+ const controller = service('sessionController');
1075
+ if (!controller || typeof controller.state !== 'function') return undefined;
1076
+ try {
1077
+ return await withSignal((signal) => controller.state({ sessionId }, signal), timeoutMs);
1078
+ } catch (error) {
1079
+ log.warn(`session state read failed for ${sessionId}: ${errorMessage(error)}`);
1080
+ return undefined;
1081
+ }
1082
+ }
1083
+
1084
+ /** Read exact projections for a session (cold-safe, no activation). */
1085
+ async function readProjections(sessionId) {
1086
+ const controller = service('sessionController');
1087
+ if (!controller || typeof controller.projections !== 'function') return undefined;
1088
+ try {
1089
+ return await withSignal((signal) => controller.projections({ sessionId }, signal), timeoutMs);
1090
+ } catch (error) {
1091
+ log.warn(`session projections read failed for ${sessionId}: ${errorMessage(error)}`);
1092
+ return undefined;
1093
+ }
1094
+ }
1095
+
1096
+ /**
1097
+ * Build a session object when the list projection is unavailable. Uses
1098
+ * projections plus passive state; title/preset/model may be absent.
1099
+ */
1100
+ async function synthesizeSession(sessionId, records) {
1101
+ const projections = await readProjections(sessionId);
1102
+ const values = isPlainObject(projections?.values) ? projections.values : {};
1103
+ const state = await readState(sessionId);
1104
+ let title = typeof values.title === 'string' ? values.title : '';
1105
+ if (!title && Array.isArray(records)) {
1106
+ for (const record of records) {
1107
+ const event = record?.event ?? record;
1108
+ if (event?.type === 'user/message' && event.data?.source?.kind === 'user') {
1109
+ const text = joinTextBlocks(event.data.content);
1110
+ if (text) {
1111
+ title = truncate(text.replace(/\s+/g, ' ').trim(), 80);
1112
+ break;
1113
+ }
1114
+ }
1115
+ }
1116
+ }
1117
+ const preset = typeof values.agentPreset === 'string' && values.agentPreset.length > 0
1118
+ ? values.agentPreset
1119
+ : null;
1120
+ const selectionState = isPlainObject(values.modelSelection) ? values.modelSelection : undefined;
1121
+ const selection = selectionState?.next ?? selectionState?.lastUsed;
1122
+ let updatedAt = 0;
1123
+ if (Array.isArray(records) && records.length > 0) {
1124
+ const last = records[records.length - 1]?.event ?? records[records.length - 1];
1125
+ if (last && Number.isFinite(last.time)) updatedAt = last.time;
1126
+ }
1127
+ return {
1128
+ id: sessionId,
1129
+ title,
1130
+ running: state?.running === true,
1131
+ updatedAt,
1132
+ preset,
1133
+ model: selectionRoute(selection),
1134
+ };
1135
+ }
1136
+
1137
+ /** Read a passive, message-aligned history page. */
1138
+ async function readHistoryRecords(sessionId, limit) {
1139
+ const controller = service('sessionController');
1140
+ if (!controller || typeof controller.events !== 'function') return null;
1141
+ const result = await withSignal(
1142
+ (signal) => controller.events({ address: { kind: 'session', sessionId }, maxMessages: limit }, signal),
1143
+ HISTORY_TIMEOUT_MS,
1144
+ );
1145
+ if (!isPlainObject(result)) return [];
1146
+ return Array.isArray(result.records) ? result.records : [];
1147
+ }
1148
+
1149
+ /**
1150
+ * Map durable Session events onto the flat HistoryItem stream.
1151
+ *
1152
+ * Sources (verified against dsh-session / dsh-agent-loop):
1153
+ * - `user/message` data is the UserMessage (`{id, role, content, source}`)
1154
+ * - `assistant/message` data is `{turn, step, message, stream, ...}`
1155
+ * - `tool/call` data is `{turn, step, callId, name, arguments}`
1156
+ * - `tool/result` data is `{turn, step, message, error?}` with
1157
+ * `message.toolCallId` identifying the call
1158
+ * - `turn/end` data is `{turn, reason}`; `reason.kind === 'error'`
1159
+ * carries `reason.error = {message, code}`
1160
+ */
1161
+ function mapHistory(records) {
1162
+ const items = [];
1163
+ const toolItems = new Map();
1164
+ if (!Array.isArray(records)) return items;
1165
+ for (const record of records) {
1166
+ const event = record && typeof record === 'object' && record.event ? record.event : record;
1167
+ if (!isPlainObject(event) || typeof event.type !== 'string') continue;
1168
+ const seq = Number.isFinite(event.seq) ? event.seq : 0;
1169
+ const ts = Number.isFinite(event.time) ? event.time : 0;
1170
+ const data = isPlainObject(event.data) ? event.data : {};
1171
+ switch (event.type) {
1172
+ case 'user/message': {
1173
+ const source = isPlainObject(data.source) ? data.source : {};
1174
+ // Only prompts the human actually sent; injected notes (runtime
1175
+ // context, model-selection notices, approval policy) are not transcript.
1176
+ if (source.kind !== 'user') continue;
1177
+ const raw = joinTextBlocks(data.content);
1178
+ if (!raw) continue;
1179
+ const split = splitAttachmentBlock(raw);
1180
+ if (!split.text && split.attachments.length === 0) continue;
1181
+ items.push({
1182
+ id: `seq:${seq}`,
1183
+ kind: 'user',
1184
+ text: split.text,
1185
+ ts,
1186
+ ...(split.attachments.length === 0 ? {} : { attachments: split.attachments }),
1187
+ });
1188
+ break;
1189
+ }
1190
+ case 'assistant/message': {
1191
+ const message = isPlainObject(data.message) ? data.message : {};
1192
+ const text = joinTextBlocks(message.content);
1193
+ if (!text) continue;
1194
+ items.push({ id: `seq:${seq}`, kind: 'assistant', text, ts });
1195
+ break;
1196
+ }
1197
+ case 'tool/call': {
1198
+ const callId = typeof data.callId === 'string' ? data.callId : undefined;
1199
+ if (!callId) continue;
1200
+ const name = typeof data.name === 'string' ? data.name : '';
1201
+ const raw = typeof data.arguments === 'string' ? data.arguments : '';
1202
+ const parsed = parseJson(raw);
1203
+ const question = name === 'ask_user_question' ? questionToolPayload(callId, parsed) : null;
1204
+ const item = {
1205
+ id: `tool:${callId}`,
1206
+ kind: 'tool',
1207
+ callId,
1208
+ name,
1209
+ title: name,
1210
+ argsPreview: previewArgs(raw, parsed),
1211
+ ok: true,
1212
+ output: '',
1213
+ diff: null,
1214
+ durationMs: 0,
1215
+ ts,
1216
+ ...(question === null ? {} : { question }),
1217
+ };
1218
+ items.push(item);
1219
+ toolItems.set(callId, item);
1220
+ break;
1221
+ }
1222
+ case 'tool/result': {
1223
+ const message = isPlainObject(data.message) ? data.message : {};
1224
+ const callId = typeof message.toolCallId === 'string'
1225
+ ? message.toolCallId
1226
+ : typeof data.callId === 'string' ? data.callId : undefined;
1227
+ if (!callId) continue;
1228
+ const isError = message.isError === true;
1229
+ const errorRecord = isPlainObject(data.error) ? data.error : undefined;
1230
+ const errorText = typeof errorRecord?.message === 'string'
1231
+ ? errorRecord.message
1232
+ : typeof errorRecord?.reason === 'string' ? errorRecord.reason : '';
1233
+ const text = joinTextBlocks(message.content) || errorText;
1234
+ const existing = toolItems.get(callId);
1235
+ if (existing !== undefined) {
1236
+ existing.ok = !isError;
1237
+ existing.output = truncate(text, maxOutputChars);
1238
+ existing.durationMs = ts >= existing.ts ? Math.max(0, ts - existing.ts) : 0;
1239
+ } else {
1240
+ items.push({
1241
+ id: `tool:${callId}`,
1242
+ kind: 'tool',
1243
+ callId,
1244
+ name: '',
1245
+ title: '',
1246
+ argsPreview: '',
1247
+ ok: !isError,
1248
+ output: truncate(text, maxOutputChars),
1249
+ diff: null,
1250
+ durationMs: 0,
1251
+ ts,
1252
+ });
1253
+ }
1254
+ break;
1255
+ }
1256
+ case 'turn/end': {
1257
+ const reason = isPlainObject(data.reason) ? data.reason : {};
1258
+ if (reason.kind !== 'error') break;
1259
+ const errorRecord = isPlainObject(reason.error) ? reason.error : {};
1260
+ const text = typeof errorRecord.message === 'string' ? errorRecord.message : 'Run failed';
1261
+ items.push({ id: `seq:${seq}`, kind: 'error', text: sanitize(text), ts });
1262
+ break;
1263
+ }
1264
+ default:
1265
+ break;
1266
+ }
1267
+ }
1268
+ return items;
1269
+ }
1270
+
1271
+ // ---------------------------------------------------------------------------
1272
+ // Live event subscriptions
1273
+ // ---------------------------------------------------------------------------
1274
+
1275
+ function emit(name, payload) {
1276
+ for (const entry of handlers) {
1277
+ const callback = entry && entry[name];
1278
+ if (typeof callback !== 'function') continue;
1279
+ try {
1280
+ callback(payload);
1281
+ } catch (error) {
1282
+ log.warn(`handler ${name} threw: ${errorMessage(error)}`);
1283
+ }
1284
+ }
1285
+ }
1286
+
1287
+ function hasHandler(name) {
1288
+ for (const entry of handlers) {
1289
+ if (entry && typeof entry[name] === 'function') return true;
1290
+ }
1291
+ return false;
1292
+ }
1293
+
1294
+ /** `agent/assistant-stream` payload: `{ agent, frame }`. */
1295
+ function onAssistantStream(payload) {
1296
+ const agent = payload?.agent;
1297
+ const frame = payload?.frame;
1298
+ if (!agent || !frame || isSubagentAgent(agent)) return;
1299
+ const sessionId = typeof agent.session?.id === 'string' ? agent.session.id : undefined;
1300
+ if (!sessionId) return;
1301
+ switch (frame.type) {
1302
+ case 'start': {
1303
+ const turn = Number.isFinite(frame.turn) ? frame.turn : 0;
1304
+ const step = Number.isFinite(frame.step) ? frame.step : 0;
1305
+ attempts.set(sessionId, { attemptId: frame.attemptId, turn, step });
1306
+ emit('onAssistant', { sessionId, phase: 'start', turn, step, text: '', reasoning: null });
1307
+ return;
1308
+ }
1309
+ case 'chunk': {
1310
+ const attempt = attempts.get(sessionId);
1311
+ if (!attempt) return;
1312
+ if (attempt.attemptId !== undefined && frame.attemptId !== undefined
1313
+ && attempt.attemptId !== frame.attemptId) return;
1314
+ const chunk = frame.chunk;
1315
+ if (!isPlainObject(chunk)) return;
1316
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string' && chunk.text.length > 0) {
1317
+ emit('onAssistant', {
1318
+ sessionId,
1319
+ phase: 'delta',
1320
+ turn: attempt.turn,
1321
+ step: attempt.step,
1322
+ // Incremental fragment, not cumulative text; the server may coalesce.
1323
+ text: chunk.text,
1324
+ reasoning: null,
1325
+ });
1326
+ } else if (chunk.type === 'reasoning-delta' && typeof chunk.text === 'string' && chunk.text.length > 0) {
1327
+ emit('onAssistant', {
1328
+ sessionId,
1329
+ phase: 'delta',
1330
+ turn: attempt.turn,
1331
+ step: attempt.step,
1332
+ text: '',
1333
+ reasoning: chunk.text,
1334
+ });
1335
+ }
1336
+ return;
1337
+ }
1338
+ case 'end': {
1339
+ const attempt = attempts.get(sessionId);
1340
+ attempts.delete(sessionId);
1341
+ emit('onAssistant', {
1342
+ sessionId,
1343
+ phase: 'end',
1344
+ turn: attempt?.turn ?? 0,
1345
+ step: attempt?.step ?? 0,
1346
+ text: '',
1347
+ reasoning: null,
1348
+ });
1349
+ return;
1350
+ }
1351
+ default:
1352
+ break;
1353
+ }
1354
+ }
1355
+
1356
+ /** `session/event` payload: `(session, event)`; durable transcript facts. */
1357
+ function onSessionEvent(session, event) {
1358
+ if (!session || !isPlainObject(event) || typeof event.type !== 'string') return;
1359
+ if (session.header?.origin === 'subagent') return;
1360
+ const sessionId = typeof session.id === 'string' ? session.id : undefined;
1361
+ if (!sessionId) return;
1362
+ switch (event.type) {
1363
+ case 'tool/call': {
1364
+ const data = isPlainObject(event.data) ? event.data : {};
1365
+ const callId = typeof data.callId === 'string' ? data.callId : undefined;
1366
+ if (!callId) return;
1367
+ const name = typeof data.name === 'string' ? data.name : '';
1368
+ const raw = typeof data.arguments === 'string' ? data.arguments : '';
1369
+ const parsed = parseJson(raw);
1370
+ toolStarts.set(callId, {
1371
+ sessionId,
1372
+ name,
1373
+ time: Number.isFinite(event.time) ? event.time : now(),
1374
+ });
1375
+ while (toolStarts.size > MAX_TOOL_STARTS) {
1376
+ const oldest = toolStarts.keys().next().value;
1377
+ if (oldest === undefined) break;
1378
+ toolStarts.delete(oldest);
1379
+ }
1380
+ // Cache the bounded, scrubbed approval-card context for a later ask.
1381
+ rememberApprovalContext(callId, name, raw, parsed);
1382
+ const question = name === 'ask_user_question' ? questionToolPayload(callId, parsed) : null;
1383
+ emit('onTool', {
1384
+ sessionId,
1385
+ phase: 'start',
1386
+ callId,
1387
+ name,
1388
+ title: name === 'ask_user_question' ? 'Question' : name,
1389
+ argsPreview: previewArgs(raw, parsed),
1390
+ detail: detailFromArgs(parsed),
1391
+ ...(question === null ? {} : { question }),
1392
+ });
1393
+ return;
1394
+ }
1395
+ case 'tool/result': {
1396
+ const data = isPlainObject(event.data) ? event.data : {};
1397
+ const message = isPlainObject(data.message) ? data.message : {};
1398
+ const callId = typeof message.toolCallId === 'string'
1399
+ ? message.toolCallId
1400
+ : typeof data.callId === 'string' ? data.callId : undefined;
1401
+ if (!callId) return;
1402
+ const started = toolStarts.get(callId);
1403
+ toolStarts.delete(callId);
1404
+ const isError = message.isError === true;
1405
+ const errorRecord = isPlainObject(data.error) ? data.error : undefined;
1406
+ const errorText = typeof errorRecord?.message === 'string'
1407
+ ? errorRecord.message
1408
+ : typeof errorRecord?.reason === 'string' ? errorRecord.reason : '';
1409
+ const output = joinTextBlocks(message.content) || errorText;
1410
+ const finishedAt = Number.isFinite(event.time) ? event.time : now();
1411
+ const durationMs = started && Number.isFinite(started.time)
1412
+ ? Math.max(0, finishedAt - started.time)
1413
+ : 0;
1414
+ emit('onTool', {
1415
+ sessionId,
1416
+ phase: 'end',
1417
+ callId,
1418
+ name: started?.name ?? '',
1419
+ title: started?.name ?? '',
1420
+ argsPreview: '',
1421
+ detail: null,
1422
+ ok: !isError,
1423
+ output: truncate(redactPaths ? sanitize(output) : output, maxOutputChars),
1424
+ durationMs,
1425
+ });
1426
+ return;
1427
+ }
1428
+ case 'turn/start': {
1429
+ emit('onStatus', { sessionId, running: true });
1430
+ return;
1431
+ }
1432
+ case 'turn/end': {
1433
+ emit('onStatus', { sessionId, running: false });
1434
+ // Claiming queued input changes the queue; a turn boundary is a cheap,
1435
+ // low-frequency point to resync it for every device.
1436
+ emitQueue(sessionId);
1437
+ return;
1438
+ }
1439
+ case 'agent/inbox/spliced': {
1440
+ // Queue mutations (prompt queueing, updateQueue edit/remove/steer) are
1441
+ // durable inbox splices. Re-read the inbox instead of parsing the event.
1442
+ emitQueue(sessionId);
1443
+ return;
1444
+ }
1445
+ default:
1446
+ break;
1447
+ }
1448
+ }
1449
+
1450
+ /** `agent/status` payload: `{ agent, status }` with status `'idle' | 'running'`. */
1451
+ function onAgentStatus(payload) {
1452
+ const agent = payload?.agent;
1453
+ if (!agent || isSubagentAgent(agent)) return;
1454
+ const sessionId = typeof agent.session?.id === 'string' ? agent.session.id : undefined;
1455
+ if (!sessionId) return;
1456
+ emit('onStatus', { sessionId, running: payload.status === 'running' });
1457
+ }
1458
+
1459
+ /** `agent/error` payload: `{ agent, turn, step, error }`. Close any open bubble. */
1460
+ function onAgentError(payload) {
1461
+ const agent = payload?.agent;
1462
+ if (!agent || isSubagentAgent(agent)) return;
1463
+ const sessionId = typeof agent.session?.id === 'string' ? agent.session.id : undefined;
1464
+ if (!sessionId) return;
1465
+ // There is no live error frame in PROTOCOL.md; close the streaming bubble
1466
+ // and let the phone learn the failure from the next history load.
1467
+ if (attempts.has(sessionId)) {
1468
+ const attempt = attempts.get(sessionId);
1469
+ attempts.delete(sessionId);
1470
+ emit('onAssistant', {
1471
+ sessionId,
1472
+ phase: 'end',
1473
+ turn: attempt?.turn ?? 0,
1474
+ step: attempt?.step ?? 0,
1475
+ text: '',
1476
+ reasoning: null,
1477
+ });
1478
+ }
1479
+ log.warn(`agent error for ${sessionId}: ${sanitize(errorMessage(payload.error))}`);
1480
+ }
1481
+
1482
+ /**
1483
+ * Approval waterfall listener.
1484
+ *
1485
+ * `approval/request` is a scoped Cordis waterfall dispatched with
1486
+ * `this: Scoped<Agent>` (dsh-user-approval). A global listener receives every
1487
+ * agent's request and may answer by returning an ApprovalOutcome or by
1488
+ * delegating with `next()`.
1489
+ *
1490
+ * Routing is exclusive: while a phone is connected the phone is the answerer,
1491
+ * so the desktop is never left showing a prompt that the phone already
1492
+ * settled. With no phone connected the request is delegated to the desktop
1493
+ * answerer (`next()`), preserving normal desktop behaviour.
1494
+ */
1495
+ function onApprovalRequest(request, next) {
1496
+ const continueChain = () => {
1497
+ try {
1498
+ return Promise.resolve(typeof next === 'function' ? next() : 'unavailable');
1499
+ } catch (error) {
1500
+ log.warn(`approval chain delegation failed: ${errorMessage(error)}`);
1501
+ return Promise.resolve('unavailable');
1502
+ }
1503
+ };
1504
+
1505
+ // Never intercept when the phone has no connected client: leave the
1506
+ // desktop answerer (or the fail-closed default) in charge.
1507
+ if (typeof opts.hasApprovalPeers === 'function') {
1508
+ let peers = false;
1509
+ try {
1510
+ peers = opts.hasApprovalPeers() === true;
1511
+ } catch (error) {
1512
+ log.warn(`hasApprovalPeers failed: ${errorMessage(error)}`);
1513
+ peers = false;
1514
+ }
1515
+ if (!peers) return continueChain();
1516
+ }
1517
+ if (!hasHandler('onApproval')) return continueChain();
1518
+ if (!isPlainObject(request)) return continueChain();
1519
+
1520
+ // The waterfall payload normally carries the agent, but accept the scoped
1521
+ // listener context or the current initiator as fallbacks so an approval is
1522
+ // never silently delegated just because the payload shape changed.
1523
+ const scoped = this && typeof this === 'object' && this.agent !== undefined ? this.agent : undefined;
1524
+ let initiator
1525
+ try {
1526
+ const registry = service('agents');
1527
+ if (registry && typeof registry.currentInitiator === 'function') {
1528
+ initiator = registry.currentInitiator();
1529
+ }
1530
+ } catch {
1531
+ initiator = undefined;
1532
+ }
1533
+ const agent = request.agent ?? scoped ?? initiator;
1534
+ if (!agent || isSubagentAgent(agent)) return continueChain();
1535
+ const sessionId = typeof agent.session?.id === 'string' ? agent.session.id : undefined;
1536
+ if (!sessionId) return continueChain();
1537
+
1538
+ const requestId = newId();
1539
+ const signal = request.signal;
1540
+
1541
+ return new Promise((resolve) => {
1542
+ let settled = false;
1543
+ let timer = null;
1544
+
1545
+ const cleanup = () => {
1546
+ if (timer !== null) {
1547
+ clearTimeout(timer);
1548
+ timer = null;
1549
+ }
1550
+ try {
1551
+ if (signal && typeof signal.removeEventListener === 'function') {
1552
+ signal.removeEventListener('abort', onAbort);
1553
+ }
1554
+ } catch {
1555
+ // ignore
1556
+ }
1557
+ };
1558
+
1559
+ const settle = (outcome) => {
1560
+ if (settled) return;
1561
+ settled = true;
1562
+ cleanup();
1563
+ pendingApprovals.delete(requestId);
1564
+ const normalized = APPROVAL_OUTCOMES.has(outcome) ? outcome : 'unavailable';
1565
+ emit('onApprovalResolved', { sessionId, requestId, outcome: normalized });
1566
+ resolve(normalized);
1567
+ };
1568
+
1569
+ const onAbort = () => settle('cancelled');
1570
+
1571
+ if (signal && typeof signal.addEventListener === 'function') {
1572
+ if (signal.aborted) {
1573
+ settle('cancelled');
1574
+ return;
1575
+ }
1576
+ signal.addEventListener('abort', onAbort, { once: true });
1577
+ }
1578
+
1579
+ const waitMs = Number(opts.approvalWaitMs);
1580
+ if (Number.isFinite(waitMs) && waitMs > 0) {
1581
+ timer = setTimeout(() => settle('unavailable'), waitMs);
1582
+ }
1583
+
1584
+ pendingApprovals.set(requestId, { sessionId, settle });
1585
+ emit('onApproval', approvalPayload(sessionId, requestId, request));
1586
+
1587
+ // Exclusive routing: while a phone is connected it is the only answerer.
1588
+ // Delegating to the desktop here would leave its copied prompt pending
1589
+ // when the phone answers, so the desktop card could never be dismissed.
1590
+ });
1591
+ }
1592
+
1593
+ function approvalPayload(sessionId, requestId, request) {
1594
+ const toolName = typeof request.toolName === 'string' ? request.toolName : '';
1595
+ const reason = typeof request.reason === 'string' ? request.reason : '';
1596
+ const displayReason = displayReasonText(request.displayReason) || reason;
1597
+ const callId = typeof request.callId === 'string' ? request.callId : null;
1598
+ // Additive card context, only when the bridge already saw this tool call.
1599
+ const context = approvalContextFor(callId);
1600
+ return {
1601
+ sessionId,
1602
+ requestId,
1603
+ toolName,
1604
+ title: toolName,
1605
+ reason,
1606
+ displayReason,
1607
+ callId,
1608
+ ...(context === undefined ? {} : {
1609
+ argsPreview: context.argsPreview,
1610
+ argsKind: context.argsKind,
1611
+ detail: context.detail,
1612
+ }),
1613
+ // No Host expiry exists today; 0 means "no known deadline".
1614
+ expiresAt: 0,
1615
+ };
1616
+ }
1617
+
1618
+ function displayReasonText(value) {
1619
+ if (typeof value === 'string') return value;
1620
+ if (!isPlainObject(value)) return '';
1621
+ if (typeof value.en === 'string' && value.en.length > 0) return value.en;
1622
+ for (const key of Object.keys(value)) {
1623
+ if (typeof value[key] === 'string' && value[key].length > 0) return value[key];
1624
+ }
1625
+ return '';
1626
+ }
1627
+
1628
+ /**
1629
+ * `user-questions/request` waterfall listener: when a phone is connected it is
1630
+ * the exclusive answerer (so the desktop never shows a duplicate, stale
1631
+ * question card); otherwise the request is delegated to the desktop chain.
1632
+ *
1633
+ * A request with `wait.callId` is a timed question whose tool call stays open:
1634
+ * the phone's answer is returned through this waterfall. A blocking request
1635
+ * has no callId; the SPA keys the card by `requestId` instead.
1636
+ */
1637
+ function onQuestionRequest(request, next) {
1638
+ const continueChain = () => {
1639
+ try {
1640
+ return Promise.resolve(typeof next === 'function' ? next() : undefined);
1641
+ } catch (error) {
1642
+ log.warn(`question chain delegation failed: ${errorMessage(error)}`);
1643
+ return Promise.resolve(undefined);
1644
+ }
1645
+ };
1646
+ const peersCheck = typeof opts.hasQuestionPeers === 'function'
1647
+ ? opts.hasQuestionPeers
1648
+ : opts.hasApprovalPeers;
1649
+ const phoneConnected = () => {
1650
+ if (typeof peersCheck !== 'function') return true;
1651
+ try {
1652
+ return peersCheck() === true;
1653
+ } catch (error) {
1654
+ log.warn(`hasQuestionPeers failed: ${errorMessage(error)}`);
1655
+ return false;
1656
+ }
1657
+ };
1658
+ if (!hasHandler('onQuestion')) return continueChain();
1659
+ if (!isPlainObject(request)) return continueChain();
1660
+
1661
+ const agent = request.agent;
1662
+ if (!agent || isSubagentAgent(agent)) return continueChain();
1663
+ const sessionId = typeof agent.session?.id === 'string' ? agent.session.id : undefined;
1664
+ if (!sessionId) return continueChain();
1665
+ const questions = wireQuestions(request.questions);
1666
+ if (questions.length === 0) return continueChain();
1667
+
1668
+ const wait = isPlainObject(request.wait) ? request.wait : undefined;
1669
+ const callId = wait !== undefined && typeof wait.callId === 'string' ? wait.callId : null;
1670
+ const requestId = newId();
1671
+ const signal = request.signal;
1672
+ const configuredHandoff = Number(opts.questionHandoffMs);
1673
+ const handoffMs = Number.isFinite(configuredHandoff) && configuredHandoff >= 0 ? configuredHandoff : 45000;
1674
+
1675
+ return new Promise((resolve) => {
1676
+ let settled = false;
1677
+ let timer = null;
1678
+
1679
+ const clearTimer = () => {
1680
+ if (timer !== null) {
1681
+ clearTimeout(timer);
1682
+ timer = null;
1683
+ }
1684
+ };
1685
+
1686
+ const finish = (value) => {
1687
+ if (settled) return;
1688
+ settled = true;
1689
+ clearTimer();
1690
+ pendingQuestions.delete(requestId);
1691
+ try {
1692
+ if (signal && typeof signal.removeEventListener === 'function') {
1693
+ signal.removeEventListener('abort', onAbort);
1694
+ }
1695
+ } catch {
1696
+ // ignore
1697
+ }
1698
+ resolve(value);
1699
+ };
1700
+
1701
+ const settleAnswers = (answers) => {
1702
+ if (settled) return;
1703
+ let batch;
1704
+ try {
1705
+ batch = normalizeAnswerBatch(answers, questions);
1706
+ } catch (error) {
1707
+ log.warn(`rejected question answer: ${errorMessage(error)}`);
1708
+ return;
1709
+ }
1710
+ const skipped = batch.answers.every((entry) =>
1711
+ entry.selected.length === 0 && (entry.custom === undefined || entry.custom.length === 0));
1712
+ emit('onQuestionResolved', {
1713
+ sessionId,
1714
+ requestId,
1715
+ callId,
1716
+ answers: batch.answers,
1717
+ outcome: skipped ? 'declined' : 'answered',
1718
+ });
1719
+ finish(batch);
1720
+ };
1721
+
1722
+ const onAbort = () => {
1723
+ if (settled) return;
1724
+ emit('onQuestionResolved', { sessionId, requestId, callId, answers: null, outcome: 'declined' });
1725
+ finish(undefined);
1726
+ };
1727
+
1728
+ // No phone at request time: keep the question queued for a short window so
1729
+ // a reconnecting phone can still receive it, then hand it to the desktop.
1730
+ // While a phone is connected it is the exclusive answerer (like approvals),
1731
+ // so no handoff timer runs in that case.
1732
+ const handoff = () => {
1733
+ timer = null;
1734
+ if (settled) return;
1735
+ if (phoneConnected()) {
1736
+ timer = setTimeout(handoff, handoffMs);
1737
+ timer.unref?.();
1738
+ return;
1739
+ }
1740
+ pendingQuestions.delete(requestId);
1741
+ emit('onQuestionResolved', { sessionId, requestId, callId, answers: null, outcome: 'unavailable' });
1742
+ let downstream;
1743
+ try {
1744
+ downstream = Promise.resolve(typeof next === 'function' ? next() : undefined);
1745
+ } catch (error) {
1746
+ log.warn(`question next() threw: ${errorMessage(error)}`);
1747
+ downstream = Promise.resolve(undefined);
1748
+ }
1749
+ downstream.then((value) => finish(value), () => finish(undefined));
1750
+ };
1751
+
1752
+ if (signal && typeof signal.addEventListener === 'function') {
1753
+ if (signal.aborted) {
1754
+ onAbort();
1755
+ return;
1756
+ }
1757
+ signal.addEventListener('abort', onAbort, { once: true });
1758
+ }
1759
+
1760
+ pendingQuestions.set(requestId, {
1761
+ sessionId,
1762
+ callId,
1763
+ questions,
1764
+ answer: settleAnswers,
1765
+ cancel: () => {
1766
+ if (settled) return;
1767
+ emit('onQuestionResolved', { sessionId, requestId, callId, answers: null, outcome: 'declined' });
1768
+ finish(undefined);
1769
+ },
1770
+ });
1771
+ emit('onQuestion', { sessionId, requestId, callId, questions });
1772
+
1773
+ if (!phoneConnected() && handoffMs > 0) {
1774
+ timer = setTimeout(handoff, handoffMs);
1775
+ timer.unref?.();
1776
+ }
1777
+ });
1778
+ }
1779
+
1780
+
1781
+ function installListeners() {
1782
+ if (listenerDisposers !== null || disposed) return;
1783
+ const disposers = [];
1784
+ const add = (name, callback, extra) => {
1785
+ try {
1786
+ if (typeof ctx?.on !== 'function') return;
1787
+ const handle = extra === undefined
1788
+ ? ctx.on(name, callback)
1789
+ : ctx.on(name, callback, extra);
1790
+ if (typeof handle === 'function') disposers.push(handle);
1791
+ } catch (error) {
1792
+ log.warn(`failed to listen for "${name}": ${errorMessage(error)}`);
1793
+ }
1794
+ };
1795
+ // Agent-scoped events need a global listener: the dispatcher scopes them to
1796
+ // the agent subject, while this plugin's context is not that agent.
1797
+ add('agent/assistant-stream', onAssistantStream, { global: true });
1798
+ add('session/event', onSessionEvent, { global: true });
1799
+ add('agent/status', onAgentStatus, { global: true });
1800
+ add('agent/error', onAgentError, { global: true });
1801
+ add('approval/request', onApprovalRequest, { global: true, prepend: true });
1802
+ add('user-questions/request', onQuestionRequest, { global: true, prepend: true });
1803
+ listenerDisposers = disposers;
1804
+ }
1805
+
1806
+ function removeListeners() {
1807
+ if (listenerDisposers === null) return;
1808
+ const disposers = listenerDisposers;
1809
+ listenerDisposers = null;
1810
+ for (const dispose of disposers.reverse()) {
1811
+ try {
1812
+ if (typeof dispose === 'function') dispose();
1813
+ } catch (error) {
1814
+ log.warn(`listener disposer failed: ${errorMessage(error)}`);
1815
+ }
1816
+ }
1817
+ }
1818
+
1819
+ function cancelPendingApprovals(outcome) {
1820
+ for (const entry of [...pendingApprovals.values()]) {
1821
+ try {
1822
+ entry.settle(outcome);
1823
+ } catch (error) {
1824
+ log.warn(`failed to settle pending approval: ${errorMessage(error)}`);
1825
+ }
1826
+ }
1827
+ pendingApprovals.clear();
1828
+ }
1829
+
1830
+ function cancelPendingQuestions() {
1831
+ for (const entry of [...pendingQuestions.values()]) {
1832
+ try {
1833
+ if (typeof entry.cancel === 'function') entry.cancel();
1834
+ } catch (error) {
1835
+ log.warn(`failed to settle pending question: ${errorMessage(error)}`);
1836
+ }
1837
+ }
1838
+ pendingQuestions.clear();
1839
+ }
1840
+
1841
+ // ---------------------------------------------------------------------------
1842
+ // Public bridge surface
1843
+ // ---------------------------------------------------------------------------
1844
+
1845
+ return {
1846
+ /** All visible sessions, newest activity first. Subagent sessions are hidden. */
1847
+ async listSessions() {
1848
+ try {
1849
+ const workspace = workspaceIndex();
1850
+ const items = await readSummaries();
1851
+ if (items === null) {
1852
+ // Fallback: live agents only (no cold sessions).
1853
+ const agents = service('agents');
1854
+ if (!agents || typeof agents.list !== 'function') return [];
1855
+ return agents.list()
1856
+ .filter((agent) => agent && !isSubagentAgent(agent))
1857
+ .map((agent) => wireSessionFromAgent(agent, workspace))
1858
+ .filter((session) => session.id.length > 0);
1859
+ }
1860
+ return items
1861
+ .filter((item) => item && !isSubagentSummary(item))
1862
+ .map((item) => wireSession(item, workspace))
1863
+ .filter((session) => session.id.length > 0);
1864
+ } catch (error) {
1865
+ log.warn(`listSessions failed: ${errorMessage(error)}`);
1866
+ return [];
1867
+ }
1868
+ },
1869
+
1870
+ /**
1871
+ * Registered project workspaces, in registry (display) order.
1872
+ * Returns `[]` when the workspace service is absent or throws. Paths and
1873
+ * titles only; never descendant session content.
1874
+ */
1875
+ async listWorkspaces() {
1876
+ try {
1877
+ const registry = service('workspaceRegistry');
1878
+ if (!registry || typeof registry.list !== 'function') return [];
1879
+ const workspaces = registry.list();
1880
+ const out = [];
1881
+ for (const workspace of Array.isArray(workspaces) ? workspaces : []) {
1882
+ const id = workspace === null || workspace === undefined ? '' : String(workspace.id ?? '');
1883
+ if (id.length === 0) continue;
1884
+ out.push({
1885
+ id,
1886
+ title: typeof workspace.title === 'string' ? workspace.title : '',
1887
+ path: typeof workspace.path === 'string' ? workspace.path : '',
1888
+ sessionIds: (Array.isArray(workspace.sessionIds) ? workspace.sessionIds : [])
1889
+ .filter((sessionId) => typeof sessionId === 'string' && sessionId.length > 0),
1890
+ });
1891
+ }
1892
+ return out;
1893
+ } catch (error) {
1894
+ log.warn(`listWorkspaces failed: ${errorMessage(error)}`);
1895
+ return [];
1896
+ }
1897
+ },
1898
+
1899
+ /**
1900
+ * Open one session: its summary, newest history page and (when the session
1901
+ * is live) its pending queue. Passive: no Agent is resumed, so `prompt()`
1902
+ * resumes on demand.
1903
+ */
1904
+ async openSession(sessionId) {
1905
+ try {
1906
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
1907
+ const workspace = workspaceIndex();
1908
+ let records;
1909
+ try {
1910
+ records = await readHistoryRecords(sessionId, DEFAULT_HISTORY_LIMIT);
1911
+ } catch (error) {
1912
+ // A missing session is the common failure; report it as not-found.
1913
+ if (errorCode(error) !== undefined || /not found/i.test(errorMessage(error))) throw error;
1914
+ log.warn(`history read failed for ${sessionId}: ${errorMessage(error)}`);
1915
+ records = [];
1916
+ }
1917
+ if (records === null) {
1918
+ // No sessionController at all: only a live agent can identify a session.
1919
+ const live = getLiveAgent(sessionId);
1920
+ if (!live) return failure(`session "${sessionId}" is not available`, 'not-found');
1921
+ return { session: wireSessionFromAgent(live, workspace), history: [], queue: [], context: null };
1922
+ }
1923
+ const summary = await findSummary(sessionId);
1924
+ const session = decorateSession(
1925
+ summary ? wireSession(summary, workspace) : await synthesizeSession(sessionId, records),
1926
+ workspace,
1927
+ );
1928
+ if (!session.id) session.id = sessionId;
1929
+ // Queue state is live-only; cold sessions get an empty array so the SPA
1930
+ // has one stable shape.
1931
+ let queue = [];
1932
+ if (agentIsLive(sessionId)) {
1933
+ const state = await readState(sessionId);
1934
+ if (isPlainObject(state)) {
1935
+ queue = queueItemsFromAgent(getLiveAgent(sessionId) ?? undefined);
1936
+ if (queue.length === 0) queue = queueItems(state.queue);
1937
+ if (typeof state.running === 'boolean') session.running = state.running;
1938
+ }
1939
+ }
1940
+ // Context pressure is cold-safe through the projection fold; a session
1941
+ // that never ran a turn simply reports `basis: "unknown"`.
1942
+ let context = null;
1943
+ try {
1944
+ const projectionValue = await readProjections(sessionId);
1945
+ const values = isPlainObject(projectionValue) && isPlainObject(projectionValue.values)
1946
+ ? projectionValue.values
1947
+ : {};
1948
+ context = summarizeContextValues(values);
1949
+ } catch (error) {
1950
+ log.warn(`context projection failed for ${sessionId}: ${errorMessage(error)}`);
1951
+ }
1952
+ return { session, history: mapHistory(records), queue, context };
1953
+ } catch (error) {
1954
+ return failure(error);
1955
+ }
1956
+ },
1957
+
1958
+ /** Create a blank session, optionally bound to an agent preset. */
1959
+ async createSession(createOptions = {}) {
1960
+ try {
1961
+ const controller = service('sessionController');
1962
+ if (!controller || typeof controller.create !== 'function') {
1963
+ return failure('session creation is unavailable: no sessionController service', 'internal');
1964
+ }
1965
+ const request = {};
1966
+ const preset = createOptions && typeof createOptions.preset === 'string' ? createOptions.preset : '';
1967
+ if (preset.length > 0) request.agentPreset = preset;
1968
+ const cwd = createOptions && typeof createOptions.cwd === 'string' ? createOptions.cwd.trim() : '';
1969
+ if (cwd.length > 0) request.cwd = cwd;
1970
+ const created = await controller.create(request);
1971
+ const id = typeof created?.sessionId === 'string' ? created.sessionId : '';
1972
+ if (!id) return failure('session creation returned no session id', 'internal');
1973
+ const workspace = workspaceIndex();
1974
+ const summary = await findSummary(id);
1975
+ if (summary) return wireSession(summary, workspace);
1976
+ return decorateSession({
1977
+ id,
1978
+ title: '',
1979
+ running: false,
1980
+ updatedAt: now(),
1981
+ preset: typeof created?.agentPreset === 'string' && created.agentPreset.length > 0
1982
+ ? created.agentPreset
1983
+ : (preset.length > 0 ? preset : null),
1984
+ model: selectionRoute(defaultSelection()),
1985
+ }, workspace);
1986
+ } catch (error) {
1987
+ return failure(error);
1988
+ }
1989
+ },
1990
+
1991
+ /**
1992
+ * Rename one session.
1993
+ *
1994
+ * The Host normalizes control characters/whitespace and truncates the title
1995
+ * to its configured UTF-8 byte budget (80 bytes in the shipped desktop
1996
+ * composition); a title with no visible characters is rejected with
1997
+ * `session/title-invalid`. Cold-safe: the controller resumes the session in
1998
+ * order to append `session/title`.
1999
+ *
2000
+ * @returns `{ ok:true, sessionId, title, seq }` or an error envelope.
2001
+ */
2002
+ async renameSession(sessionId, title) {
2003
+ try {
2004
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2005
+ if (typeof title !== 'string') return failure('title must be a string', 'bad-request');
2006
+ if (title.trim().length === 0) {
2007
+ return failure('a title needs at least one visible character', 'bad-request');
2008
+ }
2009
+ const controller = service('sessionController');
2010
+ if (!controller || typeof controller.rename !== 'function') {
2011
+ return failure('renaming is unavailable in this deployment', 'internal');
2012
+ }
2013
+ const result = await controller.rename({ sessionId, title });
2014
+ return {
2015
+ ok: true,
2016
+ sessionId,
2017
+ title: typeof result?.title === 'string' ? result.title : title,
2018
+ seq: Number.isFinite(result?.seq) ? result.seq : 0,
2019
+ };
2020
+ } catch (error) {
2021
+ if (errorCode(error) === 'session/title-invalid') {
2022
+ return failure('a title needs at least one visible character', 'bad-request');
2023
+ }
2024
+ return failure(error);
2025
+ }
2026
+ },
2027
+
2028
+ /**
2029
+ * Fork one session at an event boundary (or the latest completed turn) into
2030
+ * a new independent session. Cold-safe. `allowMigration` is left undefined
2031
+ * so the Host may migrate an old source; a source that still cannot be
2032
+ * opened yields a friendly error.
2033
+ *
2034
+ * @returns `{ ok:true, sessionId, sourceSessionId }` or an error envelope.
2035
+ */
2036
+ async forkSession(sessionId, atSeq) {
2037
+ try {
2038
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2039
+ const request = { sessionId };
2040
+ if (Number.isSafeInteger(atSeq) && atSeq >= 0) request.atSeq = atSeq;
2041
+ const controller = service('sessionController');
2042
+ if (!controller || typeof controller.fork !== 'function') {
2043
+ return failure('forking is unavailable in this deployment', 'internal');
2044
+ }
2045
+ const result = await controller.fork(request);
2046
+ const forkId = typeof result?.sessionId === 'string' ? result.sessionId : '';
2047
+ if (!forkId) return failure('fork returned no session id', 'internal');
2048
+ return { ok: true, sessionId: forkId, sourceSessionId: sessionId };
2049
+ } catch (error) {
2050
+ if (errorCode(error) === 'session/migration-required') {
2051
+ return failure('open this session on the desktop once before forking it', 'bad-request');
2052
+ }
2053
+ if (errorCode(error) === 'session/fork-unavailable') {
2054
+ return failure('this session has no completed turn to fork', 'bad-request');
2055
+ }
2056
+ return failure(error);
2057
+ }
2058
+ },
2059
+
2060
+ /**
2061
+ * Literal message-content search across visible sessions (cold-safe).
2062
+ * The Host caps the result at 20 sessions and 240 code points per snippet.
2063
+ *
2064
+ * @returns `{ ok:true, query, results, hasMore }` or an error envelope.
2065
+ */
2066
+ async searchSessions(query) {
2067
+ try {
2068
+ if (typeof query !== 'string' || query.trim().length === 0) {
2069
+ return failure('search query must not be empty', 'bad-request');
2070
+ }
2071
+ const trimmed = query.trim();
2072
+ if (trimmed.length > 500) return failure('search query is too long', 'bad-request');
2073
+ const controller = service('sessionController');
2074
+ if (!controller || typeof controller.search !== 'function') {
2075
+ return failure('search is unavailable in this deployment', 'internal');
2076
+ }
2077
+ const value = await withSignal((signal) => controller.search({ query: trimmed }, signal), timeoutMs);
2078
+ const items = isPlainObject(value) && Array.isArray(value.items) ? value.items : [];
2079
+ const summaries = await readSummaries();
2080
+ const workspace = workspaceIndex();
2081
+ const byId = new Map();
2082
+ for (const summary of summaries ?? []) {
2083
+ if (summary && typeof summary.sessionId === 'string') byId.set(summary.sessionId, summary);
2084
+ }
2085
+ const results = [];
2086
+ for (const item of items) {
2087
+ const id = typeof item?.sessionId === 'string' ? item.sessionId : '';
2088
+ if (!id) continue;
2089
+ const summary = byId.get(id);
2090
+ const wire = summary ? wireSession(summary, workspace) : undefined;
2091
+ results.push({
2092
+ id,
2093
+ title: wire?.title ?? '',
2094
+ snippet: truncate(typeof item.snippet === 'string' ? item.snippet : '', 240),
2095
+ updatedAt: wire?.updatedAt ?? 0,
2096
+ running: wire?.running === true,
2097
+ pinned: wire?.pinned === true,
2098
+ archived: wire?.archived === true,
2099
+ agentAvailable: wire?.agentAvailable === true,
2100
+ workspaceId: wire?.workspaceId ?? null,
2101
+ });
2102
+ }
2103
+ return { ok: true, query: trimmed, results, hasMore: value?.hasMore === true };
2104
+ } catch (error) {
2105
+ if (/search is disabled|SessionQueryError/i.test(errorMessage(error))) {
2106
+ return failure('session content search is disabled in this deployment', 'unavailable');
2107
+ }
2108
+ return failure(error);
2109
+ }
2110
+ },
2111
+
2112
+ /**
2113
+ * Pin or unpin one session (registry-global; cold-safe).
2114
+ *
2115
+ * @returns `{ ok:true, sessionId, pinned, archived, pinnedSessionIds,
2116
+ * archivedSessionIds }` or an error envelope.
2117
+ */
2118
+ async setSessionPinned(sessionId, pinned) {
2119
+ try {
2120
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2121
+ const wantPinned = pinned === true;
2122
+ const registry = service('workspaceRegistry');
2123
+ const controller = service('workspaceController');
2124
+ if (wantPinned) {
2125
+ if (registry && typeof registry.pinSession === 'function') await registry.pinSession(sessionId);
2126
+ else if (controller && typeof controller.pinSession === 'function') await controller.pinSession({ sessionId });
2127
+ else return failure('pinning is unavailable in this deployment', 'internal');
2128
+ } else if (registry && typeof registry.unpinSession === 'function') {
2129
+ await registry.unpinSession(sessionId);
2130
+ } else if (controller && typeof controller.unpinSession === 'function') {
2131
+ await controller.unpinSession({ sessionId });
2132
+ } else {
2133
+ return failure('pinning is unavailable in this deployment', 'internal');
2134
+ }
2135
+ const workspace = workspaceIndex();
2136
+ return {
2137
+ ok: true,
2138
+ sessionId,
2139
+ pinned: workspace.pinned.has(sessionId),
2140
+ archived: workspace.archived.has(sessionId),
2141
+ pinnedSessionIds: [...workspace.pinned],
2142
+ archivedSessionIds: [...workspace.archived],
2143
+ };
2144
+ } catch (error) {
2145
+ return mapWorkspaceFailure(error, pinned === true ? 'pin' : 'unpin');
2146
+ }
2147
+ },
2148
+
2149
+ /**
2150
+ * Archive or unarchive one session. Archived sessions stay listed so the
2151
+ * phone can show them separately, but they cannot run a model step until
2152
+ * unarchived. `stopActivity` stops a running turn/job first.
2153
+ *
2154
+ * @returns `{ ok:true, sessionId, pinned, archived, ... }` or an error
2155
+ * envelope.
2156
+ */
2157
+ async setSessionArchived(sessionId, archived, stopActivity) {
2158
+ try {
2159
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2160
+ const wantArchived = archived === true;
2161
+ const force = stopActivity === true;
2162
+ const registry = service('workspaceRegistry');
2163
+ const controller = service('workspaceController');
2164
+ if (wantArchived) {
2165
+ if (registry && typeof registry.archiveSession === 'function') {
2166
+ await registry.archiveSession(sessionId, force ? { stopActivity: true } : {});
2167
+ } else if (controller && typeof controller.archiveSession === 'function') {
2168
+ await controller.archiveSession(force ? { sessionId, stopActivity: true } : { sessionId });
2169
+ } else {
2170
+ return failure('archiving is unavailable in this deployment', 'internal');
2171
+ }
2172
+ } else if (registry && typeof registry.unarchiveSession === 'function') {
2173
+ await registry.unarchiveSession(sessionId);
2174
+ } else if (controller && typeof controller.unarchiveSession === 'function') {
2175
+ await controller.unarchiveSession({ sessionId });
2176
+ } else {
2177
+ return failure('archiving is unavailable in this deployment', 'internal');
2178
+ }
2179
+ const workspace = workspaceIndex();
2180
+ return {
2181
+ ok: true,
2182
+ sessionId,
2183
+ pinned: workspace.pinned.has(sessionId),
2184
+ archived: workspace.archived.has(sessionId),
2185
+ pinnedSessionIds: [...workspace.pinned],
2186
+ archivedSessionIds: [...workspace.archived],
2187
+ };
2188
+ } catch (error) {
2189
+ return mapWorkspaceFailure(error, archived === true ? 'archive' : 'unarchive');
2190
+ }
2191
+ },
2192
+
2193
+ /**
2194
+ * Current queue + pending-input snapshot for one live session.
2195
+ * Cold sessions cannot have a queue: returns `errorCode: 'not-live'`.
2196
+ */
2197
+ async listQueue(sessionId) {
2198
+ try {
2199
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2200
+ if (!agentIsLive(sessionId)) {
2201
+ return { ok: false, error: 'this session is not live on the Host; open it first', errorCode: 'not-live' };
2202
+ }
2203
+ const state = await readState(sessionId);
2204
+ if (!isPlainObject(state)) return failure('session state is unavailable', 'internal');
2205
+ const items = queueItems(state.queue);
2206
+ return {
2207
+ ok: true,
2208
+ sessionId,
2209
+ items: items.length > 0 ? items : queueItemsFromAgent(getLiveAgent(sessionId)),
2210
+ pendingInput: Array.isArray(state.pendingInput)
2211
+ ? state.pendingInput.filter((kind) => typeof kind === 'string')
2212
+ : [],
2213
+ running: state.running === true,
2214
+ active: state.active === true,
2215
+ };
2216
+ } catch (error) {
2217
+ return failure(error);
2218
+ }
2219
+ },
2220
+
2221
+ /**
2222
+ * Edit, remove or steer one queued message. Live-only; there is no reorder
2223
+ * action. Returns the refreshed queue items on success.
2224
+ */
2225
+ async updateQueue(sessionId, itemId, action, text) {
2226
+ try {
2227
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2228
+ if (typeof itemId !== 'string' || itemId.length === 0) {
2229
+ return failure('itemId is required', 'bad-request');
2230
+ }
2231
+ const kind = action === 'edit' || action === 'remove' || action === 'steer' ? action : '';
2232
+ if (!kind) return failure('action must be edit, remove or steer', 'bad-request');
2233
+ if (!agentIsLive(sessionId)) {
2234
+ return { ok: false, error: 'this session is not live on the Host; open it first', errorCode: 'not-live' };
2235
+ }
2236
+ const value = { kind };
2237
+ if (kind === 'edit') {
2238
+ const body = typeof text === 'string' ? text.trim() : '';
2239
+ if (body.length === 0) return failure('edited text must not be empty', 'bad-request');
2240
+ value.content = [{ type: 'text', text: body }];
2241
+ }
2242
+ const controller = service('sessionController');
2243
+ if (!controller || typeof controller.updateQueue !== 'function') {
2244
+ return failure('queue editing is unavailable in this deployment', 'internal');
2245
+ }
2246
+ try {
2247
+ await controller.updateQueue({ sessionId, itemId, action: value });
2248
+ } catch (error) {
2249
+ const code = errorCode(error);
2250
+ if (code === 'session/queue-item-not-found') {
2251
+ return failure('that queued message is no longer pending', 'not-found');
2252
+ }
2253
+ if (code === 'session/steer-unavailable') {
2254
+ return failure('the running turn no longer accepts steering', 'bad-request');
2255
+ }
2256
+ throw error;
2257
+ }
2258
+ const state = await readState(sessionId);
2259
+ const items = queueItems(state?.queue);
2260
+ return {
2261
+ ok: true,
2262
+ sessionId,
2263
+ items: items.length > 0 ? items : queueItemsFromAgent(getLiveAgent(sessionId)),
2264
+ };
2265
+ } catch (error) {
2266
+ return failure(error);
2267
+ }
2268
+ },
2269
+
2270
+ /** Newest history page for one session. */
2271
+ async history(sessionId, historyOptions = {}) {
2272
+ try {
2273
+ if (!isSessionId(sessionId)) return [];
2274
+ const limit = clampLimit(historyOptions && historyOptions.limit);
2275
+ const records = await readHistoryRecords(sessionId, limit);
2276
+ return mapHistory(records ?? []);
2277
+ } catch (error) {
2278
+ log.warn(`history failed for ${sessionId}: ${errorMessage(error)}`);
2279
+ return [];
2280
+ }
2281
+ },
2282
+
2283
+ /**
2284
+ * Save one file uploaded by the phone into the session's workspace, so the
2285
+ * agent can read it with its normal file tools (images via read_image).
2286
+ *
2287
+ * @param {string} sessionId - target session
2288
+ * @param {{ name?: string, mediaType?: string, data?: Uint8Array }} upload
2289
+ * @returns {{ ok: true, name: string, path: string, relativePath: string, size: number, mediaType: string } | object}
2290
+ */
2291
+ async saveUpload(sessionId, upload = {}) {
2292
+ try {
2293
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2294
+ const data = upload.data;
2295
+ if (!(data instanceof Uint8Array) || data.length === 0) {
2296
+ return failure('uploaded file is empty', 'bad-request');
2297
+ }
2298
+ const rawName = typeof upload.name === 'string' && upload.name.trim().length > 0
2299
+ ? upload.name.trim()
2300
+ : 'attachment'
2301
+ const safeName = rawName.replace(/[^\w.\- ]+/g, '_').slice(-100) || 'attachment'
2302
+ const mediaType = typeof upload.mediaType === 'string' && upload.mediaType.length > 0
2303
+ ? upload.mediaType
2304
+ : 'application/octet-stream'
2305
+ const base = await resolveSessionBase(sessionId)
2306
+ const directory = join(base, 'var', 'remote-mobile-uploads')
2307
+ await mkdir(directory, { recursive: true })
2308
+ const fileName = `${Date.now()}-${safeName}`
2309
+ const absolutePath = join(directory, fileName)
2310
+ await writeFile(absolutePath, data)
2311
+ return {
2312
+ ok: true,
2313
+ name: rawName,
2314
+ path: absolutePath,
2315
+ relativePath: join('var', 'remote-mobile-uploads', fileName),
2316
+ size: data.length,
2317
+ mediaType,
2318
+ }
2319
+ } catch (error) {
2320
+ return failure(error);
2321
+ }
2322
+ },
2323
+
2324
+ /**
2325
+ * Read one previously uploaded image for an inline preview in the phone UI.
2326
+ * Only files under that session's `var/remote-mobile-uploads` directory with
2327
+ * an image extension are served; everything else is refused.
2328
+ *
2329
+ * @param {string} sessionId - owning session
2330
+ * @param {string} requestedPath - absolute path from the upload result
2331
+ * @returns {{ ok: true, data: Buffer, mediaType: string, name: string } | object}
2332
+ */
2333
+ async readUpload(sessionId, requestedPath) {
2334
+ try {
2335
+ if (!isSessionId(sessionId) || typeof requestedPath !== 'string' || requestedPath.length === 0) {
2336
+ return failure('invalid upload reference', 'bad-request');
2337
+ }
2338
+ const extension = extname(requestedPath).toLowerCase();
2339
+ const mediaType = PREVIEW_MEDIA_TYPES[extension];
2340
+ if (mediaType === undefined) return failure('not a previewable image', 'bad-request');
2341
+ const base = await resolveSessionBase(sessionId);
2342
+ const directory = join(base, 'var', 'remote-mobile-uploads');
2343
+ const absolutePath = resolve(requestedPath);
2344
+ if (absolutePath !== directory && !absolutePath.startsWith(directory + sep)) {
2345
+ return failure('upload is outside this session', 'bad-request');
2346
+ }
2347
+ // Resolve symlinks before serving: a link created inside the upload
2348
+ // directory must not turn into an arbitrary file read.
2349
+ const realDirectory = await realpath(directory);
2350
+ const realPath = await realpath(absolutePath);
2351
+ if (realPath !== realDirectory && !realPath.startsWith(realDirectory + sep)) {
2352
+ return failure('upload is outside this session', 'bad-request');
2353
+ }
2354
+ const info = await stat(realPath);
2355
+ if (!info.isFile()) return failure('upload is not a file', 'bad-request');
2356
+ if (info.size > MAX_PREVIEW_BYTES) return failure('image is too large to preview', 'bad-request');
2357
+ const data = await readFile(realPath);
2358
+ return { ok: true, data, mediaType, name: basename(realPath) };
2359
+ } catch (error) {
2360
+ return failure(error);
2361
+ }
2362
+ },
2363
+
2364
+ /**
2365
+ * Context-window meter for one session. Cold-safe: reads the projection fold
2366
+ * (`contextPressure`, `tokenUsage`), never resumes an Agent.
2367
+ */
2368
+ async contextFor(sessionId) {
2369
+ try {
2370
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2371
+ let values = {};
2372
+ try {
2373
+ const projectionValue = await readProjections(sessionId);
2374
+ if (isPlainObject(projectionValue) && isPlainObject(projectionValue.values)) {
2375
+ values = projectionValue.values;
2376
+ }
2377
+ } catch (error) {
2378
+ log.warn(`context projection failed for ${sessionId}: ${errorMessage(error)}`);
2379
+ }
2380
+ return { ok: true, sessionId, ...summarizeContextValues(values) };
2381
+ } catch (error) {
2382
+ return failure(error);
2383
+ }
2384
+ },
2385
+
2386
+ /**
2387
+ * Recent `workspace/changes` events with their in-memory file summaries.
2388
+ * The summaries live only for this Host process, so a cold/foreign session
2389
+ * yields `{ available: false }` entries instead of an error.
2390
+ */
2391
+ async changesList(sessionId, limit) {
2392
+ try {
2393
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2394
+ const cap = Number.isInteger(limit) ? Math.min(Math.max(limit, 1), 20) : 10;
2395
+ let records = [];
2396
+ try {
2397
+ records = await readHistoryRecords(sessionId, 400);
2398
+ } catch (error) {
2399
+ return failure(error);
2400
+ }
2401
+ const seqs = [];
2402
+ for (const record of records ?? []) {
2403
+ const event = record && typeof record === 'object' && record.event ? record.event : record;
2404
+ if (!isPlainObject(event) || event.type !== 'workspace/changes') continue;
2405
+ const seq = finiteOrNull(event.seq);
2406
+ if (seq === null || seqs.includes(seq)) continue;
2407
+ seqs.push(seq);
2408
+ }
2409
+ const changesService = service('workspaceChanges');
2410
+ const items = [];
2411
+ for (const seq of seqs.slice(-cap)) {
2412
+ let summary;
2413
+ try {
2414
+ summary = changesService && typeof changesService.summary === 'function'
2415
+ ? changesService.summary(sessionId, seq)
2416
+ : undefined;
2417
+ } catch (error) {
2418
+ summary = undefined;
2419
+ }
2420
+ if (!summary) {
2421
+ items.push({ seq, available: false, files: [] });
2422
+ continue;
2423
+ }
2424
+ const cwd = typeof summary.cwd === 'string' ? summary.cwd : '';
2425
+ items.push({
2426
+ seq,
2427
+ available: true,
2428
+ turn: finiteOrNull(summary.turn),
2429
+ total: finiteOrNull(summary.total) ?? 0,
2430
+ added: finiteOrNull(summary.added) ?? 0,
2431
+ deleted: finiteOrNull(summary.deleted) ?? 0,
2432
+ files: (Array.isArray(summary.files) ? summary.files : []).slice(0, MAX_CHANGE_FILES).map((file, index) => ({
2433
+ index,
2434
+ path: phonePath(typeof file?.path === 'string' ? file.path : '', cwd),
2435
+ display: phonePath(typeof file?.display === 'string' ? file.display : '', cwd),
2436
+ added: finiteOrNull(file?.added) ?? 0,
2437
+ deleted: finiteOrNull(file?.deleted) ?? 0,
2438
+ binary: file?.binary === true,
2439
+ oversized: file?.oversized === true,
2440
+ })),
2441
+ });
2442
+ }
2443
+ return { ok: true, sessionId, items };
2444
+ } catch (error) {
2445
+ return failure(error);
2446
+ }
2447
+ },
2448
+
2449
+ /**
2450
+ * One file diff inside a `workspace/changes` event. Live-process only: the
2451
+ * Host recorder forgets a session when it is disposed.
2452
+ */
2453
+ async changesDiff(sessionId, seq, index) {
2454
+ try {
2455
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2456
+ if (!Number.isSafeInteger(seq) || seq < 0) return failure('seq must be a non-negative integer', 'bad-request');
2457
+ if (!Number.isSafeInteger(index) || index < 0) return failure('index must be a non-negative integer', 'bad-request');
2458
+ const changesService = service('workspaceChanges');
2459
+ if (!changesService || typeof changesService.diff !== 'function') {
2460
+ return failure('file diffs are unavailable in this deployment', 'unavailable');
2461
+ }
2462
+ const value = await withSignal((signal) => changesService.diff(sessionId, seq, index, signal), timeoutMs);
2463
+ if (!value) {
2464
+ return failure('this change is no longer available (the session is not live on this Host)', 'unavailable');
2465
+ }
2466
+ const rawPath = typeof value.path === 'string'
2467
+ ? value.path
2468
+ : typeof value.display === 'string' ? value.display : '';
2469
+ const path = phonePath(rawPath, '');
2470
+ if (value.kind === 'text') {
2471
+ const hunks = (Array.isArray(value.hunks) ? value.hunks : []).map((hunk) => ({
2472
+ oldStart: finiteOrNull(hunk?.oldStart) ?? 0,
2473
+ oldLines: finiteOrNull(hunk?.oldLines) ?? 0,
2474
+ newStart: finiteOrNull(hunk?.newStart) ?? 0,
2475
+ newLines: finiteOrNull(hunk?.newLines) ?? 0,
2476
+ lines: (Array.isArray(hunk?.lines) ? hunk.lines : [])
2477
+ .slice(0, MAX_DIFF_LINES)
2478
+ .map((line) => truncate(String(line), 400)),
2479
+ }));
2480
+ return { ok: true, sessionId, seq, index, kind: 'text', path, coarse: value.coarse === true, hunks };
2481
+ }
2482
+ return {
2483
+ ok: true,
2484
+ sessionId,
2485
+ seq,
2486
+ index,
2487
+ kind: value.kind === 'binary' ? 'binary' : 'oversized',
2488
+ path,
2489
+ coarse: false,
2490
+ hunks: [],
2491
+ };
2492
+ } catch (error) {
2493
+ return failure(error);
2494
+ }
2495
+ },
2496
+
2497
+ /**
2498
+ * Every command the live Agent's registry offers, except the phone-hidden
2499
+ * set (`export`: its Host command only records a lifecycle and the desktop
2500
+ * browser then downloads a Host-only route the phone server cannot proxy).
2501
+ *
2502
+ * Listing needs a live Agent (the registry is Agent-scoped); cold sessions
2503
+ * report `available:false` instead of activating the session just to list.
2504
+ */
2505
+ async listCommands(sessionId) {
2506
+ try {
2507
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2508
+ if (!agentIsLive(sessionId)) {
2509
+ return { ok: true, sessionId, available: false, items: [], reason: 'not-live' };
2510
+ }
2511
+ const agent = getLiveAgent(sessionId);
2512
+ if (!agent) return { ok: true, sessionId, available: false, items: [], reason: 'not-live' };
2513
+ const descriptors = await visibleCommands(agent);
2514
+ return {
2515
+ ok: true,
2516
+ sessionId,
2517
+ available: true,
2518
+ items: descriptors.map(({ name, description, hint, attachments }) => ({
2519
+ name,
2520
+ description,
2521
+ hint,
2522
+ attachments,
2523
+ })),
2524
+ };
2525
+ } catch (error) {
2526
+ return failure(error);
2527
+ }
2528
+ },
2529
+
2530
+ /**
2531
+ * Execute one Host command for a live session. The name is validated against
2532
+ * the Agent's CURRENT registry (never a static set), arguments are preserved,
2533
+ * and the full trimmed line is executed. Results arrive as durable
2534
+ * `command/run` + `command/done` events, so the phone may need to reload
2535
+ * history afterwards.
2536
+ */
2537
+ async executeCommand(sessionId, line) {
2538
+ try {
2539
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2540
+ if (typeof line !== 'string' || line.trim().length === 0) {
2541
+ return failure('command line is required', 'bad-request');
2542
+ }
2543
+ const trimmed = line.trim();
2544
+ const withoutSlash = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;
2545
+ const name = withoutSlash.split(/\s+/)[0];
2546
+ if (typeof name !== 'string' || name.length === 0 || PHONE_HIDDEN_COMMANDS.has(name)) {
2547
+ return failure('this command is not available from the phone', 'forbidden');
2548
+ }
2549
+ if (!agentIsLive(sessionId)) {
2550
+ return failure('this session is not live on the Host; send a message first', 'not-live');
2551
+ }
2552
+ const agent = getLiveAgent(sessionId);
2553
+ if (!agent) return failure('this session is not live on the Host; send a message first', 'not-live');
2554
+ const descriptors = await visibleCommands(agent);
2555
+ const command = descriptors.find((item) => item.name === name);
2556
+ if (command === undefined) {
2557
+ return failure('this command is not available from the phone', 'forbidden');
2558
+ }
2559
+ const executor = typeof command.instance?.execute === 'function'
2560
+ ? command.instance
2561
+ : service('commands');
2562
+ if (!executor || typeof executor.execute !== 'function') {
2563
+ return failure('commands are unavailable in this deployment', 'unavailable');
2564
+ }
2565
+ const value = await withSignal(
2566
+ (signal) => executor.execute(agent, trimmed, [], signal),
2567
+ COMMAND_TIMEOUT_MS,
2568
+ );
2569
+ if (!value) return failure('the command was not recognized', 'bad-request');
2570
+ const result = isPlainObject(value.result) ? value.result : {};
2571
+ return {
2572
+ ok: true,
2573
+ sessionId,
2574
+ commandId: typeof value.commandId === 'string' ? value.commandId : null,
2575
+ name,
2576
+ // Closed union in the Host: success | error | method (no listed
2577
+ // command should return `method`; treat it as a text-free success).
2578
+ kind: result.kind === 'error' ? 'error' : 'success',
2579
+ text: typeof result.text === 'string' ? truncate(result.text, 2000) : null,
2580
+ sourceEventSeq: finiteOrNull(result.sourceEventSeq),
2581
+ };
2582
+ } catch (error) {
2583
+ return failure(error);
2584
+ }
2585
+ },
2586
+
2587
+ /**
2588
+ * Admit one prompt into the session's turn queue.
2589
+ * `requestId` is the caller's idempotency key (duplicate ids are ignored by
2590
+ * the Harness). Optional `attachments` are uploads returned by `saveUpload`.
2591
+ *
2592
+ * Image uploads (`mediaType` starting with `image/`) are sent as real inline
2593
+ * image content parts when they can be read back from the session's upload
2594
+ * directory; every attachment also keeps a path reference in the text so
2595
+ * history and `/api/preview` keep working. If the Host rejects the image
2596
+ * parts, the send is retried once as text-only (path references).
2597
+ *
2598
+ * `mode` is `'queue'` (default, next turn) or `'steer'` (inject into the
2599
+ * running turn; the Host rejects/no-ops it when the agent is idle).
2600
+ * Returns `undefined` on success.
2601
+ */
2602
+ async prompt(sessionId, text, requestId, attachments, mode) {
2603
+ try {
2604
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2605
+ const promptMode = mode === 'steer' ? 'steer' : 'queue';
2606
+ const attachmentList = Array.isArray(attachments)
2607
+ ? attachments.filter((item) => isPlainObject(item) && typeof item.path === 'string' && item.path.length > 0)
2608
+ : [];
2609
+ const trimmed = typeof text === 'string' ? text.trim() : '';
2610
+ if (trimmed.length === 0 && attachmentList.length === 0) {
2611
+ return failure('prompt text must be a non-empty string', 'bad-request');
2612
+ }
2613
+ // Partition: readable images go inline, everything else (and any image
2614
+ // that exceeds the caps or cannot be read back) keeps a path reference.
2615
+ const policy = inlineImagePolicy();
2616
+ const fileAttachments = [];
2617
+ const inlineImages = [];
2618
+ let inlineBytes = 0;
2619
+ let base;
2620
+ for (const item of attachmentList) {
2621
+ const isImage = normalizeImageMediaType(item.mediaType) !== null;
2622
+ if (!isImage || inlineImages.length >= policy.maxImages) {
2623
+ fileAttachments.push(item);
2624
+ continue;
2625
+ }
2626
+ if (base === undefined) base = await resolveSessionBase(sessionId);
2627
+ const image = await readInlineImage(base, item, policy);
2628
+ if (image === null || inlineBytes + image.bytes > policy.maxMessageBytes) {
2629
+ fileAttachments.push(item);
2630
+ continue;
2631
+ }
2632
+ inlineBytes += image.bytes;
2633
+ inlineImages.push(image);
2634
+ }
2635
+ // Normal message text: user text, file path references, then the image
2636
+ // block only for images actually delivered inline.
2637
+ let normalText = trimmed;
2638
+ normalText += attachmentBlock(ATTACHMENT_BLOCK_MARKER, fileAttachments);
2639
+ normalText += attachmentBlock(IMAGE_ATTACHMENT_BLOCK_MARKER, inlineImages);
2640
+ // Fallback text lists every attachment under the legacy file-path block,
2641
+ // so a rejected image batch still reaches the model as readable paths.
2642
+ let fallbackText = trimmed;
2643
+ fallbackText += attachmentBlock(ATTACHMENT_BLOCK_MARKER, attachmentList);
2644
+ const idempotencyKey = typeof requestId === 'string' && requestId.length > 0 ? requestId : newId();
2645
+ const normalContent = [];
2646
+ if (normalText.length > 0) normalContent.push({ type: 'text', text: normalText });
2647
+ for (const image of inlineImages) {
2648
+ normalContent.push({ type: 'image', mediaType: image.mediaType, data: image.data });
2649
+ }
2650
+ const fallbackContent = fallbackText.length > 0 ? [{ type: 'text', text: fallbackText }] : [];
2651
+ const controller = service('sessionController');
2652
+ if (controller && typeof controller.prompt === 'function') {
2653
+ const send = (content) => withSignal(
2654
+ (signal) => controller.prompt({
2655
+ sessionId,
2656
+ requestId: idempotencyKey,
2657
+ // 'queue' targets the next turn; 'steer' injects into the nearest
2658
+ // step of a running turn (the Host errors when there is none).
2659
+ mode: promptMode,
2660
+ content,
2661
+ }, signal),
2662
+ PROMPT_TIMEOUT_MS,
2663
+ );
2664
+ if (inlineImages.length > 0) {
2665
+ try {
2666
+ await send(normalContent);
2667
+ return undefined;
2668
+ } catch (error) {
2669
+ // Inline images are best-effort: a Host refusal must never make a
2670
+ // phone send fail. Retry once with readable paths only.
2671
+ log.warn(`inline image prompt rejected; retrying text-only (${inlineImages.length} image(s)): ${sanitize(errorMessage(error))}`);
2672
+ await send(fallbackContent);
2673
+ return undefined;
2674
+ }
2675
+ }
2676
+ await send(normalContent);
2677
+ return undefined;
2678
+ }
2679
+ // Controller-less fallback: the loop expects frozen, identified content
2680
+ // and we cannot build image blocks without the LLM package, so send the
2681
+ // readable path references instead.
2682
+ const agent = getLiveAgent(sessionId);
2683
+ const message = {
2684
+ id: newId(),
2685
+ role: 'user',
2686
+ content: fallbackContent,
2687
+ source: { kind: 'user', rpcId: idempotencyKey },
2688
+ };
2689
+ if (promptMode === 'steer' && typeof agent?.steer === 'function') {
2690
+ agent.steer(message);
2691
+ return undefined;
2692
+ }
2693
+ if (!agent || typeof agent.followup !== 'function') {
2694
+ return failure(`session "${sessionId}" is not available`, 'not-found');
2695
+ }
2696
+ agent.followup(message);
2697
+ return undefined;
2698
+ } catch (error) {
2699
+ return failure(error);
2700
+ }
2701
+ },
2702
+
2703
+ /**
2704
+ * Deployment image limits for the SPA picker (inline-image policy applied),
2705
+ * or `null` when the attachment store is not composed.
2706
+ */
2707
+ imageLimits() {
2708
+ try {
2709
+ return imageLimitsWire();
2710
+ } catch (error) {
2711
+ log.warn(`imageLimits failed: ${errorMessage(error)}`);
2712
+ return null;
2713
+ }
2714
+ },
2715
+
2716
+ /** Stop the active turn. Stopping a cold/idle session is a no-op. */
2717
+ async cancel(sessionId) {
2718
+ try {
2719
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2720
+ const controller = service('sessionController');
2721
+ if (controller && typeof controller.cancel === 'function') {
2722
+ try {
2723
+ await controller.cancel({ sessionId });
2724
+ } catch (error) {
2725
+ // The Host only accepts cancellation for an attached agent; a cold
2726
+ // session has nothing to stop.
2727
+ if (errorCode(error) === 'session/not-found') return undefined;
2728
+ throw error;
2729
+ }
2730
+ return undefined;
2731
+ }
2732
+ const agent = getLiveAgent(sessionId);
2733
+ if (agent && typeof agent.cancel === 'function') {
2734
+ agent.cancel({ kind: 'user' });
2735
+ return undefined;
2736
+ }
2737
+ return undefined;
2738
+ } catch (error) {
2739
+ return failure(error);
2740
+ }
2741
+ },
2742
+
2743
+ /** Model catalog plus the deployment default selection. */
2744
+ async listModels() {
2745
+ try {
2746
+ const controller = service('sessionController');
2747
+ if (controller && typeof controller.modelCatalog === 'function') {
2748
+ const catalog = await controller.modelCatalog();
2749
+ return {
2750
+ catalog: flattenCatalog(catalog),
2751
+ current: selectionWire(catalog?.default),
2752
+ };
2753
+ }
2754
+ return await catalogFromLlm();
2755
+ } catch (error) {
2756
+ log.warn(`listModels failed: ${errorMessage(error)}`);
2757
+ return { catalog: [], current: null };
2758
+ }
2759
+ },
2760
+
2761
+ /** Bind a model (and optional reasoning effort) to one session. */
2762
+ async selectModel(sessionId, selection = {}) {
2763
+ try {
2764
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2765
+ if (!isPlainObject(selection)) return failure('model selection must be an object', 'bad-request');
2766
+ const provider = typeof selection.provider === 'string' ? selection.provider : '';
2767
+ const model = typeof selection.model === 'string' ? selection.model : '';
2768
+ if (!provider || !model) return failure('provider and model are required', 'bad-request');
2769
+ const request = { sessionId, provider, model };
2770
+ if (typeof selection.reasoningEffort === 'string' && selection.reasoningEffort.length > 0) {
2771
+ request.reasoningEffort = selection.reasoningEffort;
2772
+ }
2773
+ const controller = service('sessionController');
2774
+ if (controller && typeof controller.selectModel === 'function') {
2775
+ await controller.selectModel(request);
2776
+ return undefined;
2777
+ }
2778
+ const agent = getLiveAgent(sessionId);
2779
+ if (agent && agent.model && typeof agent.model.select === 'function') {
2780
+ agent.model.select(request);
2781
+ return undefined;
2782
+ }
2783
+ return failure(`session "${sessionId}" is not available`, 'not-found');
2784
+ } catch (error) {
2785
+ return failure(error);
2786
+ }
2787
+ },
2788
+
2789
+ /** Agent preset roster plus the configured default preset. */
2790
+ async listPresets() {
2791
+ try {
2792
+ const presets = service('agentPresets');
2793
+ if (!presets || typeof presets.list !== 'function') return { presets: [], current: null };
2794
+ const rows = await presets.list();
2795
+ let current = null;
2796
+ try {
2797
+ if (typeof presets.defaultId === 'string' && presets.defaultId.length > 0) current = presets.defaultId;
2798
+ } catch (error) {
2799
+ log.warn(`reading default preset failed: ${errorMessage(error)}`);
2800
+ }
2801
+ const mapped = (Array.isArray(rows) ? rows : [])
2802
+ .filter((row) => row && typeof row.id === 'string' && row.id.length > 0)
2803
+ .map((row) => ({
2804
+ id: row.id,
2805
+ title: typeof row.name === 'string' && row.name.length > 0 ? row.name : row.id,
2806
+ description: typeof row.description === 'string' ? row.description : '',
2807
+ }));
2808
+ return { presets: mapped, current };
2809
+ } catch (error) {
2810
+ log.warn(`listPresets failed: ${errorMessage(error)}`);
2811
+ return { presets: [], current: null };
2812
+ }
2813
+ },
2814
+
2815
+ /** Bind an agent preset to a still-blank session. */
2816
+ async selectPreset(sessionId, preset) {
2817
+ try {
2818
+ if (!isSessionId(sessionId)) return failure('invalid sessionId', 'bad-request');
2819
+ if (typeof preset !== 'string' || preset.length === 0) {
2820
+ return failure('preset must be a non-empty string', 'bad-request');
2821
+ }
2822
+ const presets = service('agentPresets');
2823
+ if (!presets || typeof presets.select !== 'function') {
2824
+ return failure('agent presets are unavailable in this deployment', 'internal');
2825
+ }
2826
+ let agent = getLiveAgent(sessionId);
2827
+ if (!agent) {
2828
+ const controller = service('sessionController');
2829
+ if (controller && typeof controller.resolveAgent === 'function') {
2830
+ const resolved = await controller.resolveAgent(sessionId);
2831
+ if (resolved && resolved.error) throw resolved.error;
2832
+ agent = resolved?.agent;
2833
+ }
2834
+ }
2835
+ if (!agent) return failure(`session "${sessionId}" is not available`, 'not-found');
2836
+ await presets.select(agent, preset);
2837
+ return undefined;
2838
+ } catch (error) {
2839
+ return failure(error);
2840
+ }
2841
+ },
2842
+
2843
+ /**
2844
+ * Answer a pending approval on behalf of the phone.
2845
+ * @returns true when this request id was still pending.
2846
+ */
2847
+ answerApproval(requestId, decision) {
2848
+ try {
2849
+ const entry = typeof requestId === 'string' ? pendingApprovals.get(requestId) : undefined;
2850
+ if (!entry) return false;
2851
+ const outcome = decision === 'allow'
2852
+ ? 'allowed-once'
2853
+ : decision === 'reject' ? 'rejected' : undefined;
2854
+ if (!outcome) return false;
2855
+ entry.settle(outcome);
2856
+ return true;
2857
+ } catch (error) {
2858
+ log.warn(`answerApproval failed: ${errorMessage(error)}`);
2859
+ return false;
2860
+ }
2861
+ },
2862
+
2863
+ /**
2864
+ * Answer a question for the phone.
2865
+ *
2866
+ * With a `requestId` this settles a live waterfall request. With only a
2867
+ * `callId` it answers a continued (timed-out) question through
2868
+ * `ctx.userQuestions.answer`, steering the reply into the agent.
2869
+ *
2870
+ * @param {object} payload - `{ requestId?, sessionId?, callId?, answers }`
2871
+ * @returns true when accepted; an `{ ok: false }` envelope on failure.
2872
+ */
2873
+ async answerQuestion(payload) {
2874
+ try {
2875
+ if (!isPlainObject(payload) || !Array.isArray(payload.answers)) {
2876
+ return failure('answers must be an array', 'bad-request');
2877
+ }
2878
+ const requestId = typeof payload.requestId === 'string' ? payload.requestId : undefined;
2879
+ const pending = requestId === undefined ? undefined : pendingQuestions.get(requestId);
2880
+ if (pending !== undefined) {
2881
+ try {
2882
+ const batch = normalizeAnswerBatch(payload.answers, pending.questions);
2883
+ pending.answer(batch.answers);
2884
+ return true;
2885
+ } catch (error) {
2886
+ return failure(error, 'bad-request');
2887
+ }
2888
+ }
2889
+ const callId = typeof payload.callId === 'string' ? payload.callId : undefined;
2890
+ const sessionId = typeof payload.sessionId === 'string' ? payload.sessionId : undefined;
2891
+ if (callId === undefined || sessionId === undefined) {
2892
+ return failure('the question is no longer open', 'not-found');
2893
+ }
2894
+ const userQuestions = service('userQuestions');
2895
+ if (!userQuestions || typeof userQuestions.answer !== 'function') {
2896
+ return failure('user questions are unavailable in this deployment', 'internal');
2897
+ }
2898
+ let agent = getLiveAgent(sessionId);
2899
+ if (!agent) agent = await resolveAgentForSession(sessionId);
2900
+ if (!agent) return failure(`session "${sessionId}" is not available`, 'not-found');
2901
+ const answers = payload.answers
2902
+ .filter((item) => isPlainObject(item) && typeof item.id === 'string')
2903
+ .map((item) => ({
2904
+ id: item.id,
2905
+ selected: Array.isArray(item.selected)
2906
+ ? item.selected.filter((label) => typeof label === 'string')
2907
+ : [],
2908
+ ...(typeof item.custom === 'string' && item.custom.length > 0 ? { custom: item.custom } : {}),
2909
+ }));
2910
+ if (answers.length !== payload.answers.length) return failure('every answer needs an id', 'bad-request');
2911
+ const accepted = userQuestions.answer(agent, callId, { answers });
2912
+ if (accepted === true) {
2913
+ const skipped = answers.every((entry) =>
2914
+ entry.selected.length === 0 && (entry.custom === undefined || entry.custom.length === 0));
2915
+ emit('onQuestionResolved', {
2916
+ sessionId,
2917
+ requestId: null,
2918
+ callId,
2919
+ answers,
2920
+ outcome: skipped ? 'declined' : 'answered',
2921
+ });
2922
+ }
2923
+ return accepted === true;
2924
+ } catch (error) {
2925
+ log.warn(`answerQuestion failed: ${errorMessage(error)}`);
2926
+ return failure(error);
2927
+ }
2928
+ },
2929
+
2930
+ /**
2931
+ * Subscribe to live bridge events.
2932
+ * @param {object} subscription - `{ onAssistant, onTool, onApproval,
2933
+ * onApprovalResolved, onQuestion, onQuestionResolved, onQueue, onStatus }`;
2934
+ * every handler is optional.
2935
+ * @returns {() => void} unsubscribe.
2936
+ */
2937
+ subscribe(subscription) {
2938
+ if (disposed) return () => {};
2939
+ const entry = isPlainObject(subscription) ? subscription : {};
2940
+ handlers.add(entry);
2941
+ installListeners();
2942
+ let active = true;
2943
+ return () => {
2944
+ if (!active) return;
2945
+ active = false;
2946
+ handlers.delete(entry);
2947
+ if (handlers.size === 0) {
2948
+ removeListeners();
2949
+ cancelPendingApprovals('cancelled');
2950
+ cancelPendingQuestions();
2951
+ }
2952
+ };
2953
+ },
2954
+
2955
+ /** Remove every listener and settle every pending waiter owned by the bridge. */
2956
+ dispose() {
2957
+ if (disposed) return;
2958
+ disposed = true;
2959
+ removeListeners();
2960
+ cancelPendingApprovals('cancelled');
2961
+ cancelPendingQuestions();
2962
+ handlers.clear();
2963
+ attempts.clear();
2964
+ toolStarts.clear();
2965
+ approvalContexts.clear();
2966
+ pendingApprovals.clear();
2967
+ pendingQuestions.clear();
2968
+ },
2969
+ };
2970
+
2971
+ // ---------------------------------------------------------------------------
2972
+ // Local helpers that need the closure (declared after the returned object for
2973
+ // readability; function declarations hoist).
2974
+ // ---------------------------------------------------------------------------
2975
+
2976
+ /** Resolve (resuming if needed) the live agent for one session. */
2977
+ async function resolveAgentForSession(sessionId) {
2978
+ const controller = service('sessionController');
2979
+ if (!controller || typeof controller.resolveAgent !== 'function') return undefined;
2980
+ try {
2981
+ const resolved = await controller.resolveAgent(sessionId);
2982
+ if (resolved && resolved.error) throw resolved.error;
2983
+ return resolved?.agent;
2984
+ } catch (error) {
2985
+ log.warn(`resolveAgent(${sessionId}) failed: ${errorMessage(error)}`);
2986
+ return undefined;
2987
+ }
2988
+ }
2989
+
2990
+ /**
2991
+ * Candidate command registries for one live Agent, preset realm first then the
2992
+ * Host instance. In the shipped composition the human commands (goal/plan/
2993
+ * compact/...) are mounted inside the Agent's preset, so a preset-scoped
2994
+ * `commands` service, when one exists, may hold descriptors the Host-plane
2995
+ * instance does not.
2996
+ */
2997
+ function commandServicesFor(agent) {
2998
+ const candidates = [];
2999
+ const seen = new Set();
3000
+ const add = (instance) => {
3001
+ if (!instance || typeof instance.list !== 'function' || seen.has(instance)) return;
3002
+ seen.add(instance);
3003
+ candidates.push(instance);
3004
+ };
3005
+ try {
3006
+ const presets = service('agentPresets');
3007
+ if (presets && typeof presets.serviceFor === 'function') {
3008
+ add(presets.serviceFor(agent, 'commands'));
3009
+ }
3010
+ } catch (error) {
3011
+ log.warn(`agentPresets.serviceFor(agent, 'commands') failed: ${errorMessage(error)}`);
3012
+ }
3013
+ add(service('commands'));
3014
+ return candidates;
3015
+ }
3016
+
3017
+ /** Read one command registry's descriptor list without throwing. */
3018
+ async function readCommandDescriptors(registry, agent) {
3019
+ try {
3020
+ const value = await Promise.resolve(registry.list(agent));
3021
+ return Array.isArray(value) ? value : [];
3022
+ } catch (error) {
3023
+ log.warn(`commands.list failed: ${errorMessage(error)}`);
3024
+ return [];
3025
+ }
3026
+ }
3027
+
3028
+ /**
3029
+ * Union of every registry's visible command descriptors, preset first so a
3030
+ * preset variant shadows the host definition. The phone-hidden set is
3031
+ * excluded after the union (a hidden name is hidden from every source).
3032
+ */
3033
+ async function visibleCommands(agent) {
3034
+ const seen = new Set();
3035
+ const descriptors = [];
3036
+ for (const instance of commandServicesFor(agent)) {
3037
+ const list = await readCommandDescriptors(instance, agent);
3038
+ for (const command of list) {
3039
+ const name = typeof command?.name === 'string' ? command.name : '';
3040
+ if (!name || seen.has(name)) continue;
3041
+ seen.add(name);
3042
+ if (PHONE_HIDDEN_COMMANDS.has(name)) continue;
3043
+ if (typeof command?.definitionId === 'string'
3044
+ && PHONE_HIDDEN_COMMAND_DEFINITION_IDS.has(command.definitionId)) continue;
3045
+ descriptors.push({
3046
+ name,
3047
+ description: typeof command?.description === 'string' ? command.description : '',
3048
+ hint: typeof command?.input?.hint === 'string' ? command.input.hint : null,
3049
+ attachments: command?.input?.attachments === true,
3050
+ instance,
3051
+ });
3052
+ }
3053
+ }
3054
+ descriptors.sort((left, right) => left.name.localeCompare(right.name));
3055
+ return descriptors;
3056
+ }
3057
+
3058
+ /** Look up a live agent without resuming anything. */
3059
+ function getLiveAgent(sessionId) {
3060
+ try {
3061
+ const agents = service('agents');
3062
+ if (agents && typeof agents.get === 'function') return agents.get(sessionId);
3063
+ } catch (error) {
3064
+ log.warn(`agents.get failed: ${errorMessage(error)}`);
3065
+ }
3066
+ return undefined;
3067
+ }
3068
+
3069
+ /** Flatten the Host model catalog into `[{ provider, model, label }]`. */
3070
+ function flattenCatalog(catalog) {
3071
+ const out = [];
3072
+ const groups = Array.isArray(catalog?.groups) ? catalog.groups : [];
3073
+ for (const group of groups) {
3074
+ const provider = typeof group?.id === 'string' ? group.id : '';
3075
+ if (!provider) continue;
3076
+ const models = Array.isArray(group?.models) ? group.models : [];
3077
+ for (const model of models) {
3078
+ const id = typeof model?.id === 'string' ? model.id : '';
3079
+ if (!id) continue;
3080
+ const reasoning = isPlainObject(model?.reasoning) ? model.reasoning : undefined;
3081
+ const efforts = Array.isArray(reasoning?.efforts)
3082
+ ? reasoning.efforts
3083
+ .filter((effort) => isPlainObject(effort) && typeof effort.id === 'string' && effort.id.length > 0)
3084
+ .map((effort) => ({
3085
+ id: effort.id,
3086
+ name: typeof effort.name === 'string' && effort.name.length > 0 ? effort.name : effort.id,
3087
+ description: typeof effort.description === 'string' ? effort.description : null,
3088
+ }))
3089
+ : [];
3090
+ const defaultEffort = typeof reasoning?.defaultEffort === 'string' && reasoning.defaultEffort.length > 0
3091
+ ? reasoning.defaultEffort
3092
+ : null;
3093
+ out.push({
3094
+ provider,
3095
+ model: id,
3096
+ label: typeof model?.name === 'string' && model.name.length > 0 ? model.name : id,
3097
+ // Only present when the model actually exposes a reasoning control.
3098
+ ...(efforts.length > 0
3099
+ ? { reasoning: { efforts, defaultEffort } }
3100
+ : {}),
3101
+ });
3102
+ }
3103
+ }
3104
+ return out;
3105
+ }
3106
+
3107
+ /** Fallback catalog built directly from the LLM registry. */
3108
+ async function catalogFromLlm() {
3109
+ const llm = service('llm');
3110
+ if (!llm || typeof llm.listProviders !== 'function') return { catalog: [], current: null };
3111
+ const catalog = [];
3112
+ let providers = [];
3113
+ try {
3114
+ providers = llm.listProviders() ?? [];
3115
+ } catch (error) {
3116
+ log.warn(`llm.listProviders failed: ${errorMessage(error)}`);
3117
+ }
3118
+ for (const provider of providers) {
3119
+ const providerId = typeof provider?.id === 'string' ? provider.id : '';
3120
+ if (!providerId) continue;
3121
+ let models = [];
3122
+ try {
3123
+ models = await llm.listModels(providerId);
3124
+ } catch (error) {
3125
+ log.warn(`llm.listModels(${providerId}) failed: ${errorMessage(error)}`);
3126
+ continue;
3127
+ }
3128
+ for (const model of models ?? []) {
3129
+ const modelId = typeof model?.id === 'string' ? model.id : '';
3130
+ if (!modelId) continue;
3131
+ let label = typeof model?.name === 'string' && model.name.length > 0 ? model.name : modelId;
3132
+ try {
3133
+ if (typeof llm.resolveModelInfo === 'function') {
3134
+ const info = await llm.resolveModelInfo(providerId, modelId);
3135
+ if (info && typeof info.name === 'string' && info.name.length > 0) label = info.name;
3136
+ }
3137
+ } catch {
3138
+ // keep the catalog name
3139
+ }
3140
+ catalog.push({ provider: providerId, model: modelId, label });
3141
+ }
3142
+ }
3143
+ return { catalog, current: selectionWire(defaultSelection()) };
3144
+ }
3145
+ }
3146
+
3147
+ /** Build a namespaced, failure-tolerant logger. */
3148
+ function createLogger(ctx) {
3149
+ const logger = ctx && typeof ctx === 'object' ? ctx.logger : undefined;
3150
+ const write = (level, message) => {
3151
+ try {
3152
+ const fn = logger && typeof logger[level] === 'function' ? logger[level] : undefined;
3153
+ if (fn) fn.call(logger, `remote-mobile/bridge: ${message}`);
3154
+ } catch {
3155
+ // logging must never break the bridge
3156
+ }
3157
+ };
3158
+ return {
3159
+ info: (message) => write('info', message),
3160
+ warn: (message) => write('warn', message),
3161
+ error: (message) => write('error', message),
3162
+ };
3163
+ }
3164
+
3165
+
3166
+
3167
+