@linxin666/dsh-remote-bridge 0.4.7 → 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.
@@ -18,20 +18,33 @@
18
18
 
19
19
  import type { ApprovalRegistry } from './approvals.ts'
20
20
  import type { DeviceRoster } from './devices.ts'
21
- import { deltaOfFollowFrame, MessageIndex, pageTurns, readFollowBaseline, ToolCallIndex, trimUnrenderedEntries, turnsOfRecords, type FollowBaseline, type SnapshotTurn } from './dsh-frames.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'
22
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'
23
25
  import { errorCodeOf, failureText, withServiceUnavailableRetry } from './gateway-errors.ts'
26
+ import { scopeKey, type JobRoster, type JobsPayload } from './jobs.ts'
24
27
  import type { PairingService } from './pairing.ts'
25
28
  import type { QuestionAnswerItem, QuestionClaims } from './questions.ts'
26
29
  import {
30
+ CAP_AGENTS,
31
+ CAP_DELTA,
32
+ CAP_FRAME_DEFLATE,
33
+ CAP_JOBS,
27
34
  CAP_QUESTIONS,
35
+ CAP_ROSTER_COMPACT,
36
+ CAP_SESSION_FORK,
28
37
  CAP_SESSION_SNAPSHOT_PAGE,
38
+ CAP_SESSION_SNAPSHOT_SINCE,
29
39
  CAP_SESSION_SNAPSHOT_TRIM,
40
+ CAP_SUBAGENT_THREAD,
30
41
  CODE_APPROVAL_UNKNOWN,
31
42
  CODE_INTERNAL,
32
43
  CODE_INVALID_ARGS,
44
+ CODE_JOBS_UNAVAILABLE,
33
45
  CODE_NONCE_INVALID,
34
46
  CODE_PROTO_UNSUPPORTED,
47
+ CODE_SESSION_NOT_FOLLOWABLE,
35
48
  CODE_SNAPSHOT_TOO_LARGE,
36
49
  CODE_SNAPSHOT_UNAVAILABLE,
37
50
  CODE_TOKEN_INVALID,
@@ -40,11 +53,16 @@ import {
40
53
  KNOWN_METHODS,
41
54
  METHOD_APPROVAL_RESOLVE,
42
55
  METHOD_HELLO,
56
+ METHOD_JOBS_LIST,
43
57
  METHOD_PAIR_BEGIN,
44
58
  METHOD_PAIR_FINISH,
59
+ METHOD_PRESETS_LIST,
45
60
  METHOD_QUESTION_ANSWER,
46
61
  METHOD_SESSION_ATTACHMENT,
62
+ METHOD_SESSION_CREATE,
63
+ METHOD_SESSION_FORK,
47
64
  METHOD_SESSION_HISTORY,
65
+ METHOD_SESSION_HISTORY_DEEP,
48
66
  METHOD_SESSION_INTERRUPT,
49
67
  METHOD_SESSION_LIST,
50
68
  METHOD_SESSION_MODELS,
@@ -56,7 +74,9 @@ import {
56
74
  METHOD_SESSION_TITLES,
57
75
  MINOR,
58
76
  PROTO,
77
+ SERVED_CAPABILITIES,
59
78
  SERVER_ID,
79
+ TOPIC_JOBS_CHANGED,
60
80
  TOPIC_SESSION_DELTA,
61
81
  UNPAIRED_METHODS,
62
82
  } from './protocol.ts'
@@ -65,15 +85,41 @@ import { TITLES_MAX_IDS, type SessionMeta } from './session-meta.ts'
65
85
  import type { SessionPermissions } from './session-permissions.ts'
66
86
  import type { BridgeGateway, GatewayPeer } from './wire.ts'
67
87
  import { CODE_SUBAGENT_ADDRESS_REQUIRED, sessionAddress, subagentAddress, wireArgs, type SessionAddress } from './wire.ts'
88
+ import { CLOSE_LIVENESS_TIMEOUT } from './ws-frames.ts'
68
89
 
69
90
  /** Protocol-level heartbeat period: a frame is sent after this long without one. */
70
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
71
102
  /** How long `session.snapshot` waits for its follow stream's opening frame. */
72
103
  export const SNAPSHOT_OPEN_TIMEOUT_MS = 10_000
73
104
  /** Largest turn window one snapshot asks DSH for. */
74
105
  export const SNAPSHOT_MAX_MESSAGES = 200
75
106
  /** Default byte budget of one `session.history` page: 512 KiB. */
76
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
77
123
  /** Highest number of prompt receipts one connection remembers for idempotency. */
78
124
  export const PROMPT_RECEIPT_LIMIT = 512
79
125
  /** Largest base64 text one prompt attachment may carry: 6 MiB (protocol §10.2). */
@@ -83,6 +129,14 @@ export const PROMPT_ATTACHMENT_MAX_BYTES = 6 * 1024 * 1024
83
129
  export interface BridgeTransport {
84
130
  send(text: string): void
85
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
86
140
  }
87
141
 
88
142
  export interface BridgeConnectionOptions {
@@ -92,6 +146,8 @@ export interface BridgeConnectionOptions {
92
146
  readonly approvals: ApprovalRegistry
93
147
  /** Pending user questions: the claims this bridge holds and the answer path back to the host. */
94
148
  readonly questions: QuestionClaims
149
+ /** The host's background jobs: the read-only projection and the scopes this connection watches. */
150
+ readonly jobs: JobRoster
95
151
  /** Process-local session metadata: live titles and the host's archive set. */
96
152
  readonly sessionMeta: SessionMeta
97
153
  /** Host-process permission presets, read and switched through their real service objects. */
@@ -114,6 +170,12 @@ export interface BridgeConnectionOptions {
114
170
  */
115
171
  readonly onDeclare?: (connection: BridgeConnection) => void
116
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
117
179
  }
118
180
 
119
181
  /** A device the connection proved itself to be, resolved from the upgrade request. */
@@ -146,8 +208,18 @@ interface CallFailure {
146
208
 
147
209
  type DispatchOutcome = { readonly ok: true; readonly r: unknown } | CallFailure
148
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
+
149
221
  /** One session-list row as the protocol publishes it. */
150
- interface SessionRow {
222
+ interface SessionRow extends DeltaRow {
151
223
  readonly id: string
152
224
  readonly title: string
153
225
  readonly updatedAt: number
@@ -167,6 +239,37 @@ function refusal(code: string, msg: string): CallFailure {
167
239
  return { ok: false, code, msg }
168
240
  }
169
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
+
170
273
  function isRecord(value: unknown): value is Record<string, unknown> {
171
274
  return typeof value === 'object' && value !== null && !Array.isArray(value)
172
275
  }
@@ -187,6 +290,14 @@ function pageNumber(value: unknown): number | undefined {
187
290
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined
188
291
  }
189
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
+
190
301
  /**
191
302
  * Read one request's page budget.
192
303
  *
@@ -206,6 +317,54 @@ function pageBudgetOf(value: unknown, method: string): { readonly ok: true; read
206
317
  return { ok: true, maxBytes }
207
318
  }
208
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
+
209
368
  /**
210
369
  * Read the capability names a `hello` announced.
211
370
  *
@@ -330,7 +489,15 @@ function promptAttachmentsOf(value: unknown): PromptAttachments {
330
489
  * one frame at a time by the carrier's reader, and the only background work is
331
490
  * a subscription's own drain loop.
332
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
+
333
499
  export class BridgeConnection {
500
+ readonly #id = `c${connectionSeq += 1}`
334
501
  readonly #options: BridgeConnectionOptions
335
502
  readonly #transport: BridgeTransport
336
503
  readonly #sequence = new EventSequence()
@@ -341,10 +508,41 @@ export class BridgeConnection {
341
508
  #capabilities: ReadonlySet<string> = new Set()
342
509
  /** Delegated children this connection has learned the durable parent of, by child id. */
343
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()
344
540
  #lineageRead = false
345
541
  #deviceId: string | undefined
346
542
  #nonce: { readonly value: string; readonly expiresAt: number } | undefined
347
543
  #heartbeat: NodeJS.Timeout | undefined
544
+ /** The deadline armed by the liveness ping currently outstanding, if any. */
545
+ #liveness: NodeJS.Timeout | undefined
348
546
  #lastSendAt = 0
349
547
  #disposed = false
350
548
 
@@ -370,6 +568,14 @@ export class BridgeConnection {
370
568
  return this.#disposed
371
569
  }
372
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
+
373
579
  /**
374
580
  * @param capability - one capability name this protocol defines.
375
581
  * @returns whether this connection announced it in `hello`.
@@ -383,7 +589,11 @@ export class BridgeConnection {
383
589
  if (this.#heartbeat !== undefined) return
384
590
  const period = this.#options.heartbeatMs ?? IDLE_PING_MS
385
591
  this.#heartbeat = setInterval(() => {
386
- if (this.#options.now() - this.#lastSendAt >= period) this.#send({ t: 'ping', ts: this.#options.now() })
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()
387
597
  }, period)
388
598
  this.#heartbeat.unref?.()
389
599
  }
@@ -401,6 +611,9 @@ export class BridgeConnection {
401
611
  */
402
612
  async handleText(text: string): Promise<void> {
403
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()
404
617
  const outcome = decodeClientFrame(text)
405
618
  if (!outcome.ok) {
406
619
  this.#send(errorFrame(outcome.id, outcome.code, outcome.msg))
@@ -431,40 +644,101 @@ export class BridgeConnection {
431
644
  * Tear the connection down: stop the heartbeat, abort every follow stream it
432
645
  * owns, and tell the carrier to go away. Idempotent, and safe to call from a
433
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.
434
651
  */
435
- dispose(): void {
652
+ dispose(close?: { readonly code: number; readonly reason: string }): void {
436
653
  if (this.#disposed) return
437
654
  this.#disposed = true
655
+ this.#clearLivenessDeadline()
438
656
  if (this.#heartbeat !== undefined) {
439
657
  clearInterval(this.#heartbeat)
440
658
  this.#heartbeat = undefined
441
659
  }
442
660
  for (const subscription of this.#subscriptions.values()) subscription.controller.abort()
443
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()
444
669
  // The bridge itself may be unloading with live sockets: the client is told
445
670
  // the endpoint is going away instead of being left on a dead protocol.
446
- this.#transport.close(1001, 'the bridge is going away')
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
447
692
  }
448
693
 
449
694
  async #dispatch(frame: ReqFrame): Promise<DispatchOutcome> {
450
- if (!KNOWN_METHODS.has(frame.m)) return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
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
+ }
451
701
  // `question.answer` exists only for a client that asked for the question
452
702
  // channel: without the capability it is an unknown method, which is exactly
453
703
  // what this frame was before the channel existed.
454
704
  if (frame.m === METHOD_QUESTION_ANSWER && !this.declares(CAP_QUESTIONS)) {
455
705
  return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
456
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
+ }
457
725
  // Unconditional: a loopback Host buys nothing here. Without a device token
458
726
  // only the handshake and the two pairing steps run.
459
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)
460
733
  switch (frame.m) {
461
734
  case METHOD_HELLO: return this.#hello(frame.p)
462
735
  case METHOD_PAIR_BEGIN: return this.#pairBegin(frame.p)
463
736
  case METHOD_PAIR_FINISH: return await this.#pairFinish(frame.p)
464
- case METHOD_SESSION_LIST: return await this.#sessionList()
737
+ case METHOD_SESSION_LIST: return await this.#sessionList(frame.p)
465
738
  case METHOD_SESSION_TITLES: return this.#sessionTitles(frame.p)
466
739
  case METHOD_SESSION_SNAPSHOT: return await this.#sessionSnapshot(frame.p, frame.id)
467
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)
468
742
  case METHOD_SESSION_PROMPT: return await this.#sessionPrompt(frame.p)
469
743
  case METHOD_SESSION_INTERRUPT: return await this.#sessionInterrupt(frame.p)
470
744
  case METHOD_SESSION_ATTACHMENT: return await this.#sessionAttachment(frame.p, frame.id)
@@ -474,13 +748,50 @@ export class BridgeConnection {
474
748
  case METHOD_SESSION_SET_MODEL: return await this.#sessionSetModel(frame.p)
475
749
  case METHOD_APPROVAL_RESOLVE: return this.#approvalResolve(frame.p)
476
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)
477
755
  default: return refusal(CODE_UNKNOWN_METHOD, `unknown method ${frame.m}`)
478
756
  }
479
757
  }
480
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
+
481
789
  #hello(payload: Readonly<Record<string, unknown>>): DispatchOutcome { const proto = payload.proto
482
790
  if (proto !== PROTO) return refusal(CODE_PROTO_UNSUPPORTED, `this bridge speaks protocol ${PROTO}`)
483
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))
484
795
  // The hub replays anything this client can now receive but missed: a phone
485
796
  // that connected after a question was raised has no other way to learn of it.
486
797
  this.#options.onDeclare?.(this)
@@ -490,6 +801,7 @@ export class BridgeConnection {
490
801
  proto: PROTO,
491
802
  minor: MINOR,
492
803
  server: SERVER_ID,
804
+ capabilities: [...SERVED_CAPABILITIES],
493
805
  resume: 'snapshot',
494
806
  auth: this.paired ? 'paired' : 'unpaired',
495
807
  },
@@ -535,17 +847,83 @@ export class BridgeConnection {
535
847
  return { ok: true, r: { deviceToken: enrollment.deviceToken, deviceId: enrollment.deviceId } }
536
848
  }
537
849
 
538
- async #sessionList(): Promise<DispatchOutcome> {
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> {
539
907
  const call = await this.#unary('session', 'list')
540
908
  if (!call.ok) return call
541
909
  const items = isRecord(call.value) ? call.value.items : undefined
542
910
  if (!Array.isArray(items)) return refusal(CODE_INTERNAL, 'session/list returned no item table')
543
911
  // Read once for the whole roster: the archive flag comes from one process-wide
544
- // set, and an unreadable registry leaves the key out of every row.
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.
545
916
  const archived = this.#options.sessionMeta.archiveSet()
546
917
  const sessions: SessionRow[] = []
547
918
  for (const item of items) {
548
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
549
927
  const cwd = optionalText(item.cwd)
550
928
  const parentSessionId = optionalText(item.parentSessionId)
551
929
  sessions.push({
@@ -567,7 +945,68 @@ export class BridgeConnection {
567
945
  // child's durable parent is on its own row, so a client that lists before it
568
946
  // opens a session never costs a second read to address that session.
569
947
  this.#rememberLineage(sessions)
570
- return { ok: true, r: { 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
+ }
571
1010
  }
572
1011
 
573
1012
  /**
@@ -606,32 +1045,137 @@ export class BridgeConnection {
606
1045
  * than a refusal, and `snapshot-too-large` cannot answer such a connection.
607
1046
  * The oldest entry's own `seq` is the `before` cursor for the next, older
608
1047
  * page; no second field restates it.
609
- * @param payload - `{sessionId, maxBytes?}`.
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?}`.
610
1071
  * @param id - the request id the page budget is measured against.
611
1072
  */
612
1073
  async #sessionSnapshot(payload: Readonly<Record<string, unknown>>, id: number): Promise<DispatchOutcome> {
613
1074
  const sessionId = stringArg(payload, 'sessionId')
614
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)
615
1078
  const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
616
1079
  if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
617
1080
  // A client that declared the trim capability chooses what it is sent, never
618
1081
  // which turns it gets: the projection is trimmed inside each turn first, and
619
1082
  // only then does any frame or page budget apply.
620
- const projection = this.#projectionOf(opening.baseline.records)
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 {
621
1130
  if (!this.#capabilities.has(CAP_SESSION_SNAPSHOT_PAGE)) {
622
1131
  // Not declared: the whole window, shrunk by whole turns, unchanged.
623
- const fitted = this.#fitTurns(projection, opening.baseline.cursor, id)
1132
+ const fitted = this.#fitTurns(projection, lastSeq, id)
624
1133
  if (fitted === undefined) return refusal(CODE_SNAPSHOT_TOO_LARGE, `session ${sessionId} does not fit one ${MAX_FRAME_BYTES} byte frame`)
625
1134
  return { ok: true, r: { turns: fitted.turns, lastSeq: fitted.lastSeq } }
626
1135
  }
627
1136
  const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_SNAPSHOT)
628
1137
  if (!budget.ok) return budget
629
- const lastSeq = opening.baseline.cursor
630
1138
  const page = pageTurns(projection, undefined, budget.maxBytes, (turns, _nextBefore, hasMore) =>
631
1139
  Buffer.byteLength(JSON.stringify(responseFrame(id, { turns, lastSeq, hasMore })), 'utf8'))
632
1140
  return { ok: true, r: { turns: page.turns, lastSeq, hasMore: page.hasMore } }
633
1141
  }
634
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
+
635
1179
  /**
636
1180
  * Read one backwards page of a session's history.
637
1181
  *
@@ -652,6 +1196,8 @@ export class BridgeConnection {
652
1196
  }
653
1197
  const budget = pageBudgetOf(payload.maxBytes, METHOD_SESSION_HISTORY)
654
1198
  if (!budget.ok) return budget
1199
+ const unfollowable = await this.#unfollowable(sessionId)
1200
+ if (unfollowable !== undefined) return refusal(CODE_SESSION_NOT_FOLLOWABLE, unfollowable)
655
1201
  const opening = await this.#awaitOpening(this.#ensureSubscription(sessionId))
656
1202
  if (!opening.ok) return refusal(opening.code, `session ${sessionId} produced no opening frame (${opening.msg})`)
657
1203
  const page = pageTurns(this.#projectionOf(opening.baseline.records), before, budget.maxBytes, (turns, nextBefore, hasMore) =>
@@ -666,10 +1212,127 @@ export class BridgeConnection {
666
1212
  }
667
1213
  }
668
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
+
669
1328
  /** The projection a baseline is served with: trimmed only for a client that asked for it. */
670
- #projectionOf(records: readonly unknown[]): SnapshotTurn[] {
671
- const projected = turnsOfRecords(records)
672
- return this.#capabilities.has(CAP_SESSION_SNAPSHOT_TRIM) ? trimUnrenderedEntries(projected) : projected
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
673
1336
  }
674
1337
 
675
1338
  async #sessionPrompt(payload: Readonly<Record<string, unknown>>): Promise<DispatchOutcome> {
@@ -823,6 +1486,63 @@ export class BridgeConnection {
823
1486
  return { ok: true, r: { ok: true, current: selected } }
824
1487
  }
825
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
+
826
1546
  #approvalResolve(payload: Readonly<Record<string, unknown>>): DispatchOutcome {
827
1547
  const id = stringArg(payload, 'id')
828
1548
  const decision = payload.decision
@@ -855,6 +1575,62 @@ export class BridgeConnection {
855
1575
  return reply.ok ? { ok: true, r: { ok: true } } : refusal(reply.code, reply.msg)
856
1576
  }
857
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
+
858
1634
  /**
859
1635
  * Run one unary Remote call with the activation retry, converting a gateway
860
1636
  * failure into a refusal that carries the gateway's own code.
@@ -898,10 +1674,20 @@ export class BridgeConnection {
898
1674
  return parent === undefined ? sessionAddress(sessionId) : subagentAddress(parent, sessionId)
899
1675
  }
900
1676
 
901
- /** Remember the durable parent of every delegated child a roster carried. */
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
+ */
902
1684
  #rememberLineage(rows: readonly SessionRow[]): void {
903
1685
  for (const row of rows) {
904
- if (row.origin === 'subagent' && row.parentSessionId !== undefined) this.#lineage.set(row.id, row.parentSessionId)
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)
905
1691
  }
906
1692
  }
907
1693
 
@@ -916,11 +1702,32 @@ export class BridgeConnection {
916
1702
  async #parentOf(sessionId: string): Promise<string | undefined> {
917
1703
  const known = this.#lineage.get(sessionId)
918
1704
  if (known !== undefined || this.#lineageRead) return known
919
- const roster = await this.#sessionList()
1705
+ const roster = await this.#readRoster()
920
1706
  if (roster.ok) this.#lineageRead = true
921
1707
  return this.#lineage.get(sessionId)
922
1708
  }
923
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
+
924
1731
  /**
925
1732
  * Open one follow stream, resolving the address kind the harness demands.
926
1733
  *
@@ -977,6 +1784,9 @@ export class BridgeConnection {
977
1784
  await iterator.return?.()
978
1785
  return { ok: false, code: CODE_SNAPSHOT_UNAVAILABLE, msg: 'session/follow returned no opening snapshot frame' }
979
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)
980
1790
  void this.#drain(subscription, iterator)
981
1791
  return { ok: true, baseline }
982
1792
  } catch (error) {
@@ -986,11 +1796,17 @@ export class BridgeConnection {
986
1796
 
987
1797
  /** Consume the rest of a follow stream, publishing every increment. */
988
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
+ }
989
1805
  try {
990
1806
  for (;;) {
991
1807
  const next = await iterator.next()
992
1808
  if (next.done === true) return
993
- const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages)
1809
+ const delta = deltaOfFollowFrame(next.value, this.#toolCalls, this.#messages, memory)
994
1810
  if (delta === undefined) continue
995
1811
  this.#emit(TOPIC_SESSION_DELTA, { sessionId: subscription.sessionId, ...delta })
996
1812
  }