@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
@@ -0,0 +1,1090 @@
1
+ /**
2
+ * One client connection's protocol v1 state machine, transport-agnostic.
3
+ *
4
+ * Everything a connected device can do lives here, and nothing about the
5
+ * WebSocket carrier does: the state machine writes frames through a
6
+ * {@link BridgeTransport}, so the tests drive a whole session — pairing,
7
+ * listing, snapshotting, prompting, approvals — without a socket.
8
+ *
9
+ * Two rules from the frozen design are load-bearing here:
10
+ * - a follow stream is opened once per session with `assistantStream: true`,
11
+ * and its opening snapshot frame doubles as `session.snapshot`'s answer
12
+ * (decided after the original §2.1/§2.2 contradiction);
13
+ * - every follow stream is aborted when the connection ends. A stream that
14
+ * outlives its connection would keep the session's process-local assistant
15
+ * stream alive for a phone that is gone.
16
+ * @module dsh-remote-bridge/core/connection
17
+ */
18
+
19
+ import type { ApprovalRegistry } from './approvals.ts'
20
+ import type { DeviceRoster } from './devices.ts'
21
+ import { deltaOfFollowFrame, MessageIndex, pageTurns, readFollowBaseline, ToolCallIndex, trimUnrenderedEntries, turnsOfRecords, type FollowBaseline, type SnapshotTurn } from './dsh-frames.ts'
22
+ import { EventSequence, FRAME_TOO_LARGE, MAX_FRAME_BYTES, decodeClientFrame, encodeFrame, errorFrame, responseFrame, type ReqFrame, type ServerFrame } from './envelope.ts'
23
+ import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
24
+ import type { PairingService } from './pairing.ts'
25
+ import type { QuestionAnswerItem, QuestionClaims } from './questions.ts'
26
+ import {
27
+ CAP_QUESTIONS,
28
+ CAP_SESSION_SNAPSHOT_PAGE,
29
+ CAP_SESSION_SNAPSHOT_TRIM,
30
+ CODE_APPROVAL_UNKNOWN,
31
+ CODE_INTERNAL,
32
+ CODE_INVALID_ARGS,
33
+ CODE_NONCE_INVALID,
34
+ CODE_PROTO_UNSUPPORTED,
35
+ CODE_SNAPSHOT_TOO_LARGE,
36
+ CODE_SNAPSHOT_UNAVAILABLE,
37
+ CODE_TOKEN_INVALID,
38
+ CODE_UNKNOWN_METHOD,
39
+ CODE_UNPAIRED,
40
+ KNOWN_METHODS,
41
+ METHOD_APPROVAL_RESOLVE,
42
+ METHOD_HELLO,
43
+ METHOD_PAIR_BEGIN,
44
+ METHOD_PAIR_FINISH,
45
+ METHOD_QUESTION_ANSWER,
46
+ METHOD_SESSION_ATTACHMENT,
47
+ METHOD_SESSION_HISTORY,
48
+ METHOD_SESSION_INTERRUPT,
49
+ METHOD_SESSION_LIST,
50
+ METHOD_SESSION_MODELS,
51
+ METHOD_SESSION_PERMISSIONS,
52
+ METHOD_SESSION_PROMPT,
53
+ METHOD_SESSION_SET_MODEL,
54
+ METHOD_SESSION_SET_PERMISSION,
55
+ METHOD_SESSION_SNAPSHOT,
56
+ METHOD_SESSION_TITLES,
57
+ MINOR,
58
+ PROTO,
59
+ SERVER_ID,
60
+ TOPIC_SESSION_DELTA,
61
+ UNPAIRED_METHODS,
62
+ } from './protocol.ts'
63
+ import { base64UrlDecode, verifyEs256 } from './crypto.ts'
64
+ import { TITLES_MAX_IDS, type SessionMeta } from './session-meta.ts'
65
+ import type { SessionPermissions } from './session-permissions.ts'
66
+ import type { BridgeGateway, GatewayPeer } from './wire.ts'
67
+ import { CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
68
+
69
+ /** Protocol-level heartbeat period: a frame is sent after this long without one. */
70
+ export const IDLE_PING_MS = 20_000
71
+ /** How long `session.snapshot` waits for its follow stream's opening frame. */
72
+ export const SNAPSHOT_OPEN_TIMEOUT_MS = 10_000
73
+ /** Largest turn window one snapshot asks DSH for. */
74
+ export const SNAPSHOT_MAX_MESSAGES = 200
75
+ /** Default byte budget of one `session.history` page: 512 KiB. */
76
+ export const HISTORY_PAGE_BYTES = 512 * 1024
77
+ /** Highest number of prompt receipts one connection remembers for idempotency. */
78
+ export const PROMPT_RECEIPT_LIMIT = 512
79
+ /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
80
+ export const PROMPT_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024
81
+
82
+ /** The carrier a connection writes through. */
83
+ export interface BridgeTransport {
84
+ send(text: string): void
85
+ close(code: number, reason: string): void
86
+ }
87
+
88
+ export interface BridgeConnectionOptions {
89
+ readonly gateway: BridgeGateway
90
+ readonly pairing: PairingService
91
+ readonly roster: DeviceRoster
92
+ readonly approvals: ApprovalRegistry
93
+ /** Pending user questions: the claims this bridge holds and the answer path back to the host. */
94
+ readonly questions: QuestionClaims
95
+ /** Process-local session metadata: live titles and the host's archive set. */
96
+ readonly sessionMeta: SessionMeta
97
+ /** Host-process permission presets, read and switched through their real service objects. */
98
+ readonly permissions: SessionPermissions
99
+ /**
100
+ * The in-process owner peer every gateway call speaks for, minted by the
101
+ * bridge itself (`core/owner-peer.ts`). Dispatch refuses unpaired
102
+ * connections before any gateway call exists, so this peer — a
103
+ * full-control credential — is exercised only behind the bridge's own
104
+ * pairing gate, and no client frame field is ever read into it.
105
+ */
106
+ readonly ownerPeer: GatewayPeer
107
+ readonly now: () => number
108
+ /** This machine's IANA time zone, sent with every prompt. */
109
+ readonly clientTimeZone: () => string | undefined
110
+ readonly log: (message: string) => void
111
+ /**
112
+ * Called after a client's `hello` records its capabilities, so the hub can hand
113
+ * it whatever it can now receive but was not there to see.
114
+ */
115
+ readonly onDeclare?: (connection: BridgeConnection) => void
116
+ readonly heartbeatMs?: number
117
+ }
118
+
119
+ /** A device the connection proved itself to be, resolved from the upgrade request. */
120
+ export interface ConnectionAuth {
121
+ readonly deviceId: string
122
+ }
123
+
124
+ /** The answer of a subscription's opening frame: a baseline, or why there is none. */
125
+ type Opening = { readonly ok: true; readonly baseline: FollowBaseline } | { readonly ok: false; readonly code: string; readonly msg: string }
126
+
127
+ /** One open follow stream and the answer its opening frame resolves. */
128
+ interface Subscription {
129
+ readonly sessionId: string
130
+ readonly controller: AbortController
131
+ /**
132
+ * Mutable on purpose: a delegated child is addressable only through its durable
133
+ * parent, and the bridge learns which address kind applies from the harness's own
134
+ * refusal on the first attempt.
135
+ */
136
+ address: SessionAddress
137
+ opened: Promise<Opening>
138
+ }
139
+
140
+ /** The refusal half of every dispatch outcome. */
141
+ interface CallFailure {
142
+ readonly ok: false
143
+ readonly code: string
144
+ readonly msg: string
145
+ }
146
+
147
+ type DispatchOutcome = { readonly ok: true; readonly r: unknown } | CallFailure
148
+
149
+ /** One session-list row as the protocol publishes it. */
150
+ interface SessionRow {
151
+ readonly id: string
152
+ readonly title: string
153
+ readonly updatedAt: number
154
+ readonly agentRunning: boolean
155
+ /** The session's working directory, omitted when the host did not report one. */
156
+ readonly cwd?: string
157
+ /** The session this one was delegated from, omitted for a root session. */
158
+ readonly parentSessionId?: string
159
+ /** `subagent` for a delegated session, omitted for an ordinary one. */
160
+ readonly origin?: 'subagent'
161
+ readonly blank: boolean
162
+ /** The host's archive flag; omitted when this process cannot read the archive set. */
163
+ readonly archived?: boolean
164
+ }
165
+
166
+ function refusal(code: string, msg: string): CallFailure {
167
+ return { ok: false, code, msg }
168
+ }
169
+
170
+ function isRecord(value: unknown): value is Record<string, unknown> {
171
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
172
+ }
173
+
174
+ /** @returns a non-empty string argument, or undefined. */
175
+ function stringArg(payload: Readonly<Record<string, unknown>>, key: string): string | undefined {
176
+ const value = payload[key]
177
+ return typeof value === 'string' && value !== '' ? value : undefined
178
+ }
179
+
180
+ /** @returns a non-empty string payload value, or undefined. */
181
+ function optionalText(value: unknown): string | undefined {
182
+ return typeof value === 'string' && value !== '' ? value : undefined
183
+ }
184
+
185
+ /** @returns a non-negative safe integer page argument, or undefined. */
186
+ function pageNumber(value: unknown): number | undefined {
187
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined
188
+ }
189
+
190
+ /**
191
+ * Read one request's page budget.
192
+ *
193
+ * An absent budget is {@link HISTORY_PAGE_BYTES}; a budget an encoded page
194
+ * could never be measured against — zero, fractional, negative or larger than
195
+ * one frame — is refused rather than clamped, so a caller never mistakes a
196
+ * silently reduced page for the one it asked for.
197
+ * @param value - the request's `maxBytes` member, or undefined.
198
+ * @param method - the method name the refusal names.
199
+ */
200
+ function pageBudgetOf(value: unknown, method: string): { readonly ok: true; readonly maxBytes: number } | CallFailure {
201
+ if (value === undefined) return { ok: true, maxBytes: HISTORY_PAGE_BYTES }
202
+ const maxBytes = pageNumber(value)
203
+ if (maxBytes === undefined || maxBytes < 1 || maxBytes > MAX_FRAME_BYTES) {
204
+ return refusal(CODE_INVALID_ARGS, `${method} maxBytes must be between 1 and ${MAX_FRAME_BYTES}`)
205
+ }
206
+ return { ok: true, maxBytes }
207
+ }
208
+
209
+ /**
210
+ * Read the capability names a `hello` announced.
211
+ *
212
+ * A capability is an announcement, not a negotiation: an unreadable `cap`, an
213
+ * unknown name and an absent key all leave the connection with no capabilities
214
+ * rather than failing the handshake.
215
+ * @param value - the `cap` member of a hello payload, as it crossed the wire.
216
+ * @returns the declared names, empty when the client declared none.
217
+ */
218
+ function capabilitiesOf(value: unknown): ReadonlySet<string> {
219
+ if (!Array.isArray(value)) return new Set()
220
+ return new Set(value.filter((name): name is string => typeof name === 'string' && name !== ''))
221
+ }
222
+
223
+ /**
224
+ * Validate `question.answer`'s answer batch.
225
+ *
226
+ * The host validates the batch against the questions it actually asked (missing,
227
+ * duplicated or invented ids are the host's own `BAD_ANSWER`), so this only
228
+ * refuses what is not an answer at all: a non-array, an entry that is not an
229
+ * object, an entry without a non-empty id, or `selected` that is not a list of
230
+ * non-empty labels.
231
+ * @param value - the request's `answers` member, or undefined.
232
+ * @returns the batch in protocol vocabulary, or undefined when it is not one.
233
+ */
234
+ function answersOf(value: unknown): readonly QuestionAnswerItem[] | undefined {
235
+ if (!Array.isArray(value)) return undefined
236
+ const answers: QuestionAnswerItem[] = []
237
+ for (const entry of value) {
238
+ if (!isRecord(entry)) return undefined
239
+ const id = optionalText(entry.id)
240
+ const selected = entry.selected
241
+ if (id === undefined || !Array.isArray(selected)) return undefined
242
+ if (!selected.every(label => typeof label === 'string' && label !== '')) return undefined
243
+ const custom = optionalText(entry.custom)
244
+ answers.push({ id, selected: selected as string[], ...(custom === undefined ? {} : { custom }) })
245
+ }
246
+ return answers
247
+ }
248
+
249
+ /** One model selection, in the field names the protocol publishes. */
250
+ type ModelSelection = {
251
+ readonly provider: string
252
+ readonly model: string
253
+ readonly reasoningEffort?: string
254
+ }
255
+
256
+ /** @returns the selection this value describes, or undefined when it describes none. */
257
+ function selectionOf(value: unknown): ModelSelection | undefined {
258
+ if (!isRecord(value)) return undefined
259
+ const provider = optionalText(value.provider)
260
+ const model = optionalText(value.model)
261
+ if (provider === undefined || model === undefined) return undefined
262
+ const reasoningEffort = optionalText(value.reasoningEffort)
263
+ return reasoningEffort === undefined ? { provider, model } : { provider, model, reasoningEffort }
264
+ }
265
+
266
+ /**
267
+ * The durable model-selection fold of one `session/projections` answer.
268
+ *
269
+ * Both halves stay optional: a session that never ran has neither, and the
270
+ * catalog default is then the only truthful current value.
271
+ */
272
+ function modelSelectionOf(value: unknown): { readonly next?: ModelSelection; readonly lastUsed?: ModelSelection } {
273
+ if (!isRecord(value) || !isRecord(value.values)) return {}
274
+ const selection = value.values.modelSelection
275
+ if (!isRecord(selection)) return {}
276
+ const next = selectionOf(selection.next)
277
+ const lastUsed = selectionOf(selection.lastUsed)
278
+ return {
279
+ ...(next === undefined ? {} : { next }),
280
+ ...(lastUsed === undefined ? {} : { lastUsed }),
281
+ }
282
+ }
283
+
284
+ /** One prompt attachment, already projected to the harness's image content part. */
285
+ type PromptAttachment = Readonly<Record<string, unknown>>
286
+
287
+ /** The validated attachments of one prompt, or the refusal that withheld it. */
288
+ type PromptAttachments = { readonly ok: true; readonly parts: readonly PromptAttachment[] } | CallFailure
289
+
290
+ /**
291
+ * Validate `session.prompt`'s optional attachments and project them to the
292
+ * harness's image content parts, keeping the order the client sent.
293
+ *
294
+ * The per-attachment budget is checked here rather than at the harness: 6 MiB of
295
+ * base64 per attachment is what keeps a prompt frame inside the envelope's
296
+ * 10 MiB, and the refusal names the attachment and its exact byte count so the
297
+ * phone can say which pick made the send fail. Nothing is truncated and nothing
298
+ * is dropped — one rejected attachment withholds the whole prompt.
299
+ * @param value - the request's `attachments` member, or undefined.
300
+ */
301
+ function promptAttachmentsOf(value: unknown): PromptAttachments {
302
+ if (value === undefined) return { ok: true, parts: [] }
303
+ if (!Array.isArray(value)) return refusal(CODE_INVALID_ARGS, 'session.prompt attachments must be an array')
304
+ const parts: PromptAttachment[] = []
305
+ for (const entry of value) {
306
+ if (!isRecord(entry)) return refusal(CODE_INVALID_ARGS, 'session.prompt attachments must be objects')
307
+ const name = optionalText(entry.name)
308
+ const label = name === undefined ? `attachment ${parts.length + 1}` : `attachment "${name}"`
309
+ const mediaType = optionalText(entry.mediaType)
310
+ const data = typeof entry.data === 'string' ? entry.data : undefined
311
+ if (mediaType === undefined || data === undefined || data === '') {
312
+ return refusal(CODE_INVALID_ARGS, `session.prompt ${label} requires mediaType and base64 data`)
313
+ }
314
+ const bytes = Buffer.byteLength(data, 'utf8')
315
+ if (bytes > PROMPT_ATTACHMENT_MAX_BYTES) {
316
+ return refusal(
317
+ CODE_INVALID_ARGS,
318
+ `session.prompt ${label} is ${bytes} base64 bytes, past the ${PROMPT_ATTACHMENT_MAX_BYTES} byte limit`,
319
+ )
320
+ }
321
+ parts.push({ type: 'image', mediaType, data, ...(name === undefined ? {} : { name }) })
322
+ }
323
+ return { ok: true, parts }
324
+ }
325
+
326
+ /**
327
+ * Everything one connected device may do.
328
+ *
329
+ * Not thread-safe by construction but safe by awaiting: handlers are invoked
330
+ * one frame at a time by the carrier's reader, and the only background work is
331
+ * a subscription's own drain loop.
332
+ */
333
+ export class BridgeConnection {
334
+ readonly #options: BridgeConnectionOptions
335
+ readonly #transport: BridgeTransport
336
+ readonly #sequence = new EventSequence()
337
+ readonly #subscriptions = new Map<string, Subscription>()
338
+ readonly #receipts = new Set<string>()
339
+ readonly #toolCalls = new ToolCallIndex()
340
+ readonly #messages = new MessageIndex()
341
+ #capabilities: ReadonlySet<string> = new Set()
342
+ /** Delegated children this connection has learned the durable parent of, by child id. */
343
+ readonly #lineage = new Map<string, string>()
344
+ #lineageRead = false
345
+ #deviceId: string | undefined
346
+ #nonce: { readonly value: string; readonly expiresAt: number } | undefined
347
+ #heartbeat: NodeJS.Timeout | undefined
348
+ #lastSendAt = 0
349
+ #disposed = false
350
+
351
+ constructor(options: BridgeConnectionOptions, transport: BridgeTransport, auth?: ConnectionAuth) {
352
+ this.#options = options
353
+ this.#transport = transport
354
+ this.#deviceId = auth?.deviceId
355
+ this.#lastSendAt = options.now()
356
+ }
357
+
358
+ /** @returns whether this connection has proven a device token (or just enrolled). */
359
+ get paired(): boolean {
360
+ return this.#deviceId !== undefined
361
+ }
362
+
363
+ /** @returns the paired device id, or undefined while unpaired. */
364
+ get deviceId(): string | undefined {
365
+ return this.#deviceId
366
+ }
367
+
368
+ /** @returns whether the connection has been torn down. */
369
+ get disposed(): boolean {
370
+ return this.#disposed
371
+ }
372
+
373
+ /**
374
+ * @param capability - one capability name this protocol defines.
375
+ * @returns whether this connection announced it in `hello`.
376
+ */
377
+ declares(capability: string): boolean {
378
+ return this.#capabilities.has(capability)
379
+ }
380
+
381
+ /** Start the idle heartbeat that keeps a quiet phone's socket alive. */
382
+ startHeartbeat(): void {
383
+ if (this.#heartbeat !== undefined) return
384
+ const period = this.#options.heartbeatMs ?? IDLE_PING_MS
385
+ this.#heartbeat = setInterval(() => {
386
+ if (this.#options.now() - this.#lastSendAt >= period) this.#send({ t: 'ping', ts: this.#options.now() })
387
+ }, period)
388
+ this.#heartbeat.unref?.()
389
+ }
390
+
391
+ /**
392
+ * Handle one received text frame.
393
+ *
394
+ * This method NEVER rejects. Its caller in the mounted wiring is
395
+ * `void connection.handleText(text)`, so a rejection here would be dropped on
396
+ * the floor and the client would wait forever for an answer that is never
397
+ * coming — the same silent stall as a socket nobody reads. Any unexpected
398
+ * failure (a roster write that cannot complete, a carrier that throws) is
399
+ * answered as an `internal` refusal and logged.
400
+ * @param text - the frame body as it crossed the wire.
401
+ */
402
+ async handleText(text: string): Promise<void> {
403
+ if (this.#disposed) return
404
+ const outcome = decodeClientFrame(text)
405
+ if (!outcome.ok) {
406
+ this.#send(errorFrame(outcome.id, outcome.code, outcome.msg))
407
+ return
408
+ }
409
+ const frame = outcome.frame
410
+ if (frame.t === 'ping') {
411
+ this.#send({ t: 'pong', ts: frame.ts })
412
+ return
413
+ }
414
+ if (frame.t === 'pong') return
415
+ try {
416
+ const answer = await this.#dispatch(frame)
417
+ if (answer.ok) this.#send(responseFrame(frame.id, answer.r))
418
+ else this.#send(errorFrame(frame.id, answer.code, answer.msg))
419
+ } catch (error) {
420
+ this.#options.log(`${frame.m} failed unexpectedly: ${failureText(error)}`)
421
+ this.#send(errorFrame(frame.id, CODE_INTERNAL, failureText(error)))
422
+ }
423
+ }
424
+
425
+ /** Push one event to this connection, advancing its own sequence. */
426
+ emit(topic: string, payload: unknown): boolean {
427
+ return this.#emit(topic, payload)
428
+ }
429
+
430
+ /**
431
+ * Tear the connection down: stop the heartbeat, abort every follow stream it
432
+ * owns, and tell the carrier to go away. Idempotent, and safe to call from a
433
+ * socket error handler — a carrier whose socket already closed ignores it.
434
+ */
435
+ dispose(): void {
436
+ if (this.#disposed) return
437
+ this.#disposed = true
438
+ if (this.#heartbeat !== undefined) {
439
+ clearInterval(this.#heartbeat)
440
+ this.#heartbeat = undefined
441
+ }
442
+ for (const subscription of this.#subscriptions.values()) subscription.controller.abort()
443
+ this.#subscriptions.clear()
444
+ // The bridge itself may be unloading with live sockets: the client is told
445
+ // the endpoint is going away instead of being left on a dead protocol.
446
+ this.#transport.close(1001, 'the bridge is going away')
447
+ }
448
+
449
+ async #dispatch(frame: ReqFrame): Promise<DispatchOutcome> {
450
+ if (!KNOWN_METHODS.has(frame.m)) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
451
+ // `question.answer` exists only for a client that asked for the question
452
+ // channel: without the capability it is an unknown method, which is exactly
453
+ // what this frame was before the channel existed.
454
+ if (frame.m === METHOD_QUESTION_ANSWER && !this.declares(CAP_QUESTIONS)) {
455
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
456
+ }
457
+ // Unconditional: a loopback Host buys nothing here. Without a device token
458
+ // only the handshake and the two pairing steps run.
459
+ if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, 'this connection is not paired')
460
+ switch (frame.m) {
461
+ case METHOD_HELLO: return this.#hello(frame.p)
462
+ case METHOD_PAIR_BEGIN: return this.#pairBegin(frame.p)
463
+ case METHOD_PAIR_FINISH: return await this.#pairFinish(frame.p)
464
+ case METHOD_SESSION_LIST: return await this.#sessionList()
465
+ case METHOD_SESSION_TITLES: return this.#sessionTitles(frame.p)
466
+ case METHOD_SESSION_SNAPSHOT: return await this.#sessionSnapshot(frame.p, frame.id)
467
+ case METHOD_SESSION_HISTORY: return await this.#sessionHistory(frame.p, frame.id)
468
+ case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p)
469
+ case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p)
470
+ case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id)
471
+ case METHOD_SESSION_PERMISSIONS: return this.#sessionPermissions(frame.p)
472
+ case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p)
473
+ case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p)
474
+ case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p)
475
+ case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
476
+ case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p)
477
+ default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
478
+ }
479
+ }
480
+
481
+ #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome { const proto = payload.proto
482
+ if (proto !== PROTO) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol ${PROTO}`)
483
+ this.#capabilities = capabilitiesOf(payload.cap)
484
+ // The hub replays anything this client can now receive but missed: a phone
485
+ // that connected after a question was raised has no other way to learn of it.
486
+ this.#options.onDeclare?.(this)
487
+ return {
488
+ ok: true,
489
+ r: {
490
+ proto: PROTO,
491
+ minor: MINOR,
492
+ server: SERVER_ID,
493
+ resume: 'snapshot',
494
+ auth: this.paired ? 'paired' : 'unpaired',
495
+ },
496
+ }
497
+ }
498
+
499
+ #pairBegin(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
500
+ const token = stringArg(payload, 'token')
501
+ if (token === undefined) return refusal(CODE_INVALID_ARGS, 'pair.begin requires token')
502
+ if (!this.#options.pairing.consumeToken(token)) return refusal(CODE_TOKEN_INVALID, 'the bootstrap token is unknown, expired or already used')
503
+ const nonce = this.#options.pairing.issueNonce()
504
+ this.#nonce = { value: nonce.value, expiresAt: nonce.expiresAt }
505
+ return { ok: true, r: { nonce: nonce.value, expiresAt: nonce.expiresAt } }
506
+ }
507
+
508
+ async #pairFinish(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
509
+ const devicePubKey = stringArg(payload, 'devicePubKey')
510
+ const signature = stringArg(payload, 'signature')
511
+ if (devicePubKey === undefined || signature === undefined) {
512
+ return refusal(CODE_INVALID_ARGS, 'pair.finish requires devicePubKey and signature')
513
+ }
514
+ const nonce = this.#nonce
515
+ if (nonce === undefined) return refusal(CODE_NONCE_INVALID, 'this connection has no open pairing')
516
+ // Consume before verifying: a wrong signature burns the challenge instead of
517
+ // leaving it available for another guess.
518
+ this.#nonce = undefined
519
+ if (!this.#options.pairing.consumeNonce(nonce.value) || nonce.expiresAt <= this.#options.now()) {
520
+ return refusal(CODE_NONCE_INVALID, 'the pairing nonce is expired or already used')
521
+ }
522
+ const raw = base64UrlDecode(nonce.value)
523
+ // The design says "the nonce's raw bytes". Both readings of that phrase are
524
+ // accepted — the decoded nonce, and the UTF-8 of the base64url text a client
525
+ // may sign without decoding — because the nonce is one-shot, 60 s, and
526
+ // bound to this connection, so accepting either encoding cannot let an
527
+ // unpaired caller in.
528
+ const signed = raw !== undefined && verifyEs256(devicePubKey, signature, raw)
529
+ ? true
530
+ : verifyEs256(devicePubKey, signature, Buffer.from(nonce.value, 'utf8'))
531
+ if (!signed) return refusal('signature-invalid', 'the ES256 signature does not verify against the device public key')
532
+ const enrollment = await this.#options.roster.enroll(devicePubKey)
533
+ if (enrollment === undefined) return refusal(CODE_INVALID_ARGS, 'devicePubKey is not a P-256 SPKI public key')
534
+ this.#deviceId = enrollment.deviceId
535
+ return { ok: true, r: { deviceToken: enrollment.deviceToken, deviceId: enrollment.deviceId } }
536
+ }
537
+
538
+ async #sessionList(): Promise<DispatchOutcome> {
539
+ const call = await this.#unary('session', 'list')
540
+ if (!call.ok) return call
541
+ const items = isRecord(call.value) ? call.value.items : undefined
542
+ if (!Array.isArray(items)) return refusal(CODE_INTERNAL, 'session/list returned no item table')
543
+ // Read once for the whole roster: the archive flag comes from one process-wide
544
+ // set, and an unreadable registry leaves the key out of every row.
545
+ const archived = this.#options.sessionMeta.archiveSet()
546
+ const sessions: SessionRow[] = []
547
+ for (const item of items) {
548
+ if (!isRecord(item) || typeof item.sessionId !== 'string') continue
549
+ const cwd = optionalText(item.cwd)
550
+ const parentSessionId = optionalText(item.parentSessionId)
551
+ sessions.push({
552
+ id: item.sessionId,
553
+ // The roster itself carries no title: `SessionSummary` has none. The
554
+ // connection fills in whatever `session.titles` already resolved for
555
+ // this id and never looks one up here, so listing stays one call.
556
+ title: this.#options.sessionMeta.cachedTitle(item.sessionId) ?? '',
557
+ updatedAt: typeof item.updatedAt === 'number' ? item.updatedAt : 0,
558
+ agentRunning: item.running === true,
559
+ ...(cwd === undefined ? {} : { cwd }),
560
+ ...(parentSessionId === undefined ? {} : { parentSessionId }),
561
+ ...(item.origin === 'subagent' ? { origin: 'subagent' as const } : {}),
562
+ blank: item.blank === true,
563
+ ...(archived === undefined ? {} : { archived: archived.has(item.sessionId) }),
564
+ })
565
+ }
566
+ // A listed roster is also the cheapest place to learn lineage: a delegated
567
+ // child's durable parent is on its own row, so a client that lists before it
568
+ // opens a session never costs a second read to address that session.
569
+ this.#rememberLineage(sessions)
570
+ return { ok: true, r: { sessions } }
571
+ }
572
+
573
+ /**
574
+ * Answer a batch of title lookups out of this process's title service.
575
+ *
576
+ * Every read is synchronous and in-process, so the batch bound is the whole
577
+ * cost bound: nothing here awaits, opens a follow stream or touches
578
+ * persistence. A session that is not live here, one whose title has not
579
+ * landed yet, and a host without the title service all answer `""` — the
580
+ * batch never fails for one id, and never fails because a service is absent.
581
+ * @param payload - `{ids}`: one to {@link TITLES_MAX_IDS} session ids.
582
+ */
583
+ #sessionTitles(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
584
+ const ids = payload.ids
585
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > TITLES_MAX_IDS) {
586
+ return refusal(CODE_INVALID_ARGS, `session.titles requires 1 to ${TITLES_MAX_IDS} session ids`)
587
+ }
588
+ for (const id of ids) {
589
+ if (typeof id !== 'string' || id === '') return refusal(CODE_INVALID_ARGS, 'session.titles requires non-empty string ids')
590
+ }
591
+ // The ids are chosen by the client, so the answer map is built on a null
592
+ // prototype: a literal id like `__proto__` has to become a real key.
593
+ const titles = Object.create(null) as Record<string, string>
594
+ for (const id of ids) titles[id] = this.#options.sessionMeta.title(id)
595
+ return { ok: true, r: { titles } }
596
+ }
597
+
598
+ /**
599
+ * Answer `session.snapshot`: the opening window, or one page of it.
600
+ *
601
+ * A client that declared {@link CAP_SESSION_SNAPSHOT_PAGE} gets the newest
602
+ * page inside `maxBytes` (default {@link HISTORY_PAGE_BYTES}) instead of the
603
+ * whole window, so an opening screen costs one page. The page is cut by the
604
+ * same entry-level slice `session.history` uses, so the two can never
605
+ * disagree, an entry larger than the whole budget is a page of its own rather
606
+ * than a refusal, and `snapshot-too-large` cannot answer such a connection.
607
+ * The oldest entry's own `seq` is the `before` cursor for the next, older
608
+ * page; no second field restates it.
609
+ * @param payload - `{sessionId, maxBytes?}`.
610
+ * @param id - the request id the page budget is measured against.
611
+ */
612
+ async #sessionSnapshot(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
613
+ const sessionId = stringArg(payload, 'sessionId')
614
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.snapshot requires sessionId')
615
+ const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
616
+ if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
617
+ // A client that declared the trim capability chooses what it is sent, never
618
+ // which turns it gets: the projection is trimmed inside each turn first, and
619
+ // only then does any frame or page budget apply.
620
+ const projection = this.#projectionOf(opening.baseline.records)
621
+ if (!this.#capabilities.has(CAP_SESSION_SNAPSHOT_PAGE)) {
622
+ // Not declared: the whole window, shrunk by whole turns, unchanged.
623
+ const fitted = this.#fitTurns(projection, opening.baseline.cursor, id)
624
+ if (fitted === undefined) return refusal(CODE_SNAPSHOT_TOO_LARGE, `session ${sessionId} does not fit one ${MAX_FRAME_BYTES} byte frame`)
625
+ return { ok: true, r: { turns: fitted.turns, lastSeq: fitted.lastSeq } }
626
+ }
627
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT)
628
+ if (!budget.ok) return budget
629
+ const lastSeq = opening.baseline.cursor
630
+ const page = pageTurns(projection, undefined, budget.maxBytes, (turns, _nextBefore, hasMore) =>
631
+ Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, lastSeq, hasMore })), 'utf8'))
632
+ return { ok: true, r: { turns: page.turns, lastSeq, hasMore: page.hasMore } }
633
+ }
634
+
635
+ /**
636
+ * Read one backwards page of a session's history.
637
+ *
638
+ * Pages are cut from the very baseline `session.snapshot` serves, so the two
639
+ * can never disagree about a turn or an entry; this method only slices that
640
+ * projection, by entry, from the newest entry below the caller's watermark. It
641
+ * is a pure read of the baseline: it never drops, replaces or re-addresses the
642
+ * subscription, and the same cursor always answers the same page.
643
+ * @param payload - `{sessionId, before?, maxBytes?}`.
644
+ * @param id - the request id the page budget is measured against.
645
+ */
646
+ async #sessionHistory(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
647
+ const sessionId = stringArg(payload, 'sessionId')
648
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.history requires sessionId')
649
+ const before = payload.before === undefined ? undefined : pageNumber(payload.before)
650
+ if (payload.before !== undefined && before === undefined) {
651
+ return refusal(CODE_INVALID_ARGS, 'session.history before must be a non-negative integer')
652
+ }
653
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY)
654
+ if (!budget.ok) return budget
655
+ const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
656
+ if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
657
+ const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) =>
658
+ Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, ...(nextBefore === undefined ? {} : { nextBefore }), hasMore })), 'utf8'))
659
+ return {
660
+ ok: true,
661
+ r: {
662
+ turns: page.turns,
663
+ ...(page.nextBefore === undefined ? {} : { nextBefore: page.nextBefore }),
664
+ hasMore: page.hasMore,
665
+ },
666
+ }
667
+ }
668
+
669
+ /** The projection a baseline is served with: trimmed only for a client that asked for it. */
670
+ #projectionOf(records: readonly unknown[]): SnapshotTurn[] {
671
+ const projected = turnsOfRecords(records)
672
+ return this.#capabilities.has(CAP_SESSION_SNAPSHOT_TRIM) ? trimUnrenderedEntries(projected) : projected
673
+ }
674
+
675
+ async #sessionPrompt(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
676
+ const sessionId = stringArg(payload, 'sessionId')
677
+ const text = stringArg(payload, 'text')
678
+ const requestId = stringArg(payload, 'requestId')
679
+ if (sessionId === undefined || text === undefined || requestId === undefined) {
680
+ return refusal(CODE_INVALID_ARGS, 'session.prompt requires sessionId, text and requestId')
681
+ }
682
+ // Attachments are settled before the receipt is read and before anything is
683
+ // sent: one rejected attachment withholds the whole prompt, so the harness is
684
+ // not even subscribed to, let alone prompted.
685
+ const attachments = promptAttachmentsOf(payload.attachments)
686
+ if (!attachments.ok) return attachments
687
+ const receipt = `${sessionId}\u0000${requestId}`
688
+ if (this.#receipts.has(receipt)) return { ok: true, r: { accepted: true } }
689
+ // A client may prompt without snapshotting first; the subscription is what
690
+ // makes its own deltas reachable.
691
+ this.#ensureSubscription(sessionId)
692
+ const timeZone = this.#options.clientTimeZone()
693
+ const call = await this.#unary('session', 'prompt', {
694
+ requestId,
695
+ sessionId,
696
+ mode: 'queue',
697
+ content: [{ type: 'text', text }, ...attachments.parts],
698
+ ...(timeZone === undefined || timeZone === '' ? {} : { clientTimeZone: timeZone }),
699
+ })
700
+ if (!call.ok) return call
701
+ this.#rememberReceipt(receipt)
702
+ return { ok: true, r: { accepted: true } }
703
+ }
704
+
705
+ async #sessionInterrupt(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
706
+ const sessionId = stringArg(payload, 'sessionId')
707
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.interrupt requires sessionId')
708
+ // The subscription deliberately outlives this: cancelling a turn is not
709
+ // unsubscribing from the session.
710
+ const call = await this.#unary('session', 'cancel', { sessionId })
711
+ if (!call.ok) return call
712
+ return { ok: true, r: { ok: true } }
713
+ }
714
+
715
+ /**
716
+ * Answer `session.attachment`: one durable image's bytes, straight from the
717
+ * harness.
718
+ *
719
+ * The bridge keeps no cache — an image can be offloaded after the fact, so
720
+ * every read goes to the session it belongs to — and it refuses rather than
721
+ * writing a frame past the envelope budget: an attachment that cannot cross at
722
+ * all is reported as such, never as an absent attachment.
723
+ * @param payload - `{sessionId, attachmentId}`.
724
+ * @param id - the request id the frame budget is measured against.
725
+ */
726
+ async #sessionAttachment(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
727
+ const sessionId = stringArg(payload, 'sessionId')
728
+ const attachmentId = stringArg(payload, 'attachmentId')
729
+ if (sessionId === undefined || attachmentId === undefined) {
730
+ return refusal(CODE_INVALID_ARGS, 'session.attachment requires sessionId and attachmentId')
731
+ }
732
+ const call = await this.#unary('session', 'attachment', { sessionId, attachmentId })
733
+ if (!call.ok) return call
734
+ if (!isRecord(call.value)) return refusal(CODE_INTERNAL, 'session/attachment returned no attachment')
735
+ const bytes = Buffer.byteLength(JSON.stringify(responseFrame(id, call.value)), 'utf8')
736
+ if (bytes > MAX_FRAME_BYTES) {
737
+ return refusal(FRAME_TOO_LARGE, `attachment ${attachmentId} needs ${bytes} bytes, past the ${MAX_FRAME_BYTES} byte frame`)
738
+ }
739
+ return { ok: true, r: call.value }
740
+ }
741
+
742
+ /** Answer `session.permissions` out of the host's own preset service. */
743
+ #sessionPermissions(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
744
+ const sessionId = stringArg(payload, 'sessionId')
745
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.permissions requires sessionId')
746
+ const answer = this.#options.permissions.describe(sessionId)
747
+ return 'code' in answer ? refusal(answer.code, answer.msg) : { ok: true, r: answer }
748
+ }
749
+
750
+ /**
751
+ * Switch one session's permission mode.
752
+ *
753
+ * This is the session-level persistent mode, deliberately apart from
754
+ * `approval.resolve`: that answers one tool question once, this changes what
755
+ * every later turn runs under.
756
+ */
757
+ #sessionSetPermission(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
758
+ const sessionId = stringArg(payload, 'sessionId')
759
+ const id = stringArg(payload, 'id')
760
+ if (sessionId === undefined || id === undefined) {
761
+ return refusal(CODE_INVALID_ARGS, 'session.setPermission requires sessionId and id')
762
+ }
763
+ const answer = this.#options.permissions.set(sessionId, id)
764
+ return 'code' in answer ? refusal(answer.code, answer.msg) : { ok: true, r: { ok: true, current: answer.current } }
765
+ }
766
+
767
+ /**
768
+ * Answer `session.models`: the host's catalog plus this session's selection.
769
+ *
770
+ * `current` is the session's FOLD — next, else last used, else the catalog
771
+ * default — and never the default on its own: a phone that showed the default
772
+ * while another model was in force would name the wrong model for the next
773
+ * turn. The catalog's groups, failures and default cross unchanged.
774
+ * @param payload - `{sessionId}`.
775
+ */
776
+ async #sessionModels(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
777
+ const sessionId = stringArg(payload, 'sessionId')
778
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.models requires sessionId')
779
+ const catalog = await this.#unary('session', 'modelCatalog')
780
+ if (!catalog.ok) return catalog
781
+ if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no catalog')
782
+ const fallback = selectionOf(catalog.value.default)
783
+ if (fallback === undefined) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no default model')
784
+ const projections = await this.#unary('session', 'projections', { sessionId })
785
+ if (!projections.ok) return projections
786
+ const folded = modelSelectionOf(projections.value)
787
+ return {
788
+ ok: true,
789
+ r: {
790
+ current: folded.next ?? folded.lastUsed ?? fallback,
791
+ default: fallback,
792
+ groups: catalog.value.groups ?? [],
793
+ failures: catalog.value.failures ?? [],
794
+ },
795
+ }
796
+ }
797
+
798
+ /**
799
+ * Answer `session.setModel`: register the next turn's selection.
800
+ *
801
+ * The harness only records the choice for the NEXT request, so the answer
802
+ * echoes the `selected` selection it accepted and nothing here claims the
803
+ * running turn changed.
804
+ * @param payload - `{sessionId, provider, model, effort?}`.
805
+ */
806
+ async #sessionSetModel(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
807
+ const sessionId = stringArg(payload, 'sessionId')
808
+ const provider = stringArg(payload, 'provider')
809
+ const model = stringArg(payload, 'model')
810
+ if (sessionId === undefined || provider === undefined || model === undefined) {
811
+ return refusal(CODE_INVALID_ARGS, 'session.setModel requires sessionId, provider and model')
812
+ }
813
+ const effort = optionalText(payload.effort)
814
+ const call = await this.#unary('session', 'selectModel', {
815
+ sessionId,
816
+ provider,
817
+ model,
818
+ ...(effort === undefined ? {} : { reasoningEffort: effort }),
819
+ })
820
+ if (!call.ok) return call
821
+ const selected = isRecord(call.value) ? selectionOf(call.value.selected) : undefined
822
+ if (selected === undefined) return refusal(CODE_INTERNAL, 'session/selectModel returned no selected model')
823
+ return { ok: true, r: { ok: true, current: selected } }
824
+ }
825
+
826
+ #approvalResolve(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
827
+ const id = stringArg(payload, 'id')
828
+ const decision = payload.decision
829
+ if (id === undefined || (decision !== 'allowed-once' && decision !== 'rejected')) {
830
+ return refusal(CODE_INVALID_ARGS, 'approval.resolve requires id and decision of allowed-once or rejected')
831
+ }
832
+ if (!this.#options.approvals.resolve(id, decision)) {
833
+ return refusal(CODE_APPROVAL_UNKNOWN, 'the question is unknown, already answered or expired')
834
+ }
835
+ return { ok: true, r: { ok: true } }
836
+ }
837
+
838
+ /**
839
+ * Answer one pending user question.
840
+ *
841
+ * The claim decides how the answer travels: an open question settles the
842
+ * host's own ask, a continued one is steered into the agent through the
843
+ * host's Remote `answer`. A call id this bridge does not hold is refused
844
+ * rather than forwarded, and a host failure crosses with its own code.
845
+ * @param payload - `{sessionId, callId, answers}`.
846
+ */
847
+ async #questionAnswer(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
848
+ const sessionId = stringArg(payload, 'sessionId')
849
+ const callId = stringArg(payload, 'callId')
850
+ const answers = answersOf(payload.answers)
851
+ if (sessionId === undefined || callId === undefined || answers === undefined) {
852
+ return refusal(CODE_INVALID_ARGS, 'question.answer requires sessionId, callId and answers of {id, selected, custom?}')
853
+ }
854
+ const reply = await this.#options.questions.answer(sessionId, callId, { answers })
855
+ return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
856
+ }
857
+
858
+ /**
859
+ * Run one unary Remote call with the activation retry, converting a gateway
860
+ * failure into a refusal that carries the gateway's own code.
861
+ */
862
+ async #unary(namespace: string, method: string, request: Readonly<Record<string, unknown>> = {}): Promise<{ readonly ok: true; readonly value: unknown } | CallFailure> {
863
+ try {
864
+ const value = await withServiceUnavailableRetry(() => this.#options.gateway.invoke({
865
+ namespace,
866
+ method,
867
+ args: wireArgs(namespace, method, request),
868
+ peer: this.#options.ownerPeer,
869
+ }))
870
+ return { ok: true, value }
871
+ } catch (error) {
872
+ this.#options.log(`${namespace}/${method} failed: ${failureText(error)}`)
873
+ return refusal(errorCodeOf(error, CODE_INTERNAL), failureText(error))
874
+ }
875
+ }
876
+
877
+ #ensureSubscription(sessionId: string): Subscription {
878
+ const existing = this.#subscriptions.get(sessionId)
879
+ if (existing !== undefined) return existing
880
+ const subscription: Subscription = {
881
+ sessionId,
882
+ controller: new AbortController(),
883
+ address: this.#addressOf(sessionId),
884
+ // Resolved without ever rejecting: a caller may subscribe without awaiting
885
+ // the opening frame (`session.prompt` does exactly that), and an unobserved
886
+ // rejection would take the whole host process down under node's default
887
+ // `--unhandled-rejections=throw`.
888
+ opened: Promise.resolve({ ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: 'the stream was not opened' }),
889
+ }
890
+ subscription.opened = this.#openSubscription(subscription)
891
+ this.#subscriptions.set(sessionId, subscription)
892
+ return subscription
893
+ }
894
+
895
+ /** The durable address of one session, as far as this connection has learned it. */
896
+ #addressOf(sessionId: string): SessionAddress {
897
+ const parent = this.#lineage.get(sessionId)
898
+ return parent === undefined ? sessionAddress(sessionId) : subagentAddress(parent, sessionId)
899
+ }
900
+
901
+ /** Remember the durable parent of every delegated child a roster carried. */
902
+ #rememberLineage(rows: readonly SessionRow[]): void {
903
+ for (const row of rows) {
904
+ if (row.origin === 'subagent' && row.parentSessionId !== undefined) this.#lineage.set(row.id, row.parentSessionId)
905
+ }
906
+ }
907
+
908
+ /**
909
+ * The durable parent of a delegated child, or undefined when the roster does
910
+ * not name one.
911
+ *
912
+ * The roster is the only endpoint that carries lineage, so it is read at most
913
+ * once per connection: a client that listed sessions has already populated the
914
+ * map, and a child opened without a listing costs exactly one roster read.
915
+ */
916
+ async #parentOf(sessionId: string): Promise<string | undefined> {
917
+ const known = this.#lineage.get(sessionId)
918
+ if (known !== undefined || this.#lineageRead) return known
919
+ const roster = await this.#sessionList()
920
+ if (roster.ok) this.#lineageRead = true
921
+ return this.#lineage.get(sessionId)
922
+ }
923
+
924
+ /**
925
+ * Open one follow stream, resolving the address kind the harness demands.
926
+ *
927
+ * A delegated child is addressable only through its durable parent, and the
928
+ * harness answers `session/agent-busy` when it is asked as an ordinary session.
929
+ * That refusal is the one signal that distinguishes it from a real failure, so
930
+ * it is the only one that triggers a roster lookup and a retry — everything
931
+ * else crosses to the caller unchanged.
932
+ */
933
+ async #openSubscription(subscription: Subscription): Promise<Opening> {
934
+ let outcome = await this.#openFollow(subscription)
935
+ if (!outcome.ok && outcome.code === CODE_SUBAGENT_ADDRESS_REQUIRED) {
936
+ const parent = await this.#parentOf(subscription.sessionId)
937
+ if (parent !== undefined) {
938
+ this.#lineage.set(subscription.sessionId, parent)
939
+ subscription.address = subagentAddress(parent, subscription.sessionId)
940
+ outcome = await this.#openFollow(subscription)
941
+ }
942
+ }
943
+ if (!outcome.ok) {
944
+ // The stream is unusable for this connection: drop it rather than leaving a
945
+ // half-open subscription behind, so a later call starts a fresh one.
946
+ this.#forget(subscription)
947
+ subscription.controller.abort()
948
+ }
949
+ return outcome
950
+ }
951
+
952
+ /** One attempt at the opening frame of a follow stream. */
953
+ async #openFollow(subscription: Subscription): Promise<Opening> {
954
+ let iterator: AsyncIterator<unknown>
955
+ try {
956
+ const stream = await withServiceUnavailableRetry(() => this.#options.gateway.stream({
957
+ namespace: 'session',
958
+ method: 'follow',
959
+ args: wireArgs('session', 'follow', {
960
+ address: subscription.address,
961
+ // Decided after the frozen design's §2.1/§2.2 contradiction: one stream
962
+ // per session carries both the baseline and the process-local deltas.
963
+ assistantStream: true,
964
+ maxMessages: SNAPSHOT_MAX_MESSAGES,
965
+ }),
966
+ peer: this.#options.ownerPeer,
967
+ signal: subscription.controller.signal,
968
+ }))
969
+ iterator = stream[Symbol.asyncIterator]()
970
+ } catch (error) {
971
+ return { ok: false, code: errorCodeOf(error, CODE_SNAPSHOT_UNAVAILABLE), msg: failureText(error) }
972
+ }
973
+ try {
974
+ const first = await iterator.next()
975
+ const baseline = first.done === true ? undefined : readFollowBaseline(first.value)
976
+ if (baseline === undefined) {
977
+ await iterator.return?.()
978
+ return { ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: 'session/follow returned no opening snapshot frame' }
979
+ }
980
+ void this.#drain(subscription, iterator)
981
+ return { ok: true, baseline }
982
+ } catch (error) {
983
+ return { ok: false, code: errorCodeOf(error, CODE_SNAPSHOT_UNAVAILABLE), msg: failureText(error) }
984
+ }
985
+ }
986
+
987
+ /** Consume the rest of a follow stream, publishing every increment. */
988
+ async #drain(subscription: Subscription, iterator: AsyncIterator<unknown>): Promise<void> {
989
+ try {
990
+ for (;;) {
991
+ const next = await iterator.next()
992
+ if (next.done === true) return
993
+ const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages)
994
+ if (delta === undefined) continue
995
+ this.#emit(TOPIC_SESSION_DELTA, { sessionId: subscription.sessionId, ...delta })
996
+ }
997
+ } catch (error) {
998
+ if (!subscription.controller.signal.aborted) {
999
+ this.#options.log(`session ${subscription.sessionId} follow stream ended: ${failureText(error)}`)
1000
+ }
1001
+ } finally {
1002
+ this.#forget(subscription)
1003
+ }
1004
+ }
1005
+
1006
+ /** Await a subscription's opening frame under a bounded wait. */
1007
+ async #awaitOpening(subscription: Subscription): Promise<Opening> {
1008
+ let timer: NodeJS.Timeout | undefined
1009
+ const expiry = new Promise<undefined>(resolve => {
1010
+ timer = setTimeout(() => { resolve(undefined) }, SNAPSHOT_OPEN_TIMEOUT_MS)
1011
+ timer.unref?.()
1012
+ })
1013
+ try {
1014
+ const outcome = await Promise.race([subscription.opened, expiry])
1015
+ if (outcome !== undefined) return outcome
1016
+ // No opening frame in time means the stream is unusable for this connection:
1017
+ // drop it rather than leaving a half-open subscription behind.
1018
+ subscription.controller.abort()
1019
+ this.#forget(subscription)
1020
+ return { ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: `no opening frame within ${SNAPSHOT_OPEN_TIMEOUT_MS} ms` }
1021
+ } finally {
1022
+ if (timer !== undefined) clearTimeout(timer)
1023
+ }
1024
+ }
1025
+
1026
+ /** Drop a subscription only while it is still the current one for its session. */
1027
+ #forget(subscription: Subscription): void {
1028
+ if (this.#subscriptions.get(subscription.sessionId) === subscription) this.#subscriptions.delete(subscription.sessionId)
1029
+ }
1030
+
1031
+ /**
1032
+ * Shrink a snapshot until it fits one frame, dropping whole oldest turns.
1033
+ * @returns the fitting payload, or undefined when even one turn cannot fit.
1034
+ */
1035
+ #fitTurns(turns: readonly SnapshotTurn[], cursor: number, id: number): { readonly turns: readonly SnapshotTurn[]; readonly lastSeq: number } | undefined {
1036
+ let kept = [...turns]
1037
+ for (;;) {
1038
+ const frame = responseFrame(id, { turns: kept, lastSeq: cursor })
1039
+ if (Buffer.byteLength(JSON.stringify(frame), 'utf8') <= MAX_FRAME_BYTES) return { turns: kept, lastSeq: cursor }
1040
+ if (kept.length <= 1) return undefined
1041
+ kept = kept.slice(1)
1042
+ }
1043
+ }
1044
+
1045
+ #rememberReceipt(receipt: string): void {
1046
+ this.#receipts.add(receipt)
1047
+ while (this.#receipts.size > PROMPT_RECEIPT_LIMIT) {
1048
+ const oldest = this.#receipts.values().next()
1049
+ if (oldest.done === true) break
1050
+ this.#receipts.delete(oldest.value)
1051
+ }
1052
+ }
1053
+
1054
+ #emit(topic: string, payload: unknown): boolean {
1055
+ if (this.#disposed) return false
1056
+ const frame: ServerFrame = { t: 'ev', seq: this.#sequence.take(), m: topic, p: payload }
1057
+ const text = encodeFrame(frame)
1058
+ if (Buffer.byteLength(text, 'utf8') > MAX_FRAME_BYTES) {
1059
+ this.#options.log(`dropped a ${topic} event past ${MAX_FRAME_BYTES} bytes`)
1060
+ return false
1061
+ }
1062
+ return this.#write(text)
1063
+ }
1064
+
1065
+ #send(frame: ServerFrame): void {
1066
+ if (this.#disposed) return
1067
+ this.#write(encodeFrame(frame))
1068
+ }
1069
+
1070
+ /**
1071
+ * Hand one encoded frame to the carrier.
1072
+ *
1073
+ * A carrier that throws must not take the process down with it: every write
1074
+ * here happens either inside a socket `data` handler or inside the approval
1075
+ * waterfall, where an escaping exception becomes an uncaught exception. A
1076
+ * failure is logged and the frame is dropped — the socket is already gone by
1077
+ * then, so there is nobody left to answer.
1078
+ * @returns whether the frame was handed to the carrier.
1079
+ */
1080
+ #write(text: string): boolean {
1081
+ try {
1082
+ this.#transport.send(text)
1083
+ } catch (error) {
1084
+ this.#options.log(`could not write a frame: ${failureText(error)}`)
1085
+ return false
1086
+ }
1087
+ this.#lastSendAt = this.#options.now()
1088
+ return true
1089
+ }
1090
+ }