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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +277 -2
  4. package/README.zh.md +276 -0
  5. package/cordis.patch.yml +17 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +1830 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +5789 -0
  10. package/lib/types/client/PairEntry.d.ts +16 -0
  11. package/lib/types/client/PairPanel.d.ts +55 -0
  12. package/lib/types/client/icons.d.ts +18 -0
  13. package/lib/types/client/index.d.ts +35 -0
  14. package/lib/types/client/locales.d.ts +42 -0
  15. package/lib/types/client/pair-token.d.ts +73 -0
  16. package/lib/types/client/semantic.d.ts +28 -0
  17. package/lib/types/core/approvals.d.ts +99 -0
  18. package/lib/types/core/connection.d.ts +170 -0
  19. package/lib/types/core/crypto.d.ts +48 -0
  20. package/lib/types/core/delta.d.ts +101 -0
  21. package/lib/types/core/devices.d.ts +72 -0
  22. package/lib/types/core/dsh-frames.d.ts +332 -0
  23. package/lib/types/core/envelope.d.ts +132 -0
  24. package/lib/types/core/extension.d.ts +144 -0
  25. package/lib/types/core/gateway-errors.d.ts +49 -0
  26. package/lib/types/core/hub.d.ts +127 -0
  27. package/lib/types/core/jobs.d.ts +204 -0
  28. package/lib/types/core/loopback.d.ts +35 -0
  29. package/lib/types/core/owner-peer.d.ts +49 -0
  30. package/lib/types/core/pairing.d.ts +61 -0
  31. package/lib/types/core/protocol.d.ts +319 -0
  32. package/lib/types/core/questions.d.ts +294 -0
  33. package/lib/types/core/session-meta.d.ts +105 -0
  34. package/lib/types/core/session-permissions.d.ts +134 -0
  35. package/lib/types/core/wire.d.ts +115 -0
  36. package/lib/types/core/ws-frames.d.ts +72 -0
  37. package/lib/types/host/dsh-home.d.ts +16 -0
  38. package/lib/types/host/pair-origin.d.ts +44 -0
  39. package/lib/types/host/routes.d.ts +27 -0
  40. package/lib/types/host/websocket.d.ts +111 -0
  41. package/lib/types/index.d.ts +55 -0
  42. package/lib/types/mount-once.d.ts +55 -0
  43. package/locale/en.json +6 -0
  44. package/locale/ru.json +6 -0
  45. package/locale/zh.json +6 -0
  46. package/package.json +93 -3
  47. package/src/client/PairEntry.tsx +151 -0
  48. package/src/client/PairPanel.tsx +183 -0
  49. package/src/client/icons.tsx +72 -0
  50. package/src/client/index.ts +81 -0
  51. package/src/client/locales.ts +72 -0
  52. package/src/client/pair-token.ts +104 -0
  53. package/src/client/panel.module.css +344 -0
  54. package/src/client/semantic.ts +37 -0
  55. package/src/core/approvals.ts +173 -0
  56. package/src/core/connection.ts +1906 -0
  57. package/src/core/crypto.ts +113 -0
  58. package/src/core/delta.ts +204 -0
  59. package/src/core/devices.ts +209 -0
  60. package/src/core/dsh-frames.ts +843 -0
  61. package/src/core/envelope.ts +219 -0
  62. package/src/core/extension.ts +197 -0
  63. package/src/core/gateway-errors.ts +92 -0
  64. package/src/core/hub.ts +310 -0
  65. package/src/core/jobs.ts +372 -0
  66. package/src/core/loopback.ts +60 -0
  67. package/src/core/owner-peer.ts +70 -0
  68. package/src/core/pairing.ts +113 -0
  69. package/src/core/protocol.ts +381 -0
  70. package/src/core/questions.ts +630 -0
  71. package/src/core/session-meta.ts +176 -0
  72. package/src/core/session-permissions.ts +266 -0
  73. package/src/core/wire.ts +159 -0
  74. package/src/core/ws-frames.ts +139 -0
  75. package/src/css-modules.d.ts +6 -0
  76. package/src/host/dsh-home.ts +42 -0
  77. package/src/host/pair-origin.ts +77 -0
  78. package/src/host/routes.ts +85 -0
  79. package/src/host/websocket.ts +359 -0
  80. package/src/index.ts +257 -0
  81. package/src/mount-once.ts +142 -0
@@ -0,0 +1,843 @@
1
+ /**
2
+ * DSH session frames to protocol v1 `session.delta` payloads, plus the reverse
3
+ * projection of a follow baseline into `session.snapshot` turns.
4
+ *
5
+ * Only frame SHAPES are read here, never DSH classes: the frame argument is
6
+ * `unknown` and every field is narrowed structurally, so a cohort that adds a
7
+ * field to a chunk cannot break the bridge and a cohort that renames one fails
8
+ * loudly at the mapping instead of emitting a half-filled delta.
9
+ * @module dsh-remote-bridge/core/dsh-frames
10
+ */
11
+
12
+ /** One image a durable `user/message` carried, as far as a client renders it. */
13
+ export interface UserMessageAttachment {
14
+ readonly attachmentId: string
15
+ readonly mediaType: string
16
+ readonly name?: string
17
+ }
18
+
19
+ /** Token usage one finished `assistant/message` reported, passed through unconverted. */
20
+ export interface MessageUsage {
21
+ readonly inputTokens: number
22
+ readonly outputTokens: number
23
+ readonly totalTokens?: number
24
+ readonly cacheReadTokens?: number
25
+ readonly cacheWriteTokens?: number
26
+ readonly reasoningTokens?: number
27
+ }
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
+
48
+ /** One protocol v1 delta, before the session id and event sequence are attached. */
49
+ export type SessionDelta =
50
+ | { readonly kind: 'text'; readonly text: string; readonly blockIndex: number }
51
+ | { readonly kind: 'reasoning'; readonly text: string; readonly blockIndex: number }
52
+ | { readonly kind: 'tool-call'; readonly callId: string; readonly name: string; readonly argumentsDelta: string }
53
+ | { readonly kind: 'tool-result'; readonly callId: string; readonly output: string; readonly isError: boolean }
54
+ | { readonly kind: 'turn-end'; readonly reason: string }
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 }
57
+ | { readonly kind: 'usage'; readonly usage: MessageUsage; readonly turn?: number; readonly step?: number }
58
+
59
+ /** Highest number of tool calls one connection remembers by id. */
60
+ export const TOOL_CALL_MEMORY = 512
61
+ /** Highest number of published user messages one connection remembers by id. */
62
+ export const USER_MESSAGE_MEMORY = 512
63
+
64
+ /**
65
+ * The durable entry types a protocol v1 client renders — `user/message`,
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.
76
+ */
77
+ export const RENDERED_ENTRY_TYPES: ReadonlySet<string> = new Set([
78
+ 'user/message',
79
+ 'assistant/message',
80
+ 'tool/call',
81
+ 'tool/result',
82
+ 'subagent/catalog',
83
+ ])
84
+
85
+ /** One raw durable event inside a snapshot turn. */
86
+ export interface SnapshotEntry {
87
+ readonly seq: number
88
+ readonly time: number
89
+ readonly type: string
90
+ readonly data: unknown
91
+ /** Where a `user/message` came from; absent on every other entry type. */
92
+ readonly actor?: MessageActor
93
+ }
94
+
95
+ /** One turn of a session snapshot: the durable events from `turn/start` to `turn/end`. */
96
+ export interface SnapshotTurn {
97
+ /** Seq of the `turn/start` event, or 0 for the lead-in before the first turn. */
98
+ readonly seq: number
99
+ readonly time: number
100
+ /** Seq of the `turn/end` event, or 0 while the turn is still open. */
101
+ readonly endSeq: number
102
+ readonly endTime: number
103
+ /** `turn/end` reason kind, or the empty string while the turn is open. */
104
+ readonly reason: string
105
+ readonly entries: readonly SnapshotEntry[]
106
+ }
107
+
108
+ /** The opening frame of a `session/follow` stream. */
109
+ export interface FollowBaseline {
110
+ readonly cursor: number
111
+ readonly records: readonly unknown[]
112
+ readonly hasMore: boolean
113
+ }
114
+
115
+ function isRecord(value: unknown): value is Record<string, unknown> {
116
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
117
+ }
118
+
119
+ function stringField(value: unknown, key: string): string | undefined {
120
+ if (!isRecord(value)) return undefined
121
+ const field = value[key]
122
+ return typeof field === 'string' ? field : undefined
123
+ }
124
+
125
+ /**
126
+ * Remembers which tool calls have already streamed their arguments, so the
127
+ * durable `tool/call` event that follows the stream is not replayed as a second
128
+ * copy of the same arguments. Bounded: a long-lived connection must not grow
129
+ * with every call it ever saw.
130
+ */
131
+ export class ToolCallIndex {
132
+ readonly #names = new Map<string, string>()
133
+
134
+ /** @returns whether this call already contributed a delta. */
135
+ has(callId: string): boolean {
136
+ return this.#names.has(callId)
137
+ }
138
+
139
+ /** @returns the last name seen for this call, if any. */
140
+ nameOf(callId: string): string | undefined {
141
+ return this.#names.get(callId)
142
+ }
143
+
144
+ /** Remember one call, evicting the oldest entry past {@link TOOL_CALL_MEMORY}. */
145
+ remember(callId: string, name: string): void {
146
+ if (name !== '') this.#names.set(callId, name)
147
+ else if (!this.#names.has(callId)) this.#names.set(callId, '')
148
+ while (this.#names.size > TOOL_CALL_MEMORY) {
149
+ const oldest = this.#names.keys().next()
150
+ if (oldest.done === true) break
151
+ this.#names.delete(oldest.value)
152
+ }
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Remembers which durable user messages this connection already published.
158
+ *
159
+ * A client only ever appends a transcript, so one durable `user/message` must
160
+ * reach the wire once: a replayed event would draw the same prompt a second
161
+ * time. Bounded for the same reason {@link ToolCallIndex} is — a long-lived
162
+ * connection must not grow with every message it ever saw.
163
+ */
164
+ export class MessageIndex {
165
+ readonly #ids = new Set<string>()
166
+
167
+ /** @returns whether this message already contributed a delta. */
168
+ has(id: string): boolean {
169
+ return this.#ids.has(id)
170
+ }
171
+
172
+ /** Remember one message, evicting the oldest entry past {@link USER_MESSAGE_MEMORY}. */
173
+ remember(id: string): void {
174
+ this.#ids.add(id)
175
+ while (this.#ids.size > USER_MESSAGE_MEMORY) {
176
+ const oldest = this.#ids.values().next()
177
+ if (oldest.done === true) break
178
+ this.#ids.delete(oldest.value)
179
+ }
180
+ }
181
+ }
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
+
351
+ /**
352
+ * Read the opening frame of a follow stream.
353
+ * @returns the cursor and records, or undefined when this frame is not a snapshot.
354
+ */
355
+ export function readFollowBaseline(frame: unknown): FollowBaseline | undefined {
356
+ if (!isRecord(frame) || frame.type !== 'snapshot') return undefined
357
+ const cursor = frame.cursor
358
+ const records = frame.records
359
+ if (typeof cursor !== 'number' || !Array.isArray(records)) return undefined
360
+ return { cursor, records, hasMore: frame.hasMore === true }
361
+ }
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
+
371
+ /**
372
+ * Map one DSH follow frame to a delta, or undefined when the frame carries no
373
+ * increment this protocol publishes.
374
+ * @param frame - one `SessionFollowFrame`.
375
+ * @param toolCalls - this connection's tool-call memory.
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.
378
+ */
379
+ export function deltaOfFollowFrame(
380
+ frame: unknown,
381
+ toolCalls: ToolCallIndex,
382
+ messages: MessageIndex,
383
+ memory: FollowMemory = {},
384
+ ): SessionDelta | undefined {
385
+ if (!isRecord(frame)) return undefined
386
+ if (frame.type === 'assistant-stream') return deltaOfAssistantStream(frame.frame, toolCalls)
387
+ if (frame.type !== 'event') return undefined
388
+ const event = frame.event
389
+ if (!isRecord(event)) return undefined
390
+ const type = event.type
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)
395
+ if (type === 'tool/result') return toolResultDelta(data)
396
+ if (type === 'turn/end') return turnEndDelta(data)
397
+ if (type === 'tool/call') return assembledToolCallDelta(data, toolCalls)
398
+ if (type === 'user/message') return userMessageDelta(data, messages)
399
+ if (type === 'assistant/message') return usageDelta(data)
400
+ if (type === 'subagent/catalog') return memory.subagentThread === true ? subagentDelta(data, memory.spawnCalls) : undefined
401
+ return undefined
402
+ }
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
+
464
+ function deltaOfAssistantStream(frame: unknown, toolCalls: ToolCallIndex): SessionDelta | undefined {
465
+ if (!isRecord(frame) || frame.type !== 'chunk') return undefined
466
+ const chunk = frame.chunk
467
+ if (!isRecord(chunk)) return undefined
468
+ const index = typeof chunk.index === 'number' ? chunk.index : 0
469
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
470
+ return { kind: 'text', text: chunk.text, blockIndex: index }
471
+ }
472
+ if (chunk.type === 'reasoning-delta' && typeof chunk.text === 'string') {
473
+ return { kind: 'reasoning', text: chunk.text, blockIndex: index }
474
+ }
475
+ if (chunk.type === 'tool-call-delta' && typeof chunk.id === 'string' && chunk.id !== '') {
476
+ const callId = chunk.id
477
+ const announced = typeof chunk.name === 'string' && chunk.name !== '' ? chunk.name : undefined
478
+ const name = announced ?? toolCalls.nameOf(callId) ?? ''
479
+ toolCalls.remember(callId, name)
480
+ return { kind: 'tool-call', callId, name, argumentsDelta: typeof chunk.argumentsDelta === 'string' ? chunk.argumentsDelta : '' }
481
+ }
482
+ return undefined
483
+ }
484
+
485
+ function toolResultDelta(data: unknown): SessionDelta | undefined {
486
+ const message = isRecord(data) ? data.message : undefined
487
+ if (!isRecord(message)) return undefined
488
+ const callId = message.toolCallId
489
+ if (typeof callId !== 'string' || callId === '') return undefined
490
+ return { kind: 'tool-result', callId, output: textOfBlocks(message.content), isError: message.isError === true }
491
+ }
492
+
493
+ function turnEndDelta(data: unknown): SessionDelta | undefined {
494
+ const reason = isRecord(data) ? data.reason : undefined
495
+ const kind = isRecord(reason) ? reason.kind : undefined
496
+ // An unreadable reason is reported as such: the client treats every non-
497
+ // `completed` value as an abnormal end, and `unknown` is the truth here.
498
+ return { kind: 'turn-end', reason: typeof kind === 'string' ? kind : 'unknown' }
499
+ }
500
+
501
+ /**
502
+ * The durable `tool/call` event carries the WHOLE argument string, not an
503
+ * increment, so it is published as a delta only when the connection never saw
504
+ * this call's increments — otherwise the client would append the arguments a
505
+ * second time.
506
+ */
507
+ function assembledToolCallDelta(data: unknown, toolCalls: ToolCallIndex): SessionDelta | undefined {
508
+ const callId = stringField(data, 'callId')
509
+ if (callId === undefined || callId === '') return undefined
510
+ if (toolCalls.has(callId)) return undefined
511
+ const name = stringField(data, 'name') ?? ''
512
+ toolCalls.remember(callId, name)
513
+ return { kind: 'tool-call', callId, name, argumentsDelta: stringField(data, 'arguments') ?? '' }
514
+ }
515
+
516
+ /** Flatten a message's model-facing blocks to display text; non-text blocks are dropped. */
517
+ function textOfBlocks(content: unknown): string {
518
+ if (!Array.isArray(content)) return ''
519
+ const parts: string[] = []
520
+ for (const block of content) {
521
+ if (!isRecord(block)) continue
522
+ if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
523
+ }
524
+ return parts.join('\n')
525
+ }
526
+
527
+ /**
528
+ * Map one durable `user/message` to the increment that shows it on a subscribed
529
+ * phone, so a prompt typed on the desktop appears without a baseline reload.
530
+ *
531
+ * Published once per message id: a replayed event must not draw the message a
532
+ * second time. The text is the message's text blocks and nothing else — image
533
+ * and file blocks travel in `attachments`, never inside it.
534
+ */
535
+ function userMessageDelta(data: unknown, messages: MessageIndex): SessionDelta | undefined {
536
+ if (!isRecord(data)) return undefined
537
+ const messageId = stringField(data, 'id')
538
+ if (messageId !== undefined) {
539
+ if (messages.has(messageId)) return undefined
540
+ messages.remember(messageId)
541
+ }
542
+ const attachments = imageAttachmentsOf(data.content)
543
+ const actor = actorOf(data)
544
+ return {
545
+ kind: 'user-message',
546
+ text: textOfBlocks(data.content),
547
+ ...(messageId === undefined ? {} : { messageId }),
548
+ ...(attachments.length === 0 ? {} : { attachments }),
549
+ ...(actor === undefined ? {} : { actor }),
550
+ }
551
+ }
552
+
553
+ /**
554
+ * The image references of one message's blocks, in content order.
555
+ *
556
+ * A durable image block nests its immutable reference under the block's own
557
+ * `attachment` key, so the id and media type are read from the reference — the
558
+ * block itself carries only its type and, once offloaded, that flag.
559
+ */
560
+ function imageAttachmentsOf(content: unknown): UserMessageAttachment[] {
561
+ if (!Array.isArray(content)) return []
562
+ const attachments: UserMessageAttachment[] = []
563
+ for (const block of content) {
564
+ if (!isRecord(block) || block.type !== 'image') continue
565
+ const ref = block.attachment
566
+ if (!isRecord(ref)) continue
567
+ const attachmentId = stringField(ref, 'attachmentId')
568
+ const mediaType = stringField(ref, 'mediaType')
569
+ if (attachmentId === undefined || mediaType === undefined) continue
570
+ const name = stringField(ref, 'name')
571
+ attachments.push({ attachmentId, mediaType, ...(name === undefined || name === '' ? {} : { name }) })
572
+ }
573
+ return attachments
574
+ }
575
+
576
+ /**
577
+ * Map one finished `assistant/message` to its usage increment, or to nothing.
578
+ *
579
+ * An event without `usage` publishes NO delta: absent is not zero, and a client
580
+ * must never record a token count the harness did not report.
581
+ */
582
+ function usageDelta(data: unknown): SessionDelta | undefined {
583
+ if (!isRecord(data)) return undefined
584
+ const usage = usageOf(data.usage)
585
+ if (usage === undefined) return undefined
586
+ const turn = numberOf(data.turn)
587
+ const step = numberOf(data.step)
588
+ return { kind: 'usage', usage, ...(turn === undefined ? {} : { turn }), ...(step === undefined ? {} : { step }) }
589
+ }
590
+
591
+ /** Read one `TokenUsage` verbatim; undefined when its two mandatory counters are not numbers. */
592
+ function usageOf(value: unknown): MessageUsage | undefined {
593
+ if (!isRecord(value)) return undefined
594
+ const inputTokens = numberOf(value.inputTokens)
595
+ const outputTokens = numberOf(value.outputTokens)
596
+ if (inputTokens === undefined || outputTokens === undefined) return undefined
597
+ const totalTokens = numberOf(value.totalTokens)
598
+ const cacheReadTokens = numberOf(value.cacheReadTokens)
599
+ const cacheWriteTokens = numberOf(value.cacheWriteTokens)
600
+ const reasoningTokens = numberOf(value.reasoningTokens)
601
+ return {
602
+ inputTokens,
603
+ outputTokens,
604
+ ...(totalTokens === undefined ? {} : { totalTokens }),
605
+ ...(cacheReadTokens === undefined ? {} : { cacheReadTokens }),
606
+ ...(cacheWriteTokens === undefined ? {} : { cacheWriteTokens }),
607
+ ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
608
+ }
609
+ }
610
+
611
+ /** @returns a finite number field, or undefined. */
612
+ function numberOf(value: unknown): number | undefined {
613
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
614
+ }
615
+
616
+ /**
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.
623
+ * @param records - the baseline's durable records, oldest first.
624
+ * @returns one turn per `turn/start`, plus a lead-in turn when records precede the first one.
625
+ */
626
+ export function turnsOfRecords(records: readonly unknown[]): SnapshotTurn[] {
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))
632
+ let current: { seq: number; time: number; endSeq: number; endTime: number; reason: string; entries: SnapshotEntry[] } | undefined
633
+ for (const record of records) {
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
638
+ if (entry.type === 'turn/start' && current !== undefined && current.endSeq === 0) {
639
+ // A previous turn never ended (an aborted resume): its tail stays with it.
640
+ turns.push(current)
641
+ current = undefined
642
+ }
643
+ if (current === undefined) {
644
+ current = { seq: entry.type === 'turn/start' ? entry.seq : 0, time: entry.time, endSeq: 0, endTime: 0, reason: '', entries: [] }
645
+ }
646
+ current.entries.push(entry)
647
+ if (entry.type === 'turn/end') {
648
+ current.endSeq = entry.seq
649
+ current.endTime = entry.time
650
+ current.reason = isRecord(entry.data) && isRecord(entry.data.reason) && typeof entry.data.reason.kind === 'string'
651
+ ? entry.data.reason.kind
652
+ : 'unknown'
653
+ turns.push(current)
654
+ current = undefined
655
+ }
656
+ }
657
+ if (current !== undefined && current.entries.length > 0) turns.push(current)
658
+ return turns
659
+ }
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
+
681
+ /**
682
+ * Drop the entries of each turn that a protocol v1 client would not render.
683
+ *
684
+ * Only the inside of a turn changes: which turns survive, their order, their
685
+ * `seq`/`endSeq` metadata and every kept entry's `type` and `data` are the
686
+ * projection's own output. A turn whose entries are all unrenderable stays as a
687
+ * turn with an empty `entries` array, so the client never sees a shape it does
688
+ * not know how to read.
689
+ * @param turns - the projection of a follow baseline, in order.
690
+ * @returns the same turns, each carrying only its rendered entries.
691
+ */
692
+ export function trimUnrenderedEntries(turns: readonly SnapshotTurn[]): SnapshotTurn[] {
693
+ return turns.map(turn => {
694
+ const entries = turn.entries.filter(entry => RENDERED_ENTRY_TYPES.has(entry.type))
695
+ return entries.length === turn.entries.length ? turn : { ...turn, entries }
696
+ })
697
+ }
698
+
699
+ /** One contiguous backwards page of a snapshot projection. */
700
+ export interface SnapshotPage {
701
+ /** The turns this page carries, oldest first; each keeps its own turn-level fields. */
702
+ readonly turns: SnapshotTurn[]
703
+ /** Durable seq of this page's oldest entry: the cursor for the next, older page. */
704
+ readonly nextBefore?: number
705
+ readonly hasMore: boolean
706
+ }
707
+
708
+ /**
709
+ * Slice one backwards page out of a projection, BY ENTRY rather than by turn.
710
+ *
711
+ * `before` is a durable watermark, not an index: the page carries the newest
712
+ * entries whose `seq` is strictly below it, so a cursor stays meaningful across
713
+ * connections and a projection that changed shape under it (a trimmed entry
714
+ * that never reaches the client) cannot make a page skip or repeat data. The
715
+ * turn list is rebuilt around exactly the entries in the page, each turn
716
+ * keeping its own `seq`/`endSeq`/`reason`, so a turn may be split across pages.
717
+ *
718
+ * A single entry that exceeds the budget on its own is a page of its own: the
719
+ * size rule never removes an entry, it only ends the page.
720
+ * @param turns - the projection to page, in order.
721
+ * @param before - exclusive durable watermark, or undefined for the newest page.
722
+ * @param maxBytes - byte budget of the encoded page.
723
+ * @param measure - exact encoded size of one page shape, owned by the caller.
724
+ */
725
+ export function pageTurns(
726
+ turns: readonly SnapshotTurn[],
727
+ before: number | undefined,
728
+ maxBytes: number,
729
+ measure: (turns: readonly SnapshotTurn[], nextBefore: number | undefined, hasMore: boolean) => number,
730
+ ): SnapshotPage {
731
+ const flat: { readonly turn: SnapshotTurn; readonly entry: SnapshotEntry }[] = []
732
+ for (const turn of turns) {
733
+ for (const entry of turn.entries) {
734
+ if (before === undefined || entry.seq < before) flat.push({ turn, entry })
735
+ }
736
+ }
737
+ if (flat.length === 0) return { turns: [], hasMore: false }
738
+
739
+ const shells = new Map<SnapshotTurn, number>()
740
+ for (const item of flat) {
741
+ if (!shells.has(item.turn)) shells.set(item.turn, Buffer.byteLength(JSON.stringify({ ...item.turn, entries: [] }), 'utf8'))
742
+ }
743
+ // Greedy from the newest entry on a conservative running estimate — every
744
+ // entry and every contributing turn shell counted once — and then verified
745
+ // against the real encoding, shrinking from the oldest side until it fits.
746
+ let start = flat.length
747
+ let estimate = 0
748
+ const counted = new Set<SnapshotTurn>()
749
+ for (let index = flat.length - 1; index >= 0; index -= 1) {
750
+ const item = flat[index]
751
+ if (item === undefined) break
752
+ let cost = Buffer.byteLength(JSON.stringify(item.entry), 'utf8') + 1
753
+ if (!counted.has(item.turn)) {
754
+ counted.add(item.turn)
755
+ cost += shells.get(item.turn) ?? 0
756
+ }
757
+ if (start < flat.length && estimate + cost > maxBytes) break
758
+ estimate += cost
759
+ start = index
760
+ }
761
+ for (;;) {
762
+ const oldest = flat[start]?.entry.seq
763
+ if (oldest === undefined) return { turns: [], hasMore: false }
764
+ const page = groupEntries(flat.slice(start))
765
+ const hasMore = start > 0
766
+ if (flat.length - start === 1 || measure(page, hasMore ? oldest : undefined, hasMore) <= maxBytes) {
767
+ return hasMore ? { turns: page, nextBefore: oldest, hasMore } : { turns: page, hasMore }
768
+ }
769
+ start += 1
770
+ }
771
+ }
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
+
810
+ /** Rebuild the turn list around one contiguous run of entries. */
811
+ function groupEntries(items: readonly { readonly turn: SnapshotTurn; readonly entry: SnapshotEntry }[]): SnapshotTurn[] {
812
+ const page: SnapshotTurn[] = []
813
+ let current: SnapshotTurn | undefined
814
+ let entries: SnapshotEntry[] = []
815
+ for (const item of items) {
816
+ if (current !== item.turn) {
817
+ if (current !== undefined) page.push({ ...current, entries })
818
+ current = item.turn
819
+ entries = []
820
+ }
821
+ entries.push(item.entry)
822
+ }
823
+ if (current !== undefined) page.push({ ...current, entries })
824
+ return page
825
+ }
826
+
827
+ function snapshotEntryOf(record: unknown): SnapshotEntry | undefined {
828
+ const event = isRecord(record) ? record.event : undefined
829
+ if (!isRecord(event)) return undefined
830
+ if (typeof event.type !== 'string' || typeof event.seq !== 'number') return undefined
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
+ }
843
+ }