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

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 (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +277 -2
  4. package/README.zh.md +276 -0
  5. package/cordis.patch.yml +17 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +1830 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +5789 -0
  10. package/lib/types/client/PairEntry.d.ts +16 -0
  11. package/lib/types/client/PairPanel.d.ts +55 -0
  12. package/lib/types/client/icons.d.ts +18 -0
  13. package/lib/types/client/index.d.ts +35 -0
  14. package/lib/types/client/locales.d.ts +42 -0
  15. package/lib/types/client/pair-token.d.ts +73 -0
  16. package/lib/types/client/semantic.d.ts +28 -0
  17. package/lib/types/core/approvals.d.ts +99 -0
  18. package/lib/types/core/connection.d.ts +170 -0
  19. package/lib/types/core/crypto.d.ts +48 -0
  20. package/lib/types/core/delta.d.ts +101 -0
  21. package/lib/types/core/devices.d.ts +72 -0
  22. package/lib/types/core/dsh-frames.d.ts +332 -0
  23. package/lib/types/core/envelope.d.ts +132 -0
  24. package/lib/types/core/extension.d.ts +144 -0
  25. package/lib/types/core/gateway-errors.d.ts +49 -0
  26. package/lib/types/core/hub.d.ts +127 -0
  27. package/lib/types/core/jobs.d.ts +204 -0
  28. package/lib/types/core/loopback.d.ts +35 -0
  29. package/lib/types/core/owner-peer.d.ts +49 -0
  30. package/lib/types/core/pairing.d.ts +61 -0
  31. package/lib/types/core/protocol.d.ts +319 -0
  32. package/lib/types/core/questions.d.ts +294 -0
  33. package/lib/types/core/session-meta.d.ts +105 -0
  34. package/lib/types/core/session-permissions.d.ts +134 -0
  35. package/lib/types/core/wire.d.ts +115 -0
  36. package/lib/types/core/ws-frames.d.ts +72 -0
  37. package/lib/types/host/dsh-home.d.ts +16 -0
  38. package/lib/types/host/pair-origin.d.ts +44 -0
  39. package/lib/types/host/routes.d.ts +27 -0
  40. package/lib/types/host/websocket.d.ts +111 -0
  41. package/lib/types/index.d.ts +55 -0
  42. package/lib/types/mount-once.d.ts +55 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +93 -3
  47. package/src/client/PairEntry.tsx +151 -0
  48. package/src/client/PairPanel.tsx +183 -0
  49. package/src/client/icons.tsx +72 -0
  50. package/src/client/index.ts +81 -0
  51. package/src/client/locales.ts +72 -0
  52. package/src/client/pair-token.ts +104 -0
  53. package/src/client/panel.module.css +344 -0
  54. package/src/client/semantic.ts +37 -0
  55. package/src/core/approvals.ts +173 -0
  56. package/src/core/connection.ts +1906 -0
  57. package/src/core/crypto.ts +113 -0
  58. package/src/core/delta.ts +204 -0
  59. package/src/core/devices.ts +209 -0
  60. package/src/core/dsh-frames.ts +843 -0
  61. package/src/core/envelope.ts +219 -0
  62. package/src/core/extension.ts +197 -0
  63. package/src/core/gateway-errors.ts +92 -0
  64. package/src/core/hub.ts +310 -0
  65. package/src/core/jobs.ts +372 -0
  66. package/src/core/loopback.ts +60 -0
  67. package/src/core/owner-peer.ts +70 -0
  68. package/src/core/pairing.ts +113 -0
  69. package/src/core/protocol.ts +381 -0
  70. package/src/core/questions.ts +630 -0
  71. package/src/core/session-meta.ts +176 -0
  72. package/src/core/session-permissions.ts +266 -0
  73. package/src/core/wire.ts +159 -0
  74. package/src/core/ws-frames.ts +139 -0
  75. package/src/css-modules.d.ts +6 -0
  76. package/src/host/dsh-home.ts +42 -0
  77. package/src/host/pair-origin.ts +77 -0
  78. package/src/host/routes.ts +85 -0
  79. package/src/host/websocket.ts +359 -0
  80. package/src/index.ts +257 -0
  81. package/src/mount-once.ts +142 -0
@@ -0,0 +1,1906 @@
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 { ROSTER_DELTA_MAX_ROWS, RemoteBridgeDeltas, type DeltaRow } from './delta.ts'
22
+ import { deltaOfFollowFrame, MessageIndex, oldestEntrySeq, pageTurns, readFollowBaseline, SpawnCallIndex, ToolCallIndex, trimUnrenderedEntries, turnsAbove, turnsOfRecords, type FollowBaseline, type SnapshotTurn } from './dsh-frames.ts'
23
+ import { EventSequence, FRAME_TOO_LARGE, MAX_FRAME_BYTES, decodeClientFrame, encodeFrame, errorFrame, responseFrame, type ReqFrame, type ServerFrame } from './envelope.ts'
24
+ import type { RemoteBridgeMethodResult, RemoteBridgeRegistry } from './extension.ts'
25
+ import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
26
+ import { scopeKey, type JobRoster, type JobsPayload } from './jobs.ts'
27
+ import type { PairingService } from './pairing.ts'
28
+ import type { QuestionAnswerItem, QuestionClaims } from './questions.ts'
29
+ import {
30
+ CAP_AGENTS,
31
+ CAP_DELTA,
32
+ CAP_FRAME_DEFLATE,
33
+ CAP_JOBS,
34
+ CAP_QUESTIONS,
35
+ CAP_ROSTER_COMPACT,
36
+ CAP_SESSION_FORK,
37
+ CAP_SESSION_SNAPSHOT_PAGE,
38
+ CAP_SESSION_SNAPSHOT_SINCE,
39
+ CAP_SESSION_SNAPSHOT_TRIM,
40
+ CAP_SUBAGENT_THREAD,
41
+ CODE_APPROVAL_UNKNOWN,
42
+ CODE_INTERNAL,
43
+ CODE_INVALID_ARGS,
44
+ CODE_JOBS_UNAVAILABLE,
45
+ CODE_NONCE_INVALID,
46
+ CODE_PROTO_UNSUPPORTED,
47
+ CODE_SESSION_NOT_FOLLOWABLE,
48
+ CODE_SNAPSHOT_TOO_LARGE,
49
+ CODE_SNAPSHOT_UNAVAILABLE,
50
+ CODE_TOKEN_INVALID,
51
+ CODE_UNKNOWN_METHOD,
52
+ CODE_UNPAIRED,
53
+ KNOWN_METHODS,
54
+ METHOD_APPROVAL_RESOLVE,
55
+ METHOD_HELLO,
56
+ METHOD_JOBS_LIST,
57
+ METHOD_PAIR_BEGIN,
58
+ METHOD_PAIR_FINISH,
59
+ METHOD_PRESETS_LIST,
60
+ METHOD_QUESTION_ANSWER,
61
+ METHOD_SESSION_ATTACHMENT,
62
+ METHOD_SESSION_CREATE,
63
+ METHOD_SESSION_FORK,
64
+ METHOD_SESSION_HISTORY,
65
+ METHOD_SESSION_HISTORY_DEEP,
66
+ METHOD_SESSION_INTERRUPT,
67
+ METHOD_SESSION_LIST,
68
+ METHOD_SESSION_MODELS,
69
+ METHOD_SESSION_PERMISSIONS,
70
+ METHOD_SESSION_PROMPT,
71
+ METHOD_SESSION_SET_MODEL,
72
+ METHOD_SESSION_SET_PERMISSION,
73
+ METHOD_SESSION_SNAPSHOT,
74
+ METHOD_SESSION_TITLES,
75
+ MINOR,
76
+ PROTO,
77
+ SERVED_CAPABILITIES,
78
+ SERVER_ID,
79
+ TOPIC_JOBS_CHANGED,
80
+ TOPIC_SESSION_DELTA,
81
+ UNPAIRED_METHODS,
82
+ } from './protocol.ts'
83
+ import { base64UrlDecode, verifyEs256 } from './crypto.ts'
84
+ import { TITLES_MAX_IDS, type SessionMeta } from './session-meta.ts'
85
+ import type { SessionPermissions } from './session-permissions.ts'
86
+ import type { BridgeGateway, GatewayPeer } from './wire.ts'
87
+ import { CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
88
+ import { CLOSE_LIVENESS_TIMEOUT } from './ws-frames.ts'
89
+
90
+ /** Protocol-level heartbeat period: a frame is sent after this long without one. */
91
+ export const IDLE_PING_MS = 20_000
92
+ /**
93
+ * Deadline behind one liveness ping: a peer that sends no frame at all within
94
+ * this long of the ping is torn down.
95
+ *
96
+ * It only ever exists because a ping was sent — a connection the host has not
97
+ * pinged has no deadline — so a quiet client is never closed for being quiet,
98
+ * only for failing to answer. The measured one-way path over the relay is about
99
+ * 410 ms (2026-10-19), so this is more than an order of magnitude of slack.
100
+ */
101
+ export const LIVENESS_TIMEOUT_MS = 10_000
102
+ /** How long `session.snapshot` waits for its follow stream's opening frame. */
103
+ export const SNAPSHOT_OPEN_TIMEOUT_MS = 10_000
104
+ /** Largest turn window one snapshot asks DSH for. */
105
+ export const SNAPSHOT_MAX_MESSAGES = 200
106
+ /** Default byte budget of one `session.history` page: 512 KiB. */
107
+ export const HISTORY_PAGE_BYTES = 512 * 1024
108
+ /**
109
+ * Window one `session.history.deep` read asks DSH for: at least 50 user or
110
+ * assistant messages across at least 2 turns, and never more than 500 messages.
111
+ *
112
+ * It is the window the harness's own Web client pages history with, and it is
113
+ * deliberately wider than one answer: a byte budget is the caller's, so the
114
+ * store is asked for a whole span once and the bridge then cuts that span to
115
+ * `maxBytes` by entry. Nothing in the answer depends on where the store cut:
116
+ * the host's `hasMore` is folded into the answer's own `hasMore`, and the
117
+ * cursor is always the oldest entry the answer carries.
118
+ */
119
+ export const DEEP_HISTORY_WINDOW = {
120
+ maxMessages: 500,
121
+ turnWindow: { minMessages: 50, minTurns: 2 },
122
+ } as const
123
+ /** Highest number of prompt receipts one connection remembers for idempotency. */
124
+ export const PROMPT_RECEIPT_LIMIT = 512
125
+ /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
126
+ export const PROMPT_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024
127
+
128
+ /** The carrier a connection writes through. */
129
+ export interface BridgeTransport {
130
+ send(text: string): void
131
+ close(code: number, reason: string): void
132
+ /**
133
+ * Optional: whether the peer declared `frame.deflate.v1`, reported once the
134
+ * `hello` that declares it has been recorded. The capability is the client's
135
+ * declaration and the wire form is the carrier's, so this is the one fact that
136
+ * has to cross between them. A carrier with no socket to compress — a
137
+ * recording double, for one — omits the member and keeps writing text.
138
+ */
139
+ frameDeflate?(declared: boolean): void
140
+ }
141
+
142
+ export interface BridgeConnectionOptions {
143
+ readonly gateway: BridgeGateway
144
+ readonly pairing: PairingService
145
+ readonly roster: DeviceRoster
146
+ readonly approvals: ApprovalRegistry
147
+ /** Pending user questions: the claims this bridge holds and the answer path back to the host. */
148
+ readonly questions: QuestionClaims
149
+ /** The host's background jobs: the read-only projection and the scopes this connection watches. */
150
+ readonly jobs: JobRoster
151
+ /** Process-local session metadata: live titles and the host's archive set. */
152
+ readonly sessionMeta: SessionMeta
153
+ /** Host-process permission presets, read and switched through their real service objects. */
154
+ readonly permissions: SessionPermissions
155
+ /**
156
+ * The in-process owner peer every gateway call speaks for, minted by the
157
+ * bridge itself (`core/owner-peer.ts`). Dispatch refuses unpaired
158
+ * connections before any gateway call exists, so this peer — a
159
+ * full-control credential — is exercised only behind the bridge's own
160
+ * pairing gate, and no client frame field is ever read into it.
161
+ */
162
+ readonly ownerPeer: GatewayPeer
163
+ readonly now: () => number
164
+ /** This machine's IANA time zone, sent with every prompt. */
165
+ readonly clientTimeZone: () => string | undefined
166
+ readonly log: (message: string) => void
167
+ /**
168
+ * Called after a client's `hello` records its capabilities, so the hub can hand
169
+ * it whatever it can now receive but was not there to see.
170
+ */
171
+ readonly onDeclare?: (connection: BridgeConnection) => void
172
+ readonly heartbeatMs?: number
173
+ /**
174
+ * Methods plugins registered on the bridge's extension seam. Absent is the
175
+ * protocol exactly as this package defines it: every name outside
176
+ * `KNOWN_METHODS` answers `unknown-method`.
177
+ */
178
+ readonly extensions?: RemoteBridgeRegistry
179
+ }
180
+
181
+ /** A device the connection proved itself to be, resolved from the upgrade request. */
182
+ export interface ConnectionAuth {
183
+ readonly deviceId: string
184
+ }
185
+
186
+ /** The answer of a subscription's opening frame: a baseline, or why there is none. */
187
+ type Opening = { readonly ok: true; readonly baseline: FollowBaseline } | { readonly ok: false; readonly code: string; readonly msg: string }
188
+
189
+ /** One open follow stream and the answer its opening frame resolves. */
190
+ interface Subscription {
191
+ readonly sessionId: string
192
+ readonly controller: AbortController
193
+ /**
194
+ * Mutable on purpose: a delegated child is addressable only through its durable
195
+ * parent, and the bridge learns which address kind applies from the harness's own
196
+ * refusal on the first attempt.
197
+ */
198
+ address: SessionAddress
199
+ opened: Promise<Opening>
200
+ }
201
+
202
+ /** The refusal half of every dispatch outcome. */
203
+ interface CallFailure {
204
+ readonly ok: false
205
+ readonly code: string
206
+ readonly msg: string
207
+ }
208
+
209
+ type DispatchOutcome = { readonly ok: true; readonly r: unknown } | CallFailure
210
+
211
+ /**
212
+ * One snapshot baseline answer, typed rather than opaque so the incremental
213
+ * fallback can extend the very payload protocol v1 serves instead of rebuilding
214
+ * it. `hasMore` is present exactly for a connection that declared the page
215
+ * capability.
216
+ */
217
+ type BaselineAnswer =
218
+ | { readonly ok: true; readonly r: { readonly turns: readonly SnapshotTurn[]; readonly lastSeq: number; readonly hasMore?: boolean } }
219
+ | CallFailure
220
+
221
+ /** One session-list row as the protocol publishes it. */
222
+ interface SessionRow extends DeltaRow {
223
+ readonly id: string
224
+ readonly title: string
225
+ readonly updatedAt: number
226
+ readonly agentRunning: boolean
227
+ /** The session's working directory, omitted when the host did not report one. */
228
+ readonly cwd?: string
229
+ /** The session this one was delegated from, omitted for a root session. */
230
+ readonly parentSessionId?: string
231
+ /** `subagent` for a delegated session, omitted for an ordinary one. */
232
+ readonly origin?: 'subagent'
233
+ readonly blank: boolean
234
+ /** The host's archive flag; omitted when this process cannot read the archive set. */
235
+ readonly archived?: boolean
236
+ }
237
+
238
+ function refusal(code: string, msg: string): CallFailure {
239
+ return { ok: false, code, msg }
240
+ }
241
+
242
+ /**
243
+ * The opaque `since` token one request carried.
244
+ *
245
+ * Anything that is not a non-empty string is "no usable token", which answers a
246
+ * reset — the same answer an unknown token gets, because a request that named
247
+ * no base cannot be diffed against one.
248
+ * @param payload - the request's `p`.
249
+ * @returns the token, or undefined.
250
+ */
251
+ function sinceOf(payload: Readonly<Record<string, unknown>>): string | undefined {
252
+ const value = payload.since
253
+ return typeof value === 'string' && value !== '' ? value : undefined
254
+ }
255
+
256
+ /**
257
+ * Whether a plugin's answer is one of the two shapes the seam defines.
258
+ *
259
+ * An extension is ordinary JavaScript calling into this bridge, so a result the
260
+ * type system never saw still has to leave the client with an answer instead of
261
+ * a lost frame.
262
+ * @param value - what the extension method returned.
263
+ * @returns whether it carries a usable answer or refusal.
264
+ */
265
+ function isMethodResult(value: unknown): value is RemoteBridgeMethodResult {
266
+ if (typeof value !== 'object' || value === null) return false
267
+ const result = value as { ok?: unknown; code?: unknown; msg?: unknown }
268
+ if (result.ok === true) return true
269
+ if (result.ok !== false) return false
270
+ return typeof result.code === 'string' && result.code !== '' && typeof result.msg === 'string'
271
+ }
272
+
273
+ function isRecord(value: unknown): value is Record<string, unknown> {
274
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
275
+ }
276
+
277
+ /** @returns a non-empty string argument, or undefined. */
278
+ function stringArg(payload: Readonly<Record<string, unknown>>, key: string): string | undefined {
279
+ const value = payload[key]
280
+ return typeof value === 'string' && value !== '' ? value : undefined
281
+ }
282
+
283
+ /** @returns a non-empty string payload value, or undefined. */
284
+ function optionalText(value: unknown): string | undefined {
285
+ return typeof value === 'string' && value !== '' ? value : undefined
286
+ }
287
+
288
+ /** @returns a non-negative safe integer page argument, or undefined. */
289
+ function pageNumber(value: unknown): number | undefined {
290
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined
291
+ }
292
+
293
+ /**
294
+ * @param value - a request's event-seq member, or undefined.
295
+ * @returns the seq, or undefined when it is not a positive safe integer.
296
+ */
297
+ function seqNumber(value: unknown): number | undefined {
298
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : undefined
299
+ }
300
+
301
+ /**
302
+ * Read one request's page budget.
303
+ *
304
+ * An absent budget is {@link HISTORY_PAGE_BYTES}; a budget an encoded page
305
+ * could never be measured against — zero, fractional, negative or larger than
306
+ * one frame — is refused rather than clamped, so a caller never mistakes a
307
+ * silently reduced page for the one it asked for.
308
+ * @param value - the request's `maxBytes` member, or undefined.
309
+ * @param method - the method name the refusal names.
310
+ */
311
+ function pageBudgetOf(value: unknown, method: string): { readonly ok: true; readonly maxBytes: number } | CallFailure {
312
+ if (value === undefined) return { ok: true, maxBytes: HISTORY_PAGE_BYTES }
313
+ const maxBytes = pageNumber(value)
314
+ if (maxBytes === undefined || maxBytes < 1 || maxBytes > MAX_FRAME_BYTES) {
315
+ return refusal(CODE_INVALID_ARGS, `${method} maxBytes must be between 1 and ${MAX_FRAME_BYTES}`)
316
+ }
317
+ return { ok: true, maxBytes }
318
+ }
319
+
320
+ /** The compact roster parameters one listing carried, when it carried any. */
321
+ interface RosterCompact {
322
+ /** Rows per page; absent means every row. */
323
+ readonly maxRows?: number
324
+ /** Exclusive cursor: serve the rows after the row this id names. */
325
+ readonly after?: string
326
+ /** Whether each row carries the host's absolute `cwd`. */
327
+ readonly cwd: boolean
328
+ }
329
+
330
+ /**
331
+ * Read one listing's compact roster parameters.
332
+ *
333
+ * The parameters are the switch, not the capability: a listing that names none
334
+ * of them is answered today's body byte for byte, so declaring
335
+ * {@link CAP_ROSTER_COMPACT} alone can never change what a client is sent. The
336
+ * page size reuses {@link pageNumber} and is bounded by the same cap the roster
337
+ * delta window retains ({@link ROSTER_DELTA_MAX_ROWS}), so no second limit is
338
+ * invented here. A value that cannot be honoured — a page size of zero,
339
+ * negative, fractional or past that cap, an `after` that is not an id, a `cwd`
340
+ * that is not a boolean — is refused rather than clamped, so a caller never
341
+ * mistakes a silently reduced page for the one it asked for.
342
+ * @param payload - the request's `p`.
343
+ * @returns the parameters, or `ok` with no `compact` member when there are none.
344
+ */
345
+ function rosterCompactOf(payload: Readonly<Record<string, unknown>>): { readonly ok: true; readonly compact?: RosterCompact } | CallFailure {
346
+ const { cwd: rawCwd, maxRows: rawRows, after: rawAfter } = payload
347
+ if (rawCwd === undefined && rawRows === undefined && rawAfter === undefined) return { ok: true }
348
+ if (rawCwd !== undefined && typeof rawCwd !== 'boolean') return refusal(CODE_INVALID_ARGS, 'session.list cwd must be a boolean')
349
+ let maxRows: number | undefined
350
+ if (rawRows !== undefined) {
351
+ maxRows = pageNumber(rawRows)
352
+ if (maxRows === undefined || maxRows < 1 || maxRows > ROSTER_DELTA_MAX_ROWS) {
353
+ return refusal(CODE_INVALID_ARGS, `session.list maxRows must be between 1 and ${ROSTER_DELTA_MAX_ROWS}`)
354
+ }
355
+ }
356
+ const after = rawAfter === undefined ? undefined : optionalText(rawAfter)
357
+ if (rawAfter !== undefined && after === undefined) return refusal(CODE_INVALID_ARGS, 'session.list after must be a non-empty session id')
358
+ return {
359
+ ok: true,
360
+ compact: {
361
+ ...(maxRows === undefined ? {} : { maxRows }),
362
+ ...(after === undefined ? {} : { after }),
363
+ cwd: rawCwd === true,
364
+ },
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Read the capability names a `hello` announced.
370
+ *
371
+ * A capability is an announcement, not a negotiation: an unreadable `cap`, an
372
+ * unknown name and an absent key all leave the connection with no capabilities
373
+ * rather than failing the handshake.
374
+ * @param value - the `cap` member of a hello payload, as it crossed the wire.
375
+ * @returns the declared names, empty when the client declared none.
376
+ */
377
+ function capabilitiesOf(value: unknown): ReadonlySet<string> {
378
+ if (!Array.isArray(value)) return new Set()
379
+ return new Set(value.filter((name): name is string => typeof name === 'string' && name !== ''))
380
+ }
381
+
382
+ /**
383
+ * Validate `question.answer`'s answer batch.
384
+ *
385
+ * The host validates the batch against the questions it actually asked (missing,
386
+ * duplicated or invented ids are the host's own `BAD_ANSWER`), so this only
387
+ * refuses what is not an answer at all: a non-array, an entry that is not an
388
+ * object, an entry without a non-empty id, or `selected` that is not a list of
389
+ * non-empty labels.
390
+ * @param value - the request's `answers` member, or undefined.
391
+ * @returns the batch in protocol vocabulary, or undefined when it is not one.
392
+ */
393
+ function answersOf(value: unknown): readonly QuestionAnswerItem[] | undefined {
394
+ if (!Array.isArray(value)) return undefined
395
+ const answers: QuestionAnswerItem[] = []
396
+ for (const entry of value) {
397
+ if (!isRecord(entry)) return undefined
398
+ const id = optionalText(entry.id)
399
+ const selected = entry.selected
400
+ if (id === undefined || !Array.isArray(selected)) return undefined
401
+ if (!selected.every(label => typeof label === 'string' && label !== '')) return undefined
402
+ const custom = optionalText(entry.custom)
403
+ answers.push({ id, selected: selected as string[], ...(custom === undefined ? {} : { custom }) })
404
+ }
405
+ return answers
406
+ }
407
+
408
+ /** One model selection, in the field names the protocol publishes. */
409
+ type ModelSelection = {
410
+ readonly provider: string
411
+ readonly model: string
412
+ readonly reasoningEffort?: string
413
+ }
414
+
415
+ /** @returns the selection this value describes, or undefined when it describes none. */
416
+ function selectionOf(value: unknown): ModelSelection | undefined {
417
+ if (!isRecord(value)) return undefined
418
+ const provider = optionalText(value.provider)
419
+ const model = optionalText(value.model)
420
+ if (provider === undefined || model === undefined) return undefined
421
+ const reasoningEffort = optionalText(value.reasoningEffort)
422
+ return reasoningEffort === undefined ? { provider, model } : { provider, model, reasoningEffort }
423
+ }
424
+
425
+ /**
426
+ * The durable model-selection fold of one `session/projections` answer.
427
+ *
428
+ * Both halves stay optional: a session that never ran has neither, and the
429
+ * catalog default is then the only truthful current value.
430
+ */
431
+ function modelSelectionOf(value: unknown): { readonly next?: ModelSelection; readonly lastUsed?: ModelSelection } {
432
+ if (!isRecord(value) || !isRecord(value.values)) return {}
433
+ const selection = value.values.modelSelection
434
+ if (!isRecord(selection)) return {}
435
+ const next = selectionOf(selection.next)
436
+ const lastUsed = selectionOf(selection.lastUsed)
437
+ return {
438
+ ...(next === undefined ? {} : { next }),
439
+ ...(lastUsed === undefined ? {} : { lastUsed }),
440
+ }
441
+ }
442
+
443
+ /** One prompt attachment, already projected to the harness's image content part. */
444
+ type PromptAttachment = Readonly<Record<string, unknown>>
445
+
446
+ /** The validated attachments of one prompt, or the refusal that withheld it. */
447
+ type PromptAttachments = { readonly ok: true; readonly parts: readonly PromptAttachment[] } | CallFailure
448
+
449
+ /**
450
+ * Validate `session.prompt`'s optional attachments and project them to the
451
+ * harness's image content parts, keeping the order the client sent.
452
+ *
453
+ * The per-attachment budget is checked here rather than at the harness: 6 MiB of
454
+ * base64 per attachment is what keeps a prompt frame inside the envelope's
455
+ * 10 MiB, and the refusal names the attachment and its exact byte count so the
456
+ * phone can say which pick made the send fail. Nothing is truncated and nothing
457
+ * is dropped — one rejected attachment withholds the whole prompt.
458
+ * @param value - the request's `attachments` member, or undefined.
459
+ */
460
+ function promptAttachmentsOf(value: unknown): PromptAttachments {
461
+ if (value === undefined) return { ok: true, parts: [] }
462
+ if (!Array.isArray(value)) return refusal(CODE_INVALID_ARGS, 'session.prompt attachments must be an array')
463
+ const parts: PromptAttachment[] = []
464
+ for (const entry of value) {
465
+ if (!isRecord(entry)) return refusal(CODE_INVALID_ARGS, 'session.prompt attachments must be objects')
466
+ const name = optionalText(entry.name)
467
+ const label = name === undefined ? `attachment ${parts.length + 1}` : `attachment "${name}"`
468
+ const mediaType = optionalText(entry.mediaType)
469
+ const data = typeof entry.data === 'string' ? entry.data : undefined
470
+ if (mediaType === undefined || data === undefined || data === '') {
471
+ return refusal(CODE_INVALID_ARGS, `session.prompt ${label} requires mediaType and base64 data`)
472
+ }
473
+ const bytes = Buffer.byteLength(data, 'utf8')
474
+ if (bytes > PROMPT_ATTACHMENT_MAX_BYTES) {
475
+ return refusal(
476
+ CODE_INVALID_ARGS,
477
+ `session.prompt ${label} is ${bytes} base64 bytes, past the ${PROMPT_ATTACHMENT_MAX_BYTES} byte limit`,
478
+ )
479
+ }
480
+ parts.push({ type: 'image', mediaType, data, ...(name === undefined ? {} : { name }) })
481
+ }
482
+ return { ok: true, parts }
483
+ }
484
+
485
+ /**
486
+ * Everything one connected device may do.
487
+ *
488
+ * Not thread-safe by construction but safe by awaiting: handlers are invoked
489
+ * one frame at a time by the carrier's reader, and the only background work is
490
+ * a subscription's own drain loop.
491
+ */
492
+ /**
493
+ * Monotonic source for {@link BridgeConnection.id}. The counter is process-wide
494
+ * and never reused, so a plugin keying connection-scoped state can trust that a
495
+ * reclaimed id belongs to no later socket.
496
+ */
497
+ let connectionSeq = 0
498
+
499
+ export class BridgeConnection {
500
+ readonly #id = `c${connectionSeq += 1}`
501
+ readonly #options: BridgeConnectionOptions
502
+ readonly #transport: BridgeTransport
503
+ readonly #sequence = new EventSequence()
504
+ readonly #subscriptions = new Map<string, Subscription>()
505
+ readonly #receipts = new Set<string>()
506
+ readonly #toolCalls = new ToolCallIndex()
507
+ readonly #messages = new MessageIndex()
508
+ #capabilities: ReadonlySet<string> = new Set()
509
+ /** Delegated children this connection has learned the durable parent of, by child id. */
510
+ readonly #lineage = new Map<string, string>()
511
+ /**
512
+ * Sessions this connection may read: the ordinary sessions the host's roster
513
+ * names, plus every session this connection already opened. A delegated child
514
+ * belongs here only once it has been opened itself, never because the roster
515
+ * merely names it.
516
+ */
517
+ readonly #authorized = new Set<string>()
518
+ /**
519
+ * The job scopes this connection asked about, by {@link scopeKey}, with the
520
+ * disposer of each watch. A scope is watched exactly while this connection has
521
+ * listed it: that is what keeps a declared capability from turning into a
522
+ * subscription the client never requested.
523
+ */
524
+ readonly #jobWatches = new Map<string, () => void>()
525
+ /**
526
+ * The `updatedAt` this connection already sent per session id, for the
527
+ * compact roster: a row whose value this client holds is answered without it.
528
+ * Pruned to the roster on every compact answer, so it is bounded by the set it
529
+ * describes rather than by every id the connection ever listed.
530
+ */
531
+ readonly #rosterUpdatedAt = new Map<string, number>()
532
+ /** The last roster payload this connection received per scope key, for whole-set dedupe. */
533
+ readonly #jobSeen = new Map<string, string>()
534
+ /**
535
+ * This connection's delta windows, one per set it is served incrementally.
536
+ * Held here so the base is released exactly when the connection is, and so no
537
+ * two connections can ever diff against each other's set.
538
+ */
539
+ readonly #deltas = new RemoteBridgeDeltas()
540
+ #lineageRead = false
541
+ #deviceId: string | undefined
542
+ #nonce: { readonly value: string; readonly expiresAt: number } | undefined
543
+ #heartbeat: NodeJS.Timeout | undefined
544
+ /** The deadline armed by the liveness ping currently outstanding, if any. */
545
+ #liveness: NodeJS.Timeout | undefined
546
+ #lastSendAt = 0
547
+ #disposed = false
548
+
549
+ constructor(options: BridgeConnectionOptions, transport: BridgeTransport, auth?: ConnectionAuth) {
550
+ this.#options = options
551
+ this.#transport = transport
552
+ this.#deviceId = auth?.deviceId
553
+ this.#lastSendAt = options.now()
554
+ }
555
+
556
+ /** @returns whether this connection has proven a device token (or just enrolled). */
557
+ get paired(): boolean {
558
+ return this.#deviceId !== undefined
559
+ }
560
+
561
+ /** @returns the paired device id, or undefined while unpaired. */
562
+ get deviceId(): string | undefined {
563
+ return this.#deviceId
564
+ }
565
+
566
+ /** @returns whether the connection has been torn down. */
567
+ get disposed(): boolean {
568
+ return this.#disposed
569
+ }
570
+
571
+ /**
572
+ * @returns this connection's identity for the extension seam. Stable for the
573
+ * life of the socket and never reused by a later one.
574
+ */
575
+ get id(): string {
576
+ return this.#id
577
+ }
578
+
579
+ /**
580
+ * @param capability - one capability name this protocol defines.
581
+ * @returns whether this connection announced it in `hello`.
582
+ */
583
+ declares(capability: string): boolean {
584
+ return this.#capabilities.has(capability)
585
+ }
586
+
587
+ /** Start the idle heartbeat that keeps a quiet phone's socket alive. */
588
+ startHeartbeat(): void {
589
+ if (this.#heartbeat !== undefined) return
590
+ const period = this.#options.heartbeatMs ?? IDLE_PING_MS
591
+ this.#heartbeat = setInterval(() => {
592
+ if (this.#options.now() - this.#lastSendAt < period) return
593
+ this.#send({ t: 'ping', ts: this.#options.now() })
594
+ // The ping is out, so the peer now owes an answer: a peer that went
595
+ // silent without closing its socket is exactly what this deadline finds.
596
+ this.#armLivenessDeadline()
597
+ }, period)
598
+ this.#heartbeat.unref?.()
599
+ }
600
+
601
+ /**
602
+ * Handle one received text frame.
603
+ *
604
+ * This method NEVER rejects. Its caller in the mounted wiring is
605
+ * `void connection.handleText(text)`, so a rejection here would be dropped on
606
+ * the floor and the client would wait forever for an answer that is never
607
+ * coming — the same silent stall as a socket nobody reads. Any unexpected
608
+ * failure (a roster write that cannot complete, a carrier that throws) is
609
+ * answered as an `internal` refusal and logged.
610
+ * @param text - the frame body as it crossed the wire.
611
+ */
612
+ async handleText(text: string): Promise<void> {
613
+ if (this.#disposed) return
614
+ // Any frame at all proves the peer is alive, so it satisfies the deadline
615
+ // behind the outstanding ping — a pong that answers no ping included.
616
+ this.#clearLivenessDeadline()
617
+ const outcome = decodeClientFrame(text)
618
+ if (!outcome.ok) {
619
+ this.#send(errorFrame(outcome.id, outcome.code, outcome.msg))
620
+ return
621
+ }
622
+ const frame = outcome.frame
623
+ if (frame.t === 'ping') {
624
+ this.#send({ t: 'pong', ts: frame.ts })
625
+ return
626
+ }
627
+ if (frame.t === 'pong') return
628
+ try {
629
+ const answer = await this.#dispatch(frame)
630
+ if (answer.ok) this.#send(responseFrame(frame.id, answer.r))
631
+ else this.#send(errorFrame(frame.id, answer.code, answer.msg))
632
+ } catch (error) {
633
+ this.#options.log(`${frame.m} failed unexpectedly: ${failureText(error)}`)
634
+ this.#send(errorFrame(frame.id, CODE_INTERNAL, failureText(error)))
635
+ }
636
+ }
637
+
638
+ /** Push one event to this connection, advancing its own sequence. */
639
+ emit(topic: string, payload: unknown): boolean {
640
+ return this.#emit(topic, payload)
641
+ }
642
+
643
+ /**
644
+ * Tear the connection down: stop the heartbeat, abort every follow stream it
645
+ * owns, and tell the carrier to go away. Idempotent, and safe to call from a
646
+ * socket error handler — a carrier whose socket already closed ignores it.
647
+ * @param close - the close frame to send instead of the bridge-unloading one.
648
+ * Only the liveness deadline passes it, so a client can tell a peer that
649
+ * stopped answering from an ordinary teardown; every other caller leaves it
650
+ * out and keeps the same code and reason as before.
651
+ */
652
+ dispose(close?: { readonly code: number; readonly reason: string }): void {
653
+ if (this.#disposed) return
654
+ this.#disposed = true
655
+ this.#clearLivenessDeadline()
656
+ if (this.#heartbeat !== undefined) {
657
+ clearInterval(this.#heartbeat)
658
+ this.#heartbeat = undefined
659
+ }
660
+ for (const subscription of this.#subscriptions.values()) subscription.controller.abort()
661
+ this.#subscriptions.clear()
662
+ // A scope nobody left can read must stop costing the host a read per burst.
663
+ for (const dispose of this.#jobWatches.values()) dispose()
664
+ this.#jobWatches.clear()
665
+ this.#jobSeen.clear()
666
+ // A dropped connection's incremental bases are released with it: a token it
667
+ // was given names nothing afterwards, and nothing here outlives its socket.
668
+ this.#deltas.clear()
669
+ // The bridge itself may be unloading with live sockets: the client is told
670
+ // the endpoint is going away instead of being left on a dead protocol.
671
+ this.#transport.close(close?.code ?? 1001, close?.reason ?? 'the bridge is going away')
672
+ }
673
+
674
+ /** Arm the deadline behind one liveness ping, replacing any earlier one. */
675
+ #armLivenessDeadline(): void {
676
+ this.#clearLivenessDeadline()
677
+ this.#liveness = setTimeout(() => {
678
+ this.#options.log(`connection closed on the liveness deadline: no frame within ${LIVENESS_TIMEOUT_MS} ms of a liveness ping`)
679
+ this.dispose({
680
+ code: CLOSE_LIVENESS_TIMEOUT,
681
+ reason: `no frame within ${LIVENESS_TIMEOUT_MS} ms of a liveness ping`,
682
+ })
683
+ }, LIVENESS_TIMEOUT_MS)
684
+ this.#liveness.unref?.()
685
+ }
686
+
687
+ /** Drop the deadline: the peer answered, or the connection is already gone. */
688
+ #clearLivenessDeadline(): void {
689
+ if (this.#liveness === undefined) return
690
+ clearTimeout(this.#liveness)
691
+ this.#liveness = undefined
692
+ }
693
+
694
+ async #dispatch(frame: ReqFrame): Promise<DispatchOutcome> {
695
+ const builtIn = KNOWN_METHODS.has(frame.m)
696
+ // A method no plugin registered is refused here, before the pairing gate, so
697
+ // the answer costs no plugin lookup and names the method the client invented.
698
+ if (!builtIn && this.#options.extensions?.has(frame.m) !== true) {
699
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
700
+ }
701
+ // `question.answer` exists only for a client that asked for the question
702
+ // channel: without the capability it is an unknown method, which is exactly
703
+ // what this frame was before the channel existed.
704
+ if (frame.m === METHOD_QUESTION_ANSWER && !this.declares(CAP_QUESTIONS)) {
705
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
706
+ }
707
+ // `jobs.list` is the whole of the job channel: without the capability the
708
+ // method does not exist, and without the method no scope is ever watched, so
709
+ // a client that never declared it can receive no `jobs.changed` either.
710
+ if (frame.m === METHOD_JOBS_LIST && !this.declares(CAP_JOBS)) {
711
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
712
+ }
713
+ // The agent channel is one capability: without `agents.v1` neither the preset
714
+ // roster nor session creation is part of this client's protocol, so a client
715
+ // that predates them is told what it was told before they existed.
716
+ if ((frame.m === METHOD_PRESETS_LIST || frame.m === METHOD_SESSION_CREATE) && !this.declares(CAP_AGENTS)) {
717
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
718
+ }
719
+ // Forking one session into another exists only for a client that declared
720
+ // the fork channel: without it the method is what it was before the channel
721
+ // existed, and the host is asked nothing on that client's behalf.
722
+ if (frame.m === METHOD_SESSION_FORK && !this.declares(CAP_SESSION_FORK)) {
723
+ return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
724
+ }
725
+ // Unconditional: a loopback Host buys nothing here. Without a device token
726
+ // only the handshake and the two pairing steps run.
727
+ if (!this.paired && !UNPAIRED_METHODS.has(frame.m)) return refusal(CODE_UNPAIRED, 'this connection is not paired')
728
+ // Extension methods run after both gates, so a registered name answers
729
+ // `unpaired` exactly as a protocol method does, and a client that never
730
+ // declared the capability is told the method does not exist rather than
731
+ // that it lacks rights to it.
732
+ if (!builtIn) return await this.#extension(frame)
733
+ switch (frame.m) {
734
+ case METHOD_HELLO: return this.#hello(frame.p)
735
+ case METHOD_PAIR_BEGIN: return this.#pairBegin(frame.p)
736
+ case METHOD_PAIR_FINISH: return await this.#pairFinish(frame.p)
737
+ case METHOD_SESSION_LIST: return await this.#sessionList(frame.p)
738
+ case METHOD_SESSION_TITLES: return this.#sessionTitles(frame.p)
739
+ case METHOD_SESSION_SNAPSHOT: return await this.#sessionSnapshot(frame.p, frame.id)
740
+ case METHOD_SESSION_HISTORY: return await this.#sessionHistory(frame.p, frame.id)
741
+ case METHOD_SESSION_HISTORY_DEEP: return await this.#sessionHistoryDeep(frame.p, frame.id)
742
+ case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p)
743
+ case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p)
744
+ case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id)
745
+ case METHOD_SESSION_PERMISSIONS: return this.#sessionPermissions(frame.p)
746
+ case METHOD_SESSION_SET_PERMISSION: return this.#sessionSetPermission(frame.p)
747
+ case METHOD_SESSION_MODELS: return await this.#sessionModels(frame.p)
748
+ case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p)
749
+ case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
750
+ case METHOD_QUESTION_ANSWER: return await this.#questionAnswer(frame.p)
751
+ case METHOD_JOBS_LIST: return await this.#jobsList(frame.p)
752
+ case METHOD_PRESETS_LIST: return await this.#presetsList()
753
+ case METHOD_SESSION_CREATE: return await this.#sessionCreate(frame.p)
754
+ case METHOD_SESSION_FORK: return await this.#sessionFork(frame.p)
755
+ default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
756
+ }
757
+ }
758
+
759
+ /**
760
+ * Run one method a plugin registered on the extension seam.
761
+ *
762
+ * The plugin decides everything: whether the payload is usable, what an
763
+ * answer looks like, and which refusal codes exist in its own protocol. This
764
+ * bridge only forwards — and owns `internal`, because a handler that throws
765
+ * or answers nothing usable has left the client with no other honest code.
766
+ * @param frame - the request being served.
767
+ */
768
+ async #extension(frame: ReqFrame): Promise<DispatchOutcome> {
769
+ const handler = this.#options.extensions?.handlerFor(frame.m, capability => this.declares(capability))
770
+ // Reached when the name is registered but this client never declared the
771
+ // capability: the method is not part of its protocol.
772
+ if (handler === undefined) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
773
+ try {
774
+ const result = await handler(frame.p, {
775
+ connectionId: this.#id,
776
+ declares: capability => this.declares(capability),
777
+ deltas: this.#deltas,
778
+ })
779
+ if (!isMethodResult(result)) return refusal(CODE_INTERNAL, `${frame.m} answered no result`)
780
+ return result.ok ? { ok: true, r: result.r } : refusal(result.code, result.msg)
781
+ } catch (error) {
782
+ // The plugin's own message is the diagnostic; the client is told the call
783
+ // failed in this bridge because no extension code would be truthful here.
784
+ this.#options.log(`${frame.m} failed: ${failureText(error)}`)
785
+ return refusal(CODE_INTERNAL, failureText(error))
786
+ }
787
+ }
788
+
789
+ #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome { const proto = payload.proto
790
+ if (proto !== PROTO) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol ${PROTO}`)
791
+ this.#capabilities = capabilitiesOf(payload.cap)
792
+ // The frame form is decided where the frame is written, so the carrier is
793
+ // told the one thing it cannot read for itself: what this peer can inflate.
794
+ this.#transport.frameDeflate?.(this.#capabilities.has(CAP_FRAME_DEFLATE))
795
+ // The hub replays anything this client can now receive but missed: a phone
796
+ // that connected after a question was raised has no other way to learn of it.
797
+ this.#options.onDeclare?.(this)
798
+ return {
799
+ ok: true,
800
+ r: {
801
+ proto: PROTO,
802
+ minor: MINOR,
803
+ server: SERVER_ID,
804
+ capabilities: [...SERVED_CAPABILITIES],
805
+ resume: 'snapshot',
806
+ auth: this.paired ? 'paired' : 'unpaired',
807
+ },
808
+ }
809
+ }
810
+
811
+ #pairBegin(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
812
+ const token = stringArg(payload, 'token')
813
+ if (token === undefined) return refusal(CODE_INVALID_ARGS, 'pair.begin requires token')
814
+ if (!this.#options.pairing.consumeToken(token)) return refusal(CODE_TOKEN_INVALID, 'the bootstrap token is unknown, expired or already used')
815
+ const nonce = this.#options.pairing.issueNonce()
816
+ this.#nonce = { value: nonce.value, expiresAt: nonce.expiresAt }
817
+ return { ok: true, r: { nonce: nonce.value, expiresAt: nonce.expiresAt } }
818
+ }
819
+
820
+ async #pairFinish(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
821
+ const devicePubKey = stringArg(payload, 'devicePubKey')
822
+ const signature = stringArg(payload, 'signature')
823
+ if (devicePubKey === undefined || signature === undefined) {
824
+ return refusal(CODE_INVALID_ARGS, 'pair.finish requires devicePubKey and signature')
825
+ }
826
+ const nonce = this.#nonce
827
+ if (nonce === undefined) return refusal(CODE_NONCE_INVALID, 'this connection has no open pairing')
828
+ // Consume before verifying: a wrong signature burns the challenge instead of
829
+ // leaving it available for another guess.
830
+ this.#nonce = undefined
831
+ if (!this.#options.pairing.consumeNonce(nonce.value) || nonce.expiresAt <= this.#options.now()) {
832
+ return refusal(CODE_NONCE_INVALID, 'the pairing nonce is expired or already used')
833
+ }
834
+ const raw = base64UrlDecode(nonce.value)
835
+ // The design says "the nonce's raw bytes". Both readings of that phrase are
836
+ // accepted — the decoded nonce, and the UTF-8 of the base64url text a client
837
+ // may sign without decoding — because the nonce is one-shot, 60 s, and
838
+ // bound to this connection, so accepting either encoding cannot let an
839
+ // unpaired caller in.
840
+ const signed = raw !== undefined && verifyEs256(devicePubKey, signature, raw)
841
+ ? true
842
+ : verifyEs256(devicePubKey, signature, Buffer.from(nonce.value, 'utf8'))
843
+ if (!signed) return refusal('signature-invalid', 'the ES256 signature does not verify against the device public key')
844
+ const enrollment = await this.#options.roster.enroll(devicePubKey)
845
+ if (enrollment === undefined) return refusal(CODE_INVALID_ARGS, 'devicePubKey is not a P-256 SPKI public key')
846
+ this.#deviceId = enrollment.deviceId
847
+ return { ok: true, r: { deviceToken: enrollment.deviceToken, deviceId: enrollment.deviceId } }
848
+ }
849
+
850
+ /**
851
+ * Answer the roster as a whole set, as one compact page, or as the increment
852
+ * since a token.
853
+ *
854
+ * `since` and the two answer modes exist only for a client that declared
855
+ * {@link CAP_DELTA}: every other client is answered the roster it always was,
856
+ * with `mode:"reset"` and an empty `token` beside it, and this connection
857
+ * keeps no copy of a set that client cannot continue from.
858
+ *
859
+ * The compact form needs both halves: the capability, and at least one compact
860
+ * parameter in the request. Either one alone is today's answer, which is what
861
+ * keeps an older client — and a client that declared the name but asks for
862
+ * nothing — byte identical to protocol v1.
863
+ * @param payload - `{since?, cwd?, maxRows?, after?}`.
864
+ */
865
+ async #sessionList(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
866
+ if (this.declares(CAP_ROSTER_COMPACT)) {
867
+ const requested = rosterCompactOf(payload)
868
+ if (!requested.ok) return requested
869
+ const compact = requested.compact
870
+ if (compact !== undefined) {
871
+ // One answer is a whole page a client continues with `after`, the other
872
+ // is an increment it continues with `token`; a request naming both bases
873
+ // is refused rather than answered against one of them silently.
874
+ if (sinceOf(payload) !== undefined) {
875
+ return refusal(CODE_INVALID_ARGS, 'session.list cannot combine a compact page with a since token')
876
+ }
877
+ const compactRoster = await this.#readRoster()
878
+ if (!compactRoster.ok) return compactRoster
879
+ return { ok: true, r: this.#compactRoster(compactRoster.rows, compact) }
880
+ }
881
+ }
882
+ const roster = await this.#readRoster()
883
+ if (!roster.ok) return roster
884
+ if (!this.declares(CAP_DELTA)) {
885
+ this.#deltas.drop('session.list')
886
+ return { ok: true, r: { mode: 'reset', token: '', sessions: roster.rows } }
887
+ }
888
+ const answer = this.#deltas
889
+ .window<SessionRow>('session.list', { maxRows: ROSTER_DELTA_MAX_ROWS })
890
+ .answer(roster.rows, sinceOf(payload))
891
+ return {
892
+ ok: true,
893
+ r: answer.mode === 'reset'
894
+ ? { mode: 'reset', token: answer.token, sessions: answer.rows }
895
+ : { mode: 'delta', token: answer.token, changed: answer.changed, removed: answer.removed },
896
+ }
897
+ }
898
+
899
+ /**
900
+ * Read the roster once, as the host answers it.
901
+ *
902
+ * Deliberately separate from {@link #sessionList}: lineage and authorization
903
+ * are learned from the same read, and an internal read must not consume or
904
+ * advance this connection's incremental base.
905
+ */
906
+ async #readRoster(): Promise<{ readonly ok: true; readonly rows: SessionRow[] } | CallFailure> {
907
+ const call = await this.#unary('session', 'list')
908
+ if (!call.ok) return call
909
+ const items = isRecord(call.value) ? call.value.items : undefined
910
+ if (!Array.isArray(items)) return refusal(CODE_INTERNAL, 'session/list returned no item table')
911
+ // Read once for the whole roster: the archive flag comes from one process-wide
912
+ // set, and an unreadable registry leaves the key out of every row — and drops
913
+ // nothing, because a bridge that cannot tell must not answer a shorter roster.
914
+ // A row that survives therefore always carries `archived: false`: the key stays
915
+ // in the schema even though no `true` crosses it any more.
916
+ const archived = this.#options.sessionMeta.archiveSet()
917
+ const sessions: SessionRow[] = []
918
+ for (const item of items) {
919
+ if (!isRecord(item) || typeof item.sessionId !== 'string') continue
920
+ // An archived session is not part of the roster this connection is sent at
921
+ // all: the phone hides such a row on arrival, so sending it is bytes paid
922
+ // for nothing. Skipped before the row is built, so no field of it is read.
923
+ // A live child keeps its own row, and with it the parent id that row names,
924
+ // so an archived parent never costs a child its lineage; the follow gate
925
+ // does notice, because that parent is no longer a session the roster names.
926
+ if (archived?.has(item.sessionId) === true) continue
927
+ const cwd = optionalText(item.cwd)
928
+ const parentSessionId = optionalText(item.parentSessionId)
929
+ sessions.push({
930
+ id: item.sessionId,
931
+ // The roster itself carries no title: `SessionSummary` has none. The
932
+ // connection fills in whatever `session.titles` already resolved for
933
+ // this id and never looks one up here, so listing stays one call.
934
+ title: this.#options.sessionMeta.cachedTitle(item.sessionId) ?? '',
935
+ updatedAt: typeof item.updatedAt === 'number' ? item.updatedAt : 0,
936
+ agentRunning: item.running === true,
937
+ ...(cwd === undefined ? {} : { cwd }),
938
+ ...(parentSessionId === undefined ? {} : { parentSessionId }),
939
+ ...(item.origin === 'subagent' ? { origin: 'subagent' as const } : {}),
940
+ blank: item.blank === true,
941
+ ...(archived === undefined ? {} : { archived: archived.has(item.sessionId) }),
942
+ })
943
+ }
944
+ // A listed roster is also the cheapest place to learn lineage: a delegated
945
+ // child's durable parent is on its own row, so a client that lists before it
946
+ // opens a session never costs a second read to address that session.
947
+ this.#rememberLineage(sessions)
948
+ return { ok: true, rows: sessions }
949
+ }
950
+
951
+ /**
952
+ * Answer one compact roster page out of the roster just read.
953
+ *
954
+ * Rows are ordered most recent first, with the id as the tiebreak, because a
955
+ * cursor is only meaningful over an order that does not depend on the order
956
+ * the host happened to answer in. `after` is exclusive and names the last row
957
+ * the previous page carried; a cursor this roster no longer names is an
958
+ * unknown base and answers a first page again, the way a delta token this
959
+ * window never issued answers a reset, so the client continues from the page
960
+ * it is given instead of stalling on an id that no longer exists.
961
+ *
962
+ * Three members are what makes the body shorter: `cwd` is present only when
963
+ * the request asked for it, `updatedAt` only when this connection has not
964
+ * already sent this id that exact value (a client keeps the one it holds), and
965
+ * `nextAfter` only while the roster continues past this page. Every other
966
+ * field of the row is today's, under today's names, so a page is the same
967
+ * roster cut short rather than a second schema — and `compact:true` says which
968
+ * schema the rows are in, so a client whose bookkeeping drifted can tell an
969
+ * omitted `updatedAt` from one this bridge never had.
970
+ * @param rows - the roster as the host answered it.
971
+ * @param compact - the parameters this listing carried.
972
+ */
973
+ #compactRoster(rows: readonly SessionRow[], compact: RosterCompact): Record<string, unknown> {
974
+ const ordered = [...rows].sort((left, right) => (right.updatedAt - left.updatedAt)
975
+ || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0))
976
+ // A cursor that names no row of this roster resolves to -1, which is a first
977
+ // page: the honest answer to a base this bridge cannot place.
978
+ const from = compact.after === undefined ? 0 : ordered.findIndex(row => row.id === compact.after) + 1
979
+ const end = compact.maxRows === undefined ? ordered.length : Math.min(ordered.length, from + compact.maxRows)
980
+ const page = ordered.slice(from, end)
981
+ const sessions = page.map(row => {
982
+ const held = this.#rosterUpdatedAt.get(row.id) === row.updatedAt
983
+ this.#rosterUpdatedAt.set(row.id, row.updatedAt)
984
+ return {
985
+ id: row.id,
986
+ title: row.title,
987
+ ...(held ? {} : { updatedAt: row.updatedAt }),
988
+ agentRunning: row.agentRunning,
989
+ ...(compact.cwd && row.cwd !== undefined ? { cwd: row.cwd } : {}),
990
+ ...(row.parentSessionId === undefined ? {} : { parentSessionId: row.parentSessionId }),
991
+ ...(row.origin === undefined ? {} : { origin: row.origin }),
992
+ blank: row.blank,
993
+ ...(row.archived === undefined ? {} : { archived: row.archived }),
994
+ }
995
+ })
996
+ // Bounded by the set it describes: an id this roster no longer names is gone
997
+ // from the memory too, and a row that comes back simply carries its value.
998
+ const current = new Set(rows.map(row => row.id))
999
+ for (const id of this.#rosterUpdatedAt.keys()) {
1000
+ if (!current.has(id)) this.#rosterUpdatedAt.delete(id)
1001
+ }
1002
+ const last = page[page.length - 1]?.id
1003
+ return {
1004
+ mode: 'reset',
1005
+ token: '',
1006
+ compact: true,
1007
+ sessions,
1008
+ ...(last === undefined || end >= ordered.length ? {} : { nextAfter: last }),
1009
+ }
1010
+ }
1011
+
1012
+ /**
1013
+ * Answer a batch of title lookups out of this process's title service.
1014
+ *
1015
+ * Every read is synchronous and in-process, so the batch bound is the whole
1016
+ * cost bound: nothing here awaits, opens a follow stream or touches
1017
+ * persistence. A session that is not live here, one whose title has not
1018
+ * landed yet, and a host without the title service all answer `""` — the
1019
+ * batch never fails for one id, and never fails because a service is absent.
1020
+ * @param payload - `{ids}`: one to {@link TITLES_MAX_IDS} session ids.
1021
+ */
1022
+ #sessionTitles(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1023
+ const ids = payload.ids
1024
+ if (!Array.isArray(ids) || ids.length === 0 || ids.length > TITLES_MAX_IDS) {
1025
+ return refusal(CODE_INVALID_ARGS, `session.titles requires 1 to ${TITLES_MAX_IDS} session ids`)
1026
+ }
1027
+ for (const id of ids) {
1028
+ if (typeof id !== 'string' || id === '') return refusal(CODE_INVALID_ARGS, 'session.titles requires non-empty string ids')
1029
+ }
1030
+ // The ids are chosen by the client, so the answer map is built on a null
1031
+ // prototype: a literal id like `__proto__` has to become a real key.
1032
+ const titles = Object.create(null) as Record<string, string>
1033
+ for (const id of ids) titles[id] = this.#options.sessionMeta.title(id)
1034
+ return { ok: true, r: { titles } }
1035
+ }
1036
+
1037
+ /**
1038
+ * Answer `session.snapshot`: the opening window, or one page of it.
1039
+ *
1040
+ * A client that declared {@link CAP_SESSION_SNAPSHOT_PAGE} gets the newest
1041
+ * page inside `maxBytes` (default {@link HISTORY_PAGE_BYTES}) instead of the
1042
+ * whole window, so an opening screen costs one page. The page is cut by the
1043
+ * same entry-level slice `session.history` uses, so the two can never
1044
+ * disagree, an entry larger than the whole budget is a page of its own rather
1045
+ * than a refusal, and `snapshot-too-large` cannot answer such a connection.
1046
+ * The oldest entry's own `seq` is the `before` cursor for the next, older
1047
+ * page; no second field restates it.
1048
+ *
1049
+ * The budget is measured on the WHOLE answer — `{turns, lastSeq, hasMore}`
1050
+ * encoded as the `res` frame the client receives — and never per turn, so a
1051
+ * turn of many small entries is cut like any other run of entries. What it
1052
+ * does not bound is a single entry: `pageTurns` ends a page at an entry, never
1053
+ * inside one, so when the newest entry alone is past the budget that entry IS
1054
+ * the page and the answer is exactly as large as it is (measured: a 2.2 MB
1055
+ * newest message answers a 2.2 MB page against a 512 KiB budget, while the
1056
+ * same window of ordinary entries answers 513794 bytes). Trimming or splitting
1057
+ * such an entry would hand the client something other than what the session
1058
+ * says, and refusing it would take the session away from the very capability
1059
+ * that exists to open big sessions, so this is a stated bound of the page
1060
+ * budget rather than a defect to be closed by a smaller number elsewhere.
1061
+ * A client that declared {@link CAP_SESSION_SNAPSHOT_SINCE} and named
1062
+ * `sinceSeq` is answered incrementally instead: only the entries above that
1063
+ * durable watermark, in the same turn shape, with `mode:"since"` and
1064
+ * `reset:false`. When the bridge cannot PROVE the chain is unbroken — the
1065
+ * window's oldest entry has scrolled past the watermark — the answer is the
1066
+ * baseline below, carrying `mode:"full"` and `reset:true` so the client knows
1067
+ * to throw its copy away. Nothing else about this method moves: a request
1068
+ * without `sinceSeq`, or from a connection that never declared the capability,
1069
+ * is answered exactly the bytes protocol v1 answered before.
1070
+ * @param payload - `{sessionId, sinceSeq?, maxBytes?}`.
1071
+ * @param id - the request id the page budget is measured against.
1072
+ */
1073
+ async #sessionSnapshot(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
1074
+ const sessionId = stringArg(payload, 'sessionId')
1075
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.snapshot requires sessionId')
1076
+ const unfollowable = await this.#unfollowable(sessionId)
1077
+ if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1078
+ const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
1079
+ if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
1080
+ // A client that declared the trim capability chooses what it is sent, never
1081
+ // which turns it gets: the projection is trimmed inside each turn first, and
1082
+ // only then does any frame or page budget apply.
1083
+ const window = turnsOfRecords(opening.baseline.records)
1084
+ const projection = this.#trimmedFor(window)
1085
+ const lastSeq = opening.baseline.cursor
1086
+ // An incremental answer takes two declarations: the capability in the
1087
+ // handshake AND the watermark in this request. Every other request keeps
1088
+ // protocol v1's own answer, byte for byte, so a client can adopt the name
1089
+ // before it relies on any of it.
1090
+ if (payload.sinceSeq !== undefined && this.#capabilities.has(CAP_SESSION_SNAPSHOT_SINCE)) {
1091
+ const sinceSeq = pageNumber(payload.sinceSeq)
1092
+ if (sinceSeq === undefined) return refusal(CODE_INVALID_ARGS, 'session.snapshot sinceSeq must be a non-negative integer')
1093
+ // A connection that declared the page capability declared the budget its
1094
+ // requests must carry, and an incremental request is one of its requests:
1095
+ // an unusable budget is refused here, so whether this reply ends up being
1096
+ // the increment or the baseline that spends the budget never decides it.
1097
+ if (this.#capabilities.has(CAP_SESSION_SNAPSHOT_PAGE)) {
1098
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT)
1099
+ if (!budget.ok) return budget
1100
+ }
1101
+ const incremental = this.#sinceAnswer(projection, window, sinceSeq, lastSeq, id)
1102
+ if (incremental !== undefined) return { ok: true, r: incremental }
1103
+ const baseline = this.#baselineAnswer(sessionId, projection, lastSeq, payload, id)
1104
+ if (!baseline.ok) return baseline
1105
+ return { ok: true, r: { ...baseline.r, mode: 'full', reset: true } }
1106
+ }
1107
+ return this.#baselineAnswer(sessionId, projection, lastSeq, payload, id)
1108
+ }
1109
+
1110
+ /**
1111
+ * The answer protocol v1 has always served: the whole window, or the newest
1112
+ * page of it for a connection that declared {@link CAP_SESSION_SNAPSHOT_PAGE}.
1113
+ *
1114
+ * One home for that answer, so an incremental request that has to fall back to
1115
+ * a full baseline is sent exactly the bytes it would have been sent without
1116
+ * asking — plus the two fields that say the client must reset.
1117
+ * @param sessionId - the session this baseline is of; the refusal names it.
1118
+ * @param projection - this connection's projection of the opening window.
1119
+ * @param lastSeq - the harness cursor the answer reports.
1120
+ * @param payload - the request, read only for `maxBytes`.
1121
+ * @param id - the request id any page budget is measured against.
1122
+ */
1123
+ #baselineAnswer(
1124
+ sessionId: string,
1125
+ projection: readonly SnapshotTurn[],
1126
+ lastSeq: number,
1127
+ payload: Readonly<Record<string, unknown>>,
1128
+ id: number,
1129
+ ): BaselineAnswer {
1130
+ if (!this.#capabilities.has(CAP_SESSION_SNAPSHOT_PAGE)) {
1131
+ // Not declared: the whole window, shrunk by whole turns, unchanged.
1132
+ const fitted = this.#fitTurns(projection, lastSeq, id)
1133
+ if (fitted === undefined) return refusal(CODE_SNAPSHOT_TOO_LARGE, `session ${sessionId} does not fit one ${MAX_FRAME_BYTES} byte frame`)
1134
+ return { ok: true, r: { turns: fitted.turns, lastSeq: fitted.lastSeq } }
1135
+ }
1136
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT)
1137
+ if (!budget.ok) return budget
1138
+ const page = pageTurns(projection, undefined, budget.maxBytes, (turns, _nextBefore, hasMore) =>
1139
+ Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, lastSeq, hasMore })), 'utf8'))
1140
+ return { ok: true, r: { turns: page.turns, lastSeq, hasMore: page.hasMore } }
1141
+ }
1142
+
1143
+ /**
1144
+ * Answer a snapshot that named a watermark, or hand back undefined when this
1145
+ * request has to be answered with the full baseline instead.
1146
+ *
1147
+ * The continuity proof is the whole contract, and it reads the WINDOW rather
1148
+ * than the trimmed projection: an entry the client never renders is still an
1149
+ * entry the window holds, and continuing past a watermark below it would hand
1150
+ * the client a view it cannot attach to what it already has. Only the window's
1151
+ * own oldest entry can say whether anything between that watermark and this
1152
+ * window is missing, and `oldest <= sinceSeq + 1` is the one case where nothing
1153
+ * is; an empty window proves it trivially, because there is nothing to lose. A
1154
+ * reset is always correct, so an unprovable window takes the safe answer.
1155
+ *
1156
+ * The bound this form still carries is the frame cap: a delta that cannot
1157
+ * cross one frame answers the baseline instead of a refusal, because the
1158
+ * client's recovery from a hole is the `reset` flag, not a failed request.
1159
+ * @param projection - the projection the incremental turns are cut from.
1160
+ * @param window - the same window before trimming, read for its oldest entry.
1161
+ * @param sinceSeq - the durable watermark the client already holds.
1162
+ * @param lastSeq - the harness cursor the answer reports.
1163
+ * @param id - the request id the frame cap is measured against.
1164
+ */
1165
+ #sinceAnswer(
1166
+ projection: readonly SnapshotTurn[],
1167
+ window: readonly SnapshotTurn[],
1168
+ sinceSeq: number,
1169
+ lastSeq: number,
1170
+ id: number,
1171
+ ): { readonly turns: readonly SnapshotTurn[]; readonly lastSeq: number; readonly mode: 'since'; readonly reset: false } | undefined {
1172
+ const oldest = oldestEntrySeq(window)
1173
+ if (oldest !== undefined && oldest > sinceSeq + 1) return undefined
1174
+ const answer = { turns: turnsAbove(projection, sinceSeq), lastSeq, mode: 'since' as const, reset: false as const }
1175
+ if (Buffer.byteLength(JSON.stringify(responseFrame(id, answer)), 'utf8') > MAX_FRAME_BYTES) return undefined
1176
+ return answer
1177
+ }
1178
+
1179
+ /**
1180
+ * Read one backwards page of a session's history.
1181
+ *
1182
+ * Pages are cut from the very baseline `session.snapshot` serves, so the two
1183
+ * can never disagree about a turn or an entry; this method only slices that
1184
+ * projection, by entry, from the newest entry below the caller's watermark. It
1185
+ * is a pure read of the baseline: it never drops, replaces or re-addresses the
1186
+ * subscription, and the same cursor always answers the same page.
1187
+ * @param payload - `{sessionId, before?, maxBytes?}`.
1188
+ * @param id - the request id the page budget is measured against.
1189
+ */
1190
+ async #sessionHistory(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
1191
+ const sessionId = stringArg(payload, 'sessionId')
1192
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.history requires sessionId')
1193
+ const before = payload.before === undefined ? undefined : pageNumber(payload.before)
1194
+ if (payload.before !== undefined && before === undefined) {
1195
+ return refusal(CODE_INVALID_ARGS, 'session.history before must be a non-negative integer')
1196
+ }
1197
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY)
1198
+ if (!budget.ok) return budget
1199
+ const unfollowable = await this.#unfollowable(sessionId)
1200
+ if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1201
+ const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
1202
+ if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
1203
+ const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) =>
1204
+ Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, ...(nextBefore === undefined ? {} : { nextBefore }), hasMore })), 'utf8'))
1205
+ return {
1206
+ ok: true,
1207
+ r: {
1208
+ turns: page.turns,
1209
+ ...(page.nextBefore === undefined ? {} : { nextBefore: page.nextBefore }),
1210
+ hasMore: page.hasMore,
1211
+ },
1212
+ }
1213
+ }
1214
+
1215
+ /**
1216
+ * Read one backwards page of a session's DURABLE history.
1217
+ *
1218
+ * `session.history` slices the follow window this connection holds, and that
1219
+ * window is only as wide as the harness was asked to open it (200 messages), so
1220
+ * a client that scrolls past it has no older page to ask for. This method reads
1221
+ * the session store itself: one `session/page` call walked backwards with
1222
+ * `beforeSeq`, with no follow stream and no window involved.
1223
+ *
1224
+ * It is a pure read in the same sense `session.history` is: nothing is
1225
+ * subscribed, remembered, dropped or re-addressed, so the same `before`
1226
+ * answers the same page and reading cannot change what the session is.
1227
+ * @param payload - `{sessionId, before?, maxBytes?}`.
1228
+ * @param id - the request id the page budget is measured against.
1229
+ */
1230
+ async #sessionHistoryDeep(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
1231
+ const sessionId = stringArg(payload, 'sessionId')
1232
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.history.deep requires sessionId')
1233
+ const before = payload.before === undefined ? undefined : pageNumber(payload.before)
1234
+ if (payload.before !== undefined && before === undefined) {
1235
+ return refusal(CODE_INVALID_ARGS, 'session.history.deep before must be a non-negative integer')
1236
+ }
1237
+ const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY_DEEP)
1238
+ if (!budget.ok) return budget
1239
+ // The same fence every other history read passes, and it runs before any
1240
+ // store call: a child this connection may not read costs no read at all.
1241
+ const unfollowable = await this.#unfollowable(sessionId)
1242
+ if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1243
+ const cut = await this.#durableCutOf(sessionId)
1244
+ if (!cut.ok) return cut
1245
+ const store = await this.#storePageOf(sessionId, cut.cut, before)
1246
+ if (!store.ok) return store
1247
+ const projection = turnsOfRecords(store.records)
1248
+ const oldestOf = (turns: readonly SnapshotTurn[]): number | undefined => turns[0]?.entries[0]?.seq
1249
+ const page = pageTurns(projection, before, budget.maxBytes, (turns, nextBefore, hasMore) => {
1250
+ // The measured frame is the ANSWER, not the store read: a store page that
1251
+ // ends short of the session's oldest entry still leaves older entries
1252
+ // behind the answer, and the cursor is the answer's own oldest entry.
1253
+ const more = hasMore || store.hasMore
1254
+ const cursor = more ? nextBefore ?? oldestOf(turns) : undefined
1255
+ return Buffer.byteLength(JSON.stringify(responseFrame(id, {
1256
+ turns,
1257
+ ...(cursor === undefined ? {} : { nextBefore: cursor }),
1258
+ hasMore: more,
1259
+ })), 'utf8')
1260
+ })
1261
+ if (page.turns.length === 0) return { ok: true, r: { turns: [], hasMore: false } }
1262
+ const hasMore = page.hasMore || store.hasMore
1263
+ const nextBefore = page.nextBefore ?? oldestOf(page.turns)
1264
+ return {
1265
+ ok: true,
1266
+ r: {
1267
+ turns: page.turns,
1268
+ ...(hasMore && nextBefore !== undefined ? { nextBefore } : {}),
1269
+ hasMore,
1270
+ },
1271
+ }
1272
+ }
1273
+
1274
+ /**
1275
+ * The inclusive log cut one durable page read names.
1276
+ *
1277
+ * `session/page` takes that cut as `throughSeq` and refuses one the store does
1278
+ * not hold, so a page read has to name a seq the session actually has. The
1279
+ * projection watermark is that seq: the cut every finished projection value has
1280
+ * folded through, read from the non-activating projection service
1281
+ * `session.models` already uses. `-1` is the harness's own name for a log with
1282
+ * no events at all, and the store answers it with an empty page.
1283
+ */
1284
+ async #durableCutOf(sessionId: string): Promise<{ readonly ok: true; readonly cut: number } | CallFailure> {
1285
+ const call = await this.#unary('session', 'projections', { sessionId })
1286
+ if (!call.ok) return call
1287
+ const cut = isRecord(call.value) ? call.value.asOfSeq : undefined
1288
+ if (typeof cut !== 'number' || !Number.isSafeInteger(cut) || cut < -1) {
1289
+ return refusal(CODE_SNAPSHOT_UNAVAILABLE, `session ${sessionId} reported no durable cut to page from`)
1290
+ }
1291
+ return { ok: true, cut }
1292
+ }
1293
+
1294
+ /**
1295
+ * Read one span of a session's durable history, at the address the harness demands.
1296
+ *
1297
+ * A delegated child is addressable only through its durable parent, and the
1298
+ * harness answers `session/agent-busy` when it is asked as an ordinary session.
1299
+ * That refusal is the one signal that distinguishes it from a real failure, so
1300
+ * it is the only one that triggers the roster lookup and the retry — the same
1301
+ * resolution {@link #openSubscription} performs for the follow stream.
1302
+ */
1303
+ async #storePageOf(sessionId: string, cut: number, before: number | undefined): Promise<{ readonly ok: true; readonly records: readonly unknown[]; readonly hasMore: boolean } | CallFailure> {
1304
+ let call = await this.#pageCall(this.#addressOf(sessionId), cut, before)
1305
+ if (!call.ok && call.code === CODE_SUBAGENT_ADDRESS_REQUIRED) {
1306
+ const parent = await this.#parentOf(sessionId)
1307
+ if (parent === undefined) return call
1308
+ this.#lineage.set(sessionId, parent)
1309
+ call = await this.#pageCall(subagentAddress(parent, sessionId), cut, before)
1310
+ }
1311
+ if (!call.ok) return call
1312
+ const value = call.value
1313
+ const records = isRecord(value) && Array.isArray(value.records) ? value.records as readonly unknown[] : undefined
1314
+ if (records === undefined) return refusal(CODE_INTERNAL, 'session/page answered no records')
1315
+ return { ok: true, records, hasMore: isRecord(value) && value.hasMore === true }
1316
+ }
1317
+
1318
+ /** One `session/page` call at one resolved address. */
1319
+ async #pageCall(address: SessionAddress, cut: number, before: number | undefined) {
1320
+ return await this.#unary('session', 'page', {
1321
+ address,
1322
+ throughSeq: cut,
1323
+ ...(before === undefined ? {} : { beforeSeq: before }),
1324
+ ...DEEP_HISTORY_WINDOW,
1325
+ })
1326
+ }
1327
+
1328
+ /** The projection a baseline is served with: trimmed only for a client that asked for it. */
1329
+ #projectionOf(records: readonly unknown[]): readonly SnapshotTurn[] {
1330
+ return this.#trimmedFor(turnsOfRecords(records))
1331
+ }
1332
+
1333
+ /** Drop the bookkeeping entries only for a client that declared the trim capability. */
1334
+ #trimmedFor(turns: readonly SnapshotTurn[]): readonly SnapshotTurn[] {
1335
+ return this.#capabilities.has(CAP_SESSION_SNAPSHOT_TRIM) ? trimUnrenderedEntries(turns) : turns
1336
+ }
1337
+
1338
+ async #sessionPrompt(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1339
+ const sessionId = stringArg(payload, 'sessionId')
1340
+ const text = stringArg(payload, 'text')
1341
+ const requestId = stringArg(payload, 'requestId')
1342
+ if (sessionId === undefined || text === undefined || requestId === undefined) {
1343
+ return refusal(CODE_INVALID_ARGS, 'session.prompt requires sessionId, text and requestId')
1344
+ }
1345
+ // Attachments are settled before the receipt is read and before anything is
1346
+ // sent: one rejected attachment withholds the whole prompt, so the harness is
1347
+ // not even subscribed to, let alone prompted.
1348
+ const attachments = promptAttachmentsOf(payload.attachments)
1349
+ if (!attachments.ok) return attachments
1350
+ const receipt = `${sessionId}\u0000${requestId}`
1351
+ if (this.#receipts.has(receipt)) return { ok: true, r: { accepted: true } }
1352
+ // A client may prompt without snapshotting first; the subscription is what
1353
+ // makes its own deltas reachable.
1354
+ this.#ensureSubscription(sessionId)
1355
+ const timeZone = this.#options.clientTimeZone()
1356
+ const call = await this.#unary('session', 'prompt', {
1357
+ requestId,
1358
+ sessionId,
1359
+ mode: 'queue',
1360
+ content: [{ type: 'text', text }, ...attachments.parts],
1361
+ ...(timeZone === undefined || timeZone === '' ? {} : { clientTimeZone: timeZone }),
1362
+ })
1363
+ if (!call.ok) return call
1364
+ this.#rememberReceipt(receipt)
1365
+ return { ok: true, r: { accepted: true } }
1366
+ }
1367
+
1368
+ async #sessionInterrupt(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1369
+ const sessionId = stringArg(payload, 'sessionId')
1370
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.interrupt requires sessionId')
1371
+ // The subscription deliberately outlives this: cancelling a turn is not
1372
+ // unsubscribing from the session.
1373
+ const call = await this.#unary('session', 'cancel', { sessionId })
1374
+ if (!call.ok) return call
1375
+ return { ok: true, r: { ok: true } }
1376
+ }
1377
+
1378
+ /**
1379
+ * Answer `session.attachment`: one durable image's bytes, straight from the
1380
+ * harness.
1381
+ *
1382
+ * The bridge keeps no cache — an image can be offloaded after the fact, so
1383
+ * every read goes to the session it belongs to — and it refuses rather than
1384
+ * writing a frame past the envelope budget: an attachment that cannot cross at
1385
+ * all is reported as such, never as an absent attachment.
1386
+ * @param payload - `{sessionId, attachmentId}`.
1387
+ * @param id - the request id the frame budget is measured against.
1388
+ */
1389
+ async #sessionAttachment(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
1390
+ const sessionId = stringArg(payload, 'sessionId')
1391
+ const attachmentId = stringArg(payload, 'attachmentId')
1392
+ if (sessionId === undefined || attachmentId === undefined) {
1393
+ return refusal(CODE_INVALID_ARGS, 'session.attachment requires sessionId and attachmentId')
1394
+ }
1395
+ const call = await this.#unary('session', 'attachment', { sessionId, attachmentId })
1396
+ if (!call.ok) return call
1397
+ if (!isRecord(call.value)) return refusal(CODE_INTERNAL, 'session/attachment returned no attachment')
1398
+ const bytes = Buffer.byteLength(JSON.stringify(responseFrame(id, call.value)), 'utf8')
1399
+ if (bytes > MAX_FRAME_BYTES) {
1400
+ return refusal(FRAME_TOO_LARGE, `attachment ${attachmentId} needs ${bytes} bytes, past the ${MAX_FRAME_BYTES} byte frame`)
1401
+ }
1402
+ return { ok: true, r: call.value }
1403
+ }
1404
+
1405
+ /** Answer `session.permissions` out of the host's own preset service. */
1406
+ #sessionPermissions(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1407
+ const sessionId = stringArg(payload, 'sessionId')
1408
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.permissions requires sessionId')
1409
+ const answer = this.#options.permissions.describe(sessionId)
1410
+ return 'code' in answer ? refusal(answer.code, answer.msg) : { ok: true, r: answer }
1411
+ }
1412
+
1413
+ /**
1414
+ * Switch one session's permission mode.
1415
+ *
1416
+ * This is the session-level persistent mode, deliberately apart from
1417
+ * `approval.resolve`: that answers one tool question once, this changes what
1418
+ * every later turn runs under.
1419
+ */
1420
+ #sessionSetPermission(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1421
+ const sessionId = stringArg(payload, 'sessionId')
1422
+ const id = stringArg(payload, 'id')
1423
+ if (sessionId === undefined || id === undefined) {
1424
+ return refusal(CODE_INVALID_ARGS, 'session.setPermission requires sessionId and id')
1425
+ }
1426
+ const answer = this.#options.permissions.set(sessionId, id)
1427
+ return 'code' in answer ? refusal(answer.code, answer.msg) : { ok: true, r: { ok: true, current: answer.current } }
1428
+ }
1429
+
1430
+ /**
1431
+ * Answer `session.models`: the host's catalog plus this session's selection.
1432
+ *
1433
+ * `current` is the session's FOLD — next, else last used, else the catalog
1434
+ * default — and never the default on its own: a phone that showed the default
1435
+ * while another model was in force would name the wrong model for the next
1436
+ * turn. The catalog's groups, failures and default cross unchanged.
1437
+ * @param payload - `{sessionId}`.
1438
+ */
1439
+ async #sessionModels(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1440
+ const sessionId = stringArg(payload, 'sessionId')
1441
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.models requires sessionId')
1442
+ const catalog = await this.#unary('session', 'modelCatalog')
1443
+ if (!catalog.ok) return catalog
1444
+ if (!isRecord(catalog.value)) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no catalog')
1445
+ const fallback = selectionOf(catalog.value.default)
1446
+ if (fallback === undefined) return refusal(CODE_INTERNAL, 'session/modelCatalog returned no default model')
1447
+ const projections = await this.#unary('session', 'projections', { sessionId })
1448
+ if (!projections.ok) return projections
1449
+ const folded = modelSelectionOf(projections.value)
1450
+ return {
1451
+ ok: true,
1452
+ r: {
1453
+ current: folded.next ?? folded.lastUsed ?? fallback,
1454
+ default: fallback,
1455
+ groups: catalog.value.groups ?? [],
1456
+ failures: catalog.value.failures ?? [],
1457
+ },
1458
+ }
1459
+ }
1460
+
1461
+ /**
1462
+ * Answer `session.setModel`: register the next turn's selection.
1463
+ *
1464
+ * The harness only records the choice for the NEXT request, so the answer
1465
+ * echoes the `selected` selection it accepted and nothing here claims the
1466
+ * running turn changed.
1467
+ * @param payload - `{sessionId, provider, model, effort?}`.
1468
+ */
1469
+ async #sessionSetModel(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1470
+ const sessionId = stringArg(payload, 'sessionId')
1471
+ const provider = stringArg(payload, 'provider')
1472
+ const model = stringArg(payload, 'model')
1473
+ if (sessionId === undefined || provider === undefined || model === undefined) {
1474
+ return refusal(CODE_INVALID_ARGS, 'session.setModel requires sessionId, provider and model')
1475
+ }
1476
+ const effort = optionalText(payload.effort)
1477
+ const call = await this.#unary('session', 'selectModel', {
1478
+ sessionId,
1479
+ provider,
1480
+ model,
1481
+ ...(effort === undefined ? {} : { reasoningEffort: effort }),
1482
+ })
1483
+ if (!call.ok) return call
1484
+ const selected = isRecord(call.value) ? selectionOf(call.value.selected) : undefined
1485
+ if (selected === undefined) return refusal(CODE_INTERNAL, 'session/selectModel returned no selected model')
1486
+ return { ok: true, r: { ok: true, current: selected } }
1487
+ }
1488
+
1489
+ /**
1490
+ * Answer `presets.list`: the host's Agent-preset roster, forwarded verbatim.
1491
+ *
1492
+ * The bridge has no vocabulary of its own for a preset — a row is whatever
1493
+ * `agentPresets/list` publishes, and that endpoint takes no request — so the
1494
+ * answer crosses exactly as the host wrote it, down to the keys a client of
1495
+ * this version does not read.
1496
+ */
1497
+ async #presetsList(): Promise<DispatchOutcome> {
1498
+ const call = await this.#unary('agentPresets', 'list')
1499
+ return call.ok ? { ok: true, r: call.value } : call
1500
+ }
1501
+
1502
+ /**
1503
+ * Answer `session.create`: hand the client's request to the host unchanged.
1504
+ *
1505
+ * A preset instantiated as an Agent is a host decision about a body this
1506
+ * bridge does not model — the field names, the defaults and the refusals
1507
+ * belong to `SessionCreateRequest` and to the host that validates it — so the
1508
+ * payload and the answer cross verbatim. Nothing is required here, renamed, or
1509
+ * defaulted: a request the host rejects is rejected with the host's own code
1510
+ * and text.
1511
+ * @param request - the host's `SessionCreateRequest`, exactly as the client wrote it.
1512
+ */
1513
+ async #sessionCreate(request: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1514
+ const call = await this.#unary('session', 'create', request)
1515
+ return call.ok ? { ok: true, r: call.value } : call
1516
+ }
1517
+
1518
+ /**
1519
+ * Answer `session.fork`: branch one session into another that inherits it.
1520
+ *
1521
+ * Only the two keys protocol v1 names are read here. `sessionId` is required
1522
+ * and `atSeq` is the host's inclusive source-event cut, so a caller that
1523
+ * omitted it must not have one invented for it: the host reads an absent
1524
+ * `atSeq` as the newest finished turn, and a zero or a fractional number is
1525
+ * not a seq at all, which is refused here rather than forwarded for the host
1526
+ * to reject with a shape this bridge could have caught. Everything else —
1527
+ * whether this host forks at all, what the new session is called, which
1528
+ * synthetic events close an open cut — belongs to `session/fork`, so a host
1529
+ * refusal crosses with its own code and text.
1530
+ * @param payload - `{sessionId, atSeq?}`.
1531
+ */
1532
+ async #sessionFork(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1533
+ const sessionId = stringArg(payload, 'sessionId')
1534
+ if (sessionId === undefined) return refusal(CODE_INVALID_ARGS, 'session.fork requires sessionId')
1535
+ const atSeq = payload.atSeq === undefined ? undefined : seqNumber(payload.atSeq)
1536
+ if (payload.atSeq !== undefined && atSeq === undefined) {
1537
+ return refusal(CODE_INVALID_ARGS, 'session.fork atSeq must be a positive integer')
1538
+ }
1539
+ const call = await this.#unary('session', 'fork', {
1540
+ sessionId,
1541
+ ...(atSeq === undefined ? {} : { atSeq }),
1542
+ })
1543
+ return call.ok ? { ok: true, r: call.value } : call
1544
+ }
1545
+
1546
+ #approvalResolve(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
1547
+ const id = stringArg(payload, 'id')
1548
+ const decision = payload.decision
1549
+ if (id === undefined || (decision !== 'allowed-once' && decision !== 'rejected')) {
1550
+ return refusal(CODE_INVALID_ARGS, 'approval.resolve requires id and decision of allowed-once or rejected')
1551
+ }
1552
+ if (!this.#options.approvals.resolve(id, decision)) {
1553
+ return refusal(CODE_APPROVAL_UNKNOWN, 'the question is unknown, already answered or expired')
1554
+ }
1555
+ return { ok: true, r: { ok: true } }
1556
+ }
1557
+
1558
+ /**
1559
+ * Answer one pending user question.
1560
+ *
1561
+ * The claim decides how the answer travels: an open question settles the
1562
+ * host's own ask, a continued one is steered into the agent through the
1563
+ * host's Remote `answer`. A call id this bridge does not hold is refused
1564
+ * rather than forwarded, and a host failure crosses with its own code.
1565
+ * @param payload - `{sessionId, callId, answers}`.
1566
+ */
1567
+ async #questionAnswer(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1568
+ const sessionId = stringArg(payload, 'sessionId')
1569
+ const callId = stringArg(payload, 'callId')
1570
+ const answers = answersOf(payload.answers)
1571
+ if (sessionId === undefined || callId === undefined || answers === undefined) {
1572
+ return refusal(CODE_INVALID_ARGS, 'question.answer requires sessionId, callId and answers of {id, selected, custom?}')
1573
+ }
1574
+ const reply = await this.#options.questions.answer(sessionId, callId, { answers })
1575
+ return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
1576
+ }
1577
+
1578
+ /**
1579
+ * Answer one `jobs.list` and start watching that scope.
1580
+ *
1581
+ * The scope is the host registry's own: naming a session reads that session's
1582
+ * fenced set (its own jobs plus every unowned one), naming none reads the
1583
+ * unowned set. Neither is a global list, and this method never assembles one —
1584
+ * a cross-session view would be a second source of truth the host does not
1585
+ * have, and it would have to aggregate N fenced reads to fake it.
1586
+ *
1587
+ * Answering is also what subscribes: every later change of this scope arrives
1588
+ * as `jobs.changed` carrying the same payload, and a scope that was never
1589
+ * listed is never watched.
1590
+ * @param payload - `{}` for the unowned scope, or `{sessionId}` for one session's.
1591
+ */
1592
+ async #jobsList(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
1593
+ const raw = payload.sessionId
1594
+ if (raw !== undefined && (typeof raw !== 'string' || raw === '')) {
1595
+ return refusal(CODE_INVALID_ARGS, 'jobs.list sessionId must be a non-empty string when present')
1596
+ }
1597
+ const sessionId = raw
1598
+ if (sessionId !== undefined) {
1599
+ // A job row names its owner and carries its label, so this read is fenced
1600
+ // by the same rule as following the session it belongs to: a delegated
1601
+ // child whose parent this connection may not read is not addressable here.
1602
+ const unfollowable = await this.#unfollowable(sessionId)
1603
+ if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
1604
+ }
1605
+ const roster = this.#options.jobs.read(sessionId)
1606
+ if (roster === undefined) {
1607
+ return refusal(CODE_JOBS_UNAVAILABLE, 'this host composes no background job registry')
1608
+ }
1609
+ this.#watchJobs(sessionId, roster)
1610
+ return { ok: true, r: roster }
1611
+ }
1612
+
1613
+ /**
1614
+ * Watch one job scope for this connection, once.
1615
+ *
1616
+ * The scope's first payload is the answer the client just received, so it is
1617
+ * seeded as already seen: a change frame only ever carries a set that differs
1618
+ * from the last one this connection was handed.
1619
+ */
1620
+ #watchJobs(sessionId: string | undefined, payload: JobsPayload): void {
1621
+ const key = scopeKey(sessionId)
1622
+ this.#jobSeen.set(key, JSON.stringify(payload.jobs))
1623
+ if (this.#jobWatches.has(key)) return
1624
+ const dispose = this.#options.jobs.watch(sessionId, (changed) => {
1625
+ if (!this.declares(CAP_JOBS)) return
1626
+ const encoded = JSON.stringify(changed.jobs)
1627
+ if (this.#jobSeen.get(key) === encoded) return
1628
+ this.#jobSeen.set(key, encoded)
1629
+ this.#emit(TOPIC_JOBS_CHANGED, changed)
1630
+ })
1631
+ if (dispose !== undefined) this.#jobWatches.set(key, dispose)
1632
+ }
1633
+
1634
+ /**
1635
+ * Run one unary Remote call with the activation retry, converting a gateway
1636
+ * failure into a refusal that carries the gateway's own code.
1637
+ */
1638
+ async #unary(namespace: string, method: string, request: Readonly<Record<string, unknown>> = {}): Promise<{ readonly ok: true; readonly value: unknown } | CallFailure> {
1639
+ try {
1640
+ const value = await withServiceUnavailableRetry(() => this.#options.gateway.invoke({
1641
+ namespace,
1642
+ method,
1643
+ args: wireArgs(namespace, method, request),
1644
+ peer: this.#options.ownerPeer,
1645
+ }))
1646
+ return { ok: true, value }
1647
+ } catch (error) {
1648
+ this.#options.log(`${namespace}/${method} failed: ${failureText(error)}`)
1649
+ return refusal(errorCodeOf(error, CODE_INTERNAL), failureText(error))
1650
+ }
1651
+ }
1652
+
1653
+ #ensureSubscription(sessionId: string): Subscription {
1654
+ const existing = this.#subscriptions.get(sessionId)
1655
+ if (existing !== undefined) return existing
1656
+ const subscription: Subscription = {
1657
+ sessionId,
1658
+ controller: new AbortController(),
1659
+ address: this.#addressOf(sessionId),
1660
+ // Resolved without ever rejecting: a caller may subscribe without awaiting
1661
+ // the opening frame (`session.prompt` does exactly that), and an unobserved
1662
+ // rejection would take the whole host process down under node's default
1663
+ // `--unhandled-rejections=throw`.
1664
+ opened: Promise.resolve({ ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: 'the stream was not opened' }),
1665
+ }
1666
+ subscription.opened = this.#openSubscription(subscription)
1667
+ this.#subscriptions.set(sessionId, subscription)
1668
+ return subscription
1669
+ }
1670
+
1671
+ /** The durable address of one session, as far as this connection has learned it. */
1672
+ #addressOf(sessionId: string): SessionAddress {
1673
+ const parent = this.#lineage.get(sessionId)
1674
+ return parent === undefined ? sessionAddress(sessionId) : subagentAddress(parent, sessionId)
1675
+ }
1676
+
1677
+ /**
1678
+ * Remember the durable parent of every delegated child a roster carried, and
1679
+ * which sessions that same roster authorizes this connection to read.
1680
+ *
1681
+ * A child is not authorized by being named: authorizing it on its own row
1682
+ * would let one refused read teach the connection to follow it on the retry.
1683
+ */
1684
+ #rememberLineage(rows: readonly SessionRow[]): void {
1685
+ for (const row of rows) {
1686
+ if (row.origin !== 'subagent') {
1687
+ this.#authorized.add(row.id)
1688
+ continue
1689
+ }
1690
+ if (row.parentSessionId !== undefined) this.#lineage.set(row.id, row.parentSessionId)
1691
+ }
1692
+ }
1693
+
1694
+ /**
1695
+ * The durable parent of a delegated child, or undefined when the roster does
1696
+ * not name one.
1697
+ *
1698
+ * The roster is the only endpoint that carries lineage, so it is read at most
1699
+ * once per connection: a client that listed sessions has already populated the
1700
+ * map, and a child opened without a listing costs exactly one roster read.
1701
+ */
1702
+ async #parentOf(sessionId: string): Promise<string | undefined> {
1703
+ const known = this.#lineage.get(sessionId)
1704
+ if (known !== undefined || this.#lineageRead) return known
1705
+ const roster = await this.#readRoster()
1706
+ if (roster.ok) this.#lineageRead = true
1707
+ return this.#lineage.get(sessionId)
1708
+ }
1709
+
1710
+ /**
1711
+ * Whether this connection may follow one session at all.
1712
+ *
1713
+ * Following a delegated child is the one case that needs an answer before the
1714
+ * stream is asked for: relaxing the child gate must not become a channel to
1715
+ * any session a caller happens to name. A session this connection already
1716
+ * opened is authorized by that fact, an ordinary session the roster names is
1717
+ * authorized by the host's own roster, and a delegated child is authorized
1718
+ * only when the parent it hangs off is one of those. A session the roster does
1719
+ * not know at all keeps the old path — the harness itself answers for an id
1720
+ * this host does not have.
1721
+ * @returns the refusal to answer with, or undefined when the session may be followed.
1722
+ */
1723
+ async #unfollowable(sessionId: string): Promise<string | undefined> {
1724
+ if (this.#authorized.has(sessionId)) return undefined
1725
+ const parent = await this.#parentOf(sessionId)
1726
+ if (parent === undefined) return undefined
1727
+ if (this.#authorized.has(parent)) return undefined
1728
+ return `session ${sessionId} is a delegated child whose parent ${parent} is not a session this connection may read`
1729
+ }
1730
+
1731
+ /**
1732
+ * Open one follow stream, resolving the address kind the harness demands.
1733
+ *
1734
+ * A delegated child is addressable only through its durable parent, and the
1735
+ * harness answers `session/agent-busy` when it is asked as an ordinary session.
1736
+ * That refusal is the one signal that distinguishes it from a real failure, so
1737
+ * it is the only one that triggers a roster lookup and a retry — everything
1738
+ * else crosses to the caller unchanged.
1739
+ */
1740
+ async #openSubscription(subscription: Subscription): Promise<Opening> {
1741
+ let outcome = await this.#openFollow(subscription)
1742
+ if (!outcome.ok && outcome.code === CODE_SUBAGENT_ADDRESS_REQUIRED) {
1743
+ const parent = await this.#parentOf(subscription.sessionId)
1744
+ if (parent !== undefined) {
1745
+ this.#lineage.set(subscription.sessionId, parent)
1746
+ subscription.address = subagentAddress(parent, subscription.sessionId)
1747
+ outcome = await this.#openFollow(subscription)
1748
+ }
1749
+ }
1750
+ if (!outcome.ok) {
1751
+ // The stream is unusable for this connection: drop it rather than leaving a
1752
+ // half-open subscription behind, so a later call starts a fresh one.
1753
+ this.#forget(subscription)
1754
+ subscription.controller.abort()
1755
+ }
1756
+ return outcome
1757
+ }
1758
+
1759
+ /** One attempt at the opening frame of a follow stream. */
1760
+ async #openFollow(subscription: Subscription): Promise<Opening> {
1761
+ let iterator: AsyncIterator<unknown>
1762
+ try {
1763
+ const stream = await withServiceUnavailableRetry(() => this.#options.gateway.stream({
1764
+ namespace: 'session',
1765
+ method: 'follow',
1766
+ args: wireArgs('session', 'follow', {
1767
+ address: subscription.address,
1768
+ // Decided after the frozen design's §2.1/§2.2 contradiction: one stream
1769
+ // per session carries both the baseline and the process-local deltas.
1770
+ assistantStream: true,
1771
+ maxMessages: SNAPSHOT_MAX_MESSAGES,
1772
+ }),
1773
+ peer: this.#options.ownerPeer,
1774
+ signal: subscription.controller.signal,
1775
+ }))
1776
+ iterator = stream[Symbol.asyncIterator]()
1777
+ } catch (error) {
1778
+ return { ok: false, code: errorCodeOf(error, CODE_SNAPSHOT_UNAVAILABLE), msg: failureText(error) }
1779
+ }
1780
+ try {
1781
+ const first = await iterator.next()
1782
+ const baseline = first.done === true ? undefined : readFollowBaseline(first.value)
1783
+ if (baseline === undefined) {
1784
+ await iterator.return?.()
1785
+ return { ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: 'session/follow returned no opening snapshot frame' }
1786
+ }
1787
+ // A stream that opened is proof this connection may read that session,
1788
+ // which is what lets a child of it be followed afterwards.
1789
+ this.#authorized.add(subscription.sessionId)
1790
+ void this.#drain(subscription, iterator)
1791
+ return { ok: true, baseline }
1792
+ } catch (error) {
1793
+ return { ok: false, code: errorCodeOf(error, CODE_SNAPSHOT_UNAVAILABLE), msg: failureText(error) }
1794
+ }
1795
+ }
1796
+
1797
+ /** Consume the rest of a follow stream, publishing every increment. */
1798
+ async #drain(subscription: Subscription, iterator: AsyncIterator<unknown>): Promise<void> {
1799
+ // Turn and step belong to this stream, not to the connection: a phone
1800
+ // following a parent and a child at once interleaves two turn sequences.
1801
+ const memory = {
1802
+ subagentThread: this.declares(CAP_SUBAGENT_THREAD),
1803
+ spawnCalls: new SpawnCallIndex(),
1804
+ }
1805
+ try {
1806
+ for (;;) {
1807
+ const next = await iterator.next()
1808
+ if (next.done === true) return
1809
+ const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages, memory)
1810
+ if (delta === undefined) continue
1811
+ this.#emit(TOPIC_SESSION_DELTA, { sessionId: subscription.sessionId, ...delta })
1812
+ }
1813
+ } catch (error) {
1814
+ if (!subscription.controller.signal.aborted) {
1815
+ this.#options.log(`session ${subscription.sessionId} follow stream ended: ${failureText(error)}`)
1816
+ }
1817
+ } finally {
1818
+ this.#forget(subscription)
1819
+ }
1820
+ }
1821
+
1822
+ /** Await a subscription's opening frame under a bounded wait. */
1823
+ async #awaitOpening(subscription: Subscription): Promise<Opening> {
1824
+ let timer: NodeJS.Timeout | undefined
1825
+ const expiry = new Promise<undefined>(resolve => {
1826
+ timer = setTimeout(() => { resolve(undefined) }, SNAPSHOT_OPEN_TIMEOUT_MS)
1827
+ timer.unref?.()
1828
+ })
1829
+ try {
1830
+ const outcome = await Promise.race([subscription.opened, expiry])
1831
+ if (outcome !== undefined) return outcome
1832
+ // No opening frame in time means the stream is unusable for this connection:
1833
+ // drop it rather than leaving a half-open subscription behind.
1834
+ subscription.controller.abort()
1835
+ this.#forget(subscription)
1836
+ return { ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: `no opening frame within ${SNAPSHOT_OPEN_TIMEOUT_MS} ms` }
1837
+ } finally {
1838
+ if (timer !== undefined) clearTimeout(timer)
1839
+ }
1840
+ }
1841
+
1842
+ /** Drop a subscription only while it is still the current one for its session. */
1843
+ #forget(subscription: Subscription): void {
1844
+ if (this.#subscriptions.get(subscription.sessionId) === subscription) this.#subscriptions.delete(subscription.sessionId)
1845
+ }
1846
+
1847
+ /**
1848
+ * Shrink a snapshot until it fits one frame, dropping whole oldest turns.
1849
+ * @returns the fitting payload, or undefined when even one turn cannot fit.
1850
+ */
1851
+ #fitTurns(turns: readonly SnapshotTurn[], cursor: number, id: number): { readonly turns: readonly SnapshotTurn[]; readonly lastSeq: number } | undefined {
1852
+ let kept = [...turns]
1853
+ for (;;) {
1854
+ const frame = responseFrame(id, { turns: kept, lastSeq: cursor })
1855
+ if (Buffer.byteLength(JSON.stringify(frame), 'utf8') <= MAX_FRAME_BYTES) return { turns: kept, lastSeq: cursor }
1856
+ if (kept.length <= 1) return undefined
1857
+ kept = kept.slice(1)
1858
+ }
1859
+ }
1860
+
1861
+ #rememberReceipt(receipt: string): void {
1862
+ this.#receipts.add(receipt)
1863
+ while (this.#receipts.size > PROMPT_RECEIPT_LIMIT) {
1864
+ const oldest = this.#receipts.values().next()
1865
+ if (oldest.done === true) break
1866
+ this.#receipts.delete(oldest.value)
1867
+ }
1868
+ }
1869
+
1870
+ #emit(topic: string, payload: unknown): boolean {
1871
+ if (this.#disposed) return false
1872
+ const frame: ServerFrame = { t: 'ev', seq: this.#sequence.take(), m: topic, p: payload }
1873
+ const text = encodeFrame(frame)
1874
+ if (Buffer.byteLength(text, 'utf8') > MAX_FRAME_BYTES) {
1875
+ this.#options.log(`dropped a ${topic} event past ${MAX_FRAME_BYTES} bytes`)
1876
+ return false
1877
+ }
1878
+ return this.#write(text)
1879
+ }
1880
+
1881
+ #send(frame: ServerFrame): void {
1882
+ if (this.#disposed) return
1883
+ this.#write(encodeFrame(frame))
1884
+ }
1885
+
1886
+ /**
1887
+ * Hand one encoded frame to the carrier.
1888
+ *
1889
+ * A carrier that throws must not take the process down with it: every write
1890
+ * here happens either inside a socket `data` handler or inside the approval
1891
+ * waterfall, where an escaping exception becomes an uncaught exception. A
1892
+ * failure is logged and the frame is dropped — the socket is already gone by
1893
+ * then, so there is nobody left to answer.
1894
+ * @returns whether the frame was handed to the carrier.
1895
+ */
1896
+ #write(text: string): boolean {
1897
+ try {
1898
+ this.#transport.send(text)
1899
+ } catch (error) {
1900
+ this.#options.log(`could not write a frame: ${failureText(error)}`)
1901
+ return false
1902
+ }
1903
+ this.#lastSendAt = this.#options.now()
1904
+ return true
1905
+ }
1906
+ }