@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.
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Per-connection delta windows: what a client that already holds a copy of a
3
+ * whole set is sent instead of the whole set again.
4
+ *
5
+ * The difference is computed here, in the bridge, because the bridge is the
6
+ * only place that holds what the host said last — the host itself is asked for
7
+ * its complete answer every time and never learns that a client is caching one.
8
+ * That is the whole point of this module: the saving is bytes on the wire
9
+ * between the bridge and the phone, not a change to any host API.
10
+ *
11
+ * Three rules live in this file and nowhere else, so the roster and the board
12
+ * cannot disagree about them:
13
+ *
14
+ * - a delta is only diffed against the exact set this window last sent, and
15
+ * only for a token this window itself issued; anything else answers a reset,
16
+ * because a wrong base is a wrong answer;
17
+ * - a change is a change of the serialised row, not of a timestamp — the host's
18
+ * `updatedAt` is not a change signal for every field, and a row whose body is
19
+ * byte-identical has not changed;
20
+ * - a delta that is not clearly smaller than the reset body is not worth
21
+ * sending: past {@link DELTA_CHANGED_RATIO} of the rows, the answer is a reset.
22
+ * @module dsh-remote-bridge/core/delta
23
+ */
24
+
25
+ import { randomBytes } from 'node:crypto'
26
+
27
+ /** Largest roster one connection's delta window retains. */
28
+ export const ROSTER_DELTA_MAX_ROWS = 5000
29
+ /** Largest board one connection's delta window retains. */
30
+ export const BOARD_DELTA_MAX_ROWS = 2000
31
+
32
+ /**
33
+ * Share of the current set that may change before a reset is the cheaper
34
+ * answer. Bytes, not cleverness: past this point the delta carries most of the
35
+ * body already and the extra keys only make it bigger.
36
+ */
37
+ export const DELTA_CHANGED_RATIO = 0.6
38
+
39
+ /**
40
+ * Identity of this bridge process, minted once at load.
41
+ *
42
+ * Part of every token, so a token minted by an earlier boot can never be
43
+ * replayed into a delta against a set that boot never sent. It is not a secret
44
+ * on its own — the per-window secret beside it is what makes a token
45
+ * unguessable, and the exact comparison below is what actually decides.
46
+ */
47
+ const BOOT_ID = randomBytes(8).toString('hex')
48
+
49
+ /** The one row field every set this module diffs is keyed by. */
50
+ export interface DeltaRow {
51
+ readonly id: string
52
+ }
53
+
54
+ /** One window's answer, before a method wraps it in its own wire shape. */
55
+ export type DeltaAnswer<T> =
56
+ | {
57
+ readonly mode: 'reset'
58
+ /** Opaque token to send back as `since`; `""` when nothing was retained. */
59
+ readonly token: string
60
+ /** The whole set, exactly as the method always published it. */
61
+ readonly rows: readonly T[]
62
+ }
63
+ | {
64
+ readonly mode: 'delta'
65
+ readonly token: string
66
+ /** Every row that is new or whose body differs from the last one sent. */
67
+ readonly changed: readonly T[]
68
+ /** Every id this window sent before and the host no longer names. */
69
+ readonly removed: readonly string[]
70
+ }
71
+
72
+ /** Cap on the set one window may retain. */
73
+ export interface DeltaLimits {
74
+ readonly maxRows: number
75
+ }
76
+
77
+ /**
78
+ * One connection's view of one set: the rows it last sent, and the token that
79
+ * set was announced under.
80
+ *
81
+ * A window is created lazily by whoever needs it and lives exactly as long as
82
+ * the connection that owns it (see {@link RemoteBridgeDeltas}), so two
83
+ * connections never share a base and a dropped connection leaks nothing.
84
+ */
85
+ export class DeltaWindow<T extends DeltaRow> {
86
+ readonly #maxRows: number
87
+ /**
88
+ * This window's own secret: what makes one connection's token useless to
89
+ * another, and what a client cannot derive from a token it was given.
90
+ */
91
+ readonly #secret = randomBytes(8).toString('hex')
92
+ readonly #sent = new Map<string, string>()
93
+ #revision = 0
94
+ #token: string | undefined
95
+
96
+ constructor(limits: DeltaLimits) {
97
+ this.#maxRows = limits.maxRows
98
+ }
99
+
100
+ /**
101
+ * Answer one call over the current full set.
102
+ * @param rows - the complete set, exactly as the host answered it this time.
103
+ * @param since - the opaque token the client sent, if it sent one.
104
+ * @returns a reset carrying every row, or a delta against the last set sent.
105
+ */
106
+ answer(rows: readonly T[], since: string | undefined): DeltaAnswer<T> {
107
+ const current = new Map<string, string>()
108
+ for (const row of rows) current.set(row.id, JSON.stringify(row))
109
+ // A set past the cap is not retained at all: one connection must never pin
110
+ // an unbounded copy of the host's state, and a reset is answered instead of
111
+ // pretending a base exists.
112
+ if (current.size > this.#maxRows) return this.#forget(rows)
113
+ // The only base a delta may be diffed against is the set this window sent
114
+ // last, named by the token it handed out with it. A token from another
115
+ // connection, another boot, an older answer of this one, or garbage is not
116
+ // that base.
117
+ if (since === undefined || this.#token === undefined || since !== this.#token) {
118
+ return this.#reset(rows, current)
119
+ }
120
+ const changed: T[] = []
121
+ for (const row of rows) if (this.#sent.get(row.id) !== current.get(row.id)) changed.push(row)
122
+ const removed: string[] = []
123
+ for (const id of this.#sent.keys()) if (!current.has(id)) removed.push(id)
124
+ // Removals are not counted against the ratio: a removal costs one id on the
125
+ // wire, not a row, so a wave of deletions is exactly what a delta is for.
126
+ if (changed.length > DELTA_CHANGED_RATIO * rows.length) return this.#reset(rows, current)
127
+ this.#sent.clear()
128
+ for (const [id, body] of current) this.#sent.set(id, body)
129
+ return { mode: 'delta', token: this.#nextToken(), changed, removed }
130
+ }
131
+
132
+ /**
133
+ * Answer the whole set and keep it as the next base.
134
+ * @param rows - the complete set.
135
+ * @param current - the set, serialised, to retain.
136
+ */
137
+ #reset(rows: readonly T[], current: Map<string, string>): DeltaAnswer<T> {
138
+ this.#sent.clear()
139
+ for (const [id, body] of current) this.#sent.set(id, body)
140
+ return { mode: 'reset', token: this.#nextToken(), rows }
141
+ }
142
+
143
+ /**
144
+ * Answer the whole set and retain nothing.
145
+ *
146
+ * The empty token says so: this answer cannot be continued from, because
147
+ * there is no copy of it here to diff against. A client that sends it back is
148
+ * answered a reset, which is the truth rather than a wrong delta.
149
+ * @param rows - the complete set.
150
+ */
151
+ #forget(rows: readonly T[]): DeltaAnswer<T> {
152
+ this.#sent.clear()
153
+ this.#token = undefined
154
+ this.#revision += 1
155
+ return { mode: 'reset', token: '', rows }
156
+ }
157
+
158
+ /** @returns the token for the set just retained, bumping the window's revision. */
159
+ #nextToken(): string {
160
+ this.#revision += 1
161
+ this.#token = `d1.${BOOT_ID}.${this.#secret}.${this.#revision}`
162
+ return this.#token
163
+ }
164
+ }
165
+
166
+ /**
167
+ * The delta windows one connection owns, by the name its owner keys them with.
168
+ *
169
+ * Held on the connection, so the state is released exactly when the connection
170
+ * is: there is no second registry to expire, and no connection's window can be
171
+ * read by another.
172
+ */
173
+ export class RemoteBridgeDeltas {
174
+ readonly #windows = new Map<string, DeltaWindow<DeltaRow>>()
175
+
176
+ /**
177
+ * @param key - the window's name within this connection; one set, one key.
178
+ * @param limits - the cap this window retains.
179
+ * @returns the window, created on first use.
180
+ */
181
+ window<T extends DeltaRow>(key: string, limits: DeltaLimits): DeltaWindow<T> {
182
+ const known = this.#windows.get(key)
183
+ if (known !== undefined) return known as DeltaWindow<T>
184
+ const created = new DeltaWindow<T>(limits)
185
+ this.#windows.set(key, created as unknown as DeltaWindow<DeltaRow>)
186
+ return created
187
+ }
188
+
189
+ /**
190
+ * @param key - one window's name.
191
+ *
192
+ * Drops that window and the set it retained, so its token names nothing and
193
+ * the next call answers a reset. Used when a connection stops being served
194
+ * increments at all, which must cost it no memory either.
195
+ */
196
+ drop(key: string): void {
197
+ this.#windows.delete(key)
198
+ }
199
+
200
+ /** Drop every window: called when the owning connection is torn down. */
201
+ clear(): void {
202
+ this.#windows.clear()
203
+ }
204
+ }
@@ -26,6 +26,25 @@ export interface MessageUsage {
26
26
  readonly reasoningTokens?: number
27
27
  }
28
28
 
29
+ /**
30
+ * Where one user message came from, as the host's durable `source` says.
31
+ *
32
+ * The three kinds are the only classification this protocol makes, and they are
33
+ * read off `source.kind` mechanically: `user` and `user-approval` are a human,
34
+ * `agent-message` and `subagent-settled` are an agent, and every other kind —
35
+ * including one this bridge has never seen — is the system. `sourceKind` is the
36
+ * host's own string, verbatim, so a client can tell "the system" apart without
37
+ * the bridge inventing a taxonomy it cannot keep current.
38
+ */
39
+ export interface MessageActor {
40
+ readonly kind: 'human' | 'agent' | 'system'
41
+ readonly sourceKind: string
42
+ /** Durable id of the session that sent the message; only known for an agent. */
43
+ readonly sessionId?: string
44
+ /** The host's own display label for the source, when it wrote one. */
45
+ readonly label?: string
46
+ }
47
+
29
48
  /** One protocol v1 delta, before the session id and event sequence are attached. */
30
49
  export type SessionDelta =
31
50
  | { readonly kind: 'text'; readonly text: string; readonly blockIndex: number }
@@ -33,7 +52,8 @@ export type SessionDelta =
33
52
  | { readonly kind: 'tool-call'; readonly callId: string; readonly name: string; readonly argumentsDelta: string }
34
53
  | { readonly kind: 'tool-result'; readonly callId: string; readonly output: string; readonly isError: boolean }
35
54
  | { readonly kind: 'turn-end'; readonly reason: string }
36
- | { readonly kind: 'user-message'; readonly text: string; readonly messageId?: string; readonly attachments?: readonly UserMessageAttachment[] }
55
+ | { readonly kind: 'user-message'; readonly text: string; readonly messageId?: string; readonly attachments?: readonly UserMessageAttachment[]; readonly actor?: MessageActor }
56
+ | { readonly kind: 'subagent'; readonly childId: string; readonly label?: string; readonly mode?: string; readonly callId?: string }
37
57
  | { readonly kind: 'usage'; readonly usage: MessageUsage; readonly turn?: number; readonly step?: number }
38
58
 
39
59
  /** Highest number of tool calls one connection remembers by id. */
@@ -43,15 +63,23 @@ export const USER_MESSAGE_MEMORY = 512
43
63
 
44
64
  /**
45
65
  * The durable entry types a protocol v1 client renders — `user/message`,
46
- * `assistant/message`, `tool/call` and `tool/result`. Everything else in a
47
- * turn's entries is the harness's own bookkeeping, which the client can only
48
- * count as unknown, so a client that asks for a trimmed baseline is not sent it.
66
+ * `assistant/message`, `tool/call`, `tool/result` and `subagent/catalog`.
67
+ * Everything else in a turn's entries is the harness's own bookkeeping, which
68
+ * the client can only count as unknown, so a client that asks for a trimmed
69
+ * baseline is not sent it.
70
+ *
71
+ * The catalog entry is here because it is the baseline half of the subagent
72
+ * thread: a phone that opens a session after children were spawned has no other
73
+ * way to learn that they exist, their labels, their modes or the call that
74
+ * spawned them. Without it the thread header can only be inferred from agent
75
+ * messages, and every field the catalog carries is lost.
49
76
  */
50
77
  export const RENDERED_ENTRY_TYPES: ReadonlySet<string> = new Set([
51
78
  'user/message',
52
79
  'assistant/message',
53
80
  'tool/call',
54
81
  'tool/result',
82
+ 'subagent/catalog',
55
83
  ])
56
84
 
57
85
  /** One raw durable event inside a snapshot turn. */
@@ -60,6 +88,8 @@ export interface SnapshotEntry {
60
88
  readonly time: number
61
89
  readonly type: string
62
90
  readonly data: unknown
91
+ /** Where a `user/message` came from; absent on every other entry type. */
92
+ readonly actor?: MessageActor
63
93
  }
64
94
 
65
95
  /** One turn of a session snapshot: the durable events from `turn/start` to `turn/end`. */
@@ -150,6 +180,174 @@ export class MessageIndex {
150
180
  }
151
181
  }
152
182
 
183
+ /**
184
+ * The child sessions one `tool/result` payload names as spawned.
185
+ *
186
+ * A spawn answers with a handle, and the handle is the only place a durable
187
+ * record ties a child id to the call that made it: the catalog event names the
188
+ * child but not the call. Two shapes are written by this harness and both are
189
+ * read here, verbatim from a real session log —
190
+ *
191
+ * - the activation handle the `subagent` tool returns, alone or nested in the
192
+ * object a `run_code` program returns:
193
+ * `{"a":{"kind":"activation","subagentId":"b0a3a569-…"}}`;
194
+ * - the plain notice the same tool prints when it runs without PTC:
195
+ * `started subagent d605390b-66f6-474b-956d-0824ec2103e0`.
196
+ *
197
+ * Nothing else is accepted: a `list_agents` answer that happens to list a child
198
+ * (`[{"kind":"child","id":"…"}]`) carries neither signature, so it can never
199
+ * lend its own call id to a thread it did not spawn.
200
+ * @param data - one durable `tool/result` payload.
201
+ * @returns the child ids the payload names, in the order it names them.
202
+ */
203
+ export function spawnedChildIdsOf(data: unknown): string[] {
204
+ const message = isRecord(data) ? data.message : undefined
205
+ const ids: string[] = []
206
+ for (const id of spawnIdsIn(textOfBlocks(isRecord(message) ? message.content : undefined))) {
207
+ if (!ids.includes(id)) ids.push(id)
208
+ }
209
+ return ids
210
+ }
211
+
212
+ /** The spawn signatures above, as the two patterns that carry a child id. */
213
+ const SPAWN_HANDLE_IDS = /"subagentId"\s*:\s*"([^"]+)"/g
214
+ const SPAWN_NOTICE_IDS = /started subagent\s+([0-9A-Za-z][0-9A-Za-z_.-]{3,})/g
215
+
216
+ /** @returns every child id one result's text names through a spawn signature. */
217
+ function spawnIdsIn(text: string): string[] {
218
+ const ids: string[] = []
219
+ for (const pattern of [SPAWN_HANDLE_IDS, SPAWN_NOTICE_IDS]) {
220
+ for (const match of text.matchAll(pattern)) {
221
+ const id = match[1]
222
+ if (id !== undefined && id !== '' && !ids.includes(id)) ids.push(id)
223
+ }
224
+ }
225
+ return ids
226
+ }
227
+
228
+ /**
229
+ * The child-to-call evidence one session's records already carry.
230
+ *
231
+ * A spawn's result can be projected after the catalog it belongs to, so a
232
+ * baseline reads the whole record list for this evidence before it resolves any
233
+ * catalog entry: the snapshot is a session that has already happened, and the
234
+ * answer it gives a client must not depend on where in the list it stopped
235
+ * looking. The live subscription feeds the same evidence in as it arrives.
236
+ * @param records - durable follow records, oldest first.
237
+ * @returns every child id a `tool/result` names, with the call that produced it.
238
+ */
239
+ export function spawnCallEvidence(records: readonly unknown[]): Map<string, string> {
240
+ const evidence = new Map<string, string>()
241
+ for (const record of records) {
242
+ const event = isRecord(record) ? record.event : undefined
243
+ if (!isRecord(event) || event.type !== 'tool/result') continue
244
+ const callId = toolResultCallIdOf(event.data)
245
+ if (callId === undefined) continue
246
+ for (const childId of spawnedChildIdsOf(event.data)) evidence.set(childId, callId)
247
+ }
248
+ return evidence
249
+ }
250
+
251
+ /** @returns the call id one durable `tool/result` payload belongs to. */
252
+ function toolResultCallIdOf(data: unknown): string | undefined {
253
+ const message = isRecord(data) ? data.message : undefined
254
+ const callId = stringField(message, 'toolCallId')
255
+ return callId === undefined || callId === '' ? undefined : callId
256
+ }
257
+
258
+ /**
259
+ * Correlates one `subagent/catalog` event to the tool call that spawned the
260
+ * child it registers.
261
+ *
262
+ * The catalog event names the child but not the call, so the call is read from
263
+ * two places, in this order:
264
+ *
265
+ * 1. the spawn's own `tool/result`, which names the child it started
266
+ * ({@link spawnedChildIdsOf}). This is the decisive one: it survives a step
267
+ * that issued several calls, and a step whose one call started a whole team
268
+ * of children, because the payload says which child it is about.
269
+ * 2. the nearest preceding `tool/call` of the same turn and step, which is
270
+ * decidable only while one call is the whole story. A step with several
271
+ * calls leaves two candidates, and a call that already produced a child
272
+ * leaves one call behind two children; a guessed id would point a thread at
273
+ * the wrong card.
274
+ *
275
+ * Neither holds: undefined, and the wire carries no call id at all. The same
276
+ * index answers both paths — a subscription as it watches, and a baseline after
277
+ * reading the session's records — so the two can never disagree about which rule
278
+ * decides a given catalog.
279
+ */
280
+ export class SpawnCallIndex {
281
+ readonly #named: Map<string, string>
282
+ #turn: number | undefined
283
+ #step: number | undefined
284
+ #calls: string[] = []
285
+ readonly #correlated = new Set<string>()
286
+
287
+ /**
288
+ * @param evidence - child-to-call pairs already read from the session's
289
+ * results, for the baseline path; empty for a live subscription.
290
+ */
291
+ constructor(evidence: ReadonlyMap<string, string> = new Map()) {
292
+ this.#named = new Map(evidence)
293
+ }
294
+
295
+ /**
296
+ * Read one durable event into the correlation state.
297
+ *
298
+ * A turn boundary or a new step is the only reset: a call belongs to the step
299
+ * that issued it, so a call from an earlier step can never be the nearest
300
+ * preceding one.
301
+ */
302
+ observe(type: string, data: unknown): void {
303
+ if (type === 'turn/start') {
304
+ this.#turn = numberOf(isRecord(data) ? data.turn : undefined)
305
+ this.#step = undefined
306
+ this.#calls = []
307
+ this.#correlated.clear()
308
+ return
309
+ }
310
+ if (type === 'step/start') {
311
+ this.#turn = numberOf(isRecord(data) ? data.turn : undefined) ?? this.#turn
312
+ this.#step = numberOf(isRecord(data) ? data.step : undefined)
313
+ this.#calls = []
314
+ this.#correlated.clear()
315
+ return
316
+ }
317
+ if (type === 'tool/result') {
318
+ const callId = toolResultCallIdOf(data)
319
+ if (callId === undefined) return
320
+ for (const childId of spawnedChildIdsOf(data)) this.#named.set(childId, callId)
321
+ return
322
+ }
323
+ if (type !== 'tool/call') return
324
+ const callId = stringField(data, 'callId')
325
+ if (callId === undefined || callId === '') return
326
+ this.#turn = numberOf(isRecord(data) ? data.turn : undefined) ?? this.#turn
327
+ this.#step = numberOf(isRecord(data) ? data.step : undefined) ?? this.#step
328
+ this.#calls.push(callId)
329
+ }
330
+
331
+ /**
332
+ * The call that spawned the child a catalog event registered.
333
+ * @param childId - the child that catalog event carries.
334
+ * @returns its call id, or undefined when nothing on the wire decides it.
335
+ */
336
+ spawnCallId(childId: string): string | undefined {
337
+ const named = this.#named.get(childId)
338
+ if (named !== undefined) {
339
+ this.#correlated.add(named)
340
+ return named
341
+ }
342
+ if (this.#turn === undefined || this.#step === undefined) return undefined
343
+ if (this.#calls.length !== 1) return undefined
344
+ const callId = this.#calls[0]
345
+ if (callId === undefined || this.#correlated.has(callId)) return undefined
346
+ this.#correlated.add(callId)
347
+ return callId
348
+ }
349
+ }
350
+
153
351
  /**
154
352
  * Read the opening frame of a follow stream.
155
353
  * @returns the cursor and records, or undefined when this frame is not a snapshot.
@@ -162,14 +360,28 @@ export function readFollowBaseline(frame: unknown): FollowBaseline | undefined {
162
360
  return { cursor, records, hasMore: frame.hasMore === true }
163
361
  }
164
362
 
363
+ /** What one follow stream remembers beyond its two bounded message indexes. */
364
+ export interface FollowMemory {
365
+ /** Whether this connection declared `subagent.thread.v1`. */
366
+ readonly subagentThread?: boolean
367
+ /** This stream's spawning-call correlation state; absent when the kind is off. */
368
+ readonly spawnCalls?: SpawnCallIndex
369
+ }
370
+
165
371
  /**
166
372
  * Map one DSH follow frame to a delta, or undefined when the frame carries no
167
373
  * increment this protocol publishes.
168
374
  * @param frame - one `SessionFollowFrame`.
169
375
  * @param toolCalls - this connection's tool-call memory.
170
376
  * @param messages - this connection's published-user-message memory.
377
+ * @param memory - the stream's own correlation state, and which optional kinds it declared.
171
378
  */
172
- export function deltaOfFollowFrame(frame: unknown, toolCalls: ToolCallIndex, messages: MessageIndex): SessionDelta | undefined {
379
+ export function deltaOfFollowFrame(
380
+ frame: unknown,
381
+ toolCalls: ToolCallIndex,
382
+ messages: MessageIndex,
383
+ memory: FollowMemory = {},
384
+ ): SessionDelta | undefined {
173
385
  if (!isRecord(frame)) return undefined
174
386
  if (frame.type === 'assistant-stream') return deltaOfAssistantStream(frame.frame, toolCalls)
175
387
  if (frame.type !== 'event') return undefined
@@ -177,14 +389,78 @@ export function deltaOfFollowFrame(frame: unknown, toolCalls: ToolCallIndex, mes
177
389
  if (!isRecord(event)) return undefined
178
390
  const type = event.type
179
391
  const data = event.data
392
+ // Observed before dispatch: a turn boundary, a new step and every call update
393
+ // the correlation state whether or not this contract publishes a delta for it.
394
+ memory.spawnCalls?.observe(typeof type === 'string' ? type : '', data)
180
395
  if (type === 'tool/result') return toolResultDelta(data)
181
396
  if (type === 'turn/end') return turnEndDelta(data)
182
397
  if (type === 'tool/call') return assembledToolCallDelta(data, toolCalls)
183
398
  if (type === 'user/message') return userMessageDelta(data, messages)
184
399
  if (type === 'assistant/message') return usageDelta(data)
400
+ if (type === 'subagent/catalog') return memory.subagentThread === true ? subagentDelta(data, memory.spawnCalls) : undefined
185
401
  return undefined
186
402
  }
187
403
 
404
+ /**
405
+ * Map one durable `subagent/catalog` to the increment that opens a thread on a
406
+ * subscribed phone.
407
+ *
408
+ * The child id is the only field the host must have written: without it the
409
+ * event registers nothing this protocol can address, so it publishes nothing
410
+ * rather than an increment a client could not use.
411
+ */
412
+ function subagentDelta(data: unknown, spawnCalls: SpawnCallIndex | undefined): SessionDelta | undefined {
413
+ const childId = stringField(data, 'childId')
414
+ if (childId === undefined || childId === '') return undefined
415
+ const label = textField(data, 'label')
416
+ const mode = textField(data, 'mode')
417
+ const callId = spawnCalls?.spawnCallId(childId)
418
+ return {
419
+ kind: 'subagent',
420
+ childId,
421
+ ...(label === undefined ? {} : { label }),
422
+ ...(mode === undefined ? {} : { mode }),
423
+ ...(callId === undefined ? {} : { callId }),
424
+ }
425
+ }
426
+
427
+ /**
428
+ * Where one durable user message came from.
429
+ *
430
+ * Absent when the event carries no readable `source.kind`: an event from a log
431
+ * written before sources existed has no source kind, and inventing one would
432
+ * report an origin the host never recorded.
433
+ */
434
+ function actorOf(data: unknown): MessageActor | undefined {
435
+ return actorOfSource(isRecord(data) ? data.source : undefined)
436
+ }
437
+
438
+ /**
439
+ * Derive one message's actor from the host's own `source` record, mechanically.
440
+ * @param source - the `source` member of a durable `user/message`.
441
+ * @returns the actor, or undefined when the source carries no kind.
442
+ */
443
+ export function actorOfSource(source: unknown): MessageActor | undefined {
444
+ const sourceKind = stringField(source, 'kind')
445
+ if (sourceKind === undefined || sourceKind === '') return undefined
446
+ const sessionId = stringField(source, 'senderSessionId')
447
+ const label = textField(source, 'label')
448
+ const named = {
449
+ sourceKind,
450
+ ...(label === undefined ? {} : { label }),
451
+ ...(sessionId === undefined || sessionId === '' ? {} : { sessionId }),
452
+ }
453
+ if (sourceKind === 'user' || sourceKind === 'user-approval') return { kind: 'human', ...named }
454
+ if (sourceKind === 'agent-message' || sourceKind === 'subagent-settled') return { kind: 'agent', ...named }
455
+ return { kind: 'system', ...named }
456
+ }
457
+
458
+ /** @returns a non-empty string field, or undefined. */
459
+ function textField(value: unknown, key: string): string | undefined {
460
+ const field = stringField(value, key)
461
+ return field === undefined || field === '' ? undefined : field
462
+ }
463
+
188
464
  function deltaOfAssistantStream(frame: unknown, toolCalls: ToolCallIndex): SessionDelta | undefined {
189
465
  if (!isRecord(frame) || frame.type !== 'chunk') return undefined
190
466
  const chunk = frame.chunk
@@ -264,11 +540,13 @@ function userMessageDelta(data: unknown, messages: MessageIndex): SessionDelta |
264
540
  messages.remember(messageId)
265
541
  }
266
542
  const attachments = imageAttachmentsOf(data.content)
543
+ const actor = actorOf(data)
267
544
  return {
268
545
  kind: 'user-message',
269
546
  text: textOfBlocks(data.content),
270
547
  ...(messageId === undefined ? {} : { messageId }),
271
548
  ...(attachments.length === 0 ? {} : { attachments }),
549
+ ...(actor === undefined ? {} : { actor }),
272
550
  }
273
551
  }
274
552
 
@@ -337,15 +615,26 @@ function numberOf(value: unknown): number | undefined {
337
615
 
338
616
  /**
339
617
  * Project a follow baseline's records into turns.
618
+ *
619
+ * A `subagent/catalog` entry leaves here carrying the call that spawned its
620
+ * child in `data.callId`, decided by the same {@link SpawnCallIndex} a live
621
+ * subscription uses — so the baseline half and the live half of the thread
622
+ * cannot answer differently about one catalog.
340
623
  * @param records - the baseline's durable records, oldest first.
341
624
  * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
342
625
  */
343
626
  export function turnsOfRecords(records: readonly unknown[]): SnapshotTurn[] {
344
627
  const turns: SnapshotTurn[] = []
628
+ // The spawn evidence is read from the whole list first: a spawn's result is
629
+ // projected after the catalog it belongs to, and a baseline that gave up at
630
+ // the catalog would lose the one record that names the call.
631
+ const spawns = new SpawnCallIndex(spawnCallEvidence(records))
345
632
  let current: { seq: number; time: number; endSeq: number; endTime: number; reason: string; entries: SnapshotEntry[] } | undefined
346
633
  for (const record of records) {
347
- const entry = snapshotEntryOf(record)
348
- if (entry === undefined) continue
634
+ const projected = snapshotEntryOf(record)
635
+ if (projected === undefined) continue
636
+ spawns.observe(projected.type, projected.data)
637
+ const entry = projected.type === 'subagent/catalog' ? catalogEntryWithCall(projected, spawns) : projected
349
638
  if (entry.type === 'turn/start' && current !== undefined && current.endSeq === 0) {
350
639
  // A previous turn never ended (an aborted resume): its tail stays with it.
351
640
  turns.push(current)
@@ -369,6 +658,26 @@ export function turnsOfRecords(records: readonly unknown[]): SnapshotTurn[] {
369
658
  return turns
370
659
  }
371
660
 
661
+ /**
662
+ * One `subagent/catalog` entry with the call that spawned its child, when the
663
+ * session decides it.
664
+ *
665
+ * Nothing else about the entry moves: the durable payload is copied as it
666
+ * arrived and `callId` is added beside it, exactly as the live `subagent`
667
+ * delta carries the same field under §13.3. A catalog whose spawning call is
668
+ * undecidable is passed through untouched rather than guessed at.
669
+ * @param entry - one projected catalog entry.
670
+ * @param spawns - the index holding this session's spawn evidence.
671
+ */
672
+ function catalogEntryWithCall(entry: SnapshotEntry, spawns: SpawnCallIndex): SnapshotEntry {
673
+ if (!isRecord(entry.data)) return entry
674
+ const childId = stringField(entry.data, 'childId')
675
+ if (childId === undefined || childId === '') return entry
676
+ const callId = spawns.spawnCallId(childId)
677
+ if (callId === undefined) return entry
678
+ return { ...entry, data: { ...entry.data, callId } }
679
+ }
680
+
372
681
  /**
373
682
  * Drop the entries of each turn that a protocol v1 client would not render.
374
683
  *
@@ -461,6 +770,43 @@ export function pageTurns(
461
770
  }
462
771
  }
463
772
 
773
+ /**
774
+ * Durable seq of a projection's oldest entry, or undefined when it carries none.
775
+ *
776
+ * The oldest entry is the first entry of the first turn that has one: a trimmed
777
+ * turn may keep no entry at all, so the scan skips those rather than reading
778
+ * `turns[0].entries[0]` and calling an empty-leading view an empty window.
779
+ * @param turns - the projection to read, in order.
780
+ */
781
+ export function oldestEntrySeq(turns: readonly SnapshotTurn[]): number | undefined {
782
+ for (const turn of turns) {
783
+ const first = turn.entries[0]
784
+ if (first !== undefined) return first.seq
785
+ }
786
+ return undefined
787
+ }
788
+
789
+ /**
790
+ * Cut a projection at a durable watermark, keeping what is strictly above it.
791
+ *
792
+ * This is the forward twin of {@link pageTurns}' own slice: the same
793
+ * entry-level rule (`seq` is a durable watermark, not an index), the same
794
+ * turn rebuild, so an incremental snapshot carries turns shaped exactly like
795
+ * the baseline it continues — a turn whose remaining entries are fewer keeps
796
+ * its own `seq`, `endSeq`, `reason` and `time`.
797
+ * @param turns - the projection to cut, in order.
798
+ * @param watermark - exclusive durable watermark; entries at or below it are dropped.
799
+ */
800
+ export function turnsAbove(turns: readonly SnapshotTurn[], watermark: number): SnapshotTurn[] {
801
+ const kept: { readonly turn: SnapshotTurn; readonly entry: SnapshotEntry }[] = []
802
+ for (const turn of turns) {
803
+ for (const entry of turn.entries) {
804
+ if (entry.seq > watermark) kept.push({ turn, entry })
805
+ }
806
+ }
807
+ return groupEntries(kept)
808
+ }
809
+
464
810
  /** Rebuild the turn list around one contiguous run of entries. */
465
811
  function groupEntries(items: readonly { readonly turn: SnapshotTurn; readonly entry: SnapshotEntry }[]): SnapshotTurn[] {
466
812
  const page: SnapshotTurn[] = []
@@ -482,5 +828,16 @@ function snapshotEntryOf(record: unknown): SnapshotEntry | undefined {
482
828
  const event = isRecord(record) ? record.event : undefined
483
829
  if (!isRecord(event)) return undefined
484
830
  if (typeof event.type !== 'string' || typeof event.seq !== 'number') return undefined
485
- return { seq: event.seq, time: typeof event.time === 'number' ? event.time : 0, type: event.type, data: event.data }
831
+ // A user message is the one entry that carries its actor: the delta and the
832
+ // baseline must report the same origin for the same message, and the entry's
833
+ // data stays the host's own record so a client written before actors existed
834
+ // still reads it unchanged.
835
+ const actor = event.type === 'user/message' ? actorOf(event.data) : undefined
836
+ return {
837
+ seq: event.seq,
838
+ time: typeof event.time === 'number' ? event.time : 0,
839
+ type: event.type,
840
+ data: event.data,
841
+ ...(actor === undefined ? {} : { actor }),
842
+ }
486
843
  }