@linxin666/dsh-remote-bridge 0.0.0-stage → 0.4.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +243 -2
  4. package/README.zh.md +244 -0
  5. package/cordis.patch.yml +17 -0
  6. package/lib/client.js +1830 -0
  7. package/lib/client.js.map +1 -0
  8. package/lib/index.js +3744 -0
  9. package/lib/types/client/PairEntry.d.ts +16 -0
  10. package/lib/types/client/PairPanel.d.ts +55 -0
  11. package/lib/types/client/icons.d.ts +18 -0
  12. package/lib/types/client/index.d.ts +35 -0
  13. package/lib/types/client/locales.d.ts +42 -0
  14. package/lib/types/client/pair-token.d.ts +73 -0
  15. package/lib/types/client/semantic.d.ts +28 -0
  16. package/lib/types/core/approvals.d.ts +75 -0
  17. package/lib/types/core/connection.d.ts +119 -0
  18. package/lib/types/core/crypto.d.ts +48 -0
  19. package/lib/types/core/devices.d.ts +72 -0
  20. package/lib/types/core/dsh-frames.d.ts +181 -0
  21. package/lib/types/core/envelope.d.ts +98 -0
  22. package/lib/types/core/gateway-errors.d.ts +49 -0
  23. package/lib/types/core/hub.d.ts +101 -0
  24. package/lib/types/core/loopback.d.ts +35 -0
  25. package/lib/types/core/owner-peer.d.ts +49 -0
  26. package/lib/types/core/pairing.d.ts +61 -0
  27. package/lib/types/core/protocol.d.ts +89 -0
  28. package/lib/types/core/questions.d.ts +246 -0
  29. package/lib/types/core/session-meta.d.ts +105 -0
  30. package/lib/types/core/session-permissions.d.ts +134 -0
  31. package/lib/types/core/wire.d.ts +115 -0
  32. package/lib/types/core/ws-frames.d.ts +61 -0
  33. package/lib/types/host/dsh-home.d.ts +16 -0
  34. package/lib/types/host/pair-origin.d.ts +44 -0
  35. package/lib/types/host/routes.d.ts +27 -0
  36. package/lib/types/host/websocket.d.ts +104 -0
  37. package/lib/types/index.d.ts +40 -0
  38. package/package.json +87 -3
  39. package/src/client/PairEntry.tsx +151 -0
  40. package/src/client/PairPanel.tsx +183 -0
  41. package/src/client/icons.tsx +72 -0
  42. package/src/client/index.ts +81 -0
  43. package/src/client/locales.ts +72 -0
  44. package/src/client/pair-token.ts +104 -0
  45. package/src/client/panel.module.css +344 -0
  46. package/src/client/semantic.ts +37 -0
  47. package/src/core/approvals.ts +142 -0
  48. package/src/core/connection.ts +1090 -0
  49. package/src/core/crypto.ts +113 -0
  50. package/src/core/devices.ts +209 -0
  51. package/src/core/dsh-frames.ts +486 -0
  52. package/src/core/envelope.ts +173 -0
  53. package/src/core/gateway-errors.ts +92 -0
  54. package/src/core/hub.ts +238 -0
  55. package/src/core/loopback.ts +60 -0
  56. package/src/core/owner-peer.ts +70 -0
  57. package/src/core/pairing.ts +113 -0
  58. package/src/core/protocol.ts +120 -0
  59. package/src/core/questions.ts +454 -0
  60. package/src/core/session-meta.ts +176 -0
  61. package/src/core/session-permissions.ts +266 -0
  62. package/src/core/wire.ts +155 -0
  63. package/src/core/ws-frames.ts +125 -0
  64. package/src/css-modules.d.ts +6 -0
  65. package/src/host/dsh-home.ts +42 -0
  66. package/src/host/pair-origin.ts +77 -0
  67. package/src/host/routes.ts +85 -0
  68. package/src/host/websocket.ts +325 -0
  69. package/src/index.ts +205 -0
package/lib/index.js ADDED
@@ -0,0 +1,3744 @@
1
+ import { dirname, isAbsolute, join } from "node:path";
2
+ import { createHash, createPublicKey, randomBytes, timingSafeEqual, verify } from "node:crypto";
3
+ import { chmod, mkdir, open, readFile, rename } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { isAbsolute as isAbsolute$1, join as join$1 } from "node:path/posix";
6
+ import { readFileSync } from "node:fs";
7
+ const BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
8
+ /** Encode bytes as unpadded base64url. */
9
+ function base64UrlEncode(bytes) {
10
+ return Buffer.from(bytes).toString("base64url");
11
+ }
12
+ /**
13
+ * Decode unpadded base64url text.
14
+ * @returns the bytes, or undefined when the text is not base64url.
15
+ */
16
+ function base64UrlDecode(text) {
17
+ if (text === "" || !BASE64URL_RE.test(text)) return void 0;
18
+ const bytes = Buffer.from(text, "base64url");
19
+ return bytes.toString("base64url") === text ? bytes : void 0;
20
+ }
21
+ /** Lowercase hex SHA-256 of a byte string or UTF-8 text. */
22
+ function sha256Hex(input) {
23
+ return createHash("sha256").update(input).digest("hex");
24
+ }
25
+ /** Cryptographically random unpadded base64url string of `byteLength` bytes. */
26
+ function randomBase64Url(byteLength) {
27
+ return base64UrlEncode(randomBytes(byteLength));
28
+ }
29
+ /**
30
+ * Compare two strings without leaking where they differ. Both sides are
31
+ * hashed first so the comparison is over two equal-length digests: a plain
32
+ * `===` on a token would return early on the first differing byte.
33
+ */
34
+ function constantTimeEqualText(left, right) {
35
+ return timingSafeEqual(createHash("sha256").update(left).digest(), createHash("sha256").update(right).digest());
36
+ }
37
+ /** @returns the token's stored hash: what the roster keeps in place of the secret. */
38
+ function tokenHash(token) {
39
+ return sha256Hex(token);
40
+ }
41
+ /**
42
+ * Fingerprint of a public key: SHA-256 over the DER of the SPKI exactly as the
43
+ * client sent it. It is the human-comparable identity of the device, and the
44
+ * roster pins it next to the key so a swapped key is visible.
45
+ * @returns the hex fingerprint, or undefined when the SPKI does not decode.
46
+ */
47
+ function fingerprintOfSpki(spkiBase64Url) {
48
+ const der = base64UrlDecode(spkiBase64Url);
49
+ if (der === void 0) return void 0;
50
+ return sha256Hex(der);
51
+ }
52
+ /** Whether an SPKI blob is an EC P-256 public key this bridge will verify against. */
53
+ function isP256Spki(spkiBase64Url) {
54
+ return importP256Spki(spkiBase64Url) !== void 0;
55
+ }
56
+ /**
57
+ * Import a client-supplied SPKI blob, refusing anything that is not EC P-256.
58
+ * The curve check is not decoration: node would happily verify a P-384 key and
59
+ * the bridge would accept a device that can never be interoperable.
60
+ */
61
+ function importP256Spki(spkiBase64Url) {
62
+ const der = base64UrlDecode(spkiBase64Url);
63
+ if (der === void 0) return void 0;
64
+ let key;
65
+ try {
66
+ key = createPublicKey({
67
+ key: der,
68
+ format: "der",
69
+ type: "spki"
70
+ });
71
+ } catch {
72
+ return;
73
+ }
74
+ if (key.asymmetricKeyType !== "ec") return void 0;
75
+ return key.asymmetricKeyDetails?.namedCurve === "prime256v1" ? key : void 0;
76
+ }
77
+ /**
78
+ * Verify one ES256 signature over a message.
79
+ * @param spkiBase64Url - the device's base64url SPKI, P-256.
80
+ * @param signatureBase64Url - base64url of the raw 64-byte r||s signature.
81
+ * @param message - the exact bytes that were signed.
82
+ * @returns whether the signature is valid for that key.
83
+ */
84
+ function verifyEs256(spkiBase64Url, signatureBase64Url, message) {
85
+ const key = importP256Spki(spkiBase64Url);
86
+ if (key === void 0) return false;
87
+ const signature = base64UrlDecode(signatureBase64Url);
88
+ if (signature === void 0 || signature.length !== 64) return false;
89
+ return verify("sha256", message, {
90
+ key,
91
+ dsaEncoding: "ieee-p1363"
92
+ }, signature);
93
+ }
94
+ /**
95
+ * Pending approval questions for one bridge process.
96
+ *
97
+ * One timer per question, one `settle` for every path (answer, timeout, agent
98
+ * cancellation, connection loss), so a question can never be answered twice and
99
+ * a withdrawn question leaves no timer or abort listener behind.
100
+ */
101
+ var ApprovalRegistry = class {
102
+ #timeoutMs;
103
+ #random;
104
+ #pending = /* @__PURE__ */ new Map();
105
+ constructor(options = {}) {
106
+ this.#timeoutMs = options.timeoutMs ?? 12e4;
107
+ this.#random = options.random ?? randomBase64Url;
108
+ }
109
+ /** @returns how many questions are currently waiting for a phone. */
110
+ get size() {
111
+ return this.#pending.size;
112
+ }
113
+ /**
114
+ * Claim one question.
115
+ * @param input - session identity, tool name, presentation summary, and the agent's own lifetime.
116
+ * @returns the prompt to publish, with its answer promise.
117
+ */
118
+ open(input) {
119
+ const id = this.#random(16);
120
+ let settle = () => void 0;
121
+ const answer = new Promise((resolve) => {
122
+ settle = resolve;
123
+ });
124
+ const withdraw = () => {
125
+ this.#withdraw(id);
126
+ };
127
+ const timer = setTimeout(withdraw, this.#timeoutMs);
128
+ timer.unref?.();
129
+ const signal = input.signal;
130
+ const detached = signal === void 0 ? () => void 0 : () => {
131
+ signal.removeEventListener("abort", withdraw);
132
+ };
133
+ signal?.addEventListener("abort", withdraw, { once: true });
134
+ this.#pending.set(id, {
135
+ settle,
136
+ timer,
137
+ detached
138
+ });
139
+ return {
140
+ id,
141
+ sessionId: input.sessionId,
142
+ toolName: input.toolName,
143
+ summary: input.summary,
144
+ answer
145
+ };
146
+ }
147
+ /**
148
+ * Answer one question.
149
+ * @returns whether the id was still pending; a stale, expired or unknown id is refused.
150
+ */
151
+ resolve(id, decision) {
152
+ return this.#settle(id, decision) !== void 0;
153
+ }
154
+ /**
155
+ * Withdraw the named questions, delegating each to the next answerer.
156
+ * @returns how many were still pending.
157
+ */
158
+ abandon(ids) {
159
+ let withdrawn = 0;
160
+ for (const id of ids) if (this.#settle(id, void 0) !== void 0) withdrawn += 1;
161
+ return withdrawn;
162
+ }
163
+ /**
164
+ * Withdraw every pending question, delegating each to the next answerer.
165
+ * Called when the last paired phone goes away: a question nobody can answer
166
+ * must not hold the agent until its own timeout.
167
+ * @returns how many questions were withdrawn.
168
+ */
169
+ abandonAll() {
170
+ return this.abandon([...this.#pending.keys()]);
171
+ }
172
+ /**
173
+ * Settle one question at most once.
174
+ * @returns whether this call is the one that settled it.
175
+ */
176
+ #settle(id, answer) {
177
+ const entry = this.#pending.get(id);
178
+ if (entry === void 0) return void 0;
179
+ this.#pending.delete(id);
180
+ clearTimeout(entry.timer);
181
+ entry.detached();
182
+ entry.settle(answer);
183
+ return true;
184
+ }
185
+ /** Withdraw without caring whether it was still pending (timeout and abort paths). */
186
+ #withdraw(id) {
187
+ this.#settle(id, void 0);
188
+ }
189
+ };
190
+ function isStoredDevice(value) {
191
+ if (typeof value !== "object" || value === null) return false;
192
+ const row = value;
193
+ return typeof row.deviceId === "string" && row.deviceId !== "" && typeof row.pubKey === "string" && row.pubKey !== "" && typeof row.fingerprint === "string" && row.fingerprint !== "" && typeof row.tokenHash === "string" && row.tokenHash !== "" && typeof row.createdAt === "number" && typeof row.lastSeenAt === "number";
194
+ }
195
+ /**
196
+ * The persisted, revocable device roster.
197
+ *
198
+ * Revocation is a file edit: protocol v1 has no revoke method, so an operator
199
+ * removes the row (or deletes the file) and restarts. The in-memory copy is
200
+ * loaded once per process.
201
+ */
202
+ var DeviceRoster = class {
203
+ #file;
204
+ #now;
205
+ #log;
206
+ #devices = /* @__PURE__ */ new Map();
207
+ #loaded;
208
+ constructor(options) {
209
+ this.#file = options.file;
210
+ this.#now = options.now ?? (() => Date.now());
211
+ this.#log = options.log ?? (() => void 0);
212
+ }
213
+ /**
214
+ * Read the roster once. A missing file is an empty roster; an unreadable or
215
+ * malformed one is moved aside and reported, never silently zeroed.
216
+ * @returns when the in-memory roster reflects the file.
217
+ */
218
+ load() {
219
+ this.#loaded ??= this.#read();
220
+ return this.#loaded;
221
+ }
222
+ /** @returns every paired device, without the token hash. */
223
+ devices() {
224
+ return [...this.#devices.values()].map(({ tokenHash: _ignored, ...record }) => record);
225
+ }
226
+ /**
227
+ * Resolve a bearer token to its device.
228
+ * @returns the device, or undefined when the token is unknown.
229
+ */
230
+ authenticate(token) {
231
+ if (token === "") return void 0;
232
+ const presented = tokenHash(token);
233
+ let matched;
234
+ for (const row of this.#devices.values()) if (constantTimeEqualText(row.tokenHash, presented)) matched = row;
235
+ if (matched === void 0) return void 0;
236
+ const { tokenHash: _ignored, ...record } = matched;
237
+ return record;
238
+ }
239
+ /**
240
+ * Admit one device for a public key it has already proven possession of.
241
+ * @param pubKey - base64url SPKI of the device's P-256 key.
242
+ * @returns the enrollment, or undefined when the key is not an acceptable P-256 SPKI.
243
+ */
244
+ async enroll(pubKey) {
245
+ if (!isP256Spki(pubKey)) return void 0;
246
+ const fingerprint = fingerprintOfSpki(pubKey);
247
+ if (fingerprint === void 0) return void 0;
248
+ const now = this.#now();
249
+ const deviceId = `dev_${randomBase64Url(12)}`;
250
+ const token = base64UrlEncode(randomBytes(32));
251
+ this.#devices.set(tokenHash(token), {
252
+ deviceId,
253
+ pubKey,
254
+ fingerprint,
255
+ createdAt: now,
256
+ lastSeenAt: now,
257
+ tokenHash: tokenHash(token)
258
+ });
259
+ await this.#persist();
260
+ return {
261
+ deviceId,
262
+ deviceToken: token
263
+ };
264
+ }
265
+ /** Record that a device just reconnected; the file is refreshed at most once per call. */
266
+ async touch(deviceId) {
267
+ let touched;
268
+ for (const row of this.#devices.values()) {
269
+ if (row.deviceId !== deviceId) continue;
270
+ touched = {
271
+ ...row,
272
+ lastSeenAt: this.#now()
273
+ };
274
+ this.#devices.set(row.tokenHash, touched);
275
+ break;
276
+ }
277
+ if (touched !== void 0) await this.#persist();
278
+ }
279
+ async #read() {
280
+ let text;
281
+ try {
282
+ text = await readFile(this.#file, "utf8");
283
+ } catch (error) {
284
+ if (error.code === "ENOENT") return;
285
+ this.#log(`device roster ${this.#file} is unreadable (${String(error)}); continuing with an empty roster`);
286
+ return;
287
+ }
288
+ let parsed;
289
+ try {
290
+ parsed = JSON.parse(text);
291
+ } catch {
292
+ await this.#quarantine("is not JSON");
293
+ return;
294
+ }
295
+ const rows = parsed?.devices;
296
+ if (!Array.isArray(rows) || !rows.every(isStoredDevice)) {
297
+ await this.#quarantine("has no valid device table");
298
+ return;
299
+ }
300
+ for (const row of rows) this.#devices.set(row.tokenHash, row);
301
+ this.#log(`device roster ${this.#file}: ${rows.length} paired device(s)`);
302
+ }
303
+ /** Move a corrupt roster aside so the failure survives and the next write cannot erase it. */
304
+ async #quarantine(reason) {
305
+ const target = `${this.#file}.corrupt-${this.#now()}`;
306
+ try {
307
+ await rename(this.#file, target);
308
+ this.#log(`device roster ${this.#file} ${reason}; moved to ${target} and starting empty`);
309
+ } catch (error) {
310
+ this.#log(`device roster ${this.#file} ${reason} and could not be moved aside (${String(error)}); starting empty`);
311
+ }
312
+ }
313
+ /**
314
+ * Write the roster atomically: same directory, 0600 from creation, flushed
315
+ * before the rename so a crash cannot leave a truncated file in place.
316
+ */
317
+ async #persist() {
318
+ await mkdir(dirname(this.#file), {
319
+ recursive: true,
320
+ mode: 448
321
+ });
322
+ const payload = JSON.stringify({
323
+ version: 1,
324
+ devices: [...this.#devices.values()]
325
+ }, null, 2);
326
+ const temporary = `${this.#file}.${process.pid}.${randomBase64Url(6)}.tmp`;
327
+ const handle = await open(temporary, "w", 384);
328
+ try {
329
+ await handle.writeFile(payload, "utf8");
330
+ await handle.sync();
331
+ } finally {
332
+ await handle.close();
333
+ }
334
+ await rename(temporary, this.#file);
335
+ await chmod(this.#file, 384);
336
+ }
337
+ };
338
+ /**
339
+ * The durable entry types a protocol v1 client renders — `user/message`,
340
+ * `assistant/message`, `tool/call` and `tool/result`. Everything else in a
341
+ * turn's entries is the harness's own bookkeeping, which the client can only
342
+ * count as unknown, so a client that asks for a trimmed baseline is not sent it.
343
+ */
344
+ const RENDERED_ENTRY_TYPES = /* @__PURE__ */ new Set([
345
+ "user/message",
346
+ "assistant/message",
347
+ "tool/call",
348
+ "tool/result"
349
+ ]);
350
+ function isRecord$2(value) {
351
+ return typeof value === "object" && value !== null && !Array.isArray(value);
352
+ }
353
+ function stringField(value, key) {
354
+ if (!isRecord$2(value)) return void 0;
355
+ const field = value[key];
356
+ return typeof field === "string" ? field : void 0;
357
+ }
358
+ /**
359
+ * Remembers which tool calls have already streamed their arguments, so the
360
+ * durable `tool/call` event that follows the stream is not replayed as a second
361
+ * copy of the same arguments. Bounded: a long-lived connection must not grow
362
+ * with every call it ever saw.
363
+ */
364
+ var ToolCallIndex = class {
365
+ #names = /* @__PURE__ */ new Map();
366
+ /** @returns whether this call already contributed a delta. */
367
+ has(callId) {
368
+ return this.#names.has(callId);
369
+ }
370
+ /** @returns the last name seen for this call, if any. */
371
+ nameOf(callId) {
372
+ return this.#names.get(callId);
373
+ }
374
+ /** Remember one call, evicting the oldest entry past {@link TOOL_CALL_MEMORY}. */
375
+ remember(callId, name) {
376
+ if (name !== "") this.#names.set(callId, name);
377
+ else if (!this.#names.has(callId)) this.#names.set(callId, "");
378
+ while (this.#names.size > 512) {
379
+ const oldest = this.#names.keys().next();
380
+ if (oldest.done === true) break;
381
+ this.#names.delete(oldest.value);
382
+ }
383
+ }
384
+ };
385
+ /**
386
+ * Remembers which durable user messages this connection already published.
387
+ *
388
+ * A client only ever appends a transcript, so one durable `user/message` must
389
+ * reach the wire once: a replayed event would draw the same prompt a second
390
+ * time. Bounded for the same reason {@link ToolCallIndex} is — a long-lived
391
+ * connection must not grow with every message it ever saw.
392
+ */
393
+ var MessageIndex = class {
394
+ #ids = /* @__PURE__ */ new Set();
395
+ /** @returns whether this message already contributed a delta. */
396
+ has(id) {
397
+ return this.#ids.has(id);
398
+ }
399
+ /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
400
+ remember(id) {
401
+ this.#ids.add(id);
402
+ while (this.#ids.size > 512) {
403
+ const oldest = this.#ids.values().next();
404
+ if (oldest.done === true) break;
405
+ this.#ids.delete(oldest.value);
406
+ }
407
+ }
408
+ };
409
+ /**
410
+ * Read the opening frame of a follow stream.
411
+ * @returns the cursor and records, or undefined when this frame is not a snapshot.
412
+ */
413
+ function readFollowBaseline(frame) {
414
+ if (!isRecord$2(frame) || frame.type !== "snapshot") return void 0;
415
+ const cursor = frame.cursor;
416
+ const records = frame.records;
417
+ if (typeof cursor !== "number" || !Array.isArray(records)) return void 0;
418
+ return {
419
+ cursor,
420
+ records,
421
+ hasMore: frame.hasMore === true
422
+ };
423
+ }
424
+ /**
425
+ * Map one DSH follow frame to a delta, or undefined when the frame carries no
426
+ * increment this protocol publishes.
427
+ * @param frame - one `SessionFollowFrame`.
428
+ * @param toolCalls - this connection's tool-call memory.
429
+ * @param messages - this connection's published-user-message memory.
430
+ */
431
+ function deltaOfFollowFrame(frame, toolCalls, messages) {
432
+ if (!isRecord$2(frame)) return void 0;
433
+ if (frame.type === "assistant-stream") return deltaOfAssistantStream(frame.frame, toolCalls);
434
+ if (frame.type !== "event") return void 0;
435
+ const event = frame.event;
436
+ if (!isRecord$2(event)) return void 0;
437
+ const type = event.type;
438
+ const data = event.data;
439
+ if (type === "tool/result") return toolResultDelta(data);
440
+ if (type === "turn/end") return turnEndDelta(data);
441
+ if (type === "tool/call") return assembledToolCallDelta(data, toolCalls);
442
+ if (type === "user/message") return userMessageDelta(data, messages);
443
+ if (type === "assistant/message") return usageDelta(data);
444
+ }
445
+ function deltaOfAssistantStream(frame, toolCalls) {
446
+ if (!isRecord$2(frame) || frame.type !== "chunk") return void 0;
447
+ const chunk = frame.chunk;
448
+ if (!isRecord$2(chunk)) return void 0;
449
+ const index = typeof chunk.index === "number" ? chunk.index : 0;
450
+ if (chunk.type === "text-delta" && typeof chunk.text === "string") return {
451
+ kind: "text",
452
+ text: chunk.text,
453
+ blockIndex: index
454
+ };
455
+ if (chunk.type === "reasoning-delta" && typeof chunk.text === "string") return {
456
+ kind: "reasoning",
457
+ text: chunk.text,
458
+ blockIndex: index
459
+ };
460
+ if (chunk.type === "tool-call-delta" && typeof chunk.id === "string" && chunk.id !== "") {
461
+ const callId = chunk.id;
462
+ const name = (typeof chunk.name === "string" && chunk.name !== "" ? chunk.name : void 0) ?? toolCalls.nameOf(callId) ?? "";
463
+ toolCalls.remember(callId, name);
464
+ return {
465
+ kind: "tool-call",
466
+ callId,
467
+ name,
468
+ argumentsDelta: typeof chunk.argumentsDelta === "string" ? chunk.argumentsDelta : ""
469
+ };
470
+ }
471
+ }
472
+ function toolResultDelta(data) {
473
+ const message = isRecord$2(data) ? data.message : void 0;
474
+ if (!isRecord$2(message)) return void 0;
475
+ const callId = message.toolCallId;
476
+ if (typeof callId !== "string" || callId === "") return void 0;
477
+ return {
478
+ kind: "tool-result",
479
+ callId,
480
+ output: textOfBlocks(message.content),
481
+ isError: message.isError === true
482
+ };
483
+ }
484
+ function turnEndDelta(data) {
485
+ const reason = isRecord$2(data) ? data.reason : void 0;
486
+ const kind = isRecord$2(reason) ? reason.kind : void 0;
487
+ return {
488
+ kind: "turn-end",
489
+ reason: typeof kind === "string" ? kind : "unknown"
490
+ };
491
+ }
492
+ /**
493
+ * The durable `tool/call` event carries the WHOLE argument string, not an
494
+ * increment, so it is published as a delta only when the connection never saw
495
+ * this call's increments — otherwise the client would append the arguments a
496
+ * second time.
497
+ */
498
+ function assembledToolCallDelta(data, toolCalls) {
499
+ const callId = stringField(data, "callId");
500
+ if (callId === void 0 || callId === "") return void 0;
501
+ if (toolCalls.has(callId)) return void 0;
502
+ const name = stringField(data, "name") ?? "";
503
+ toolCalls.remember(callId, name);
504
+ return {
505
+ kind: "tool-call",
506
+ callId,
507
+ name,
508
+ argumentsDelta: stringField(data, "arguments") ?? ""
509
+ };
510
+ }
511
+ /** Flatten a message's model-facing blocks to display text; non-text blocks are dropped. */
512
+ function textOfBlocks(content) {
513
+ if (!Array.isArray(content)) return "";
514
+ const parts = [];
515
+ for (const block of content) {
516
+ if (!isRecord$2(block)) continue;
517
+ if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
518
+ }
519
+ return parts.join("\n");
520
+ }
521
+ /**
522
+ * Map one durable `user/message` to the increment that shows it on a subscribed
523
+ * phone, so a prompt typed on the desktop appears without a baseline reload.
524
+ *
525
+ * Published once per message id: a replayed event must not draw the message a
526
+ * second time. The text is the message's text blocks and nothing else — image
527
+ * and file blocks travel in `attachments`, never inside it.
528
+ */
529
+ function userMessageDelta(data, messages) {
530
+ if (!isRecord$2(data)) return void 0;
531
+ const messageId = stringField(data, "id");
532
+ if (messageId !== void 0) {
533
+ if (messages.has(messageId)) return void 0;
534
+ messages.remember(messageId);
535
+ }
536
+ const attachments = imageAttachmentsOf(data.content);
537
+ return {
538
+ kind: "user-message",
539
+ text: textOfBlocks(data.content),
540
+ ...messageId === void 0 ? {} : { messageId },
541
+ ...attachments.length === 0 ? {} : { attachments }
542
+ };
543
+ }
544
+ /**
545
+ * The image references of one message's blocks, in content order.
546
+ *
547
+ * A durable image block nests its immutable reference under the block's own
548
+ * `attachment` key, so the id and media type are read from the reference — the
549
+ * block itself carries only its type and, once offloaded, that flag.
550
+ */
551
+ function imageAttachmentsOf(content) {
552
+ if (!Array.isArray(content)) return [];
553
+ const attachments = [];
554
+ for (const block of content) {
555
+ if (!isRecord$2(block) || block.type !== "image") continue;
556
+ const ref = block.attachment;
557
+ if (!isRecord$2(ref)) continue;
558
+ const attachmentId = stringField(ref, "attachmentId");
559
+ const mediaType = stringField(ref, "mediaType");
560
+ if (attachmentId === void 0 || mediaType === void 0) continue;
561
+ const name = stringField(ref, "name");
562
+ attachments.push({
563
+ attachmentId,
564
+ mediaType,
565
+ ...name === void 0 || name === "" ? {} : { name }
566
+ });
567
+ }
568
+ return attachments;
569
+ }
570
+ /**
571
+ * Map one finished `assistant/message` to its usage increment, or to nothing.
572
+ *
573
+ * An event without `usage` publishes NO delta: absent is not zero, and a client
574
+ * must never record a token count the harness did not report.
575
+ */
576
+ function usageDelta(data) {
577
+ if (!isRecord$2(data)) return void 0;
578
+ const usage = usageOf(data.usage);
579
+ if (usage === void 0) return void 0;
580
+ const turn = numberOf(data.turn);
581
+ const step = numberOf(data.step);
582
+ return {
583
+ kind: "usage",
584
+ usage,
585
+ ...turn === void 0 ? {} : { turn },
586
+ ...step === void 0 ? {} : { step }
587
+ };
588
+ }
589
+ /** Read one `TokenUsage` verbatim; undefined when its two mandatory counters are not numbers. */
590
+ function usageOf(value) {
591
+ if (!isRecord$2(value)) return void 0;
592
+ const inputTokens = numberOf(value.inputTokens);
593
+ const outputTokens = numberOf(value.outputTokens);
594
+ if (inputTokens === void 0 || outputTokens === void 0) return void 0;
595
+ const totalTokens = numberOf(value.totalTokens);
596
+ const cacheReadTokens = numberOf(value.cacheReadTokens);
597
+ const cacheWriteTokens = numberOf(value.cacheWriteTokens);
598
+ const reasoningTokens = numberOf(value.reasoningTokens);
599
+ return {
600
+ inputTokens,
601
+ outputTokens,
602
+ ...totalTokens === void 0 ? {} : { totalTokens },
603
+ ...cacheReadTokens === void 0 ? {} : { cacheReadTokens },
604
+ ...cacheWriteTokens === void 0 ? {} : { cacheWriteTokens },
605
+ ...reasoningTokens === void 0 ? {} : { reasoningTokens }
606
+ };
607
+ }
608
+ /** @returns a finite number field, or undefined. */
609
+ function numberOf(value) {
610
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
611
+ }
612
+ /**
613
+ * Project a follow baseline's records into turns.
614
+ * @param records - the baseline's durable records, oldest first.
615
+ * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
616
+ */
617
+ function turnsOfRecords(records) {
618
+ const turns = [];
619
+ let current;
620
+ for (const record of records) {
621
+ const entry = snapshotEntryOf(record);
622
+ if (entry === void 0) continue;
623
+ if (entry.type === "turn/start" && current !== void 0 && current.endSeq === 0) {
624
+ turns.push(current);
625
+ current = void 0;
626
+ }
627
+ if (current === void 0) current = {
628
+ seq: entry.type === "turn/start" ? entry.seq : 0,
629
+ time: entry.time,
630
+ endSeq: 0,
631
+ endTime: 0,
632
+ reason: "",
633
+ entries: []
634
+ };
635
+ current.entries.push(entry);
636
+ if (entry.type === "turn/end") {
637
+ current.endSeq = entry.seq;
638
+ current.endTime = entry.time;
639
+ current.reason = isRecord$2(entry.data) && isRecord$2(entry.data.reason) && typeof entry.data.reason.kind === "string" ? entry.data.reason.kind : "unknown";
640
+ turns.push(current);
641
+ current = void 0;
642
+ }
643
+ }
644
+ if (current !== void 0 && current.entries.length > 0) turns.push(current);
645
+ return turns;
646
+ }
647
+ /**
648
+ * Drop the entries of each turn that a protocol v1 client would not render.
649
+ *
650
+ * Only the inside of a turn changes: which turns survive, their order, their
651
+ * `seq`/`endSeq` metadata and every kept entry's `type` and `data` are the
652
+ * projection's own output. A turn whose entries are all unrenderable stays as a
653
+ * turn with an empty `entries` array, so the client never sees a shape it does
654
+ * not know how to read.
655
+ * @param turns - the projection of a follow baseline, in order.
656
+ * @returns the same turns, each carrying only its rendered entries.
657
+ */
658
+ function trimUnrenderedEntries(turns) {
659
+ return turns.map((turn) => {
660
+ const entries = turn.entries.filter((entry) => RENDERED_ENTRY_TYPES.has(entry.type));
661
+ return entries.length === turn.entries.length ? turn : {
662
+ ...turn,
663
+ entries
664
+ };
665
+ });
666
+ }
667
+ /**
668
+ * Slice one backwards page out of a projection, BY ENTRY rather than by turn.
669
+ *
670
+ * `before` is a durable watermark, not an index: the page carries the newest
671
+ * entries whose `seq` is strictly below it, so a cursor stays meaningful across
672
+ * connections and a projection that changed shape under it (a trimmed entry
673
+ * that never reaches the client) cannot make a page skip or repeat data. The
674
+ * turn list is rebuilt around exactly the entries in the page, each turn
675
+ * keeping its own `seq`/`endSeq`/`reason`, so a turn may be split across pages.
676
+ *
677
+ * A single entry that exceeds the budget on its own is a page of its own: the
678
+ * size rule never removes an entry, it only ends the page.
679
+ * @param turns - the projection to page, in order.
680
+ * @param before - exclusive durable watermark, or undefined for the newest page.
681
+ * @param maxBytes - byte budget of the encoded page.
682
+ * @param measure - exact encoded size of one page shape, owned by the caller.
683
+ */
684
+ function pageTurns(turns, before, maxBytes, measure) {
685
+ const flat = [];
686
+ for (const turn of turns) for (const entry of turn.entries) if (before === void 0 || entry.seq < before) flat.push({
687
+ turn,
688
+ entry
689
+ });
690
+ if (flat.length === 0) return {
691
+ turns: [],
692
+ hasMore: false
693
+ };
694
+ const shells = /* @__PURE__ */ new Map();
695
+ for (const item of flat) if (!shells.has(item.turn)) shells.set(item.turn, Buffer.byteLength(JSON.stringify({
696
+ ...item.turn,
697
+ entries: []
698
+ }), "utf8"));
699
+ let start = flat.length;
700
+ let estimate = 0;
701
+ const counted = /* @__PURE__ */ new Set();
702
+ for (let index = flat.length - 1; index >= 0; index -= 1) {
703
+ const item = flat[index];
704
+ if (item === void 0) break;
705
+ let cost = Buffer.byteLength(JSON.stringify(item.entry), "utf8") + 1;
706
+ if (!counted.has(item.turn)) {
707
+ counted.add(item.turn);
708
+ cost += shells.get(item.turn) ?? 0;
709
+ }
710
+ if (start < flat.length && estimate + cost > maxBytes) break;
711
+ estimate += cost;
712
+ start = index;
713
+ }
714
+ for (;;) {
715
+ const oldest = flat[start]?.entry.seq;
716
+ if (oldest === void 0) return {
717
+ turns: [],
718
+ hasMore: false
719
+ };
720
+ const page = groupEntries(flat.slice(start));
721
+ const hasMore = start > 0;
722
+ if (flat.length - start === 1 || measure(page, hasMore ? oldest : void 0, hasMore) <= maxBytes) return hasMore ? {
723
+ turns: page,
724
+ nextBefore: oldest,
725
+ hasMore
726
+ } : {
727
+ turns: page,
728
+ hasMore
729
+ };
730
+ start += 1;
731
+ }
732
+ }
733
+ /** Rebuild the turn list around one contiguous run of entries. */
734
+ function groupEntries(items) {
735
+ const page = [];
736
+ let current;
737
+ let entries = [];
738
+ for (const item of items) {
739
+ if (current !== item.turn) {
740
+ if (current !== void 0) page.push({
741
+ ...current,
742
+ entries
743
+ });
744
+ current = item.turn;
745
+ entries = [];
746
+ }
747
+ entries.push(item.entry);
748
+ }
749
+ if (current !== void 0) page.push({
750
+ ...current,
751
+ entries
752
+ });
753
+ return page;
754
+ }
755
+ function snapshotEntryOf(record) {
756
+ const event = isRecord$2(record) ? record.event : void 0;
757
+ if (!isRecord$2(event)) return void 0;
758
+ if (typeof event.type !== "string" || typeof event.seq !== "number") return void 0;
759
+ return {
760
+ seq: event.seq,
761
+ time: typeof event.time === "number" ? event.time : 0,
762
+ type: event.type,
763
+ data: event.data
764
+ };
765
+ }
766
+ //#endregion
767
+ //#region src/core/envelope.ts
768
+ /**
769
+ * Protocol v1 frame envelope: the one JSON-object-per-text-frame codec both
770
+ * ends of the bridge speak. Shapes are frozen by the parent card and are not
771
+ * ours to extend:
772
+ *
773
+ * request {"t":"req","id":<uint>,"m":"<method>","p":{...}}
774
+ * response {"t":"res","id":<uint>,"ok":true,"r":{...}}
775
+ * {"t":"res","id":<uint>,"ok":false,"e":{"code":"<str>","msg":"<str>"}}
776
+ * event {"t":"ev","seq":<uint>,"m":"<topic>","p":{...}}
777
+ * heartbeat {"t":"ping","ts":<ms>} / {"t":"pong","ts":<ms>}
778
+ *
779
+ * Decisions this module owns (not restated by the frozen design):
780
+ * - the 10 MiB cap is measured in UTF-8 bytes of the received text, before
781
+ * parsing, so an oversized frame never allocates a parsed object graph;
782
+ * - direction violations (a `res` or `ev` arriving FROM the client) are their
783
+ * own failure code instead of `malformed`, because "the peer is speaking the
784
+ * wrong half of the protocol" is an actionable diagnostic;
785
+ * - a frame whose identity cannot be recovered is answered with the reserved
786
+ * id 0, since the envelope has no way to decline answering.
787
+ * @module dsh-remote-bridge/core/envelope
788
+ */
789
+ /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
790
+ const MAX_FRAME_BYTES = 10 * 1024 * 1024;
791
+ /** Failure codes the codec itself raises. */
792
+ const FRAME_TOO_LARGE = "frame-too-large";
793
+ const MALFORMED_FRAME = "malformed";
794
+ const DIRECTION_VIOLATION = "direction-violation";
795
+ function isRecord$1(value) {
796
+ return typeof value === "object" && value !== null && !Array.isArray(value);
797
+ }
798
+ /** An envelope id is a non-negative safe integer. */
799
+ function isFrameId(value) {
800
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
801
+ }
802
+ /**
803
+ * Decode one received text frame.
804
+ * @param text - the frame body exactly as it crossed the wire.
805
+ * @returns the frame, or the refusal to answer with.
806
+ */
807
+ function decodeClientFrame(text) {
808
+ if (Buffer.byteLength(text, "utf8") > 10485760) return {
809
+ ok: false,
810
+ id: 0,
811
+ code: FRAME_TOO_LARGE,
812
+ msg: `frame exceeds ${MAX_FRAME_BYTES} bytes`
813
+ };
814
+ let parsed;
815
+ try {
816
+ parsed = JSON.parse(text);
817
+ } catch {
818
+ return {
819
+ ok: false,
820
+ id: 0,
821
+ code: MALFORMED_FRAME,
822
+ msg: "frame is not JSON"
823
+ };
824
+ }
825
+ if (!isRecord$1(parsed)) return {
826
+ ok: false,
827
+ id: 0,
828
+ code: MALFORMED_FRAME,
829
+ msg: "frame is not a JSON object"
830
+ };
831
+ const kind = parsed.t;
832
+ if (kind === "ping" || kind === "pong") {
833
+ if (typeof parsed.ts !== "number" || !Number.isFinite(parsed.ts)) return {
834
+ ok: false,
835
+ id: 0,
836
+ code: MALFORMED_FRAME,
837
+ msg: `${kind} requires a numeric ts`
838
+ };
839
+ return {
840
+ ok: true,
841
+ frame: {
842
+ t: kind,
843
+ ts: parsed.ts
844
+ }
845
+ };
846
+ }
847
+ if (kind === "res" || kind === "ev") return {
848
+ ok: false,
849
+ id: isFrameId(parsed.id) ? parsed.id : 0,
850
+ code: DIRECTION_VIOLATION,
851
+ msg: `a client must not send a ${kind} frame`
852
+ };
853
+ if (kind !== "req") return {
854
+ ok: false,
855
+ id: 0,
856
+ code: MALFORMED_FRAME,
857
+ msg: "frame has no known t discriminator"
858
+ };
859
+ if (!isFrameId(parsed.id)) return {
860
+ ok: false,
861
+ id: 0,
862
+ code: MALFORMED_FRAME,
863
+ msg: "req requires a non-negative integer id"
864
+ };
865
+ if (typeof parsed.m !== "string" || parsed.m === "") return {
866
+ ok: false,
867
+ id: parsed.id,
868
+ code: MALFORMED_FRAME,
869
+ msg: "req requires a method name"
870
+ };
871
+ if (parsed.p !== void 0 && !isRecord$1(parsed.p)) return {
872
+ ok: false,
873
+ id: parsed.id,
874
+ code: MALFORMED_FRAME,
875
+ msg: "req payload must be a JSON object"
876
+ };
877
+ return {
878
+ ok: true,
879
+ frame: {
880
+ t: "req",
881
+ id: parsed.id,
882
+ m: parsed.m,
883
+ p: parsed.p ?? {}
884
+ }
885
+ };
886
+ }
887
+ /** Encode one outgoing frame. */
888
+ function encodeFrame(frame) {
889
+ return JSON.stringify(frame);
890
+ }
891
+ /** One successful response frame. */
892
+ function responseFrame(id, result) {
893
+ return {
894
+ t: "res",
895
+ id,
896
+ ok: true,
897
+ r: result
898
+ };
899
+ }
900
+ /** One failed response frame. */
901
+ function errorFrame(id, code, msg) {
902
+ return {
903
+ t: "res",
904
+ id,
905
+ ok: false,
906
+ e: {
907
+ code,
908
+ msg
909
+ }
910
+ };
911
+ }
912
+ /**
913
+ * Per-connection event sequence. The frozen design gives each connection its
914
+ * own counter starting at 1; it is deliberately NOT the DSH session cursor
915
+ * (§3.4), so the two numbers are never compared.
916
+ */
917
+ var EventSequence = class {
918
+ #next = 1;
919
+ /** @returns the next sequence number, advancing the counter. */
920
+ take() {
921
+ const value = this.#next;
922
+ this.#next += 1;
923
+ return value;
924
+ }
925
+ /** @returns the value {@link take} will return next, without advancing. */
926
+ peek() {
927
+ return this.#next;
928
+ }
929
+ };
930
+ /** Namespace-qualified and bare spellings of the same failure. */
931
+ function codeIsOneOf(error, bare) {
932
+ const code = error?.code;
933
+ return code === bare || code === `gateway/${bare}`;
934
+ }
935
+ /**
936
+ * Whether a failure means the target service has not finished activating.
937
+ * This is the one failure worth retrying: the same call succeeds moments later.
938
+ */
939
+ function isServiceUnavailable(error) {
940
+ return codeIsOneOf(error, "service-unavailable");
941
+ }
942
+ function delay(ms) {
943
+ return new Promise((resolve) => {
944
+ setTimeout(resolve, ms);
945
+ });
946
+ }
947
+ /** One-line text of a failure, for a decideable reason the phone can show. */
948
+ function failureText(error) {
949
+ const message = error instanceof Error ? error.message : String(error);
950
+ return message.length > 300 ? `${message.slice(0, 297)}...` : message;
951
+ }
952
+ /**
953
+ * The failure's own code, for the response envelope. The gateway's codes cross
954
+ * to the phone unchanged (`gateway/arguments-invalid` and friends) so the client
955
+ * can tell "this deployment cannot" from "this build is wrong"; anything
956
+ * without a string code is `internal`.
957
+ */
958
+ function errorCodeOf(error, fallback) {
959
+ const code = error?.code;
960
+ return typeof code === "string" && code !== "" ? code : fallback;
961
+ }
962
+ /**
963
+ * Run one unary call, retrying only the service-activation window.
964
+ * @param run - the call to attempt.
965
+ * @param options.attempts - total tries (default {@link SERVICE_UNAVAILABLE_ATTEMPTS}).
966
+ * @param options.backoffMs - wait between tries (default {@link SERVICE_UNAVAILABLE_BACKOFF_MS}).
967
+ * @returns the call's own result or failure; the failure is never swallowed.
968
+ */
969
+ async function withServiceUnavailableRetry(run, options = {}) {
970
+ const attempts = options.attempts ?? 5;
971
+ const backoffMs = options.backoffMs ?? 2e3;
972
+ for (let attempt = 1;; attempt += 1) try {
973
+ return await run();
974
+ } catch (error) {
975
+ if (!isServiceUnavailable(error) || attempt >= attempts) throw error;
976
+ await delay(backoffMs);
977
+ }
978
+ }
979
+ //#endregion
980
+ //#region src/core/protocol.ts
981
+ /**
982
+ * The frozen protocol surface: method names, topic names, refusal codes, and
983
+ * the one authorization rule the dispatcher enforces before any method runs.
984
+ * @module dsh-remote-bridge/core/protocol
985
+ */
986
+ /** Client-callable methods of protocol v1. */
987
+ const METHOD_HELLO = "hello";
988
+ const METHOD_SESSION_LIST = "session.list";
989
+ const METHOD_SESSION_TITLES = "session.titles";
990
+ const METHOD_SESSION_SNAPSHOT = "session.snapshot";
991
+ const METHOD_SESSION_HISTORY = "session.history";
992
+ const METHOD_SESSION_PROMPT = "session.prompt";
993
+ const METHOD_SESSION_INTERRUPT = "session.interrupt";
994
+ const METHOD_SESSION_ATTACHMENT = "session.attachment";
995
+ const METHOD_SESSION_PERMISSIONS = "session.permissions";
996
+ const METHOD_SESSION_SET_PERMISSION = "session.setPermission";
997
+ const METHOD_SESSION_MODELS = "session.models";
998
+ const METHOD_SESSION_SET_MODEL = "session.setModel";
999
+ const METHOD_PAIR_BEGIN = "pair.begin";
1000
+ const METHOD_PAIR_FINISH = "pair.finish";
1001
+ const METHOD_APPROVAL_RESOLVE = "approval.resolve";
1002
+ const METHOD_QUESTION_ANSWER = "question.answer";
1003
+ /** Server-pushed topics of protocol v1. */
1004
+ const TOPIC_SESSION_DELTA = "session.delta";
1005
+ const TOPIC_QUESTION_REQUEST = "question.request";
1006
+ /**
1007
+ * Capability a client declares in `hello`'s `cap` array to be shown the
1008
+ * host's pending user questions and to answer them with `question.answer`.
1009
+ *
1010
+ * Declaring it is what makes `question.request` reachable and what makes the
1011
+ * method part of that client's protocol at all: a client that does not declare
1012
+ * it — including every client written before this channel existed — receives no
1013
+ * such event, and its `question.answer` is refused as an unknown method,
1014
+ * exactly as that frame was refused before.
1015
+ */
1016
+ const CAP_QUESTIONS = "questions.v1";
1017
+ /**
1018
+ * Methods an unpaired connection may still call: the handshake itself and the
1019
+ * two pairing steps. Everything else answers `unpaired` — a caller can pair
1020
+ * without a device token, but cannot touch a session without one.
1021
+ */
1022
+ const UNPAIRED_METHODS = /* @__PURE__ */ new Set([
1023
+ METHOD_HELLO,
1024
+ METHOD_PAIR_BEGIN,
1025
+ METHOD_PAIR_FINISH
1026
+ ]);
1027
+ /** Every method this protocol version serves. */
1028
+ const KNOWN_METHODS = /* @__PURE__ */ new Set([
1029
+ METHOD_HELLO,
1030
+ METHOD_SESSION_LIST,
1031
+ METHOD_SESSION_TITLES,
1032
+ METHOD_SESSION_SNAPSHOT,
1033
+ METHOD_SESSION_HISTORY,
1034
+ METHOD_SESSION_PROMPT,
1035
+ METHOD_SESSION_INTERRUPT,
1036
+ METHOD_SESSION_ATTACHMENT,
1037
+ METHOD_SESSION_PERMISSIONS,
1038
+ METHOD_SESSION_SET_PERMISSION,
1039
+ METHOD_SESSION_MODELS,
1040
+ METHOD_SESSION_SET_MODEL,
1041
+ METHOD_PAIR_BEGIN,
1042
+ METHOD_PAIR_FINISH,
1043
+ METHOD_APPROVAL_RESOLVE,
1044
+ METHOD_QUESTION_ANSWER
1045
+ ]);
1046
+ /** Refusal codes the bridge itself raises (DSH failures cross as their own code). */
1047
+ const CODE_UNPAIRED = "unpaired";
1048
+ const CODE_UNKNOWN_METHOD = "unknown-method";
1049
+ const CODE_INVALID_ARGS = "invalid-args";
1050
+ const CODE_PROTO_UNSUPPORTED = "proto-unsupported";
1051
+ const CODE_TOKEN_INVALID = "token-invalid";
1052
+ const CODE_NONCE_INVALID = "nonce-invalid";
1053
+ const CODE_APPROVAL_UNKNOWN = "approval-unknown";
1054
+ /**
1055
+ * The bridge does not hold the named question: it never claimed that call id, it
1056
+ * already answered it, or the host no longer holds it as answerable. Host
1057
+ * failures crossing this method keep their own codes instead.
1058
+ */
1059
+ const CODE_QUESTION_UNKNOWN = "question-unknown";
1060
+ const CODE_SNAPSHOT_UNAVAILABLE = "snapshot-unavailable";
1061
+ const CODE_SNAPSHOT_TOO_LARGE = "snapshot-too-large";
1062
+ const CODE_INTERNAL = "internal";
1063
+ /** `server` field of the hello response. */
1064
+ const SERVER_ID = "dsh-remote-bridge";
1065
+ /** Exact route path of the bridge's WebSocket endpoint. */
1066
+ const WS_PATH = "/ios/v1";
1067
+ /** Exact route path of the loopback-only bootstrap token endpoint. */
1068
+ const PAIR_TOKEN_PATH = "/remote-bridge/pair/token";
1069
+ //#endregion
1070
+ //#region src/core/session-meta.ts
1071
+ /**
1072
+ * Process-local session metadata the roster rows carry beyond the gateway's own
1073
+ * summary, and the cache that keeps a phone's title lookups off the title
1074
+ * service's hot path.
1075
+ *
1076
+ * Every read here goes to a service of the host process the bridge already runs
1077
+ * in, so nothing in this module opens a follow stream, waits on a socket or
1078
+ * touches persistence: a title is a synchronous read like a map lookup, which
1079
+ * is what makes a batch of them cheap enough to serve on request.
1080
+ *
1081
+ * The services are reached through structural faces rather than the SDK's own
1082
+ * service types, for the reason `wire.ts` states for the gateway: the live
1083
+ * objects carry far more than this package calls, and a face keeps a test
1084
+ * double down to what is actually read.
1085
+ * @module dsh-remote-bridge/core/session-meta
1086
+ */
1087
+ /** How long one resolved title is served before the service is asked again. */
1088
+ const TITLE_CACHE_TTL_MS = 1e4;
1089
+ /**
1090
+ * The bridge's session-metadata reads: live titles with a bounded cache, and
1091
+ * the host's archive set.
1092
+ *
1093
+ * One instance is built per host mount and shared by every connection, because
1094
+ * a title is a fact about the host's session, not about the device that asked.
1095
+ *
1096
+ * The cache is time-bounded rather than event-invalidated: a title change is a
1097
+ * `session/title` *log* event, which no cordis event announces, so an
1098
+ * invalidation hook would mean plumbing a listener into every live session. A
1099
+ * short TTL bounds how stale a served title can be while keeping the read off
1100
+ * the service for every repeat, and each batch call is itself a refresh point.
1101
+ */
1102
+ var SessionMeta = class {
1103
+ #faces;
1104
+ #now;
1105
+ #log;
1106
+ #ttlMs;
1107
+ #titles = /* @__PURE__ */ new Map();
1108
+ /**
1109
+ * @param faces - resolves the host services now; called per read, never captured once, so a service that mounts later is still picked up.
1110
+ * @param now - the clock the cache window is measured on.
1111
+ * @param log - where a failed metadata read is reported.
1112
+ * @param ttlMs - cache window; the default is {@link TITLE_CACHE_TTL_MS}.
1113
+ */
1114
+ constructor(faces, now, log, ttlMs = TITLE_CACHE_TTL_MS) {
1115
+ this.#faces = faces;
1116
+ this.#now = now;
1117
+ this.#log = log;
1118
+ this.#ttlMs = ttlMs;
1119
+ }
1120
+ /**
1121
+ * Latest title this host knows for one session.
1122
+ *
1123
+ * Synchronous by construction: the title service folds titles out of the
1124
+ * session log it already holds. An id that is not live here, a session whose
1125
+ * title has not landed yet, and a host without the title service all answer
1126
+ * `""`, which is the protocol's "no title" value rather than a failure.
1127
+ * @param id - session to read.
1128
+ * @returns the title, or an empty string when there is none to read.
1129
+ */
1130
+ title(id) {
1131
+ const now = this.#now();
1132
+ const cached = this.#titles.get(id);
1133
+ if (cached !== void 0 && now - cached.at < this.#ttlMs) return cached.title;
1134
+ const title = this.#resolve(id);
1135
+ this.#titles.delete(id);
1136
+ this.#titles.set(id, {
1137
+ title,
1138
+ at: now
1139
+ });
1140
+ this.#evict();
1141
+ return title;
1142
+ }
1143
+ /**
1144
+ * The title already resolved for one id, without reading any service.
1145
+ *
1146
+ * `session.list` uses this to fill a row it can fill for free; a roster must
1147
+ * not put one title read on the path of every row it lists.
1148
+ * @param id - session to look up.
1149
+ * @returns the cached title while the cache window is open, else undefined.
1150
+ */
1151
+ cachedTitle(id) {
1152
+ const cached = this.#titles.get(id);
1153
+ if (cached === void 0 || this.#now() - cached.at >= this.#ttlMs) return void 0;
1154
+ return cached.title;
1155
+ }
1156
+ /**
1157
+ * The host's archive set, or undefined when it cannot be read.
1158
+ *
1159
+ * Reading it is the only way a row can carry `archived`: the key is omitted
1160
+ * rather than guessed when the workspace registry is not mounted, so a client
1161
+ * never reads "not archived" out of a bridge that simply could not tell.
1162
+ * @returns the archived session ids, or undefined when the registry is unavailable.
1163
+ */
1164
+ archiveSet() {
1165
+ try {
1166
+ const ids = this.#faces().archive?.archivedSessionIds;
1167
+ return ids === void 0 ? void 0 : new Set(ids);
1168
+ } catch (error) {
1169
+ this.#log(`the session archive set could not be read: ${failureText(error)}`);
1170
+ return;
1171
+ }
1172
+ }
1173
+ /** Resolve one title through the host services, degrading to `""` on any failure. */
1174
+ #resolve(id) {
1175
+ try {
1176
+ const faces = this.#faces();
1177
+ const session = faces.sessions?.get(id);
1178
+ if (session === void 0) return "";
1179
+ return faces.titles?.get(session)?.title ?? "";
1180
+ } catch (error) {
1181
+ this.#log(`the title of session "${id}" could not be read: ${failureText(error)}`);
1182
+ return "";
1183
+ }
1184
+ }
1185
+ /** Drop the oldest ids until the cache is back inside its bound. */
1186
+ #evict() {
1187
+ while (this.#titles.size > 512) {
1188
+ const oldest = this.#titles.keys().next();
1189
+ if (oldest.done === true) return;
1190
+ this.#titles.delete(oldest.value);
1191
+ }
1192
+ }
1193
+ };
1194
+ //#endregion
1195
+ //#region src/core/wire.ts
1196
+ /** The durable address of one ordinary session. */
1197
+ function sessionAddress(sessionId) {
1198
+ return {
1199
+ kind: "session",
1200
+ sessionId
1201
+ };
1202
+ }
1203
+ /**
1204
+ * The durable address of one delegated child.
1205
+ *
1206
+ * The mode is always `unknown`: the bridge has no reliable way to read a
1207
+ * child's mode before the call, and the harness accepts `unknown` for every
1208
+ * child while checking a claimed mode against the descriptor.
1209
+ */
1210
+ function subagentAddress(parentSessionId, childSessionId) {
1211
+ return {
1212
+ kind: "subagent",
1213
+ parentSessionId,
1214
+ childSessionId,
1215
+ mode: "unknown"
1216
+ };
1217
+ }
1218
+ /**
1219
+ * Every endpoint of the frozen mapping table, in the order the parent card
1220
+ * lists them. Rows whose endpoint no method of protocol v1 exposes yet
1221
+ * (`pluginInventory/list`, `pluginManager/listPlugins`) stay in the table: they
1222
+ * are the layout a future method must not get wrong, and the table is the
1223
+ * single place it is written.
1224
+ */
1225
+ const WIRE_TABLE = [
1226
+ {
1227
+ namespace: "session",
1228
+ method: "list",
1229
+ wire: "_request"
1230
+ },
1231
+ {
1232
+ namespace: "session",
1233
+ method: "page",
1234
+ wire: "request"
1235
+ },
1236
+ {
1237
+ namespace: "session",
1238
+ method: "follow",
1239
+ wire: "request"
1240
+ },
1241
+ {
1242
+ namespace: "session",
1243
+ method: "prompt",
1244
+ wire: "request"
1245
+ },
1246
+ {
1247
+ namespace: "session",
1248
+ method: "cancel",
1249
+ wire: "request"
1250
+ },
1251
+ {
1252
+ namespace: "session",
1253
+ method: "attachment",
1254
+ wire: "request"
1255
+ },
1256
+ {
1257
+ namespace: "session",
1258
+ method: "projections",
1259
+ wire: "request"
1260
+ },
1261
+ {
1262
+ namespace: "session",
1263
+ method: "modelCatalog",
1264
+ wire: "none"
1265
+ },
1266
+ {
1267
+ namespace: "session",
1268
+ method: "selectModel",
1269
+ wire: "request"
1270
+ },
1271
+ {
1272
+ namespace: "userQuestions",
1273
+ method: "answer",
1274
+ wire: { names: [
1275
+ "agentId",
1276
+ "callId",
1277
+ "answer"
1278
+ ] }
1279
+ },
1280
+ {
1281
+ namespace: "pluginInventory",
1282
+ method: "list",
1283
+ wire: "none"
1284
+ },
1285
+ {
1286
+ namespace: "pluginManager",
1287
+ method: "listPlugins",
1288
+ wire: "none"
1289
+ }
1290
+ ];
1291
+ /** @returns the declared row for an endpoint, or undefined when it is not tabulated. */
1292
+ function wireRowFor(namespace, method) {
1293
+ return WIRE_TABLE.find((row) => row.namespace === namespace && row.method === method);
1294
+ }
1295
+ /**
1296
+ * Build the `args` object for one endpoint.
1297
+ *
1298
+ * An untabulated endpoint falls back to `{ request }`: that is the layout of
1299
+ * every tabulated endpoint but a few, and a wrong guess fails loudly at the
1300
+ * gateway with `arguments-invalid` rather than silently invoking the wrong
1301
+ * shape. A multi-parameter endpoint carries one key per declared name, and a
1302
+ * name the caller left out stays out — the gateway refuses it by name, which is
1303
+ * the failure a caller should see.
1304
+ * @param namespace - Remote namespace.
1305
+ * @param method - Service method name.
1306
+ * @param request - the endpoint's request payload.
1307
+ * @returns the exact named-argument object.
1308
+ */
1309
+ function wireArgs(namespace, method, request = {}) {
1310
+ const wire = wireRowFor(namespace, method)?.wire ?? "request";
1311
+ if (wire === "none") return {};
1312
+ if (typeof wire === "object") {
1313
+ const named = {};
1314
+ for (const name of wire.names) if (Object.hasOwn(request, name)) named[name] = request[name];
1315
+ return named;
1316
+ }
1317
+ return { [wire]: request };
1318
+ }
1319
+ /** How long `session.snapshot` waits for its follow stream's opening frame. */
1320
+ const SNAPSHOT_OPEN_TIMEOUT_MS = 1e4;
1321
+ /** Default byte budget of one `session.history` page: 512 KiB. */
1322
+ const HISTORY_PAGE_BYTES = 512 * 1024;
1323
+ /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
1324
+ const PROMPT_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024;
1325
+ function refusal(code, msg) {
1326
+ return {
1327
+ ok: false,
1328
+ code,
1329
+ msg
1330
+ };
1331
+ }
1332
+ function isRecord(value) {
1333
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1334
+ }
1335
+ /** @returns a non-empty string argument, or undefined. */
1336
+ function stringArg(payload, key) {
1337
+ const value = payload[key];
1338
+ return typeof value === "string" && value !== "" ? value : void 0;
1339
+ }
1340
+ /** @returns a non-empty string payload value, or undefined. */
1341
+ function optionalText(value) {
1342
+ return typeof value === "string" && value !== "" ? value : void 0;
1343
+ }
1344
+ /** @returns a non-negative safe integer page argument, or undefined. */
1345
+ function pageNumber(value) {
1346
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1347
+ }
1348
+ /**
1349
+ * Read one request's page budget.
1350
+ *
1351
+ * An absent budget is {@link HISTORY_PAGE_BYTES}; a budget an encoded page
1352
+ * could never be measured against — zero, fractional, negative or larger than
1353
+ * one frame — is refused rather than clamped, so a caller never mistakes a
1354
+ * silently reduced page for the one it asked for.
1355
+ * @param value - the request's `maxBytes` member, or undefined.
1356
+ * @param method - the method name the refusal names.
1357
+ */
1358
+ function pageBudgetOf(value, method) {
1359
+ if (value === void 0) return {
1360
+ ok: true,
1361
+ maxBytes: HISTORY_PAGE_BYTES
1362
+ };
1363
+ const maxBytes = pageNumber(value);
1364
+ if (maxBytes === void 0 || maxBytes < 1 || maxBytes > 10485760) return refusal(CODE_INVALID_ARGS, `${method} maxBytes must be between 1 and ${MAX_FRAME_BYTES}`);
1365
+ return {
1366
+ ok: true,
1367
+ maxBytes
1368
+ };
1369
+ }
1370
+ /**
1371
+ * Read the capability names a `hello` announced.
1372
+ *
1373
+ * A capability is an announcement, not a negotiation: an unreadable `cap`, an
1374
+ * unknown name and an absent key all leave the connection with no capabilities
1375
+ * rather than failing the handshake.
1376
+ * @param value - the `cap` member of a hello payload, as it crossed the wire.
1377
+ * @returns the declared names, empty when the client declared none.
1378
+ */
1379
+ function capabilitiesOf(value) {
1380
+ if (!Array.isArray(value)) return /* @__PURE__ */ new Set();
1381
+ return new Set(value.filter((name) => typeof name === "string" && name !== ""));
1382
+ }
1383
+ /**
1384
+ * Validate `question.answer`'s answer batch.
1385
+ *
1386
+ * The host validates the batch against the questions it actually asked (missing,
1387
+ * duplicated or invented ids are the host's own `BAD_ANSWER`), so this only
1388
+ * refuses what is not an answer at all: a non-array, an entry that is not an
1389
+ * object, an entry without a non-empty id, or `selected` that is not a list of
1390
+ * non-empty labels.
1391
+ * @param value - the request's `answers` member, or undefined.
1392
+ * @returns the batch in protocol vocabulary, or undefined when it is not one.
1393
+ */
1394
+ function answersOf(value) {
1395
+ if (!Array.isArray(value)) return void 0;
1396
+ const answers = [];
1397
+ for (const entry of value) {
1398
+ if (!isRecord(entry)) return void 0;
1399
+ const id = optionalText(entry.id);
1400
+ const selected = entry.selected;
1401
+ if (id === void 0 || !Array.isArray(selected)) return void 0;
1402
+ if (!selected.every((label) => typeof label === "string" && label !== "")) return void 0;
1403
+ const custom = optionalText(entry.custom);
1404
+ answers.push({
1405
+ id,
1406
+ selected,
1407
+ ...custom === void 0 ? {} : { custom }
1408
+ });
1409
+ }
1410
+ return answers;
1411
+ }
1412
+ /** @returns the selection this value describes, or undefined when it describes none. */
1413
+ function selectionOf(value) {
1414
+ if (!isRecord(value)) return void 0;
1415
+ const provider = optionalText(value.provider);
1416
+ const model = optionalText(value.model);
1417
+ if (provider === void 0 || model === void 0) return void 0;
1418
+ const reasoningEffort = optionalText(value.reasoningEffort);
1419
+ return reasoningEffort === void 0 ? {
1420
+ provider,
1421
+ model
1422
+ } : {
1423
+ provider,
1424
+ model,
1425
+ reasoningEffort
1426
+ };
1427
+ }
1428
+ /**
1429
+ * The durable model-selection fold of one `session/projections` answer.
1430
+ *
1431
+ * Both halves stay optional: a session that never ran has neither, and the
1432
+ * catalog default is then the only truthful current value.
1433
+ */
1434
+ function modelSelectionOf(value) {
1435
+ if (!isRecord(value) || !isRecord(value.values)) return {};
1436
+ const selection = value.values.modelSelection;
1437
+ if (!isRecord(selection)) return {};
1438
+ const next = selectionOf(selection.next);
1439
+ const lastUsed = selectionOf(selection.lastUsed);
1440
+ return {
1441
+ ...next === void 0 ? {} : { next },
1442
+ ...lastUsed === void 0 ? {} : { lastUsed }
1443
+ };
1444
+ }
1445
+ /**
1446
+ * Validate `session.prompt`'s optional attachments and project them to the
1447
+ * harness's image content parts, keeping the order the client sent.
1448
+ *
1449
+ * The per-attachment budget is checked here rather than at the harness: 6 MiB of
1450
+ * base64 per attachment is what keeps a prompt frame inside the envelope's
1451
+ * 10 MiB, and the refusal names the attachment and its exact byte count so the
1452
+ * phone can say which pick made the send fail. Nothing is truncated and nothing
1453
+ * is dropped — one rejected attachment withholds the whole prompt.
1454
+ * @param value - the request's `attachments` member, or undefined.
1455
+ */
1456
+ function promptAttachmentsOf(value) {
1457
+ if (value === void 0) return {
1458
+ ok: true,
1459
+ parts: []
1460
+ };
1461
+ if (!Array.isArray(value)) return refusal(CODE_INVALID_ARGS, "session.prompt attachments must be an array");
1462
+ const parts = [];
1463
+ for (const entry of value) {
1464
+ if (!isRecord(entry)) return refusal(CODE_INVALID_ARGS, "session.prompt attachments must be objects");
1465
+ const name = optionalText(entry.name);
1466
+ const label = name === void 0 ? `attachment ${parts.length + 1}` : `attachment "${name}"`;
1467
+ const mediaType = optionalText(entry.mediaType);
1468
+ const data = typeof entry.data === "string" ? entry.data : void 0;
1469
+ if (mediaType === void 0 || data === void 0 || data === "") return refusal(CODE_INVALID_ARGS, `session.prompt ${label} requires mediaType and base64 data`);
1470
+ const bytes = Buffer.byteLength(data, "utf8");
1471
+ if (bytes > 6291456) return refusal(CODE_INVALID_ARGS, `session.prompt ${label} is ${bytes} base64 bytes, past the ${PROMPT_ATTACHMENT_MAX_BYTES} byte limit`);
1472
+ parts.push({
1473
+ type: "image",
1474
+ mediaType,
1475
+ data,
1476
+ ...name === void 0 ? {} : { name }
1477
+ });
1478
+ }
1479
+ return {
1480
+ ok: true,
1481
+ parts
1482
+ };
1483
+ }
1484
+ /**
1485
+ * Everything one connected device may do.
1486
+ *
1487
+ * Not thread-safe by construction but safe by awaiting: handlers are invoked
1488
+ * one frame at a time by the carrier's reader, and the only background work is
1489
+ * a subscription's own drain loop.
1490
+ */
1491
+ var BridgeConnection = class {
1492
+ #options;
1493
+ #transport;
1494
+ #sequence = new EventSequence();
1495
+ #subscriptions = /* @__PURE__ */ new Map();
1496
+ #receipts = /* @__PURE__ */ new Set();
1497
+ #toolCalls = new ToolCallIndex();
1498
+ #messages = new MessageIndex();
1499
+ #capabilities = /* @__PURE__ */ new Set();
1500
+ /** Delegated children this connection has learned the durable parent of, by child id. */
1501
+ #lineage = /* @__PURE__ */ new Map();
1502
+ #lineageRead = false;
1503
+ #deviceId;
1504
+ #nonce;
1505
+ #heartbeat;
1506
+ #lastSendAt = 0;
1507
+ #disposed = false;
1508
+ constructor(options, transport, auth) {
1509
+ this.#options = options;
1510
+ this.#transport = transport;
1511
+ this.#deviceId = auth?.deviceId;
1512
+ this.#lastSendAt = options.now();
1513
+ }
1514
+ /** @returns whether this connection has proven a device token (or just enrolled). */
1515
+ get paired() {
1516
+ return this.#deviceId !== void 0;
1517
+ }
1518
+ /** @returns the paired device id, or undefined while unpaired. */
1519
+ get deviceId() {
1520
+ return this.#deviceId;
1521
+ }
1522
+ /** @returns whether the connection has been torn down. */
1523
+ get disposed() {
1524
+ return this.#disposed;
1525
+ }
1526
+ /**
1527
+ * @param capability - one capability name this protocol defines.
1528
+ * @returns whether this connection announced it in `hello`.
1529
+ */
1530
+ declares(capability) {
1531
+ return this.#capabilities.has(capability);
1532
+ }
1533
+ /** Start the idle heartbeat that keeps a quiet phone's socket alive. */
1534
+ startHeartbeat() {
1535
+ if (this.#heartbeat !== void 0) return;
1536
+ const period = this.#options.heartbeatMs ?? 2e4;
1537
+ this.#heartbeat = setInterval(() => {
1538
+ if (this.#options.now() - this.#lastSendAt >= period) this.#send({
1539
+ t: "ping",
1540
+ ts: this.#options.now()
1541
+ });
1542
+ }, period);
1543
+ this.#heartbeat.unref?.();
1544
+ }
1545
+ /**
1546
+ * Handle one received text frame.
1547
+ *
1548
+ * This method NEVER rejects. Its caller in the mounted wiring is
1549
+ * `void connection.handleText(text)`, so a rejection here would be dropped on
1550
+ * the floor and the client would wait forever for an answer that is never
1551
+ * coming — the same silent stall as a socket nobody reads. Any unexpected
1552
+ * failure (a roster write that cannot complete, a carrier that throws) is
1553
+ * answered as an `internal` refusal and logged.
1554
+ * @param text - the frame body as it crossed the wire.
1555
+ */
1556
+ async handleText(text) {
1557
+ if (this.#disposed) return;
1558
+ const outcome = decodeClientFrame(text);
1559
+ if (!outcome.ok) {
1560
+ this.#send(errorFrame(outcome.id, outcome.code, outcome.msg));
1561
+ return;
1562
+ }
1563
+ const frame = outcome.frame;
1564
+ if (frame.t === "ping") {
1565
+ this.#send({
1566
+ t: "pong",
1567
+ ts: frame.ts
1568
+ });
1569
+ return;
1570
+ }
1571
+ if (frame.t === "pong") return;
1572
+ try {
1573
+ const answer = await this.#dispatch(frame);
1574
+ if (answer.ok) this.#send(responseFrame(frame.id, answer.r));
1575
+ else this.#send(errorFrame(frame.id, answer.code, answer.msg));
1576
+ } catch (error) {
1577
+ this.#options.log(`${frame.m} failed unexpectedly: ${failureText(error)}`);
1578
+ this.#send(errorFrame(frame.id, CODE_INTERNAL, failureText(error)));
1579
+ }
1580
+ }
1581
+ /** Push one event to this connection, advancing its own sequence. */
1582
+ emit(topic, payload) {
1583
+ return this.#emit(topic, payload);
1584
+ }
1585
+ /**
1586
+ * Tear the connection down: stop the heartbeat, abort every follow stream it
1587
+ * owns, and tell the carrier to go away. Idempotent, and safe to call from a
1588
+ * socket error handler — a carrier whose socket already closed ignores it.
1589
+ */
1590
+ dispose() {
1591
+ if (this.#disposed) return;
1592
+ this.#disposed = true;
1593
+ if (this.#heartbeat !== void 0) {
1594
+ clearInterval(this.#heartbeat);
1595
+ this.#heartbeat = void 0;
1596
+ }
1597
+ for (const subscription of this.#subscriptions.values()) subscription.controller.abort();
1598
+ this.#subscriptions.clear();
1599
+ this.#transport.close(1001, "the bridge is going away");
1600
+ }
1601
+ async #dispatch(frame) {
1602
+ if (!KNOWN_METHODS.has(frame.m)) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
1603
+ if (frame.m === "question.answer" && !this.declares("questions.v1")) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
1604
+ if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, "this connection is not paired");
1605
+ switch (frame.m) {
1606
+ case METHOD_HELLO: return this.#hello(frame.p);
1607
+ case METHOD_PAIR_BEGIN: return this.#pairBegin(frame.p);
1608
+ case METHOD_PAIR_FINISH: return await this.#pairFinish(frame.p);
1609
+ case METHOD_SESSION_LIST: return await this.#sessionList();
1610
+ case METHOD_SESSION_TITLES: return this.#sessionTitles(frame.p);
1611
+ case METHOD_SESSION_SNAPSHOT: return await this.#sessionSnapshot(frame.p, frame.id);
1612
+ case METHOD_SESSION_HISTORY: return await this.#sessionHistory(frame.p, frame.id);
1613
+ case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p);
1614
+ case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p);
1615
+ case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id);
1616
+ case METHOD_SESSION_PERMISSIONS: return this.#sessionPermissions(frame.p);
1617
+ case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p);
1618
+ case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p);
1619
+ case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p);
1620
+ case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p);
1621
+ case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p);
1622
+ default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`);
1623
+ }
1624
+ }
1625
+ #hello(payload) {
1626
+ if (payload.proto !== 1) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol 1`);
1627
+ this.#capabilities = capabilitiesOf(payload.cap);
1628
+ this.#options.onDeclare?.(this);
1629
+ return {
1630
+ ok: true,
1631
+ r: {
1632
+ proto: 1,
1633
+ minor: 0,
1634
+ server: SERVER_ID,
1635
+ resume: "snapshot",
1636
+ auth: this.paired ? "paired" : "unpaired"
1637
+ }
1638
+ };
1639
+ }
1640
+ #pairBegin(payload) {
1641
+ const token = stringArg(payload, "token");
1642
+ if (token === void 0) return refusal(CODE_INVALID_ARGS, "pair.begin requires token");
1643
+ if (!this.#options.pairing.consumeToken(token)) return refusal(CODE_TOKEN_INVALID, "the bootstrap token is unknown, expired or already used");
1644
+ const nonce = this.#options.pairing.issueNonce();
1645
+ this.#nonce = {
1646
+ value: nonce.value,
1647
+ expiresAt: nonce.expiresAt
1648
+ };
1649
+ return {
1650
+ ok: true,
1651
+ r: {
1652
+ nonce: nonce.value,
1653
+ expiresAt: nonce.expiresAt
1654
+ }
1655
+ };
1656
+ }
1657
+ async #pairFinish(payload) {
1658
+ const devicePubKey = stringArg(payload, "devicePubKey");
1659
+ const signature = stringArg(payload, "signature");
1660
+ if (devicePubKey === void 0 || signature === void 0) return refusal(CODE_INVALID_ARGS, "pair.finish requires devicePubKey and signature");
1661
+ const nonce = this.#nonce;
1662
+ if (nonce === void 0) return refusal(CODE_NONCE_INVALID, "this connection has no open pairing");
1663
+ this.#nonce = void 0;
1664
+ if (!this.#options.pairing.consumeNonce(nonce.value) || nonce.expiresAt <= this.#options.now()) return refusal(CODE_NONCE_INVALID, "the pairing nonce is expired or already used");
1665
+ const raw = base64UrlDecode(nonce.value);
1666
+ if (!(raw !== void 0 && verifyEs256(devicePubKey, signature, raw) ? true : verifyEs256(devicePubKey, signature, Buffer.from(nonce.value, "utf8")))) return refusal("signature-invalid", "the ES256 signature does not verify against the device public key");
1667
+ const enrollment = await this.#options.roster.enroll(devicePubKey);
1668
+ if (enrollment === void 0) return refusal(CODE_INVALID_ARGS, "devicePubKey is not a P-256 SPKI public key");
1669
+ this.#deviceId = enrollment.deviceId;
1670
+ return {
1671
+ ok: true,
1672
+ r: {
1673
+ deviceToken: enrollment.deviceToken,
1674
+ deviceId: enrollment.deviceId
1675
+ }
1676
+ };
1677
+ }
1678
+ async #sessionList() {
1679
+ const call = await this.#unary("session", "list");
1680
+ if (!call.ok) return call;
1681
+ const items = isRecord(call.value) ? call.value.items : void 0;
1682
+ if (!Array.isArray(items)) return refusal(CODE_INTERNAL, "session/list returned no item table");
1683
+ const archived = this.#options.sessionMeta.archiveSet();
1684
+ const sessions = [];
1685
+ for (const item of items) {
1686
+ if (!isRecord(item) || typeof item.sessionId !== "string") continue;
1687
+ const cwd = optionalText(item.cwd);
1688
+ const parentSessionId = optionalText(item.parentSessionId);
1689
+ sessions.push({
1690
+ id: item.sessionId,
1691
+ title: this.#options.sessionMeta.cachedTitle(item.sessionId) ?? "",
1692
+ updatedAt: typeof item.updatedAt === "number" ? item.updatedAt : 0,
1693
+ agentRunning: item.running === true,
1694
+ ...cwd === void 0 ? {} : { cwd },
1695
+ ...parentSessionId === void 0 ? {} : { parentSessionId },
1696
+ ...item.origin === "subagent" ? { origin: "subagent" } : {},
1697
+ blank: item.blank === true,
1698
+ ...archived === void 0 ? {} : { archived: archived.has(item.sessionId) }
1699
+ });
1700
+ }
1701
+ this.#rememberLineage(sessions);
1702
+ return {
1703
+ ok: true,
1704
+ r: { sessions }
1705
+ };
1706
+ }
1707
+ /**
1708
+ * Answer a batch of title lookups out of this process's title service.
1709
+ *
1710
+ * Every read is synchronous and in-process, so the batch bound is the whole
1711
+ * cost bound: nothing here awaits, opens a follow stream or touches
1712
+ * persistence. A session that is not live here, one whose title has not
1713
+ * landed yet, and a host without the title service all answer `""` — the
1714
+ * batch never fails for one id, and never fails because a service is absent.
1715
+ * @param payload - `{ids}`: one to {@link TITLES_MAX_IDS} session ids.
1716
+ */
1717
+ #sessionTitles(payload) {
1718
+ const ids = payload.ids;
1719
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > 100) return refusal(CODE_INVALID_ARGS, `session.titles requires 1 to 100 session ids`);
1720
+ for (const id of ids) if (typeof id !== "string" || id === "") return refusal(CODE_INVALID_ARGS, "session.titles requires non-empty string ids");
1721
+ const titles = Object.create(null);
1722
+ for (const id of ids) titles[id] = this.#options.sessionMeta.title(id);
1723
+ return {
1724
+ ok: true,
1725
+ r: { titles }
1726
+ };
1727
+ }
1728
+ /**
1729
+ * Answer `session.snapshot`: the opening window, or one page of it.
1730
+ *
1731
+ * A client that declared {@link CAP_SESSION_SNAPSHOT_PAGE} gets the newest
1732
+ * page inside `maxBytes` (default {@link HISTORY_PAGE_BYTES}) instead of the
1733
+ * whole window, so an opening screen costs one page. The page is cut by the
1734
+ * same entry-level slice `session.history` uses, so the two can never
1735
+ * disagree, an entry larger than the whole budget is a page of its own rather
1736
+ * than a refusal, and `snapshot-too-large` cannot answer such a connection.
1737
+ * The oldest entry's own `seq` is the `before` cursor for the next, older
1738
+ * page; no second field restates it.
1739
+ * @param payload - `{sessionId, maxBytes?}`.
1740
+ * @param id - the request id the page budget is measured against.
1741
+ */
1742
+ async #sessionSnapshot(payload, id) {
1743
+ const sessionId = stringArg(payload, "sessionId");
1744
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.snapshot requires sessionId");
1745
+ const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId));
1746
+ if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`);
1747
+ const projection = this.#projectionOf(opening.baseline.records);
1748
+ if (!this.#capabilities.has("session.snapshot.page.v1")) {
1749
+ const fitted = this.#fitTurns(projection, opening.baseline.cursor, id);
1750
+ if (fitted === void 0) return refusal(CODE_SNAPSHOT_TOO_LARGE, `session ${sessionId} does not fit one ${MAX_FRAME_BYTES} byte frame`);
1751
+ return {
1752
+ ok: true,
1753
+ r: {
1754
+ turns: fitted.turns,
1755
+ lastSeq: fitted.lastSeq
1756
+ }
1757
+ };
1758
+ }
1759
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT);
1760
+ if (!budget.ok) return budget;
1761
+ const lastSeq = opening.baseline.cursor;
1762
+ const page = pageTurns(projection, void 0, budget.maxBytes, (turns, _nextBefore, hasMore) => Buffer.byteLength(JSON.stringify(responseFrame(id, {
1763
+ turns,
1764
+ lastSeq,
1765
+ hasMore
1766
+ })), "utf8"));
1767
+ return {
1768
+ ok: true,
1769
+ r: {
1770
+ turns: page.turns,
1771
+ lastSeq,
1772
+ hasMore: page.hasMore
1773
+ }
1774
+ };
1775
+ }
1776
+ /**
1777
+ * Read one backwards page of a session's history.
1778
+ *
1779
+ * Pages are cut from the very baseline `session.snapshot` serves, so the two
1780
+ * can never disagree about a turn or an entry; this method only slices that
1781
+ * projection, by entry, from the newest entry below the caller's watermark. It
1782
+ * is a pure read of the baseline: it never drops, replaces or re-addresses the
1783
+ * subscription, and the same cursor always answers the same page.
1784
+ * @param payload - `{sessionId, before?, maxBytes?}`.
1785
+ * @param id - the request id the page budget is measured against.
1786
+ */
1787
+ async #sessionHistory(payload, id) {
1788
+ const sessionId = stringArg(payload, "sessionId");
1789
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.history requires sessionId");
1790
+ const before = payload.before === void 0 ? void 0 : pageNumber(payload.before);
1791
+ if (payload.before !== void 0 && before === void 0) return refusal(CODE_INVALID_ARGS, "session.history before must be a non-negative integer");
1792
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY);
1793
+ if (!budget.ok) return budget;
1794
+ const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId));
1795
+ if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`);
1796
+ const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) => Buffer.byteLength(JSON.stringify(responseFrame(id, {
1797
+ turns,
1798
+ ...nextBefore === void 0 ? {} : { nextBefore },
1799
+ hasMore
1800
+ })), "utf8"));
1801
+ return {
1802
+ ok: true,
1803
+ r: {
1804
+ turns: page.turns,
1805
+ ...page.nextBefore === void 0 ? {} : { nextBefore: page.nextBefore },
1806
+ hasMore: page.hasMore
1807
+ }
1808
+ };
1809
+ }
1810
+ /** The projection a baseline is served with: trimmed only for a client that asked for it. */
1811
+ #projectionOf(records) {
1812
+ const projected = turnsOfRecords(records);
1813
+ return this.#capabilities.has("session.snapshot.trim.v1") ? trimUnrenderedEntries(projected) : projected;
1814
+ }
1815
+ async #sessionPrompt(payload) {
1816
+ const sessionId = stringArg(payload, "sessionId");
1817
+ const text = stringArg(payload, "text");
1818
+ const requestId = stringArg(payload, "requestId");
1819
+ if (sessionId === void 0 || text === void 0 || requestId === void 0) return refusal(CODE_INVALID_ARGS, "session.prompt requires sessionId, text and requestId");
1820
+ const attachments = promptAttachmentsOf(payload.attachments);
1821
+ if (!attachments.ok) return attachments;
1822
+ const receipt = `${sessionId}\u0000${requestId}`;
1823
+ if (this.#receipts.has(receipt)) return {
1824
+ ok: true,
1825
+ r: { accepted: true }
1826
+ };
1827
+ this.#ensureSubscription(sessionId);
1828
+ const timeZone = this.#options.clientTimeZone();
1829
+ const call = await this.#unary("session", "prompt", {
1830
+ requestId,
1831
+ sessionId,
1832
+ mode: "queue",
1833
+ content: [{
1834
+ type: "text",
1835
+ text
1836
+ }, ...attachments.parts],
1837
+ ...timeZone === void 0 || timeZone === "" ? {} : { clientTimeZone: timeZone }
1838
+ });
1839
+ if (!call.ok) return call;
1840
+ this.#rememberReceipt(receipt);
1841
+ return {
1842
+ ok: true,
1843
+ r: { accepted: true }
1844
+ };
1845
+ }
1846
+ async #sessionInterrupt(payload) {
1847
+ const sessionId = stringArg(payload, "sessionId");
1848
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.interrupt requires sessionId");
1849
+ const call = await this.#unary("session", "cancel", { sessionId });
1850
+ if (!call.ok) return call;
1851
+ return {
1852
+ ok: true,
1853
+ r: { ok: true }
1854
+ };
1855
+ }
1856
+ /**
1857
+ * Answer `session.attachment`: one durable image's bytes, straight from the
1858
+ * harness.
1859
+ *
1860
+ * The bridge keeps no cache — an image can be offloaded after the fact, so
1861
+ * every read goes to the session it belongs to — and it refuses rather than
1862
+ * writing a frame past the envelope budget: an attachment that cannot cross at
1863
+ * all is reported as such, never as an absent attachment.
1864
+ * @param payload - `{sessionId, attachmentId}`.
1865
+ * @param id - the request id the frame budget is measured against.
1866
+ */
1867
+ async #sessionAttachment(payload, id) {
1868
+ const sessionId = stringArg(payload, "sessionId");
1869
+ const attachmentId = stringArg(payload, "attachmentId");
1870
+ if (sessionId === void 0 || attachmentId === void 0) return refusal(CODE_INVALID_ARGS, "session.attachment requires sessionId and attachmentId");
1871
+ const call = await this.#unary("session", "attachment", {
1872
+ sessionId,
1873
+ attachmentId
1874
+ });
1875
+ if (!call.ok) return call;
1876
+ if (!isRecord(call.value)) return refusal(CODE_INTERNAL, "session/attachment returned no attachment");
1877
+ const bytes = Buffer.byteLength(JSON.stringify(responseFrame(id, call.value)), "utf8");
1878
+ if (bytes > 10485760) return refusal(FRAME_TOO_LARGE, `attachment ${attachmentId} needs ${bytes} bytes, past the ${MAX_FRAME_BYTES} byte frame`);
1879
+ return {
1880
+ ok: true,
1881
+ r: call.value
1882
+ };
1883
+ }
1884
+ /** Answer `session.permissions` out of the host's own preset service. */
1885
+ #sessionPermissions(payload) {
1886
+ const sessionId = stringArg(payload, "sessionId");
1887
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.permissions requires sessionId");
1888
+ const answer = this.#options.permissions.describe(sessionId);
1889
+ return "code" in answer ? refusal(answer.code, answer.msg) : {
1890
+ ok: true,
1891
+ r: answer
1892
+ };
1893
+ }
1894
+ /**
1895
+ * Switch one session's permission mode.
1896
+ *
1897
+ * This is the session-level persistent mode, deliberately apart from
1898
+ * `approval.resolve`: that answers one tool question once, this changes what
1899
+ * every later turn runs under.
1900
+ */
1901
+ #sessionSetPermission(payload) {
1902
+ const sessionId = stringArg(payload, "sessionId");
1903
+ const id = stringArg(payload, "id");
1904
+ if (sessionId === void 0 || id === void 0) return refusal(CODE_INVALID_ARGS, "session.setPermission requires sessionId and id");
1905
+ const answer = this.#options.permissions.set(sessionId, id);
1906
+ return "code" in answer ? refusal(answer.code, answer.msg) : {
1907
+ ok: true,
1908
+ r: {
1909
+ ok: true,
1910
+ current: answer.current
1911
+ }
1912
+ };
1913
+ }
1914
+ /**
1915
+ * Answer `session.models`: the host's catalog plus this session's selection.
1916
+ *
1917
+ * `current` is the session's FOLD — next, else last used, else the catalog
1918
+ * default — and never the default on its own: a phone that showed the default
1919
+ * while another model was in force would name the wrong model for the next
1920
+ * turn. The catalog's groups, failures and default cross unchanged.
1921
+ * @param payload - `{sessionId}`.
1922
+ */
1923
+ async #sessionModels(payload) {
1924
+ const sessionId = stringArg(payload, "sessionId");
1925
+ if (sessionId === void 0) return refusal(CODE_INVALID_ARGS, "session.models requires sessionId");
1926
+ const catalog = await this.#unary("session", "modelCatalog");
1927
+ if (!catalog.ok) return catalog;
1928
+ if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, "session/modelCatalog returned no catalog");
1929
+ const fallback = selectionOf(catalog.value.default);
1930
+ if (fallback === void 0) return refusal(CODE_INTERNAL, "session/modelCatalog returned no default model");
1931
+ const projections = await this.#unary("session", "projections", { sessionId });
1932
+ if (!projections.ok) return projections;
1933
+ const folded = modelSelectionOf(projections.value);
1934
+ return {
1935
+ ok: true,
1936
+ r: {
1937
+ current: folded.next ?? folded.lastUsed ?? fallback,
1938
+ default: fallback,
1939
+ groups: catalog.value.groups ?? [],
1940
+ failures: catalog.value.failures ?? []
1941
+ }
1942
+ };
1943
+ }
1944
+ /**
1945
+ * Answer `session.setModel`: register the next turn's selection.
1946
+ *
1947
+ * The harness only records the choice for the NEXT request, so the answer
1948
+ * echoes the `selected` selection it accepted and nothing here claims the
1949
+ * running turn changed.
1950
+ * @param payload - `{sessionId, provider, model, effort?}`.
1951
+ */
1952
+ async #sessionSetModel(payload) {
1953
+ const sessionId = stringArg(payload, "sessionId");
1954
+ const provider = stringArg(payload, "provider");
1955
+ const model = stringArg(payload, "model");
1956
+ if (sessionId === void 0 || provider === void 0 || model === void 0) return refusal(CODE_INVALID_ARGS, "session.setModel requires sessionId, provider and model");
1957
+ const effort = optionalText(payload.effort);
1958
+ const call = await this.#unary("session", "selectModel", {
1959
+ sessionId,
1960
+ provider,
1961
+ model,
1962
+ ...effort === void 0 ? {} : { reasoningEffort: effort }
1963
+ });
1964
+ if (!call.ok) return call;
1965
+ const selected = isRecord(call.value) ? selectionOf(call.value.selected) : void 0;
1966
+ if (selected === void 0) return refusal(CODE_INTERNAL, "session/selectModel returned no selected model");
1967
+ return {
1968
+ ok: true,
1969
+ r: {
1970
+ ok: true,
1971
+ current: selected
1972
+ }
1973
+ };
1974
+ }
1975
+ #approvalResolve(payload) {
1976
+ const id = stringArg(payload, "id");
1977
+ const decision = payload.decision;
1978
+ if (id === void 0 || decision !== "allowed-once" && decision !== "rejected") return refusal(CODE_INVALID_ARGS, "approval.resolve requires id and decision of allowed-once or rejected");
1979
+ if (!this.#options.approvals.resolve(id, decision)) return refusal(CODE_APPROVAL_UNKNOWN, "the question is unknown, already answered or expired");
1980
+ return {
1981
+ ok: true,
1982
+ r: { ok: true }
1983
+ };
1984
+ }
1985
+ /**
1986
+ * Answer one pending user question.
1987
+ *
1988
+ * The claim decides how the answer travels: an open question settles the
1989
+ * host's own ask, a continued one is steered into the agent through the
1990
+ * host's Remote `answer`. A call id this bridge does not hold is refused
1991
+ * rather than forwarded, and a host failure crosses with its own code.
1992
+ * @param payload - `{sessionId, callId, answers}`.
1993
+ */
1994
+ async #questionAnswer(payload) {
1995
+ const sessionId = stringArg(payload, "sessionId");
1996
+ const callId = stringArg(payload, "callId");
1997
+ const answers = answersOf(payload.answers);
1998
+ if (sessionId === void 0 || callId === void 0 || answers === void 0) return refusal(CODE_INVALID_ARGS, "question.answer requires sessionId, callId and answers of {id, selected, custom?}");
1999
+ const reply = await this.#options.questions.answer(sessionId, callId, { answers });
2000
+ return reply.ok ? {
2001
+ ok: true,
2002
+ r: { ok: true }
2003
+ } : refusal(reply.code, reply.msg);
2004
+ }
2005
+ /**
2006
+ * Run one unary Remote call with the activation retry, converting a gateway
2007
+ * failure into a refusal that carries the gateway's own code.
2008
+ */
2009
+ async #unary(namespace, method, request = {}) {
2010
+ try {
2011
+ return {
2012
+ ok: true,
2013
+ value: await withServiceUnavailableRetry(() => this.#options.gateway.invoke({
2014
+ namespace,
2015
+ method,
2016
+ args: wireArgs(namespace, method, request),
2017
+ peer: this.#options.ownerPeer
2018
+ }))
2019
+ };
2020
+ } catch (error) {
2021
+ this.#options.log(`${namespace}/${method} failed: ${failureText(error)}`);
2022
+ return refusal(errorCodeOf(error, CODE_INTERNAL), failureText(error));
2023
+ }
2024
+ }
2025
+ #ensureSubscription(sessionId) {
2026
+ const existing = this.#subscriptions.get(sessionId);
2027
+ if (existing !== void 0) return existing;
2028
+ const subscription = {
2029
+ sessionId,
2030
+ controller: new AbortController(),
2031
+ address: this.#addressOf(sessionId),
2032
+ opened: Promise.resolve({
2033
+ ok: false,
2034
+ code: CODE_SNAPSHOT_UNAVAILABLE,
2035
+ msg: "the stream was not opened"
2036
+ })
2037
+ };
2038
+ subscription.opened = this.#openSubscription(subscription);
2039
+ this.#subscriptions.set(sessionId, subscription);
2040
+ return subscription;
2041
+ }
2042
+ /** The durable address of one session, as far as this connection has learned it. */
2043
+ #addressOf(sessionId) {
2044
+ const parent = this.#lineage.get(sessionId);
2045
+ return parent === void 0 ? sessionAddress(sessionId) : subagentAddress(parent, sessionId);
2046
+ }
2047
+ /** Remember the durable parent of every delegated child a roster carried. */
2048
+ #rememberLineage(rows) {
2049
+ for (const row of rows) if (row.origin === "subagent" && row.parentSessionId !== void 0) this.#lineage.set(row.id, row.parentSessionId);
2050
+ }
2051
+ /**
2052
+ * The durable parent of a delegated child, or undefined when the roster does
2053
+ * not name one.
2054
+ *
2055
+ * The roster is the only endpoint that carries lineage, so it is read at most
2056
+ * once per connection: a client that listed sessions has already populated the
2057
+ * map, and a child opened without a listing costs exactly one roster read.
2058
+ */
2059
+ async #parentOf(sessionId) {
2060
+ const known = this.#lineage.get(sessionId);
2061
+ if (known !== void 0 || this.#lineageRead) return known;
2062
+ if ((await this.#sessionList()).ok) this.#lineageRead = true;
2063
+ return this.#lineage.get(sessionId);
2064
+ }
2065
+ /**
2066
+ * Open one follow stream, resolving the address kind the harness demands.
2067
+ *
2068
+ * A delegated child is addressable only through its durable parent, and the
2069
+ * harness answers `session/agent-busy` when it is asked as an ordinary session.
2070
+ * That refusal is the one signal that distinguishes it from a real failure, so
2071
+ * it is the only one that triggers a roster lookup and a retry — everything
2072
+ * else crosses to the caller unchanged.
2073
+ */
2074
+ async #openSubscription(subscription) {
2075
+ let outcome = await this.#openFollow(subscription);
2076
+ if (!outcome.ok && outcome.code === "session/agent-busy") {
2077
+ const parent = await this.#parentOf(subscription.sessionId);
2078
+ if (parent !== void 0) {
2079
+ this.#lineage.set(subscription.sessionId, parent);
2080
+ subscription.address = subagentAddress(parent, subscription.sessionId);
2081
+ outcome = await this.#openFollow(subscription);
2082
+ }
2083
+ }
2084
+ if (!outcome.ok) {
2085
+ this.#forget(subscription);
2086
+ subscription.controller.abort();
2087
+ }
2088
+ return outcome;
2089
+ }
2090
+ /** One attempt at the opening frame of a follow stream. */
2091
+ async #openFollow(subscription) {
2092
+ let iterator;
2093
+ try {
2094
+ iterator = (await withServiceUnavailableRetry(() => this.#options.gateway.stream({
2095
+ namespace: "session",
2096
+ method: "follow",
2097
+ args: wireArgs("session", "follow", {
2098
+ address: subscription.address,
2099
+ assistantStream: true,
2100
+ maxMessages: 200
2101
+ }),
2102
+ peer: this.#options.ownerPeer,
2103
+ signal: subscription.controller.signal
2104
+ })))[Symbol.asyncIterator]();
2105
+ } catch (error) {
2106
+ return {
2107
+ ok: false,
2108
+ code: errorCodeOf(error, CODE_SNAPSHOT_UNAVAILABLE),
2109
+ msg: failureText(error)
2110
+ };
2111
+ }
2112
+ try {
2113
+ const first = await iterator.next();
2114
+ const baseline = first.done === true ? void 0 : readFollowBaseline(first.value);
2115
+ if (baseline === void 0) {
2116
+ await iterator.return?.();
2117
+ return {
2118
+ ok: false,
2119
+ code: CODE_SNAPSHOT_UNAVAILABLE,
2120
+ msg: "session/follow returned no opening snapshot frame"
2121
+ };
2122
+ }
2123
+ this.#drain(subscription, iterator);
2124
+ return {
2125
+ ok: true,
2126
+ baseline
2127
+ };
2128
+ } catch (error) {
2129
+ return {
2130
+ ok: false,
2131
+ code: errorCodeOf(error, CODE_SNAPSHOT_UNAVAILABLE),
2132
+ msg: failureText(error)
2133
+ };
2134
+ }
2135
+ }
2136
+ /** Consume the rest of a follow stream, publishing every increment. */
2137
+ async #drain(subscription, iterator) {
2138
+ try {
2139
+ for (;;) {
2140
+ const next = await iterator.next();
2141
+ if (next.done === true) return;
2142
+ const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages);
2143
+ if (delta === void 0) continue;
2144
+ this.#emit(TOPIC_SESSION_DELTA, {
2145
+ sessionId: subscription.sessionId,
2146
+ ...delta
2147
+ });
2148
+ }
2149
+ } catch (error) {
2150
+ if (!subscription.controller.signal.aborted) this.#options.log(`session ${subscription.sessionId} follow stream ended: ${failureText(error)}`);
2151
+ } finally {
2152
+ this.#forget(subscription);
2153
+ }
2154
+ }
2155
+ /** Await a subscription's opening frame under a bounded wait. */
2156
+ async #awaitOpening(subscription) {
2157
+ let timer;
2158
+ const expiry = new Promise((resolve) => {
2159
+ timer = setTimeout(() => {
2160
+ resolve(void 0);
2161
+ }, SNAPSHOT_OPEN_TIMEOUT_MS);
2162
+ timer.unref?.();
2163
+ });
2164
+ try {
2165
+ const outcome = await Promise.race([subscription.opened, expiry]);
2166
+ if (outcome !== void 0) return outcome;
2167
+ subscription.controller.abort();
2168
+ this.#forget(subscription);
2169
+ return {
2170
+ ok: false,
2171
+ code: CODE_SNAPSHOT_UNAVAILABLE,
2172
+ msg: `no opening frame within ${SNAPSHOT_OPEN_TIMEOUT_MS} ms`
2173
+ };
2174
+ } finally {
2175
+ if (timer !== void 0) clearTimeout(timer);
2176
+ }
2177
+ }
2178
+ /** Drop a subscription only while it is still the current one for its session. */
2179
+ #forget(subscription) {
2180
+ if (this.#subscriptions.get(subscription.sessionId) === subscription) this.#subscriptions.delete(subscription.sessionId);
2181
+ }
2182
+ /**
2183
+ * Shrink a snapshot until it fits one frame, dropping whole oldest turns.
2184
+ * @returns the fitting payload, or undefined when even one turn cannot fit.
2185
+ */
2186
+ #fitTurns(turns, cursor, id) {
2187
+ let kept = [...turns];
2188
+ for (;;) {
2189
+ const frame = responseFrame(id, {
2190
+ turns: kept,
2191
+ lastSeq: cursor
2192
+ });
2193
+ if (Buffer.byteLength(JSON.stringify(frame), "utf8") <= 10485760) return {
2194
+ turns: kept,
2195
+ lastSeq: cursor
2196
+ };
2197
+ if (kept.length <= 1) return void 0;
2198
+ kept = kept.slice(1);
2199
+ }
2200
+ }
2201
+ #rememberReceipt(receipt) {
2202
+ this.#receipts.add(receipt);
2203
+ while (this.#receipts.size > 512) {
2204
+ const oldest = this.#receipts.values().next();
2205
+ if (oldest.done === true) break;
2206
+ this.#receipts.delete(oldest.value);
2207
+ }
2208
+ }
2209
+ #emit(topic, payload) {
2210
+ if (this.#disposed) return false;
2211
+ const text = encodeFrame({
2212
+ t: "ev",
2213
+ seq: this.#sequence.take(),
2214
+ m: topic,
2215
+ p: payload
2216
+ });
2217
+ if (Buffer.byteLength(text, "utf8") > 10485760) {
2218
+ this.#options.log(`dropped a ${topic} event past ${MAX_FRAME_BYTES} bytes`);
2219
+ return false;
2220
+ }
2221
+ return this.#write(text);
2222
+ }
2223
+ #send(frame) {
2224
+ if (this.#disposed) return;
2225
+ this.#write(encodeFrame(frame));
2226
+ }
2227
+ /**
2228
+ * Hand one encoded frame to the carrier.
2229
+ *
2230
+ * A carrier that throws must not take the process down with it: every write
2231
+ * here happens either inside a socket `data` handler or inside the approval
2232
+ * waterfall, where an escaping exception becomes an uncaught exception. A
2233
+ * failure is logged and the frame is dropped — the socket is already gone by
2234
+ * then, so there is nobody left to answer.
2235
+ * @returns whether the frame was handed to the carrier.
2236
+ */
2237
+ #write(text) {
2238
+ try {
2239
+ this.#transport.send(text);
2240
+ } catch (error) {
2241
+ this.#options.log(`could not write a frame: ${failureText(error)}`);
2242
+ return false;
2243
+ }
2244
+ this.#lastSendAt = this.#options.now();
2245
+ return true;
2246
+ }
2247
+ };
2248
+ //#endregion
2249
+ //#region src/core/hub.ts
2250
+ /** The summary line a phone shows for one question. */
2251
+ function approvalSummary(request) {
2252
+ return request.displayReason?.zh ?? request.displayReason?.en ?? request.toolName;
2253
+ }
2254
+ /**
2255
+ * The `question.request` payload for one claim.
2256
+ *
2257
+ * No `expiresAt`: the host's foreground deadline is not part of the request the
2258
+ * waterfall carries, and a bridge-invented deadline would be a timeout of the
2259
+ * bridge's own — the exact thing this channel must not have.
2260
+ * @param state - whether the foreground ask still holds the question.
2261
+ * @param question - the claim being published.
2262
+ */
2263
+ function questionPayload(state, question) {
2264
+ return {
2265
+ sessionId: question.sessionId,
2266
+ callId: question.callId,
2267
+ state,
2268
+ questions: question.questions
2269
+ };
2270
+ }
2271
+ /** The bridge's live connections plus the answerer it composes onto the approval chain. */
2272
+ var BridgeHub = class {
2273
+ #options;
2274
+ #connections = /* @__PURE__ */ new Set();
2275
+ constructor(options) {
2276
+ this.#options = options;
2277
+ }
2278
+ /** @returns how many paired devices could answer a question right now. */
2279
+ get pairedClients() {
2280
+ let count = 0;
2281
+ for (const connection of this.#connections) if (connection.paired) count += 1;
2282
+ return count;
2283
+ }
2284
+ /**
2285
+ * Register one accepted socket.
2286
+ * @param transport - the carrier the connection writes through.
2287
+ * @param auth - the device the upgrade proved, when it carried a valid token.
2288
+ */
2289
+ attach(transport, auth) {
2290
+ const connection = new BridgeConnection({
2291
+ ...this.#options,
2292
+ onDeclare: (fresh) => {
2293
+ this.replayQuestions(fresh);
2294
+ }
2295
+ }, transport, auth);
2296
+ this.#connections.add(connection);
2297
+ connection.startHeartbeat();
2298
+ if (auth !== void 0) this.#options.roster.touch(auth.deviceId).catch(() => void 0);
2299
+ this.#options.log(`connection open (${auth === void 0 ? "unpaired" : `device ${auth.deviceId}`})`);
2300
+ return connection;
2301
+ }
2302
+ /**
2303
+ * Forget one connection and abort everything it owns. When it was the last
2304
+ * paired device, every pending question is withdrawn: nobody left can answer.
2305
+ */
2306
+ detach(connection) {
2307
+ this.#connections.delete(connection);
2308
+ connection.dispose();
2309
+ if (this.pairedClients > 0) return;
2310
+ const withdrawn = this.#options.approvals.abandonAll();
2311
+ if (withdrawn > 0) this.#options.log(`${withdrawn} approval question(s) withdrew: no paired device is connected`);
2312
+ const released = this.#options.questions.withdrawAll();
2313
+ if (released > 0) this.#options.log(`${released} user question(s) released: no paired device is connected`);
2314
+ }
2315
+ /**
2316
+ * Publish one event to every paired device.
2317
+ * @returns how many connections actually took the frame.
2318
+ */
2319
+ broadcast(topic, payload) {
2320
+ let delivered = 0;
2321
+ for (const connection of this.#connections) {
2322
+ if (!connection.paired) continue;
2323
+ if (connection.emit(topic, payload)) delivered += 1;
2324
+ }
2325
+ return delivered;
2326
+ }
2327
+ /**
2328
+ * Publish one event to every paired device that announced a capability.
2329
+ * @returns how many connections actually took the frame.
2330
+ */
2331
+ /**
2332
+ * Hand one freshly declared connection the questions it can now answer.
2333
+ *
2334
+ * Without this, a question raised while the phone was reconnecting stays on the
2335
+ * host with no card anywhere on the phone: the original broadcast was addressed
2336
+ * to clients that had already announced the channel.
2337
+ */
2338
+ replayQuestions(connection) {
2339
+ if (!connection.paired || !connection.declares("questions.v1")) return;
2340
+ for (const claim of this.#options.questions.openClaims()) connection.emit(TOPIC_QUESTION_REQUEST, questionPayload("open", claim));
2341
+ }
2342
+ broadcastTo(capability, topic, payload) {
2343
+ let delivered = 0;
2344
+ for (const connection of this.#connections) {
2345
+ if (!connection.paired || !connection.declares(capability)) continue;
2346
+ if (connection.emit(topic, payload)) delivered += 1;
2347
+ }
2348
+ return delivered;
2349
+ }
2350
+ /**
2351
+ * The body of this plugin's `approval/request` listener.
2352
+ * @param request - the pending question.
2353
+ * @param next - the rest of the answerer chain.
2354
+ * @returns a claimed decision, or whatever the next answerer says.
2355
+ */
2356
+ async approve(request, next) {
2357
+ if (this.pairedClients === 0) return await next();
2358
+ const sessionId = request.agent.id;
2359
+ const prompt = this.#options.approvals.open({
2360
+ sessionId,
2361
+ toolName: request.toolName,
2362
+ summary: approvalSummary(request),
2363
+ ...request.signal === void 0 ? {} : { signal: request.signal }
2364
+ });
2365
+ if (this.broadcast("approval.request", {
2366
+ sessionId,
2367
+ id: prompt.id,
2368
+ summary: prompt.summary,
2369
+ toolName: request.toolName
2370
+ }) === 0) this.#options.approvals.abandon([prompt.id]);
2371
+ const answer = await prompt.answer;
2372
+ return answer === void 0 ? await next() : answer;
2373
+ }
2374
+ /**
2375
+ * The body of this plugin's `user-questions/request` listener.
2376
+ *
2377
+ * Claimed only while a paired device is connected and the ask names an agent:
2378
+ * the payload has no session field of its own, and a question nobody can be
2379
+ * told about is not one this bridge may hold. The wire id is the host's own
2380
+ * when the ask is timed, and minted here when it is blocking and the host
2381
+ * assigned none — either way the phone answers the id it was shown. A claim
2382
+ * nobody received is withdrawn at once instead of holding the agent until the
2383
+ * host's deadline.
2384
+ * @param request - the pending question batch.
2385
+ * @param next - the rest of the answerer chain.
2386
+ * @returns the phone's answer, the host's own deadline outcome, or whatever the next answerer says.
2387
+ */
2388
+ async question(request, next) {
2389
+ const sessionId = request.agent?.id;
2390
+ if (sessionId === void 0) return await next();
2391
+ if (this.pairedClients === 0) return await next();
2392
+ const hosted = request.wait?.callId;
2393
+ const callId = hosted ?? this.#options.questions.mintCallId();
2394
+ const claim = this.#options.questions.open({
2395
+ sessionId,
2396
+ callId,
2397
+ hosted: hosted !== void 0,
2398
+ questions: request.questions,
2399
+ next,
2400
+ ...request.signal === void 0 ? {} : { signal: request.signal },
2401
+ onSettled: (question) => {
2402
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload("settled", question));
2403
+ },
2404
+ onContinued: (question) => {
2405
+ this.broadcastTo(CAP_QUESTIONS, TOPIC_QUESTION_REQUEST, questionPayload("continued", question));
2406
+ }
2407
+ });
2408
+ if (claim === void 0) return await next();
2409
+ if (this.broadcastTo("questions.v1", "question.request", questionPayload("open", claim)) === 0) this.#options.questions.withdraw([callId]);
2410
+ return await claim.answer;
2411
+ }
2412
+ /** Close every connection and withdraw every question. Idempotent. */
2413
+ dispose() {
2414
+ for (const connection of [...this.#connections]) {
2415
+ this.#connections.delete(connection);
2416
+ connection.dispose();
2417
+ }
2418
+ this.#options.approvals.abandonAll();
2419
+ this.#options.questions.withdrawAll();
2420
+ }
2421
+ };
2422
+ //#endregion
2423
+ //#region src/core/owner-peer.ts
2424
+ /**
2425
+ * Mint the in-process owner peer this bridge's Host calls speak for.
2426
+ *
2427
+ * The bridge's security model states that pairing is a full-control
2428
+ * credential: a paired device reaches the harness in-process — sessions,
2429
+ * prompts, approvals. Protocol v1 is therefore deliberately paired with the
2430
+ * one principal that preserves the pre-0.2.1 capability of the bridge's own
2431
+ * in-process calls: the owner. That claim is safe only because of WHERE this
2432
+ * peer is attached:
2433
+ *
2434
+ * - Every gateway call a connection can trigger sits behind the bridge's own
2435
+ * pairing gate: dispatch answers `unpaired` before any session, approval or
2436
+ * roster work, and the three unpaired methods (`hello`, `pair.begin`,
2437
+ * `pair.finish`) never invoke the gateway at all. The owner peer crosses to
2438
+ * the harness only after a connection proved a device token (or just
2439
+ * enrolled one), never for an unpaired one.
2440
+ * - No wire field can set a principal: the connection never reads a `peer`
2441
+ * or `principal` (or any identity) out of a client frame. The peer is minted
2442
+ * here, in-process, fixed at `{ kind: 'owner' }`, and a client that names
2443
+ * one in its payload is ignored — the call still speaks for this peer.
2444
+ *
2445
+ * `interactions` stays `'none'`: the bridge only invokes unary methods and
2446
+ * opens the `session/follow` business stream. The gateway's interactions
2447
+ * check gates exactly the forwarded-event endpoints (opening an event stream,
2448
+ * answering a waterfall), which this caller never touches; an `'answer'`
2449
+ * peer would additionally receive forwarded Host events, a capability the
2450
+ * bridge neither needs nor wants — approvals reach devices through this
2451
+ * plugin's own `approval/request` listener and the protocol's own events, not
2452
+ * through a Typert forwarded-event subscription.
2453
+ *
2454
+ * The peer's signal aborts once `ctx` disposes, so calls and streams opened
2455
+ * for it end with the plugin fiber, and `dispose()` is idempotent with racing
2456
+ * calls sharing one completion. The id carries no credential — the protocol
2457
+ * fixes `principal` as the only identity persisted in a session log — so a
2458
+ * fresh unique id per mount is sufficient.
2459
+ */
2460
+ function createOwnerPeer(ctx) {
2461
+ const controller = new AbortController();
2462
+ let completion;
2463
+ const peer = {
2464
+ id: `remote-bridge-owner:${crypto.randomUUID()}`,
2465
+ ctx,
2466
+ principal: { kind: "owner" },
2467
+ signal: controller.signal,
2468
+ interactions: "none",
2469
+ dispose() {
2470
+ if (completion === void 0) {
2471
+ controller.abort();
2472
+ completion = Promise.resolve();
2473
+ }
2474
+ return completion;
2475
+ }
2476
+ };
2477
+ ctx.effect(() => () => {
2478
+ peer.dispose();
2479
+ }, "remote-bridge owner peer");
2480
+ return peer;
2481
+ }
2482
+ /**
2483
+ * The two one-shot secrets of the pairing handshake.
2484
+ *
2485
+ * `issueToken` is called by the loopback-only route an operator reaches from
2486
+ * the Host itself; `beginPairing` consumes that token and mints the nonce the
2487
+ * phone signs; `consumeNonce` closes the handshake. Consumption happens BEFORE
2488
+ * any signature check in the caller, so a wrong signature still burns the
2489
+ * nonce: a brute-force loop cannot reuse one challenge.
2490
+ */
2491
+ var PairingService = class {
2492
+ #now;
2493
+ #tokenTtlMs;
2494
+ #nonceTtlMs;
2495
+ #random;
2496
+ #tokens = /* @__PURE__ */ new Map();
2497
+ #nonces = /* @__PURE__ */ new Map();
2498
+ constructor(options = {}) {
2499
+ this.#now = options.now ?? (() => Date.now());
2500
+ this.#tokenTtlMs = options.tokenTtlMs ?? 3e4;
2501
+ this.#nonceTtlMs = options.nonceTtlMs ?? 6e4;
2502
+ this.#random = options.random ?? randomBase64Url;
2503
+ }
2504
+ /** Mint one bootstrap token, valid until its own expiry. */
2505
+ issueToken() {
2506
+ this.#prune();
2507
+ const value = this.#random(32);
2508
+ const expiresAt = this.#now() + this.#tokenTtlMs;
2509
+ this.#tokens.set(value, expiresAt);
2510
+ return {
2511
+ value,
2512
+ expiresAt
2513
+ };
2514
+ }
2515
+ /**
2516
+ * Consume one bootstrap token.
2517
+ * @returns whether the token was live; a consumed or expired token is gone.
2518
+ */
2519
+ consumeToken(token) {
2520
+ this.#prune();
2521
+ if (this.#tokens.get(token) === void 0) return false;
2522
+ this.#tokens.delete(token);
2523
+ return true;
2524
+ }
2525
+ /** Mint one pairing nonce for a connection that just consumed a valid token. */
2526
+ issueNonce() {
2527
+ this.#prune();
2528
+ const value = this.#random(16);
2529
+ const expiresAt = this.#now() + this.#nonceTtlMs;
2530
+ this.#nonces.set(value, expiresAt);
2531
+ return {
2532
+ value,
2533
+ expiresAt
2534
+ };
2535
+ }
2536
+ /**
2537
+ * Consume one pairing nonce.
2538
+ * @returns whether the nonce was live; a consumed or expired nonce is gone.
2539
+ */
2540
+ consumeNonce(nonce) {
2541
+ this.#prune();
2542
+ if (this.#nonces.get(nonce) === void 0) return false;
2543
+ this.#nonces.delete(nonce);
2544
+ return true;
2545
+ }
2546
+ /** @returns how many tokens and nonces are currently acceptable, for tests and diagnostics. */
2547
+ get pending() {
2548
+ this.#prune();
2549
+ return {
2550
+ tokens: this.#tokens.size,
2551
+ nonces: this.#nonces.size
2552
+ };
2553
+ }
2554
+ #prune() {
2555
+ const now = this.#now();
2556
+ for (const [value, expiresAt] of this.#tokens) if (expiresAt <= now) this.#tokens.delete(value);
2557
+ for (const [value, expiresAt] of this.#nonces) if (expiresAt <= now) this.#nonces.delete(value);
2558
+ }
2559
+ };
2560
+ //#endregion
2561
+ //#region src/core/questions.ts
2562
+ /**
2563
+ * The bridge's claims on `user-questions/request`: which questions a phone may
2564
+ * answer, and the one path an answer travels back into the host.
2565
+ *
2566
+ * The host asks in two shapes, and they are two shapes of the SAME channel:
2567
+ *
2568
+ * - a timed ask (`askTimed`, the tool schema that declares a `timeout`) rides
2569
+ * the waterfall with a `wait.callId`. While it is open the bridge HOLDS the
2570
+ * host's promise, so the answer is that promise's resolution — exactly what an
2571
+ * in-process answerer does, and the only way an open question can be answered
2572
+ * at all (`ctx.userQuestions.answer` refuses an open question by returning
2573
+ * false). Once the host's own deadline released the model, the ask is gone and
2574
+ * the question can only be answered through the host's Remote `answer`, which
2575
+ * steers the reply into the agent as a queued user message.
2576
+ * - a blocking ask (the schema without `timeout`, which is the `ask_user_question`
2577
+ * a phone actually shows) carries NO `wait` at all, and the host assigns no
2578
+ * call id. It is still claimed, and the bridge mints its own opaque id for the
2579
+ * wire — resolving the promise it holds needs no host identity at all. Such a
2580
+ * question is only ever `open`: the host has no deadline for it, so it never
2581
+ * becomes `continued` and never takes the Remote `answer` path.
2582
+ *
2583
+ * Every claim is one record keyed by the id published on the wire, so an answer
2584
+ * that arrives late still lands, and an answer for an id this bridge never
2585
+ * claimed is refused instead of being forwarded to the host blindly.
2586
+ *
2587
+ * The bridge invents no deadline, for either shape: a timed ask's deadline is
2588
+ * the host's own and is only propagated here, and a blocking ask simply has
2589
+ * none — a phone that never answers leaves it open for as long as the asker
2590
+ * waits. It also never fabricates a refusal: a question nobody can answer is
2591
+ * delegated to `next()`, never answered with a decision the operator did not
2592
+ * make.
2593
+ *
2594
+ * The types below mirror `@deepseek-ai/dsh-user-questions` field for field. The
2595
+ * package is not a dependency of this one (it is the host's, not the bridge's),
2596
+ * so the contract is declared locally instead of imported.
2597
+ * @module dsh-remote-bridge/core/questions
2598
+ */
2599
+ /** The code the host raises when its own foreground deadline ends the ask. */
2600
+ const QUESTION_TIMED_OUT_CODE = "ASK_TIMED_OUT";
2601
+ /**
2602
+ * Prefix of a call id this bridge minted for a question the host never named.
2603
+ *
2604
+ * A blocking ask has no host call id, but the phone still needs one opaque
2605
+ * handle to answer with. The prefix keeps that handle in a namespace of its own,
2606
+ * so a minted id can never be mistaken for a host `ToolCallId` — by this bridge
2607
+ * or by anything reading the wire.
2608
+ */
2609
+ const MINTED_CALL_ID_PREFIX = "bridge:";
2610
+ /** @returns whether a failure is the host's own foreground deadline. */
2611
+ function isTimedOut(reason) {
2612
+ return reason?.code === QUESTION_TIMED_OUT_CODE;
2613
+ }
2614
+ /**
2615
+ * Project a host question into the contract's own fields.
2616
+ *
2617
+ * Explicitly field by field: the host's items carry presentation intents this
2618
+ * protocol does not publish, and a payload that grew a key the contract does
2619
+ * not declare would be a wire change nobody agreed to.
2620
+ * @param items - the host's question batch.
2621
+ * @returns the same questions in protocol vocabulary.
2622
+ */
2623
+ function projectQuestions(items) {
2624
+ return items.map((item) => ({
2625
+ id: item.id,
2626
+ question: item.question,
2627
+ ...item.header === void 0 ? {} : { header: item.header },
2628
+ ...item.detail === void 0 ? {} : { detail: item.detail },
2629
+ ...item.options === void 0 ? {} : { options: item.options.map((option) => ({
2630
+ label: option.label,
2631
+ ...option.description === void 0 ? {} : { description: option.description }
2632
+ })) },
2633
+ ...item.multiSelect === void 0 ? {} : { multiSelect: item.multiSelect }
2634
+ }));
2635
+ }
2636
+ /**
2637
+ * Pending questions of one bridge process.
2638
+ *
2639
+ * One record per id published on the wire — the host's own, or one minted here
2640
+ * for a blocking ask — and one settle for every path (answer, the host's
2641
+ * deadline, the last phone leaving, bridge unload), so a question can never be
2642
+ * settled twice and a withdrawn claim leaves no abort listener behind.
2643
+ */
2644
+ var QuestionClaims = class {
2645
+ #gateway;
2646
+ #peer;
2647
+ #log;
2648
+ #random;
2649
+ #claims = /* @__PURE__ */ new Map();
2650
+ constructor(options) {
2651
+ this.#gateway = options.gateway;
2652
+ this.#peer = options.peer;
2653
+ this.#log = options.log;
2654
+ this.#random = options.random ?? randomBase64Url;
2655
+ }
2656
+ /** @returns how many questions this bridge currently holds. */
2657
+ get size() {
2658
+ return this.#claims.size;
2659
+ }
2660
+ /**
2661
+ * Mint the opaque wire id of a question the host never named.
2662
+ * @returns an id in this bridge's own namespace.
2663
+ */
2664
+ mintCallId() {
2665
+ return `${MINTED_CALL_ID_PREFIX}${this.#random(16)}`;
2666
+ }
2667
+ /** @returns the state of one claimed call, or undefined when it is not claimed. */
2668
+ stateOf(callId) {
2669
+ return this.#claims.get(callId)?.state;
2670
+ }
2671
+ /**
2672
+ * Claim one question.
2673
+ * @param input - session identity, wire call id and its provenance, questions, the rest of the chain, and the host's lifetime.
2674
+ * @returns the claim the hub publishes, or undefined when this call id is already claimed.
2675
+ */
2676
+ open(input) {
2677
+ if (this.#claims.has(input.callId)) return void 0;
2678
+ let settle = () => void 0;
2679
+ let fail = () => void 0;
2680
+ const answer = new Promise((resolve, reject) => {
2681
+ settle = resolve;
2682
+ fail = reject;
2683
+ });
2684
+ const signal = input.signal;
2685
+ const onAbort = () => {
2686
+ this.#expire(input.callId, signal?.reason);
2687
+ };
2688
+ let nextStarted;
2689
+ const startNext = () => {
2690
+ if (nextStarted === void 0) try {
2691
+ nextStarted = input.next();
2692
+ } catch (error) {
2693
+ nextStarted = Promise.reject(error);
2694
+ }
2695
+ return nextStarted;
2696
+ };
2697
+ const record = {
2698
+ sessionId: input.sessionId,
2699
+ callId: input.callId,
2700
+ hosted: input.hosted,
2701
+ questions: projectQuestions(input.questions),
2702
+ state: "open",
2703
+ notifySettled: () => {
2704
+ input.onSettled?.({
2705
+ sessionId: input.sessionId,
2706
+ callId: input.callId,
2707
+ questions: projectQuestions(input.questions)
2708
+ });
2709
+ },
2710
+ settle,
2711
+ fail,
2712
+ delegate: () => {
2713
+ startNext().then(settle, fail);
2714
+ },
2715
+ detach: () => {
2716
+ signal?.removeEventListener("abort", onAbort);
2717
+ },
2718
+ onContinued: input.onContinued
2719
+ };
2720
+ this.#claims.set(input.callId, record);
2721
+ if (signal?.aborted === true) onAbort();
2722
+ else signal?.addEventListener("abort", onAbort, { once: true });
2723
+ return {
2724
+ sessionId: record.sessionId,
2725
+ callId: record.callId,
2726
+ questions: record.questions,
2727
+ answer
2728
+ };
2729
+ }
2730
+ /**
2731
+ * Answer one claimed question.
2732
+ *
2733
+ * An open claim is settled by resolving the host's own ask; a continued one
2734
+ * only through the host's Remote `answer`, whose result and failures cross
2735
+ * unchanged.
2736
+ * @param sessionId - the session the client believes owns the question.
2737
+ * @param callId - the wire call id the client was shown.
2738
+ * @param answer - the complete answer batch.
2739
+ */
2740
+ async answer(sessionId, callId, answer) {
2741
+ const record = this.#claims.get(callId);
2742
+ if (record === void 0 || record.sessionId !== sessionId) return {
2743
+ ok: false,
2744
+ code: CODE_QUESTION_UNKNOWN,
2745
+ msg: "the question is unknown, already answered or not this bridge's to answer"
2746
+ };
2747
+ if (record.state === "open") {
2748
+ this.#claims.delete(callId);
2749
+ record.detach();
2750
+ record.settle({ answers: answer.answers });
2751
+ return { ok: true };
2752
+ }
2753
+ if (!record.hosted) return {
2754
+ ok: false,
2755
+ code: CODE_QUESTION_UNKNOWN,
2756
+ msg: "the question is not one the host can take a late answer for"
2757
+ };
2758
+ return await this.#forward(sessionId, callId, answer);
2759
+ }
2760
+ /**
2761
+ * Every claim still waiting on an answer.
2762
+ *
2763
+ * A phone that connects after the question was raised never saw the original
2764
+ * broadcast, so it has to be handed the live claims again — otherwise the
2765
+ * question sits on the host with an answerable card nowhere.
2766
+ */
2767
+ openClaims() {
2768
+ return [...this.#claims.values()].map((record) => ({
2769
+ sessionId: record.sessionId,
2770
+ callId: record.callId,
2771
+ questions: record.questions
2772
+ }));
2773
+ }
2774
+ /**
2775
+ * Withdraw the named questions, delegating each to the next answerer.
2776
+ * @returns how many were still open and therefore delegated.
2777
+ */
2778
+ withdraw(callIds) {
2779
+ let withdrawn = 0;
2780
+ for (const callId of callIds) {
2781
+ const record = this.#claims.get(callId);
2782
+ if (record === void 0) continue;
2783
+ this.#claims.delete(callId);
2784
+ record.detach();
2785
+ record.notifySettled();
2786
+ if (record.state !== "open") continue;
2787
+ record.delegate();
2788
+ withdrawn += 1;
2789
+ }
2790
+ return withdrawn;
2791
+ }
2792
+ /**
2793
+ * Withdraw every claim, delegating each open question to the next answerer.
2794
+ * Called when the last paired phone goes away and when the bridge unloads: a
2795
+ * question nobody can answer must not hold the agent until its own deadline.
2796
+ * @returns how many questions were still open.
2797
+ */
2798
+ withdrawAll() {
2799
+ return this.withdraw([...this.#claims.keys()]);
2800
+ }
2801
+ /**
2802
+ * Ask the host to steer one continued answer into its agent.
2803
+ *
2804
+ * A host that answers `false` no longer holds the question; it is reported,
2805
+ * not swallowed, and the claim is kept so a client that answered a beat too
2806
+ * early can retry once the host has folded the pending result.
2807
+ */
2808
+ async #forward(sessionId, callId, answer) {
2809
+ try {
2810
+ if (await withServiceUnavailableRetry(() => this.#gateway.invoke({
2811
+ namespace: "userQuestions",
2812
+ method: "answer",
2813
+ args: wireArgs("userQuestions", "answer", {
2814
+ agentId: sessionId,
2815
+ callId,
2816
+ answer: { answers: answer.answers }
2817
+ }),
2818
+ peer: this.#peer
2819
+ })) !== true) return {
2820
+ ok: false,
2821
+ code: CODE_QUESTION_UNKNOWN,
2822
+ msg: "the host does not hold this question as answerable yet"
2823
+ };
2824
+ this.#claims.delete(callId);
2825
+ return { ok: true };
2826
+ } catch (error) {
2827
+ this.#log(`userQuestions/answer failed: ${failureText(error)}`);
2828
+ return {
2829
+ ok: false,
2830
+ code: errorCodeOf(error, CODE_INTERNAL),
2831
+ msg: failureText(error)
2832
+ };
2833
+ }
2834
+ }
2835
+ /**
2836
+ * Settle one open claim from the host's own cancellation lifetime.
2837
+ *
2838
+ * The reason is propagated verbatim, so the host's deadline still maps to its
2839
+ * pending result. Only a deadline keeps the claim: every other abort means
2840
+ * the ask itself is gone.
2841
+ */
2842
+ #expire(callId, reason) {
2843
+ const record = this.#claims.get(callId);
2844
+ if (record === void 0 || record.state !== "open") return;
2845
+ record.detach();
2846
+ record.fail(reason);
2847
+ if (!record.hosted || !isTimedOut(reason)) {
2848
+ this.#claims.delete(callId);
2849
+ return;
2850
+ }
2851
+ record.state = "continued";
2852
+ record.onContinued?.({
2853
+ sessionId: record.sessionId,
2854
+ callId: record.callId,
2855
+ questions: record.questions
2856
+ });
2857
+ }
2858
+ };
2859
+ //#endregion
2860
+ //#region src/core/session-permissions.ts
2861
+ /**
2862
+ * The host's permission presets, projected into the shape `session.permissions`
2863
+ * and `session.setPermission` publish.
2864
+ *
2865
+ * The services are reached through structural faces for the reason
2866
+ * `session-meta.ts` states: the live objects carry far more than this package
2867
+ * calls, and a face keeps a test double down to what is actually read.
2868
+ *
2869
+ * Two facts of the real service shape this module:
2870
+ *
2871
+ * - `current` and `set` take the LIVE `Session` object, never an id, so a
2872
+ * session this host process does not hold — a cold, disk-only roster entry —
2873
+ * has no truthful answer at all. That case is refused by name instead of
2874
+ * being reported as an empty or defaulted mode.
2875
+ * - `custom` is DERIVED state, never a switch target: it can be the current
2876
+ * value and must never be offered as an option.
2877
+ * @module dsh-remote-bridge/core/session-permissions
2878
+ */
2879
+ /** The permission service's name for "no preset matches the two knobs". */
2880
+ const CUSTOM_PRESET = "custom";
2881
+ /**
2882
+ * The code the harness raises for a session it has no live instance of.
2883
+ * Verbatim from the harness's own error table, not a bridge-invented one.
2884
+ */
2885
+ const CODE_SESSION_NOT_FOUND = "session/not-found";
2886
+ /**
2887
+ * Read one knob's effective value: the session's own fold, else the deployment
2888
+ * default.
2889
+ * @returns the value, or undefined when neither could be read.
2890
+ */
2891
+ function knobOf(read, fallback) {
2892
+ try {
2893
+ return read() ?? fallback;
2894
+ } catch {
2895
+ return fallback;
2896
+ }
2897
+ }
2898
+ /**
2899
+ * The bridge's permission reads and writes.
2900
+ *
2901
+ * One instance is built per host mount and shared by every connection, because a
2902
+ * preset table is a fact about the deployment, not about the device that asked.
2903
+ */
2904
+ var SessionPermissions = class {
2905
+ #faces;
2906
+ #log;
2907
+ /**
2908
+ * @param faces - resolves the host services now; called per read, never captured once, so a service that mounts later is still picked up.
2909
+ * @param log - where an unreadable preset state is reported.
2910
+ */
2911
+ constructor(faces, log) {
2912
+ this.#faces = faces;
2913
+ this.#log = log;
2914
+ }
2915
+ /**
2916
+ * Describe one session's permission modes.
2917
+ *
2918
+ * `current` is the service's own folded value: the preset the session's two
2919
+ * knobs currently match, or `custom` with both knobs' real values. It is never
2920
+ * the deployment default dressed up as the current mode.
2921
+ * @param sessionId - the session the client is looking at.
2922
+ */
2923
+ describe(sessionId) {
2924
+ const live = this.#live(sessionId);
2925
+ if ("code" in live) return live;
2926
+ return this.#answer(live.presets, live.session);
2927
+ }
2928
+ /**
2929
+ * Switch one session to a preset this host offers.
2930
+ *
2931
+ * The id is validated against the same option list `describe` publishes before
2932
+ * the service is touched at all, so an unknown id changes nothing — the switch
2933
+ * appends durable events and must never run on a rejected argument.
2934
+ * @param sessionId - the session to switch.
2935
+ * @param id - one of `describe(sessionId).options`' ids.
2936
+ */
2937
+ set(sessionId, id) {
2938
+ const live = this.#live(sessionId);
2939
+ if ("code" in live) return live;
2940
+ const before = this.#answer(live.presets, live.session);
2941
+ if ("code" in before) return before;
2942
+ if (!before.options.some((option) => option.id === id)) return {
2943
+ code: CODE_INVALID_ARGS,
2944
+ msg: `session.setPermission requires an id this host offers, not "${id}"`
2945
+ };
2946
+ try {
2947
+ live.presets.set(live.session, id);
2948
+ } catch (error) {
2949
+ this.#log(`the permission of one session could not be switched: ${failureText(error)}`);
2950
+ return {
2951
+ code: errorCodeOf(error, CODE_INTERNAL),
2952
+ msg: failureText(error)
2953
+ };
2954
+ }
2955
+ return this.#answer(live.presets, live.session);
2956
+ }
2957
+ /** Resolve the service and the live session one call is about. */
2958
+ #live(sessionId) {
2959
+ const faces = this.#faces();
2960
+ const presets = faces.presets;
2961
+ if (presets === void 0 || typeof presets.catalog !== "function" || typeof presets.current !== "function") return {
2962
+ code: CODE_UNKNOWN_METHOD,
2963
+ msg: "this host does not compose permissionPresets"
2964
+ };
2965
+ const session = faces.sessions?.get(sessionId);
2966
+ if (session === void 0) return {
2967
+ code: CODE_SESSION_NOT_FOUND,
2968
+ msg: `session ${sessionId} is not live in this host process`
2969
+ };
2970
+ return {
2971
+ presets,
2972
+ session
2973
+ };
2974
+ }
2975
+ /** Build one answer out of the service's own folded state. */
2976
+ #answer(presets, session) {
2977
+ let current;
2978
+ try {
2979
+ current = presets.current(session);
2980
+ } catch (error) {
2981
+ this.#log(`the permission preset of one session could not be read: ${failureText(error)}`);
2982
+ return {
2983
+ code: errorCodeOf(error, CODE_INTERNAL),
2984
+ msg: failureText(error)
2985
+ };
2986
+ }
2987
+ const custom = current === CUSTOM_PRESET;
2988
+ const name = this.#labelOf(presets, current);
2989
+ return {
2990
+ current: custom ? {
2991
+ id: current,
2992
+ name,
2993
+ ...this.#knobs(session)
2994
+ } : {
2995
+ id: current,
2996
+ name
2997
+ },
2998
+ options: this.#options(presets),
2999
+ custom
3000
+ };
3001
+ }
3002
+ /**
3003
+ * The switchable presets, in the service's own order.
3004
+ *
3005
+ * The catalog already advertises only presets that can be selected right now,
3006
+ * so this only drops the derived value: `custom` is a state, not a target.
3007
+ */
3008
+ #options(presets) {
3009
+ let catalog;
3010
+ try {
3011
+ catalog = presets.catalog();
3012
+ } catch (error) {
3013
+ this.#log(`the permission catalog could not be read: ${failureText(error)}`);
3014
+ return [];
3015
+ }
3016
+ const options = [];
3017
+ for (const option of catalog?.options ?? []) {
3018
+ if (option === void 0 || typeof option.value !== "string" || option.value === "" || option.value === "custom") continue;
3019
+ const name = typeof option.name === "string" && option.name !== "" ? option.name : option.value;
3020
+ options.push({
3021
+ id: option.value,
3022
+ name,
3023
+ ...option.description === void 0 ? {} : { description: option.description }
3024
+ });
3025
+ }
3026
+ return options;
3027
+ }
3028
+ /** The label for one current value, falling back to the value itself. */
3029
+ #labelOf(presets, name) {
3030
+ try {
3031
+ const option = presets.optionOf(name);
3032
+ if (typeof option?.name === "string" && option.name !== "") return option.name;
3033
+ } catch {}
3034
+ return name;
3035
+ }
3036
+ /** The two knobs' effective values, for a session whose state matches no preset. */
3037
+ #knobs(session) {
3038
+ const faces = this.#faces();
3039
+ const sandbox = knobOf(() => faces.sandbox?.overrideOf(session), faces.sandbox?.defaultMode);
3040
+ const approval = knobOf(() => faces.approval?.overrideOf(session), faces.approval?.config?.policy ?? "ask");
3041
+ return {
3042
+ ...sandbox === void 0 ? {} : { sandbox },
3043
+ ...approval === void 0 ? {} : { approval }
3044
+ };
3045
+ }
3046
+ };
3047
+ //#endregion
3048
+ //#region src/host/dsh-home.ts
3049
+ /**
3050
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
3051
+ * environment override wins, the platform home fallback follows. Mirrors
3052
+ * what dsh-pet and dsh-liangshen each used to implement locally.
3053
+ */
3054
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
3055
+ function expandHome(path, home = homedir()) {
3056
+ const j = home.startsWith("/") ? join$1 : join;
3057
+ if (path === "~") return home;
3058
+ if (path.startsWith("~/") || path.startsWith("~\\")) return j(home, path.slice(2));
3059
+ return path;
3060
+ }
3061
+ /**
3062
+ * Resolve the DSH home directory.
3063
+ * @param env - process environment to read DSH_HOME from.
3064
+ * @param home - platform home directory fallback (test seam).
3065
+ * @returns the absolute DSH home path.
3066
+ */
3067
+ function resolveDshHome(env = process.env, home = homedir()) {
3068
+ const isPosix = home.startsWith("/");
3069
+ const j = isPosix ? join$1 : join;
3070
+ const isAbs = isPosix ? isAbsolute$1 : isAbsolute;
3071
+ const raw = env.DSH_HOME;
3072
+ if (raw !== void 0 && raw.trim() !== "") {
3073
+ const expanded = expandHome(raw.trim(), home);
3074
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded);
3075
+ }
3076
+ return j(home, ".dsh");
3077
+ }
3078
+ /** Resolve the DSH home directory from the live environment. */
3079
+ function dshHome() {
3080
+ return resolveDshHome();
3081
+ }
3082
+ //#endregion
3083
+ //#region src/core/loopback.ts
3084
+ /** Socket addresses that count as "this machine". */
3085
+ const LOOPBACK_ADDRESSES = /* @__PURE__ */ new Set([
3086
+ "127.0.0.1",
3087
+ "::1",
3088
+ "::ffff:127.0.0.1"
3089
+ ]);
3090
+ /** Host header values that count as "this machine". */
3091
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
3092
+ "127.0.0.1",
3093
+ "localhost",
3094
+ "[::1]"
3095
+ ]);
3096
+ /** @returns whether a socket's remote address is this machine. */
3097
+ function isLoopbackAddress(remoteAddress) {
3098
+ return remoteAddress !== void 0 && LOOPBACK_ADDRESSES.has(remoteAddress);
3099
+ }
3100
+ /**
3101
+ * @returns whether a `Host` header names this machine. The port is ignored;
3102
+ * anything that is not a loopback literal — including a public tunnel
3103
+ * hostname — is refused.
3104
+ */
3105
+ function isLoopbackHost(host) {
3106
+ if (host === void 0) return false;
3107
+ const name = host.trim().toLowerCase();
3108
+ if (name === "") return false;
3109
+ const bare = name.startsWith("[") ? name.slice(0, name.indexOf("]") + 1) : name.split(":")[0] ?? "";
3110
+ return LOOPBACK_HOSTS.has(bare);
3111
+ }
3112
+ /**
3113
+ * Why this request may not reach the bootstrap token endpoint, or undefined
3114
+ * when it may.
3115
+ * @param req - the incoming request.
3116
+ * @returns a one-line reason, or undefined.
3117
+ */
3118
+ function loopbackDenialOf(req) {
3119
+ if (!isLoopbackAddress(req.socket.remoteAddress)) return "the request did not arrive from this machine";
3120
+ if (!isLoopbackHost(req.headers.host)) return "the request names a Host that is not this machine";
3121
+ }
3122
+ //#endregion
3123
+ //#region src/host/pair-origin.ts
3124
+ /**
3125
+ * The public origin a phone should dial, discovered rather than asked for.
3126
+ *
3127
+ * A pairing code is far better when it carries the address too: the phone then
3128
+ * needs one scan and no typing. This module is where that address comes from,
3129
+ * in the order the family already trusts:
3130
+ *
3131
+ * 1. `DSH_REMOTE_PUBLIC_BASE_URL` — the same environment contract
3132
+ * `dsh-remote-web-ui` reads for its own public base.
3133
+ * 2. The relay registry row `$DSH_HOME/remote-web-ui-registry/<profile>.json`,
3134
+ * whose `id` is the stable `<id>.<relay>` subdomain that plugin registers
3135
+ * for this profile (see its `relay-registry.ts`). Reading that row is a
3136
+ * deliberate, documented data dependency: it is one small JSON file per
3137
+ * profile, it is written by the machine itself, and a missing or unreadable
3138
+ * row simply means "no origin known" rather than an error.
3139
+ *
3140
+ * Nothing here reaches the network, and nothing here mints or spends anything.
3141
+ * @module dsh-remote-bridge/host/pair-origin
3142
+ */
3143
+ /** The relay's worker domain; a profile's stable origin is `<id>.<this>`. */
3144
+ const RELAY_DOMAIN = "dsh-market.com";
3145
+ /** The registry directory `dsh-remote-web-ui` keeps its per-profile row in. */
3146
+ const RELAY_REGISTRY_DIR = "remote-web-ui-registry";
3147
+ /** Trim trailing slashes so the caller can append a path unconditionally. */
3148
+ function originOf(base) {
3149
+ return base.replace(/\/+$/, "");
3150
+ }
3151
+ /**
3152
+ * Discover the public origin of this instance.
3153
+ * @param options - environment, home and profile seams for tests.
3154
+ * @returns the origin and its source, or `undefined` when nothing is known.
3155
+ */
3156
+ function discoverPairOrigin(options = {}) {
3157
+ const env = options.env ?? process.env;
3158
+ const configured = env.DSH_REMOTE_PUBLIC_BASE_URL?.trim();
3159
+ if (configured !== void 0 && configured !== "") return {
3160
+ origin: originOf(configured),
3161
+ source: "env"
3162
+ };
3163
+ const home = options.home ?? resolveDshHome(env);
3164
+ const profile = options.profile ?? env.DSH_PROFILE?.trim() ?? "desktop";
3165
+ if (profile === "") return void 0;
3166
+ let row;
3167
+ try {
3168
+ row = JSON.parse(readFileSync(join(home, RELAY_REGISTRY_DIR, `${profile}.json`), "utf8"));
3169
+ } catch {
3170
+ return;
3171
+ }
3172
+ if (typeof row !== "object" || row === null) return void 0;
3173
+ const id = row.id;
3174
+ if (typeof id !== "string" || id === "") return void 0;
3175
+ return {
3176
+ origin: `wss://${id}.${RELAY_DOMAIN}`,
3177
+ source: "registry"
3178
+ };
3179
+ }
3180
+ //#endregion
3181
+ //#region src/host/routes.ts
3182
+ /** Write one JSON response. The family's shared reader/writer is not copied into this package. */
3183
+ function writeJson(res, status, body) {
3184
+ const text = JSON.stringify(body);
3185
+ res.writeHead(status, {
3186
+ "content-type": "application/json; charset=utf-8",
3187
+ "content-length": Buffer.byteLength(text),
3188
+ "cache-control": "no-store",
3189
+ "referrer-policy": "no-referrer"
3190
+ });
3191
+ res.end(text);
3192
+ }
3193
+ /**
3194
+ * Build the handler for `GET /remote-bridge/pair/token`.
3195
+ * @param deps - the pairing service that mints the token, plus the Host log.
3196
+ * @returns the handler; the caller owns route registration.
3197
+ */
3198
+ function makePairTokenHandler(deps) {
3199
+ return (req, res) => {
3200
+ const denial = loopbackDenialOf(req);
3201
+ if (denial !== void 0) {
3202
+ writeJson(res, 403, {
3203
+ ok: false,
3204
+ error: "forbidden",
3205
+ reason: denial
3206
+ });
3207
+ return;
3208
+ }
3209
+ if ((req.method ?? "GET") !== "GET") {
3210
+ res.writeHead(405, { allow: "GET" });
3211
+ res.end();
3212
+ return;
3213
+ }
3214
+ const ticket = deps.pairing.issueToken();
3215
+ const url = `ws://${req.headers.host ?? "127.0.0.1"}${WS_PATH}?token=${ticket.value}`;
3216
+ const discovered = (deps.pairOrigin ?? discoverPairOrigin)();
3217
+ const pairingUrl = discovered === void 0 ? void 0 : `${discovered.origin}${WS_PATH}?token=${ticket.value}`;
3218
+ deps.log(pairingUrl === void 0 ? `pair a device with ${url}` : `pair a device with ${url} (phone: ${pairingUrl})`);
3219
+ writeJson(res, 200, {
3220
+ token: ticket.value,
3221
+ expiresAt: ticket.expiresAt,
3222
+ url,
3223
+ ...discovered === void 0 ? {} : {
3224
+ origin: discovered.origin,
3225
+ originSource: discovered.source
3226
+ },
3227
+ ...pairingUrl === void 0 ? {} : { pairingUrl }
3228
+ });
3229
+ };
3230
+ }
3231
+ /** The route as the host web server takes it: one exact path, no trailing slash. */
3232
+ function makePairTokenRoute(deps) {
3233
+ return {
3234
+ kind: "exact",
3235
+ path: PAIR_TOKEN_PATH,
3236
+ handler: makePairTokenHandler(deps)
3237
+ };
3238
+ }
3239
+ //#endregion
3240
+ //#region src/core/ws-frames.ts
3241
+ /**
3242
+ * RFC 6455 server-side framing, kept as pure functions so the length, mask and
3243
+ * opcode rules are unit-tested without a socket.
3244
+ *
3245
+ * Only what a server must accept is implemented: client frames are always
3246
+ * masked, one logical message may arrive as a text frame or as a fragmented
3247
+ * sequence, and anything the protocol forbids answers with the close code that
3248
+ * names the violation instead of being ignored.
3249
+ * @module dsh-remote-bridge/core/ws-frames
3250
+ */
3251
+ /** The magic GUID every WebSocket handshake is keyed with. */
3252
+ const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
3253
+ /** Close code for a protocol violation. */
3254
+ const CLOSE_PROTOCOL_ERROR = 1002;
3255
+ /** Close code for a message this bridge will not carry. */
3256
+ const CLOSE_UNSUPPORTED_DATA = 1003;
3257
+ /** Close code for a message past the size this bridge will carry. */
3258
+ const CLOSE_TOO_LARGE = 1009;
3259
+ /** @returns the `Sec-WebSocket-Accept` value for a client's key. */
3260
+ function webSocketAccept(secWebSocketKey) {
3261
+ return createHash("sha1").update(`${secWebSocketKey}${WS_GUID}`).digest("base64");
3262
+ }
3263
+ /**
3264
+ * Decode one frame from the head of a buffer.
3265
+ * @param buffer - the bytes received so far.
3266
+ * @param maxBytes - largest payload this bridge accepts.
3267
+ */
3268
+ function parseClientFrame(buffer, maxBytes) {
3269
+ if (buffer.length < 2) return { status: "incomplete" };
3270
+ const first = buffer[0] ?? 0;
3271
+ const second = buffer[1] ?? 0;
3272
+ const fin = (first & 128) !== 0;
3273
+ if ((first & 112) !== 0) return fault(CLOSE_PROTOCOL_ERROR, "reserved bits set");
3274
+ const opcode = first & 15;
3275
+ if (!((second & 128) !== 0)) return fault(CLOSE_PROTOCOL_ERROR, "client frames must be masked");
3276
+ let length = second & 127;
3277
+ let offset = 2;
3278
+ if (length === 126) {
3279
+ if (buffer.length < offset + 2) return { status: "incomplete" };
3280
+ length = buffer.readUInt16BE(offset);
3281
+ offset += 2;
3282
+ } else if (length === 127) {
3283
+ if (buffer.length < offset + 8) return { status: "incomplete" };
3284
+ const wide = buffer.readBigUInt64BE(offset);
3285
+ if (wide > BigInt(Number.MAX_SAFE_INTEGER)) return fault(CLOSE_TOO_LARGE, "frame length out of range");
3286
+ length = Number(wide);
3287
+ offset += 8;
3288
+ }
3289
+ if (length > maxBytes) return fault(CLOSE_TOO_LARGE, `frame payload exceeds ${maxBytes} bytes`);
3290
+ if (buffer.length < offset + 4 + length) return { status: "incomplete" };
3291
+ const mask = buffer.subarray(offset, offset + 4);
3292
+ offset += 4;
3293
+ const payload = Buffer.allocUnsafe(length);
3294
+ for (let index = 0; index < length; index += 1) payload[index] = (buffer[offset + index] ?? 0) ^ (mask[index % 4] ?? 0);
3295
+ return {
3296
+ status: "frame",
3297
+ frame: {
3298
+ fin,
3299
+ opcode,
3300
+ payload,
3301
+ consumed: offset + length
3302
+ }
3303
+ };
3304
+ }
3305
+ function fault(closeCode, reason) {
3306
+ return {
3307
+ status: "fault",
3308
+ closeCode,
3309
+ reason
3310
+ };
3311
+ }
3312
+ /**
3313
+ * Encode one server frame. Server frames are never masked.
3314
+ * @param opcode - the frame opcode.
3315
+ * @param payload - already-serialized payload bytes.
3316
+ * @param fin - whether this frame completes the message.
3317
+ */
3318
+ function encodeServerFrame(opcode, payload, fin = true) {
3319
+ const length = payload.length;
3320
+ const header = length < 126 ? Buffer.from([(fin ? 128 : 0) | opcode, length]) : length <= 65535 ? Buffer.from([
3321
+ (fin ? 128 : 0) | opcode,
3322
+ 126,
3323
+ length >> 8,
3324
+ length & 255
3325
+ ]) : (() => {
3326
+ const wide = Buffer.alloc(10);
3327
+ wide[0] = (fin ? 128 : 0) | opcode;
3328
+ wide[1] = 127;
3329
+ wide.writeBigUInt64BE(BigInt(length), 2);
3330
+ return wide;
3331
+ })();
3332
+ return Buffer.concat([header, payload]);
3333
+ }
3334
+ /** Encode one text message. */
3335
+ function encodeTextFrame(text) {
3336
+ return encodeServerFrame(1, Buffer.from(text, "utf8"));
3337
+ }
3338
+ /** Encode one close frame with a code and a short reason. */
3339
+ function encodeCloseFrame(code, reason) {
3340
+ const text = Buffer.from(reason, "utf8").subarray(0, 123);
3341
+ const payload = Buffer.alloc(2 + text.length);
3342
+ payload.writeUInt16BE(code, 0);
3343
+ text.copy(payload, 2);
3344
+ return encodeServerFrame(8, payload);
3345
+ }
3346
+ //#endregion
3347
+ //#region src/host/websocket.ts
3348
+ /** Close code a well-behaved peer sends when it goes away. */
3349
+ const CLOSE_NORMAL = 1e3;
3350
+ /** @returns whether this request asks for a WebSocket upgrade. */
3351
+ function isWebSocketUpgrade(req) {
3352
+ const upgrade = req.headers.upgrade;
3353
+ return typeof upgrade === "string" && upgrade.toLowerCase() === "websocket";
3354
+ }
3355
+ /** @returns the client's `Sec-WebSocket-Key`, or undefined when the handshake is incomplete. */
3356
+ function readSecWebSocketKey(req) {
3357
+ const key = req.headers["sec-websocket-key"];
3358
+ if (typeof key !== "string") return void 0;
3359
+ const trimmed = key.trim();
3360
+ return trimmed === "" ? void 0 : trimmed;
3361
+ }
3362
+ /** @returns the device token on `Authorization: Bearer …`, if the client sent one. */
3363
+ function bearerTokenOf(req) {
3364
+ const header = req.headers.authorization;
3365
+ if (typeof header !== "string") return void 0;
3366
+ const value = /^Bearer\s+(.+)$/i.exec(header.trim())?.[1]?.trim();
3367
+ return value === void 0 || value === "" ? void 0 : value;
3368
+ }
3369
+ /**
3370
+ * @returns the token on `?token=…`, the fallback for clients whose handshake
3371
+ * cannot set a header (share sheets, `wscat`, plain scripts).
3372
+ */
3373
+ function queryTokenOf(requestUrl) {
3374
+ if (requestUrl === void 0 || requestUrl === "") return void 0;
3375
+ let value;
3376
+ try {
3377
+ value = new URL(requestUrl, "http://127.0.0.1").searchParams.get("token");
3378
+ } catch {
3379
+ return;
3380
+ }
3381
+ return value === null || value === "" ? void 0 : value;
3382
+ }
3383
+ /**
3384
+ * @returns the token this upgrade presents: the header first, then the query.
3385
+ * A bootstrap token presented here is simply not a device token, which leaves
3386
+ * the connection unpaired — the state `pair.begin` needs.
3387
+ */
3388
+ function presentedTokenOf(req) {
3389
+ return bearerTokenOf(req) ?? queryTokenOf(req.url);
3390
+ }
3391
+ /**
3392
+ * Answer an upgrade this endpoint will not take, and close the write side.
3393
+ *
3394
+ * The refusal rides `end()`, which flushes the response before the FIN. Writing
3395
+ * and then destroying in the same tick aborts the in-flight write on Linux, and
3396
+ * that abort surfaces as the socket's own `error` event - which nothing on a
3397
+ * refused socket listens for, because the carrier's subscriptions only exist
3398
+ * once an upgrade is accepted. One malformed upgrade therefore reached the host
3399
+ * as an uncaught exception. The listener absorbs the transport's own failures: a
3400
+ * peer that vanished mid-refusal is the client's problem, never the host's.
3401
+ */
3402
+ function refuseUpgrade(socket, status, reason) {
3403
+ socket.on("error", () => {});
3404
+ socket.end(`HTTP/1.1 ${status} ${reason}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
3405
+ }
3406
+ /**
3407
+ * Hand one accepted upgrade to the hub, in the one order that is correct.
3408
+ *
3409
+ * Every step here is synchronous, which is what makes the carrier's own
3410
+ * pre-handler buffer unnecessary in practice — and the buffer is there anyway,
3411
+ * so the bytes of `head` (and anything that beats the handler) are delivered
3412
+ * instead of dropped. The order is the point of this function: reading the
3413
+ * socket without a handler, or attaching a connection whose carrier is never
3414
+ * written to, both end in a client that waits forever.
3415
+ * @param handoff - the socket, its handshake facts, and the hub to join.
3416
+ * @returns the carrier, for a caller that needs to observe it.
3417
+ */
3418
+ function serveUpgrade(handoff) {
3419
+ const { socket, secWebSocketKey, head, hub, auth } = handoff;
3420
+ const carrier = new WebSocketCarrier(socket);
3421
+ carrier.handshake(secWebSocketKey);
3422
+ const connection = hub.attach(carrier, auth);
3423
+ carrier.onMessage((text) => {
3424
+ connection.handleText(text);
3425
+ });
3426
+ carrier.onClose(() => {
3427
+ hub.detach(connection);
3428
+ });
3429
+ if (head.length > 0) carrier.feed(head);
3430
+ return carrier;
3431
+ }
3432
+ /**
3433
+ * One accepted socket, framed.
3434
+ *
3435
+ * Frames are buffered until a whole one has arrived; a fragmented message is
3436
+ * reassembled up to {@link MAX_FRAME_BYTES} and anything larger closes the
3437
+ * socket with the code that names the violation. The carrier is inert until
3438
+ * {@link handshake} runs, so a caller can refuse a connection without having
3439
+ * written a byte of the protocol.
3440
+ */
3441
+ var WebSocketCarrier = class {
3442
+ #socket;
3443
+ #buffer = Buffer.alloc(0);
3444
+ #fragments = [];
3445
+ #fragmentOpcode = 0;
3446
+ #fragmentBytes = 0;
3447
+ #opened = false;
3448
+ #closed = false;
3449
+ #onMessage;
3450
+ #onClose;
3451
+ /** Messages that arrived before a handler was registered; see {@link deliver}. */
3452
+ #pending = [];
3453
+ constructor(socket) {
3454
+ this.#socket = socket;
3455
+ socket.on("data", (chunk) => {
3456
+ this.feed(chunk);
3457
+ });
3458
+ socket.on("error", () => {
3459
+ this.#shut();
3460
+ });
3461
+ socket.on("close", () => {
3462
+ this.#shut();
3463
+ });
3464
+ socket.on("end", () => {
3465
+ this.#shut();
3466
+ });
3467
+ }
3468
+ /** Write the 101 handshake carrying the accept value for the client's key. */
3469
+ handshake(secWebSocketKey) {
3470
+ if (this.#opened || this.#closed) return;
3471
+ this.#opened = true;
3472
+ this.#socket.write([
3473
+ "HTTP/1.1 101 Switching Protocols",
3474
+ "upgrade: websocket",
3475
+ "connection: Upgrade",
3476
+ `sec-websocket-accept: ${webSocketAccept(secWebSocketKey)}`,
3477
+ "",
3478
+ ""
3479
+ ].join("\r\n"));
3480
+ }
3481
+ /** Register the handler for every complete text message. */
3482
+ onMessage(handler) {
3483
+ this.#onMessage = handler;
3484
+ for (const text of this.#pending.splice(0)) handler(text);
3485
+ }
3486
+ /** Register the one teardown hook; it runs exactly once. */
3487
+ onClose(handler) {
3488
+ this.#onClose = handler;
3489
+ }
3490
+ /** Feed raw bytes from the socket into the frame loop. */
3491
+ feed(chunk) {
3492
+ if (this.#closed) return;
3493
+ this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk]);
3494
+ for (;;) {
3495
+ const outcome = parseClientFrame(this.#buffer, MAX_FRAME_BYTES);
3496
+ if (outcome.status === "incomplete") return;
3497
+ if (outcome.status === "fault") {
3498
+ this.close(outcome.closeCode, outcome.reason);
3499
+ return;
3500
+ }
3501
+ this.#buffer = this.#buffer.subarray(outcome.frame.consumed);
3502
+ if (!this.#accept(outcome.frame.fin, outcome.frame.opcode, outcome.frame.payload)) return;
3503
+ }
3504
+ }
3505
+ /** Send one text frame. */
3506
+ send(text) {
3507
+ if (this.#closed) return;
3508
+ this.#socket.write(encodeTextFrame(text));
3509
+ }
3510
+ /** Send a close frame and end the socket. Idempotent. */
3511
+ close(code, reason) {
3512
+ if (this.#closed) return;
3513
+ this.#closed = true;
3514
+ this.#socket.write(encodeCloseFrame(code, reason));
3515
+ this.#socket.end();
3516
+ this.#notifyClose();
3517
+ }
3518
+ /** @returns whether the carrier has been torn down. */
3519
+ get closed() {
3520
+ return this.#closed;
3521
+ }
3522
+ #accept(fin, opcode, payload) {
3523
+ switch (opcode) {
3524
+ case 1:
3525
+ case 2:
3526
+ if (this.#fragmentOpcode !== 0) {
3527
+ this.close(CLOSE_PROTOCOL_ERROR, "a new message started before the previous one finished");
3528
+ return false;
3529
+ }
3530
+ if (fin) return this.#deliver(opcode, payload);
3531
+ this.#fragmentOpcode = opcode;
3532
+ this.#fragments = [payload];
3533
+ this.#fragmentBytes = payload.length;
3534
+ return true;
3535
+ case 0: {
3536
+ if (this.#fragmentOpcode === 0) {
3537
+ this.close(CLOSE_PROTOCOL_ERROR, "continuation frame without a started message");
3538
+ return false;
3539
+ }
3540
+ this.#fragmentBytes += payload.length;
3541
+ if (this.#fragmentBytes > 10485760) {
3542
+ this.close(CLOSE_TOO_LARGE, `a message may not exceed ${MAX_FRAME_BYTES} bytes`);
3543
+ return false;
3544
+ }
3545
+ this.#fragments.push(payload);
3546
+ if (!fin) return true;
3547
+ const message = Buffer.concat(this.#fragments, this.#fragmentBytes);
3548
+ const opcodeOfMessage = this.#fragmentOpcode;
3549
+ this.#fragments = [];
3550
+ this.#fragmentBytes = 0;
3551
+ this.#fragmentOpcode = 0;
3552
+ return this.#deliver(opcodeOfMessage, message);
3553
+ }
3554
+ case 9:
3555
+ this.#socket.write(encodeServerFrame(10, payload));
3556
+ return true;
3557
+ case 10: return true;
3558
+ case 8:
3559
+ this.close(CLOSE_NORMAL, "");
3560
+ return false;
3561
+ default:
3562
+ this.close(CLOSE_PROTOCOL_ERROR, `unsupported opcode ${opcode}`);
3563
+ return false;
3564
+ }
3565
+ }
3566
+ #deliver(opcode, payload) {
3567
+ if (opcode !== 1) {
3568
+ this.close(CLOSE_UNSUPPORTED_DATA, "this endpoint carries text frames only");
3569
+ return false;
3570
+ }
3571
+ const text = payload.toString("utf8");
3572
+ if (this.#onMessage === void 0) {
3573
+ if (this.#pending.length >= 32) {
3574
+ this.close(CLOSE_TOO_LARGE, "this connection has no message handler");
3575
+ return false;
3576
+ }
3577
+ this.#pending.push(text);
3578
+ return true;
3579
+ }
3580
+ this.#onMessage(text);
3581
+ return true;
3582
+ }
3583
+ /** The socket went away without a close frame: tear down without writing. */
3584
+ #shut() {
3585
+ if (this.#closed) return;
3586
+ this.#closed = true;
3587
+ this.#notifyClose();
3588
+ }
3589
+ #notifyClose() {
3590
+ const handler = this.#onClose;
3591
+ this.#onClose = void 0;
3592
+ handler?.();
3593
+ }
3594
+ };
3595
+ //#endregion
3596
+ //#region src/index.ts
3597
+ /** Loader row identity of this plugin. */
3598
+ const name = "remote-bridge";
3599
+ /** The Host services this plugin cannot run without. */
3600
+ const inject = ["typertGateway", "webServer"];
3601
+ /** Where the paired-device roster lives inside the DSH home. */
3602
+ const ROSTER_PATH = "remote-bridge/devices.json";
3603
+ /** This machine's IANA time zone, or undefined when the platform has none. */
3604
+ function localTimeZone() {
3605
+ try {
3606
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
3607
+ return zone === "" ? void 0 : zone;
3608
+ } catch {
3609
+ return;
3610
+ }
3611
+ }
3612
+ /**
3613
+ * The `/ios/v1` upgrade handler.
3614
+ *
3615
+ * A bad, absent or bootstrap token is NOT a refusal: the connection is simply
3616
+ * unpaired, which is the state the pairing handshake starts from. Only a
3617
+ * malformed handshake is refused.
3618
+ */
3619
+ function makeUpgradeHandler(hub, roster, log) {
3620
+ return async (req, socket, head) => {
3621
+ if (!isWebSocketUpgrade(req)) {
3622
+ refuseUpgrade(socket, 400, "Bad Request");
3623
+ return;
3624
+ }
3625
+ const key = readSecWebSocketKey(req);
3626
+ if (key === void 0) {
3627
+ refuseUpgrade(socket, 400, "Bad Request");
3628
+ return;
3629
+ }
3630
+ try {
3631
+ await roster.load();
3632
+ } catch (error) {
3633
+ log(`could not read the device roster: ${String(error)}`);
3634
+ refuseUpgrade(socket, 503, "Service Unavailable");
3635
+ return;
3636
+ }
3637
+ const token = presentedTokenOf(req);
3638
+ const device = token === void 0 ? void 0 : roster.authenticate(token);
3639
+ const auth = device === void 0 ? void 0 : { deviceId: device.deviceId };
3640
+ serveUpgrade({
3641
+ socket,
3642
+ secWebSocketKey: key,
3643
+ head,
3644
+ hub,
3645
+ ...auth === void 0 ? {} : { auth }
3646
+ });
3647
+ };
3648
+ }
3649
+ /**
3650
+ * Resolve the host services session metadata is read from, now.
3651
+ *
3652
+ * All three are read per call rather than captured at mount: none of them is in
3653
+ * this plugin's `inject` list, because requiring them would let the title or
3654
+ * workspace plugin's absence take the whole bridge down with it. An unmounted
3655
+ * service simply reads as undefined, and the protocol degrades one key of one
3656
+ * row instead of failing a method. The faces are structural — this package
3657
+ * imports no part of those services' own types.
3658
+ * @param ctx - the plugin's context.
3659
+ * @returns the metadata faces as they stand right now.
3660
+ */
3661
+ function sessionMetaFaces(ctx) {
3662
+ return {
3663
+ sessions: ctx.get("sessions"),
3664
+ titles: ctx.get("sessionTitle"),
3665
+ archive: ctx.get("workspaceRegistry")
3666
+ };
3667
+ }
3668
+ /**
3669
+ * Resolve the host services permission presets are read and switched through, now.
3670
+ *
3671
+ * Read per call, never captured at mount, for the reason the metadata faces are:
3672
+ * none of these is in this plugin's `inject` list, and a host that composes no
3673
+ * permission plugin answers `unknown-method` instead of failing to start. The
3674
+ * `Session` object the preset service needs is the store's own live instance —
3675
+ * the same object `sessionTitle` already takes — so no second lookup path exists
3676
+ * for it.
3677
+ * @param ctx - the plugin's context.
3678
+ * @returns the permission faces as they stand right now.
3679
+ */
3680
+ function permissionFaces(ctx) {
3681
+ return {
3682
+ sessions: ctx.get("sessions"),
3683
+ presets: ctx.get("permissionPresets"),
3684
+ sandbox: ctx.get("sandboxPolicy"),
3685
+ approval: ctx.get("approval")
3686
+ };
3687
+ }
3688
+ /**
3689
+ * Mount the bridge.
3690
+ * @param ctx - the plugin's context, carrying the gateway and web server.
3691
+ */
3692
+ function apply(ctx) {
3693
+ const log = (message) => {
3694
+ console.log(`[remote-bridge] ${message}`);
3695
+ };
3696
+ const roster = new DeviceRoster({
3697
+ file: join(dshHome(), ROSTER_PATH),
3698
+ log
3699
+ });
3700
+ const pairing = new PairingService();
3701
+ const approvals = new ApprovalRegistry();
3702
+ const ownerPeer = createOwnerPeer(ctx);
3703
+ const questions = new QuestionClaims({
3704
+ gateway: ctx.typertGateway,
3705
+ peer: ownerPeer,
3706
+ log
3707
+ });
3708
+ const sessionMeta = new SessionMeta(() => sessionMetaFaces(ctx), () => Date.now(), log);
3709
+ const permissions = new SessionPermissions(() => permissionFaces(ctx), log);
3710
+ const hub = new BridgeHub({
3711
+ gateway: ctx.typertGateway,
3712
+ pairing,
3713
+ roster,
3714
+ approvals,
3715
+ questions,
3716
+ sessionMeta,
3717
+ permissions,
3718
+ ownerPeer,
3719
+ now: () => Date.now(),
3720
+ clientTimeZone: localTimeZone,
3721
+ log
3722
+ });
3723
+ ctx.effect(() => {
3724
+ roster.load();
3725
+ const disposeUpgrade = ctx.webServer.registerUpgrade({
3726
+ path: WS_PATH,
3727
+ handler: makeUpgradeHandler(hub, roster, log)
3728
+ });
3729
+ const disposeRoute = ctx.webServer.register(makePairTokenRoute({
3730
+ pairing,
3731
+ log
3732
+ }));
3733
+ log(`protocol v1 listening on ${WS_PATH}`);
3734
+ return () => {
3735
+ disposeUpgrade();
3736
+ disposeRoute();
3737
+ hub.dispose();
3738
+ };
3739
+ }, "remote-bridge: protocol v1 routes");
3740
+ ctx.on("approval/request", (request, next) => hub.approve(request, next));
3741
+ ctx.on("user-questions/request", (request, next) => hub.question(request, next), { prepend: true });
3742
+ }
3743
+ //#endregion
3744
+ export { ROSTER_PATH, apply, inject, name };