@linxin666/dsh-remote-bridge 0.4.7 → 0.4.9

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 (78) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +93 -26
  3. package/README.zh.md +91 -26
  4. package/icon.svg +3 -0
  5. package/lib/client.js +274 -253
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +8891 -2433
  8. package/lib/types/client/PairEntry.d.ts +2 -2
  9. package/lib/types/client/PairPanel.d.ts +10 -2
  10. package/lib/types/client/icons.d.ts +5 -13
  11. package/lib/types/client/locales.d.ts +10 -14
  12. package/lib/types/client/semantic.d.ts +9 -5
  13. package/lib/types/core/approvals.d.ts +24 -0
  14. package/lib/types/core/commands.d.ts +59 -0
  15. package/lib/types/core/connection.d.ts +124 -5
  16. package/lib/types/core/delta.d.ts +101 -0
  17. package/lib/types/core/devices.d.ts +98 -2
  18. package/lib/types/core/dsh-frames.d.ts +155 -4
  19. package/lib/types/core/envelope.d.ts +34 -0
  20. package/lib/types/core/extension.d.ts +144 -0
  21. package/lib/types/core/hub.d.ts +96 -20
  22. package/lib/types/core/jobs.d.ts +204 -0
  23. package/lib/types/core/liveactivity.d.ts +324 -0
  24. package/lib/types/core/protocol.d.ts +491 -2
  25. package/lib/types/core/push.d.ts +178 -0
  26. package/lib/types/core/questions.d.ts +109 -9
  27. package/lib/types/core/session-meta.d.ts +55 -1
  28. package/lib/types/core/squads.d.ts +130 -0
  29. package/lib/types/core/usage-stats.d.ts +160 -0
  30. package/lib/types/core/usage.d.ts +294 -0
  31. package/lib/types/core/wire.d.ts +1 -1
  32. package/lib/types/core/ws-frames.d.ts +11 -0
  33. package/lib/types/host/apns.d.ts +151 -0
  34. package/lib/types/host/squads-ledger.d.ts +39 -0
  35. package/lib/types/host/squads.d.ts +77 -0
  36. package/lib/types/host/usage-stats.d.ts +75 -0
  37. package/lib/types/host/watchers.d.ts +88 -0
  38. package/lib/types/host/websocket.d.ts +8 -1
  39. package/lib/types/index.d.ts +34 -3
  40. package/lib/types/mount-once.d.ts +55 -0
  41. package/locale/en.json +6 -0
  42. package/locale/ru.json +6 -0
  43. package/locale/zh.json +6 -0
  44. package/package.json +20 -14
  45. package/src/client/PairEntry.tsx +58 -31
  46. package/src/client/PairPanel.tsx +181 -97
  47. package/src/client/icons.tsx +17 -60
  48. package/src/client/locales.ts +15 -23
  49. package/src/client/panel.module.css +239 -186
  50. package/src/client/semantic.ts +10 -6
  51. package/src/core/approvals.ts +32 -1
  52. package/src/core/commands.ts +95 -0
  53. package/src/core/connection.ts +1483 -31
  54. package/src/core/delta.ts +204 -0
  55. package/src/core/devices.ts +221 -3
  56. package/src/core/dsh-frames.ts +365 -8
  57. package/src/core/envelope.ts +46 -0
  58. package/src/core/extension.ts +197 -0
  59. package/src/core/hub.ts +441 -49
  60. package/src/core/jobs.ts +372 -0
  61. package/src/core/liveactivity.ts +833 -0
  62. package/src/core/protocol.ts +556 -2
  63. package/src/core/push.ts +354 -0
  64. package/src/core/questions.ts +264 -17
  65. package/src/core/session-meta.ts +73 -1
  66. package/src/core/squads.ts +345 -0
  67. package/src/core/usage-stats.ts +424 -0
  68. package/src/core/usage.ts +937 -0
  69. package/src/core/wire.ts +13 -1
  70. package/src/core/ws-frames.ts +14 -0
  71. package/src/host/apns.ts +320 -0
  72. package/src/host/squads-ledger.ts +105 -0
  73. package/src/host/squads.ts +206 -0
  74. package/src/host/usage-stats.ts +155 -0
  75. package/src/host/watchers.ts +272 -0
  76. package/src/host/websocket.ts +37 -3
  77. package/src/index.ts +310 -9
  78. package/src/mount-once.ts +142 -0
@@ -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
  }
@@ -20,9 +20,17 @@
20
20
  * @module dsh-remote-bridge/core/envelope
21
21
  */
22
22
 
23
+ import { deflateRawSync } from 'node:zlib'
24
+
23
25
  /** Largest single text frame either direction may carry, in UTF-8 bytes: 10 MiB. */
24
26
  export const MAX_FRAME_BYTES = 10 * 1024 * 1024
25
27
 
28
+ /**
29
+ * Smallest frame the host compresses, in UTF-8 bytes. Below it the DEFLATE
30
+ * header alone can outweigh a small object, so such a frame is never even tried.
31
+ */
32
+ export const FRAME_DEFLATE_MIN_BYTES = 1024
33
+
26
34
  /** Reserved response id for a frame whose own id could not be recovered. */
27
35
  export const UNIDENTIFIED_FRAME_ID = 0
28
36
 
@@ -141,6 +149,44 @@ export function encodeFrame(frame: ServerFrame): string {
141
149
  return JSON.stringify(frame)
142
150
  }
143
151
 
152
+ /**
153
+ * How one encoded frame crosses the wire: as the text the codec produced, or as
154
+ * raw DEFLATE of exactly that text.
155
+ */
156
+ export type OutboundPayload =
157
+ | { readonly binary: false; readonly text: string }
158
+ | { readonly binary: true; readonly deflated: Buffer }
159
+
160
+ /**
161
+ * Decide the wire form of one encoded frame.
162
+ *
163
+ * The decision is a byte-level question only, asked after the frame has been
164
+ * measured against {@link MAX_FRAME_BYTES}: the text is deflated exactly as it
165
+ * stands, so a peer that inflates gets back the frame the text path would have
166
+ * written. A frame below {@link FRAME_DEFLATE_MIN_BYTES}, and a frame DEFLATE
167
+ * does not shrink (zlib's default level), both stay text — a binary frame that
168
+ * is larger than the text it replaces would pay for itself in neither direction.
169
+ * @param text - the frame as {@link encodeFrame} produced it.
170
+ * @param compress - whether the peer declared the capability that permits this.
171
+ * @param deflate - the compressor: zlib's raw DEFLATE at its default level, unless
172
+ * a caller injects one. Real deflate shrinks every frame that reaches the
173
+ * threshold, so an injected compressor is the only way to exercise the no-gain
174
+ * rule with content that truly cannot be compressed.
175
+ * @returns the text, or raw DEFLATE of it.
176
+ */
177
+ export function outboundPayloadOf(
178
+ text: string,
179
+ compress: boolean,
180
+ deflate: (source: Buffer) => Buffer = deflateRawSync,
181
+ ): OutboundPayload {
182
+ if (!compress) return { binary: false, text }
183
+ const source = Buffer.from(text, 'utf8')
184
+ if (source.length < FRAME_DEFLATE_MIN_BYTES) return { binary: false, text }
185
+ const deflated = deflate(source)
186
+ if (deflated.length >= source.length) return { binary: false, text }
187
+ return { binary: true, deflated }
188
+ }
189
+
144
190
  /** One successful response frame. */
145
191
  export function responseFrame(id: number, result: unknown): ResFrame {
146
192
  return { t: 'res', id, ok: true, r: result }