@silverprotocol/core 0.12.5 → 1.0.0-rc.2

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 (54) hide show
  1. package/README.md +17 -9
  2. package/dist/agjson.d.ts +594 -594
  3. package/dist/agjson.d.ts.map +1 -1
  4. package/dist/agjson.js +25 -14
  5. package/dist/agjson.js.map +1 -1
  6. package/dist/atomic-push.d.ts +15 -9
  7. package/dist/atomic-push.d.ts.map +1 -1
  8. package/dist/atomic-push.js +16 -5
  9. package/dist/atomic-push.js.map +1 -1
  10. package/dist/copy-json.d.ts +27 -4
  11. package/dist/copy-json.d.ts.map +1 -1
  12. package/dist/copy-json.js +135 -1
  13. package/dist/copy-json.js.map +1 -1
  14. package/dist/depth.d.ts +0 -8
  15. package/dist/depth.d.ts.map +1 -1
  16. package/dist/depth.js +0 -9
  17. package/dist/depth.js.map +1 -1
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/ingest.d.ts +2 -2
  23. package/dist/ingest.js +4 -4
  24. package/dist/ingest.js.map +1 -1
  25. package/dist/json-patch.d.ts.map +1 -1
  26. package/dist/json-patch.js +5 -1
  27. package/dist/json-patch.js.map +1 -1
  28. package/dist/persist.js.map +1 -1
  29. package/dist/record.js +2 -2
  30. package/dist/record.js.map +1 -1
  31. package/dist/reduce.d.ts +1 -1
  32. package/dist/reduce.d.ts.map +1 -1
  33. package/dist/reduce.js +277 -113
  34. package/dist/reduce.js.map +1 -1
  35. package/dist/stream-assembler.d.ts +6 -7
  36. package/dist/stream-assembler.d.ts.map +1 -1
  37. package/dist/stream-assembler.js +21 -18
  38. package/dist/stream-assembler.js.map +1 -1
  39. package/dist/wire.d.ts +21 -3
  40. package/dist/wire.d.ts.map +1 -1
  41. package/dist/wire.js +34 -5
  42. package/dist/wire.js.map +1 -1
  43. package/package.json +1 -1
  44. package/src/agjson.ts +36 -25
  45. package/src/atomic-push.ts +25 -13
  46. package/src/copy-json.ts +132 -4
  47. package/src/depth.ts +0 -10
  48. package/src/index.ts +1 -0
  49. package/src/ingest.ts +4 -4
  50. package/src/json-patch.ts +5 -1
  51. package/src/record.ts +2 -2
  52. package/src/reduce.ts +256 -112
  53. package/src/stream-assembler.ts +21 -18
  54. package/src/wire.ts +36 -6
package/src/reduce.ts CHANGED
@@ -14,7 +14,9 @@ import type {
14
14
  } from "./agjson.js";
15
15
  import { REMOVE_ALL } from "./agjson.js";
16
16
  import { applyPatch } from "./json-patch.js";
17
- import { AG_EVENT_MAX_DEPTH, exceedsDepth, scanDepth } from "./depth.js";
17
+ import { deleteOwnProtoMember, withoutOwnProtoMember } from "./copy-json.js";
18
+ import { exceedsDepth, scanDepth } from "./depth.js";
19
+ import { AG_EVENT_MAX_DEPTH } from "./wire.js";
18
20
 
19
21
  // ─────────────────────────────────────────────────────────────────────────────
20
22
  // Reducer — the normative event→state fold (spec §5).
@@ -135,10 +137,10 @@ export class Reducer {
135
137
  // Message ids sealed by message.end.
136
138
  #sealed: Set<string> = new Set();
137
139
  // turnIds legitimately opened via turn.start / subagent.start (or restored
138
- // by a messages.snapshot's turns?) — Task 8c leg 3 (guuey capstone finding
139
- // B). Distinguishes "a real turn genuinely exists" from a turn the fold only
140
- // knows by name, so the tool.done adoption CREATE path degrades loudly
141
- // (resync) instead of creating a message for a turn that was never opened.
140
+ // by a messages.snapshot's turns?). Distinguishes "a real turn genuinely
141
+ // exists" from a turn the fold only knows by name, so the tool.done adoption
142
+ // CREATE path degrades loudly (resync) instead of creating a message for a
143
+ // turn that was never opened.
142
144
  #openedTurns: Set<string> = new Set();
143
145
  // draft.4 §5.0 INV-OWNER: every
144
146
  // turnId the fold has seen opened — by turn.start, by subagent.start, or by a
@@ -150,15 +152,28 @@ export class Reducer {
150
152
  // #openedTurns (tool.done adoption) and never rebuilt from #turns, whose
151
153
  // records non-terminal arms may have minted as stubs.
152
154
  #seenOpened: Map<string, string | undefined> = new Map();
155
+ // §5 `subagent.start` row (rc.1): the fold's root thread — the first threadId a
156
+ // folded turn.start, message.start, artifact.start or messages.snapshot carried.
157
+ // A nested turn whose parent's thread is not known takes it.
158
+ #rootThread: string | undefined;
159
+ // Nested turns a `subagent.start` opened while neither the parent's thread nor
160
+ // the root thread was known: turnId → parentTurnId. Each one's record is held in
161
+ // #held (result() omits it) until one of the two becomes known (#releaseHeldNested).
162
+ #heldNested: Map<string, string> = new Map();
153
163
  // draft.5 §5.0 INV-OWNER (a held record lands on its own turn's thread): the landings of
154
164
  // the six record events (source, handoff, prompt.blocked, guardrail.result,
155
165
  // display.required, agent.capabilities) for a turn whose thread the fold does
156
166
  // not know yet. Each is a turn record result() never shows; it moves into
157
167
  // #turns on the turn's thread once a turn.start, subagent.start, message.start
158
168
  // or messages.snapshot makes that thread known (#adoptHeld). `landings` counts
159
- // the events held on it, for the implementation bound below.
160
- #held: Map<string, { record: AgTurnRecord; landings: number }> = new Map();
169
+ // the record events held on it other than display.required, `dr` the
170
+ // display.required ones, each against its own implementation bound below: a
171
+ // display.required is never discarded, so it survives a turns-carrying
172
+ // snapshot, and counting it apart keeps it from filling the bound the other
173
+ // five landings recover through that snapshot.
174
+ #held: Map<string, { record: AgTurnRecord; landings: number; dr: number }> = new Map();
161
175
  #heldLandings = 0;
176
+ #heldDrLandings = 0;
162
177
  // draft.5 §5.0 INV-MSG (the paused refresh): closed turns a turn.start has
163
178
  // named since their last terminal folded. Only such a turn, closed paused,
164
179
  // takes a turn.done{paused}; every terminal that folds removes its id. A
@@ -194,10 +209,11 @@ export class Reducer {
194
209
  */
195
210
  push(ev: AgEvent): void {
196
211
  // One pass before anything reads the event: whether a node sits deeper
197
- // than AG_EVENT_MAX_DEPTH. A too-deep event occupies its seq slot like any
198
- // other and is folded no further: copying it, or patching the state with
199
- // it, would overflow the stack. A consuming ingest never yields one; it
200
- // stubs such a frame.
212
+ // than AG_EVENT_MAX_DEPTH, and whether an own `__proto__` member is held
213
+ // (the delete walk below runs only on an event that holds one). A
214
+ // too-deep event occupies its seq slot like any other and is folded no
215
+ // further: copying it, or patching the state with it, would overflow the
216
+ // stack. A consuming ingest never yields one; it stubs such a frame.
201
217
  const scan = scanDepth(ev, AG_EVENT_MAX_DEPTH);
202
218
 
203
219
  // ── Seq-gap detection (R9) ────────────────────────────────────────────────
@@ -207,7 +223,7 @@ export class Reducer {
207
223
  // other live-only events). This must run BEFORE the isClosedEvent skip
208
224
  // below: an ext/live-only event between two closed events still occupies a
209
225
  // seq slot, so skipping it here would let the NEXT closed event look like
210
- // a forward gap that never happened (found by M46 review — the false-park
226
+ // a forward gap that never happened (found in review — the false-park
211
227
  // this fixes voided every fold with an ext emission between closed events).
212
228
  // After the first event (#lastSeq >= 0), a forward gap sets #resync (park)
213
229
  // — including when an ext/live-only event is the one revealing the gap.
@@ -251,10 +267,21 @@ export class Reducer {
251
267
  // It runs before the ext guard below, which then narrows the copy. An event
252
268
  // structuredClone cannot copy (a function-valued field) folds as pushed, as
253
269
  // it always did, rather than throwing out of push().
270
+ //
271
+ // §13.7: the fold omits an own `__proto__` member at every depth of every
272
+ // event it folds. On the clone the walk deletes in place, when the scan
273
+ // above found one; an event that cannot be cloned gets a rebuilt copy, so
274
+ // the host's object is never mutated. Neither walk throws out of push().
254
275
  try {
255
276
  ev = structuredClone(ev);
277
+ if (scan.hasOwnProto) deleteOwnProtoMember(ev);
256
278
  } catch {
257
- // not cloneable: fold the event as pushed
279
+ // not cloneable: fold the event as pushed, less the member
280
+ try {
281
+ ev = withoutOwnProtoMember(ev);
282
+ } catch {
283
+ // a host getter that throws: fold the event as pushed
284
+ }
258
285
  }
259
286
 
260
287
  // Ext events (`ext.<vendor>.<key>`) are live-only / non-folding (§4/§12).
@@ -269,7 +296,7 @@ export class Reducer {
269
296
  case "turn.start": {
270
297
  // draft.5 INV-MSG: a turn.start naming a closed turn opens its paused refresh.
271
298
  if (this.#isClosedTurn(ev.turnId)) this.#restartedSinceClose.add(ev.turnId);
272
- // Task 8c leg 3: a turn.start always counts as a legitimately opened turn.
299
+ // A turn.start always counts as a legitimately opened turn.
273
300
  this.#openedTurns.add(ev.turnId);
274
301
  this.#seenOpened.set(ev.turnId, ev.threadId);
275
302
  // Idempotent: if the turn already exists, merge defined fields only. A
@@ -289,15 +316,24 @@ export class Reducer {
289
316
  existing.trigger = ev.trigger;
290
317
  }
291
318
  }
319
+ this.#rootThread ??= ev.threadId;
320
+ this.#releaseHeldNested();
292
321
  break;
293
322
  }
294
323
 
295
324
  // ── MESSAGE lifecycle ──────────────────────────────────────────────────
296
325
  case "message.start": {
326
+ // INV-MSG (rc.1): a message.start naming an id the fold already holds as a
327
+ // message — open or sealed, carried by a folded messages.snapshot, or
328
+ // adopted by a tool.done — parks and the fold is unchanged. The message
329
+ // set is fold-wide, so a later invoke reusing a held id parks too; a
330
+ // folded message.remove, or a snapshot that omits the id, releases it.
331
+ // Checked before any write below, so a parked repeat registers nothing.
332
+ if (this.#messages.has(ev.id)) { this.#resync = true; break; }
297
333
  // INV-MSG: a message.start for a turn that already closed parks.
298
334
  if (this.#isClosedTurn(this.#resolveTurnId(ev.turnId) ?? ev.turnId)) { this.#resync = true; break; }
299
335
  // draft.5 INV-OWNER: a live message.start makes its turn's thread
300
- // known and joins D9's seen-opened set (a turn.start's thread wins; else
336
+ // known and joins the seen-opened set (§5.0 INV-OWNER) (a turn.start's thread wins; else
301
337
  // the first one folded), and a record held for the turn is adopted onto it.
302
338
  if (this.#seenOpened.get(ev.turnId) === undefined) this.#seenOpened.set(ev.turnId, ev.threadId);
303
339
  const knownThread = this.#seenOpened.get(ev.turnId);
@@ -319,6 +355,8 @@ export class Reducer {
319
355
  this.#messages.set(ev.id, msg);
320
356
  // Register partition pointer: (turnId, candidateIndex ?? 0) → message id.
321
357
  this.#openMsg.set(partKey(ev.turnId, ev.candidateIndex ?? 0), ev.id);
358
+ this.#rootThread ??= ev.threadId;
359
+ this.#releaseHeldNested();
322
360
  break;
323
361
  }
324
362
 
@@ -340,35 +378,38 @@ export class Reducer {
340
378
 
341
379
  // ── SUBAGENT lifecycle ─────────────────────────────────────────────────
342
380
  case "subagent.start": {
343
- // Task 8c leg 3: a subagent.start always counts as a legitimately
381
+ // A subagent.start always counts as a legitimately
344
382
  // opened turn, even on the idempotent-duplicate early return below.
345
383
  this.#openedTurns.add(ev.turnId);
346
- // Idempotent: if the nested turn already exists, skip (never duplicate).
384
+ // Idempotent: a second open of a turn the fold already holds merges fields and never duplicates it (§5
385
+ // turn-open idempotency): a record with no parentTurnId takes this one; a record that has one keeps it, and
386
+ // a known thread stays.
347
387
  const existingNested = this.#turns.get(ev.turnId);
348
388
  if (existingNested !== undefined) {
389
+ if (existingNested.parentTurnId === undefined) existingNested.parentTurnId = ev.parentTurnId;
349
390
  this.#seenOpened.set(ev.turnId, existingNested.threadId);
350
391
  break;
351
392
  }
352
- // threadId is required on AgTurnRecord; inherit from the parent turn.
353
- // subagent.start does not carry threadId on the wire, so we look it up.
354
- const parentTurn = this.#turns.get(ev.parentTurnId);
355
- let threadId: string;
356
- if (parentTurn !== undefined) {
357
- threadId = parentTurn.threadId;
358
- } else {
359
- // Task 8c leg 2 (SPEC §1.2 + guuey capstone finding A): a parent
360
- // lookup miss means ev.parentTurnId is a wire label that was never
361
- // opened as a real turn (e.g. claude's synthetic `turn_${toolCallId}`
362
- // Task-tool cross-ref) — NOT a legitimate cross-thread reference.
363
- // Every entity in a fold shares one root threadId (SPEC §1.2), so
364
- // fall back to any ALREADY-OPENED real turn's threadId instead of
365
- // adopting the unresolvable label as this subagent's own threadId.
366
- // A "real" turn is identified by threadId !== turnId: through draft.4
367
- // a defensive stub used its own turnId as a placeholder thread. draft.5
368
- // retires the stubs, and the check stays as a guard.
369
- // `ev.parentTurnId` remains the last resort when no real turn exists yet.
370
- const realTurn = [...this.#turns.values()].find((t) => t.threadId !== t.turnId);
371
- threadId = realTurn?.threadId ?? ev.parentTurnId;
393
+ // §5 `subagent.start` row (rc.1): the nested turn's thread is the parent
394
+ // turn's thread when that thread is known (INV-OWNER), else the fold's root
395
+ // thread; until one of the two is known the record is held, result() omits
396
+ // it, and the first that becomes known gives its thread (#releaseHeldNested).
397
+ const threadId = this.#threadOfTurn(ev.parentTurnId) ?? this.#rootThread;
398
+ if (threadId === undefined) {
399
+ if (!this.#heldNested.has(ev.turnId) && this.#heldNested.size >= HELD_TURNS_CAP) {
400
+ this.#resync = true; // degrade loudly past the implementation bound
401
+ break;
402
+ }
403
+ let held = this.#held.get(ev.turnId);
404
+ if (held === undefined) {
405
+ held = { record: { turnId: ev.turnId, threadId: "" }, landings: 0, dr: 0 };
406
+ this.#held.set(ev.turnId, held);
407
+ }
408
+ held.record.parentTurnId ??= ev.parentTurnId;
409
+ this.#heldNested.set(ev.turnId, held.record.parentTurnId ?? ev.parentTurnId);
410
+ // Seen opened, its thread not known yet: a terminal for it lands on the held record.
411
+ this.#seenOpened.set(ev.turnId, undefined);
412
+ break;
372
413
  }
373
414
  // A record held for this nested turn takes the thread and the
374
415
  // parentTurnId here; otherwise a new record opens.
@@ -380,6 +421,7 @@ export class Reducer {
380
421
  });
381
422
  }
382
423
  this.#seenOpened.set(ev.turnId, threadId);
424
+ this.#releaseHeldNested();
383
425
  break;
384
426
  }
385
427
 
@@ -439,16 +481,16 @@ export class Reducer {
439
481
  if (pos === undefined) break;
440
482
  const msg = this.#messages.get(pos.messageId);
441
483
  if (msg === undefined) break;
442
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
484
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
443
485
  // message, or into any message of a closed turn, parks like a delta.
444
- if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard (E5)
486
+ if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard
445
487
  const block = msg.content[pos.index];
446
488
  if (block === undefined || block.type !== "text") break;
447
489
  // draft.4 phase: a value on the end REPLACES the start one; absent keeps
448
490
  // it; never filled once the owning message is sealed.
449
491
  if (ev.phase !== undefined && !this.#sealed.has(msg.id)) block.phase = ev.phase;
450
492
  setProviderMeta(block, ev.providerMetadata);
451
- // STREAMED-text citations carrier (audit M22): attach citations to the
493
+ // STREAMED-text citations carrier: attach citations to the
452
494
  // sealed block named by `ev.id` — never re-emitted as a duplicate
453
495
  // supplement block.
454
496
  if (ev.citations !== undefined) block.citations = ev.citations;
@@ -495,9 +537,9 @@ export class Reducer {
495
537
  if (pos === undefined) break;
496
538
  const msg = this.#messages.get(pos.messageId);
497
539
  if (msg === undefined) break;
498
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
540
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
499
541
  // message, or into any message of a closed turn, parks like a delta.
500
- if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard (E5)
542
+ if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard
501
543
  const block = msg.content[pos.index];
502
544
  if (block === undefined || block.type !== "reasoning") break;
503
545
  // draft.4 phase: same rule as text.end (end REPLACES, absent keeps, no post-seal fill).
@@ -527,9 +569,9 @@ export class Reducer {
527
569
  if (pos === undefined) break;
528
570
  const msg = this.#messages.get(pos.messageId);
529
571
  if (msg === undefined) break;
530
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
572
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
531
573
  // message, or into any message of a closed turn, parks like a delta.
532
- if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard (E5)
574
+ if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard
533
575
  const block = msg.content[pos.index];
534
576
  if (block === undefined || block.type !== "reasoning") break;
535
577
  // Use accumulated opaque scratch if present; otherwise use ev.value directly.
@@ -588,9 +630,9 @@ export class Reducer {
588
630
  if (pos === undefined) break;
589
631
  const msg = this.#messages.get(pos.messageId);
590
632
  if (msg === undefined) break;
591
- // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
633
+ // INV-MSG (SPEC.md:745, draft.4): a block-finalizing event into a sealed
592
634
  // message, or into any message of a closed turn, parks like a delta.
593
- if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard (E5)
635
+ if (this.#isClosedTarget(msg.id)) { this.#resync = true; break; } // INV-MSG finalizer guard
594
636
  const block = msg.content[pos.index];
595
637
  if (block === undefined || block.type !== "tool-call") break;
596
638
  block.input = ev.input;
@@ -612,10 +654,10 @@ export class Reducer {
612
654
  // ── TOOL-RESULT blocks ────────────────────────────────────────────────────
613
655
  case "tool.done": {
614
656
  // INV-BLOCK: a second FINAL (more-less) tool.done for one call parks.
615
- if (ev.more !== true) {
616
- if (this.#finalToolDone.has(ev.toolCallId)) { this.#resync = true; break; }
617
- this.#finalToolDone.add(ev.toolCallId);
618
- }
657
+ // INV-BLOCK (rc.1): a more:true after the call's final (more-less) result
658
+ // landed in this invoke parks; a final result is never re-opened within its
659
+ // invoke. #finalToolDone is invoke-scoped (reset at seq 0).
660
+ if (this.#finalToolDone.has(ev.toolCallId)) { this.#resync = true; break; }
619
661
  const resultKey = `result:${ev.toolCallId}`;
620
662
  const existingPos = this.#blockPos.get(resultKey);
621
663
 
@@ -632,8 +674,7 @@ export class Reducer {
632
674
  // published content. Resolve the block's owning turn via the
633
675
  // #blockPos → messageId → message.turnId chain and park instead of mutating
634
676
  // (mirrors the adoption path's closed-turn/sealed guard above).
635
- const ownerTurnKey = msg.turnId ?? "unknown-turn";
636
- if (this.#sealed.has(msg.id) || this.#isClosedTurn(ownerTurnKey)) {
677
+ if (this.#sealed.has(msg.id) || this.#isClosedTurn(msg.turnId)) {
637
678
  this.#resync = true;
638
679
  break;
639
680
  }
@@ -666,7 +707,7 @@ export class Reducer {
666
707
  if (ev.dynamic !== undefined) block.dynamic = ev.dynamic;
667
708
  if (ev._meta !== undefined) block._meta = ev._meta;
668
709
  setProviderMeta(block, ev.providerMetadata);
669
- // Typed preliminary flag mirrors the block's `more` state (audit M20):
710
+ // Typed preliminary flag mirrors the block's `more` state:
670
711
  // more:true keeps it set (kept open); the final more-less tool.done
671
712
  // clears it and closes the result (removed from open tracking).
672
713
  if (ev.more) {
@@ -674,13 +715,14 @@ export class Reducer {
674
715
  } else {
675
716
  delete block.preliminary;
676
717
  this.#blockPos.delete(resultKey);
718
+ this.#finalToolDone.add(ev.toolCallId);
677
719
  }
678
720
  } else {
679
721
  // CREATE path: first tool.done for this toolCallId.
680
722
  let msg: AgMessage | undefined;
681
723
  if (ev.messageId !== undefined) {
682
724
  // SPEC §5 tool.done row: the landed tool-result message ADOPTS
683
- // ev.messageId as its own id (stable ToolMessage identity; audit B10).
725
+ // ev.messageId as its own id (stable ToolMessage identity).
684
726
  const existing = this.#messages.get(ev.messageId);
685
727
  // INV-MSG enforcement: a sealed message, or ANY message of a closed
686
728
  // turn — including one that would need to be freshly created — is
@@ -688,17 +730,19 @@ export class Reducer {
688
730
  // would land in (the existing message's own turnId, or the turn a
689
731
  // new message would take) BEFORE either sub-path runs, and park
690
732
  // instead of silently attaching/creating past the seal or the
691
- // turn's binding window. "unknown-turn" is only a key that names no
692
- // record, so an unresolvable owner parks below.
733
+ // turn's binding window. A message with no turnId, or a new one whose
734
+ // turn resolves to none, has no turn open to adoption and parks below,
735
+ // whatever the fold's turns are named.
693
736
  const targetTurnKey =
694
737
  existing !== undefined
695
- ? (existing.turnId ?? "unknown-turn")
696
- : (this.#resolveTurnId(ev.turnId) ?? ev.turnId ?? "unknown-turn");
697
- // Task 8c leg 3 (guuey capstone finding B): a turn that was never
698
- // legitimately opened (turn.start / subagent.start / a snapshot's
699
- // turns?) is just as invalid an adoption target as a sealed
700
- // message or a closed turn: park rather than create a message for it.
738
+ ? existing.turnId
739
+ : (this.#resolveTurnId(ev.turnId) ?? ev.turnId);
740
+ // A turn that was never legitimately opened (turn.start /
741
+ // subagent.start / a snapshot's turns?) is just as invalid an
742
+ // adoption target as a sealed message or a closed turn: park rather
743
+ // than create a message for it.
701
744
  if (
745
+ targetTurnKey === undefined ||
702
746
  this.#sealed.has(ev.messageId) ||
703
747
  this.#isClosedTurn(targetTurnKey) ||
704
748
  !this.#openedTurns.has(targetTurnKey)
@@ -755,6 +799,8 @@ export class Reducer {
755
799
  // If more:true, keep the block open for subsequent merge.
756
800
  if (ev.more) {
757
801
  this.#blockPos.set(resultKey, { messageId: msg.id, index });
802
+ } else {
803
+ this.#finalToolDone.add(ev.toolCallId);
758
804
  }
759
805
  }
760
806
  break;
@@ -808,7 +854,7 @@ export class Reducer {
808
854
  // ── TURN-RECORD events (R5) ───────────────────────────────────────────────
809
855
 
810
856
  case "turn.done": {
811
- // D9 (draft.4 §5.0 INV-OWNER): a terminal for a turn this fold never saw
857
+ // INV-OWNER (draft.4 §5.0): a terminal for a turn this fold never saw
812
858
  // opened is not an unresolvable owner: it folds onto no turn record and
813
859
  // does not park. A CORE client that ignores subagent.*, or a fold whose
814
860
  // opener was dropped, sees exactly this; a producer's lone terminal fails
@@ -833,7 +879,7 @@ export class Reducer {
833
879
  }
834
880
  // messageMetadata: REPLACE the whole messageMetadata bag of the message named
835
881
  // by turn.done.messageId when present, else of the open message of this turn
836
- // (audit M20; §5 turn.done row, §13.10). No per-key merge.
882
+ // (§5 turn.done row, §13.10). No per-key merge.
837
883
  // (Read happens BEFORE the binding window closes below.)
838
884
  if (ev.messageMetadata !== undefined) {
839
885
  const msg = ev.messageId !== undefined ? this.#messages.get(ev.messageId) : this.openMessage(ev.turnId, 0);
@@ -849,15 +895,14 @@ export class Reducer {
849
895
 
850
896
  case "turn.error": {
851
897
  // Non-folding into content; sets outcome={type:"error",...} on the turn record.
852
- // D9, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
898
+ // INV-OWNER, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
853
899
  // the sole OPEN turn, never a closed one; with none or several open its
854
900
  // owner is unresolvable and the fold parks (INV-OWNER, draft.5).
855
901
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId)) break;
856
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.#soleOpenRecord();
857
- if (turn === undefined) {
858
- if (ev.turnId === undefined) this.#resync = true;
859
- break;
860
- }
902
+ const owner = ev.turnId ?? this.#soleOpenTurn();
903
+ if (owner === undefined) { this.#resync = true; break; }
904
+ const turn = this.#seenTurnRecord(owner);
905
+ if (turn === undefined) break;
861
906
  // draft.5 INV-MSG: a turn.error for a closed turn parks, writing nothing.
862
907
  if (!this.#terminalMayFold(turn, false)) break;
863
908
  // draft.5: `code` and `retriable` are recorded when turn.error carries them.
@@ -880,16 +925,15 @@ export class Reducer {
880
925
  case "turn.abort": {
881
926
  // Non-folding into content; sets a dedicated aborted outcome on the turn record
882
927
  // (symmetric with turn.error). taskState is verbatim-A2A only and is NEVER
883
- // reducer-invented (audit M29) — it stays whatever a prior turn.done left it as.
884
- // D9, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
928
+ // reducer-invented — it stays whatever a prior turn.done left it as.
929
+ // INV-OWNER, as turn.done, for a NAMED turnId. A turnId-less terminal resolves to
885
930
  // the sole OPEN turn, never a closed one; with none or several open its
886
931
  // owner is unresolvable and the fold parks (INV-OWNER, draft.5).
887
932
  if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId)) break;
888
- const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.#soleOpenRecord();
889
- if (turn === undefined) {
890
- if (ev.turnId === undefined) this.#resync = true;
891
- break;
892
- }
933
+ const owner = ev.turnId ?? this.#soleOpenTurn();
934
+ if (owner === undefined) { this.#resync = true; break; }
935
+ const turn = this.#seenTurnRecord(owner);
936
+ if (turn === undefined) break;
893
937
  // draft.5 INV-MSG: a turn.abort for a closed turn parks, writing nothing.
894
938
  if (!this.#terminalMayFold(turn, false)) break;
895
939
  turn.outcome = { type: "aborted", ...(ev.reason !== undefined ? { reason: ev.reason } : {}) };
@@ -902,7 +946,7 @@ export class Reducer {
902
946
  case "source": {
903
947
  // Append sourceId to the turn's sourceIds[] in order (preserve groundingChunks order),
904
948
  // AND land the FULL record (payload/chunkIndex/providerMetadata) on sources[] so
905
- // citations can resolve post-fold (audit M23) — sourceIds[] stays as the derived index.
949
+ // citations can resolve post-fold — sourceIds[] stays as the derived index.
906
950
  const turn = this.#landingRecord(ev.turnId);
907
951
  if (turn === undefined) break;
908
952
  if (turn.sourceIds === undefined) {
@@ -942,7 +986,7 @@ export class Reducer {
942
986
  // Record safety[] on the turn (merge — append to existing safety, or create) AND
943
987
  // land the dedicated promptBlocked record {reason, safety?} so the REQUIRED reason
944
988
  // and the blockedness itself survive the fold — a bare-reason block used to fold to
945
- // ZERO trace (audit M28).
989
+ // ZERO trace.
946
990
  const turn = this.#landingRecord(ev.turnId);
947
991
  if (turn === undefined) break;
948
992
  if (ev.safety !== undefined) {
@@ -980,7 +1024,7 @@ export class Reducer {
980
1024
 
981
1025
  case "display.required": {
982
1026
  // MUST NOT drop (ToS). Push {provider, html} onto turn's displayRequired[].
983
- const turn = this.#landingRecord(ev.turnId);
1027
+ const turn = this.#landingRecord(ev.turnId, true);
984
1028
  if (turn === undefined) break;
985
1029
  if (turn.displayRequired === undefined) {
986
1030
  turn.displayRequired = [];
@@ -1012,6 +1056,8 @@ export class Reducer {
1012
1056
  ...(ev.extensions !== undefined ? { extensions: ev.extensions } : {}),
1013
1057
  };
1014
1058
  this.#artifacts.set(ev.artifactId, artifact);
1059
+ this.#rootThread ??= ev.threadId;
1060
+ this.#releaseHeldNested();
1015
1061
  break;
1016
1062
  }
1017
1063
 
@@ -1070,6 +1116,9 @@ export class Reducer {
1070
1116
  if (Array.isArray(patch)) {
1071
1117
  // RFC-6902 path: requires an existing document to patch against.
1072
1118
  if (this.#state === undefined) {
1119
+ // An empty patch applies no operation: nothing to resync, and the
1120
+ // state stays absent.
1121
+ if (patch.length === 0) break;
1073
1122
  // No document to apply the patch to — signal resync (same semantics
1074
1123
  // as memory.write patch against a never-seeded record).
1075
1124
  this.#resync = true;
@@ -1134,6 +1183,8 @@ export class Reducer {
1134
1183
  // PATCH path: mutate an existing record via R6 applyPatch.
1135
1184
  const existing = this.#memory.get(memKey);
1136
1185
  if (existing === undefined) {
1186
+ // An empty patch applies no operation: no record, no resync.
1187
+ if (Array.isArray(ev.patch) && ev.patch.length === 0) break;
1137
1188
  // NEVER seed from {} — set resync flag and bail.
1138
1189
  this.#resync = true;
1139
1190
  break;
@@ -1190,9 +1241,24 @@ export class Reducer {
1190
1241
  // CONDITIONALLY replace #turns (only if turns? present in event).
1191
1242
  if (ev.turns !== undefined) {
1192
1243
  this.#turns = new Map(structuredClone(ev.turns).map((t) => [t.turnId, t]));
1193
- // The snapshot's turns are authoritative: a landing held before it goes too.
1194
- this.#held = new Map();
1244
+ // The snapshot's turns are authoritative for a landing held before it,
1245
+ // except a display.required: it MUST NOT be dropped by a reducer and is
1246
+ // held, never discarded, until its turn's thread is known (§5, §13.3).
1247
+ // Only those entries stay held; the other landings go.
1248
+ const kept: Map<string, { record: AgTurnRecord; landings: number; dr: number }> = new Map();
1249
+ let keptLandings = 0;
1250
+ for (const [turnId, held] of this.#held) {
1251
+ const entries = held.record.displayRequired;
1252
+ if (entries === undefined || entries.length === 0) continue;
1253
+ kept.set(turnId, { record: { turnId, threadId: "", displayRequired: entries }, landings: 0, dr: entries.length });
1254
+ keptLandings += entries.length;
1255
+ }
1256
+ this.#held = kept;
1195
1257
  this.#heldLandings = 0;
1258
+ this.#heldDrLandings = keptLandings;
1259
+ // ...and a held nested record goes with them, keeping only its
1260
+ // display.required landings, placed below.
1261
+ this.#heldNested.clear();
1196
1262
  }
1197
1263
 
1198
1264
  // CONDITIONALLY replace #artifacts (only if artifacts? present in event).
@@ -1229,10 +1295,9 @@ export class Reducer {
1229
1295
  this.#sealed = new Set();
1230
1296
  this.#blockPos = new Map();
1231
1297
  // #restartedSinceClose is NOT cleared: a snapshot folds no terminal (draft.5 INV-MSG).
1232
- // Task 8c leg 3: a snapshot-restored turn counts as opened (guuey
1233
- // capstone finding B) — reseed #openedTurns from the replaced turns in
1234
- // lockstep with #turns above; a turns-omitting snapshot re-seeds it from
1235
- // the records it keeps.
1298
+ // A snapshot-restored turn counts as opened: reseed #openedTurns from
1299
+ // the replaced turns in lockstep with #turns above; a turns-omitting
1300
+ // snapshot re-seeds it from the records it keeps.
1236
1301
  this.#openedTurns = ev.turns !== undefined
1237
1302
  ? new Set(ev.turns.map((t) => t.turnId))
1238
1303
  : new Set(this.#turns.keys());
@@ -1255,11 +1320,37 @@ export class Reducer {
1255
1320
  // draft.5 INV-OWNER: a held record whose thread this snapshot taught is adopted onto
1256
1321
  // it. #openedTurns was seeded above from records with a known thread
1257
1322
  // only, so an adopted record is not an adoption target by this snapshot.
1323
+ // A held record for a turn the snapshot itself carries joins that record
1324
+ // instead of replacing it: only display.required entries survive a
1325
+ // turns-carrying snapshot. Each held entry matches at most one entry the
1326
+ // snapshot's record already carried (the same landing, folded by the
1327
+ // snapshot's producer); an unmatched one is appended, so repeated entries
1328
+ // keep their count.
1258
1329
  for (const turnId of [...this.#held.keys()]) {
1259
1330
  const threadId = this.#seenOpened.get(turnId);
1260
- if (threadId !== undefined) this.#adoptHeld(turnId, threadId);
1331
+ if (threadId === undefined || this.#heldNested.has(turnId)) continue;
1332
+ const present = this.#turns.get(turnId);
1333
+ if (present === undefined) {
1334
+ this.#adoptHeld(turnId, threadId);
1335
+ continue;
1336
+ }
1337
+ const held = this.#held.get(turnId)!;
1338
+ this.#held.delete(turnId);
1339
+ this.#heldLandings -= held.landings;
1340
+ this.#heldDrLandings -= held.dr;
1341
+ const list = (present.displayRequired ??= []);
1342
+ const unmatched = [...list];
1343
+ for (const entry of held.record.displayRequired ?? []) {
1344
+ const i = unmatched.findIndex((e) => e.provider === entry.provider && e.html === entry.html);
1345
+ if (i >= 0) unmatched.splice(i, 1);
1346
+ else list.push(entry);
1347
+ }
1261
1348
  }
1262
1349
 
1350
+ // The root thread: the first threadId the snapshot carried, in its turns, else its messages.
1351
+ this.#rootThread ??= ev.turns?.find((t) => t.threadId !== undefined)?.threadId ?? ev.messages.find((m) => m.threadId !== undefined)?.threadId;
1352
+ this.#releaseHeldNested();
1353
+
1263
1354
  // Un-park.
1264
1355
  this.#resync = false;
1265
1356
  break;
@@ -1310,7 +1401,7 @@ export class Reducer {
1310
1401
  // Clear the per-block scratch buffers too (same block-id / toolCallId key),
1311
1402
  // else a stale opaque-signature / arg buffer leaks into a LATER message that
1312
1403
  // reuses the same id (cross-task scratch leak — byte-identity can't catch it
1313
- // because it corrupts batch AND incremental identically). (final-review M1)
1404
+ // because it corrupts batch AND incremental identically).
1314
1405
  this.#toolArgs.delete(blockId);
1315
1406
  this.#opaque.delete(blockId);
1316
1407
  // INV-BLOCK is about ids PRESENT in the fold (SPEC INV-BLOCK): a removed
@@ -1392,8 +1483,8 @@ export class Reducer {
1392
1483
  }
1393
1484
 
1394
1485
  /**
1395
- * Evict dangling per-block streaming scratch owned by a closed turn
1396
- * (audit M51): #toolArgs/#opaque entries are otherwise reclaimed only on
1486
+ * Evict dangling per-block streaming scratch owned by a closed turn:
1487
+ * #toolArgs/#opaque entries are otherwise reclaimed only on
1397
1488
  * assembled/seal/snapshot — an errored/aborted turn leaks them and a reused
1398
1489
  * per-invoke block id in a LATER turn would concatenate stale scratch.
1399
1490
  */
@@ -1429,11 +1520,11 @@ export class Reducer {
1429
1520
  * folds onto no record closes nothing; a messages.snapshot changes closure
1430
1521
  * only through the records its §5 per-container rule leaves in the fold. No
1431
1522
  * message of a closed turn (sealed or not, existing or not yet created) is a
1432
- * valid attach or adoption target. `key` is a resolved turnId, or the
1433
- * "unknown-turn" key of a message with no turnId, which names no record.
1523
+ * valid attach or adoption target. `key` is a resolved turnId, or undefined
1524
+ * for a message with no turnId, which names no record.
1434
1525
  */
1435
1526
  #isClosedTurn(key: string | undefined): boolean {
1436
- return key !== undefined && this.#turns.get(key)?.outcome !== undefined;
1527
+ return key !== undefined && (this.#turns.get(key) ?? this.#held.get(key)?.record)?.outcome !== undefined;
1437
1528
  }
1438
1529
 
1439
1530
  /**
@@ -1475,20 +1566,60 @@ export class Reducer {
1475
1566
  // §4 per-turn routing / INV-OWNER (draft.5): an omitted turnId
1476
1567
  // resolves to the sole OPEN turn, never to a closed one (through draft.4
1477
1568
  // this counted records, so a lone closed turn or a stub could be picked).
1478
- return this.#soleOpenRecord()?.turnId;
1569
+ return this.#soleOpenTurn();
1479
1570
  }
1480
1571
 
1481
- /** The sole OPEN turn record (no `outcome` yet), or undefined when none or several are open. */
1482
- #soleOpenRecord(): AgTurnRecord | undefined {
1483
- let found: AgTurnRecord | undefined;
1484
- for (const t of this.#turns.values()) {
1485
- if (t.outcome !== undefined) continue;
1572
+ /**
1573
+ * The sole OPEN turn (§4 per-turn routing, INV-OWNER): one the reducer has seen
1574
+ * opened (or holds a record for) that is not closed. Undefined when none or
1575
+ * several are open.
1576
+ */
1577
+ #soleOpenTurn(): string | undefined {
1578
+ let found: string | undefined;
1579
+ for (const turnId of new Set([...this.#seenOpened.keys(), ...this.#turns.keys()])) {
1580
+ if (this.#isClosedTurn(turnId)) continue;
1486
1581
  if (found !== undefined) return undefined;
1487
- found = t;
1582
+ found = turnId;
1488
1583
  }
1489
1584
  return found;
1490
1585
  }
1491
1586
 
1587
+ /** A turn's known thread: its record's, else the one it was seen opened on. */
1588
+ #threadOfTurn(turnId: string): string | undefined {
1589
+ if (this.#heldNested.has(turnId)) return undefined;
1590
+ return this.#turns.get(turnId)?.threadId ?? this.#seenOpened.get(turnId);
1591
+ }
1592
+
1593
+ /**
1594
+ * Release every held nested record whose parent's thread or the root thread is
1595
+ * now known onto that thread (the parent's first). Repeats until none moves, so
1596
+ * a chain of held nested turns releases in one pass.
1597
+ */
1598
+ #releaseHeldNested(): void {
1599
+ const release = (turnId: string, parentTurnId: string, threadId: string) => {
1600
+ this.#heldNested.delete(turnId);
1601
+ this.#adoptHeld(turnId, threadId, parentTurnId);
1602
+ this.#seenOpened.set(turnId, threadId);
1603
+ };
1604
+ let moved = true;
1605
+ while (moved && this.#heldNested.size > 0) {
1606
+ moved = false;
1607
+ for (const [turnId, parentTurnId] of [...this.#heldNested]) {
1608
+ const threadId = this.#threadOfTurn(parentTurnId);
1609
+ if (threadId === undefined) continue;
1610
+ release(turnId, parentTurnId, threadId);
1611
+ moved = true;
1612
+ }
1613
+ if (moved || this.#rootThread === undefined) continue;
1614
+ let heads = [...this.#heldNested].filter(([, p]) => !this.#heldNested.has(p));
1615
+ if (heads.length === 0) heads = [...this.#heldNested].slice(0, 1);
1616
+ for (const [turnId, parentTurnId] of heads) {
1617
+ release(turnId, parentTurnId, this.#rootThread);
1618
+ moved = true;
1619
+ }
1620
+ }
1621
+ }
1622
+
1492
1623
  /**
1493
1624
  * Where a record event lands (draft.5 INV-OWNER). A named turn with a
1494
1625
  * record lands on it; one whose thread is known gets a new record on that
@@ -1497,28 +1628,36 @@ export class Reducer {
1497
1628
  * event lands on the sole open turn's record, else its owner is unresolvable
1498
1629
  * and the fold parks.
1499
1630
  */
1500
- #landingRecord(turnId: string | undefined): AgTurnRecord | undefined {
1631
+ #landingRecord(turnId: string | undefined, displayRequired = false): AgTurnRecord | undefined {
1501
1632
  if (turnId === undefined) {
1502
- const sole = this.#soleOpenRecord();
1503
- if (sole === undefined) this.#resync = true;
1504
- return sole;
1633
+ turnId = this.#soleOpenTurn();
1634
+ if (turnId === undefined) { this.#resync = true; return undefined; }
1505
1635
  }
1506
1636
  const existing = this.#turns.get(turnId);
1507
1637
  if (existing !== undefined) return existing;
1508
1638
  const threadId = this.#seenOpened.get(turnId);
1509
1639
  if (threadId !== undefined) return this.#seenTurnRecord(turnId);
1510
1640
  let held = this.#held.get(turnId);
1511
- if ((held === undefined && this.#held.size >= HELD_TURNS_CAP) || this.#heldLandings >= HELD_LANDINGS_CAP) {
1641
+ // The bound counts display.required landings and the other five apart (#held).
1642
+ const newTurn = held === undefined || (displayRequired ? held.dr === 0 : held.landings === 0);
1643
+ const heldTurns = newTurn ? [...this.#held.values()].filter((h) => (displayRequired ? h.dr : h.landings) > 0).length : 0;
1644
+ const heldLandings = displayRequired ? this.#heldDrLandings : this.#heldLandings;
1645
+ if ((newTurn && heldTurns >= HELD_TURNS_CAP) || heldLandings >= HELD_LANDINGS_CAP) {
1512
1646
  this.#resync = true; // degrade loudly past the bound
1513
1647
  return undefined;
1514
1648
  }
1515
1649
  if (held === undefined) {
1516
1650
  // threadId is set on adoption; a held record is never emitted.
1517
- held = { record: { turnId, threadId: "" }, landings: 0 };
1651
+ held = { record: { turnId, threadId: "" }, landings: 0, dr: 0 };
1518
1652
  this.#held.set(turnId, held);
1519
1653
  }
1520
- held.landings++;
1521
- this.#heldLandings++;
1654
+ if (displayRequired) {
1655
+ held.dr++;
1656
+ this.#heldDrLandings++;
1657
+ } else {
1658
+ held.landings++;
1659
+ this.#heldLandings++;
1660
+ }
1522
1661
  return held.record;
1523
1662
  }
1524
1663
 
@@ -1531,7 +1670,9 @@ export class Reducer {
1531
1670
  const held = this.#held.get(turnId);
1532
1671
  if (held === undefined) return undefined;
1533
1672
  this.#held.delete(turnId);
1673
+ this.#heldNested.delete(turnId);
1534
1674
  this.#heldLandings -= held.landings;
1675
+ this.#heldDrLandings -= held.dr;
1535
1676
  const { turnId: _turnId, threadId: _placeholder, ...landings } = held.record;
1536
1677
  const record: AgTurnRecord = {
1537
1678
  turnId,
@@ -1544,18 +1685,21 @@ export class Reducer {
1544
1685
  }
1545
1686
 
1546
1687
  /**
1547
- * D9: the record a terminal for a SEEN turn folds onto — the existing one,
1688
+ * INV-OWNER: the record a terminal for a SEEN turn folds onto — the existing one,
1548
1689
  * else one created on the thread the fold saw the turn opened on. With no
1549
1690
  * thread known it returns undefined and the terminal folds onto no record.
1550
1691
  * No other turn's thread is borrowed (that could adopt a subagent's parent
1551
- * label as a threadId), and a D9 path never writes a threadId equal to its
1692
+ * label as a threadId), and an INV-OWNER path never writes a threadId equal to its
1552
1693
  * turnId.
1553
1694
  */
1554
1695
  #seenTurnRecord(turnId: string): AgTurnRecord | undefined {
1555
1696
  const existing = this.#turns.get(turnId);
1556
1697
  if (existing !== undefined) return existing;
1557
1698
  const threadId = this.#seenOpened.get(turnId);
1558
- if (threadId === undefined) return undefined;
1699
+ if (threadId === undefined) {
1700
+ // A nested turn whose record is held: a terminal lands on that record (INV-OWNER).
1701
+ return this.#heldNested.has(turnId) ? this.#held.get(turnId)?.record : undefined;
1702
+ }
1559
1703
  const adopted = this.#adoptHeld(turnId, threadId);
1560
1704
  if (adopted !== undefined) return adopted;
1561
1705
  const record: AgTurnRecord = { turnId, threadId };
@@ -1599,7 +1743,7 @@ export class Reducer {
1599
1743
 
1600
1744
  /**
1601
1745
  * Batch fold. Returns the folded result AND the resync signal — a parked fold
1602
- * is never a silent truncation (audit M50; INV-SEQ: "a conformant reducer MUST
1746
+ * is never a silent truncation (INV-SEQ: "a conformant reducer MUST
1603
1747
  * expose its resync condition to the caller").
1604
1748
  */
1605
1749
  export function reduce(events: AgEvent[]): { result: AgReduceResult; needsResync: boolean } {