@silverprotocol/core 0.6.7 → 0.7.0

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 (52) hide show
  1. package/README.md +54 -6
  2. package/dist/agjson.d.ts +29 -8
  3. package/dist/agjson.d.ts.map +1 -1
  4. package/dist/agjson.js +28 -7
  5. package/dist/agjson.js.map +1 -1
  6. package/dist/atomic-push.d.ts +51 -0
  7. package/dist/atomic-push.d.ts.map +1 -0
  8. package/dist/atomic-push.js +188 -0
  9. package/dist/atomic-push.js.map +1 -0
  10. package/dist/copy-json.d.ts +12 -0
  11. package/dist/copy-json.d.ts.map +1 -0
  12. package/dist/copy-json.js +21 -0
  13. package/dist/copy-json.js.map +1 -0
  14. package/dist/index.d.ts +3 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +3 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/ingest.d.ts +41 -5
  19. package/dist/ingest.d.ts.map +1 -1
  20. package/dist/ingest.js +53 -30
  21. package/dist/ingest.js.map +1 -1
  22. package/dist/input-check.d.ts +51 -0
  23. package/dist/input-check.d.ts.map +1 -0
  24. package/dist/input-check.js +113 -0
  25. package/dist/input-check.js.map +1 -0
  26. package/dist/record.d.ts +68 -0
  27. package/dist/record.d.ts.map +1 -0
  28. package/dist/record.js +112 -0
  29. package/dist/record.js.map +1 -0
  30. package/dist/reduce.d.ts +0 -14
  31. package/dist/reduce.d.ts.map +1 -1
  32. package/dist/reduce.js +270 -68
  33. package/dist/reduce.js.map +1 -1
  34. package/dist/stream-assembler.d.ts +47 -4
  35. package/dist/stream-assembler.d.ts.map +1 -1
  36. package/dist/stream-assembler.js +55 -4
  37. package/dist/stream-assembler.js.map +1 -1
  38. package/dist/wire.d.ts +96 -0
  39. package/dist/wire.d.ts.map +1 -1
  40. package/dist/wire.js +309 -0
  41. package/dist/wire.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/agjson.ts +33 -10
  44. package/src/atomic-push.ts +217 -0
  45. package/src/copy-json.ts +27 -0
  46. package/src/index.ts +3 -0
  47. package/src/ingest.ts +71 -26
  48. package/src/input-check.ts +124 -0
  49. package/src/record.ts +132 -0
  50. package/src/reduce.ts +234 -56
  51. package/src/stream-assembler.ts +74 -8
  52. package/src/wire.ts +303 -0
package/dist/reduce.js CHANGED
@@ -28,6 +28,28 @@ function mergeProviderMeta(existing, incoming) {
28
28
  return incoming;
29
29
  return { ...existing, ...incoming };
30
30
  }
31
+ /**
32
+ * Merge `incoming` into a block's providerMetadata, assigning only a defined
33
+ * result. A bare `block.providerMetadata = mergeProviderMeta(...)` left an
34
+ * explicit `providerMetadata: undefined` key on blocks that never had any:
35
+ * invisible in JSON, but visible to `in` / `toHaveProperty` / Object.keys
36
+ * consumers (sp-openai's PH-2 finding, 2026-09-23).
37
+ */
38
+ function setProviderMeta(block, incoming) {
39
+ const merged = mergeProviderMeta(block.providerMetadata, incoming);
40
+ if (merged !== undefined)
41
+ block.providerMetadata = merged;
42
+ }
43
+ /**
44
+ * Snapshot-fold one optional result field (draft.4 §5 tool.done): the later
45
+ * event's value, or no key at all when the later event omits it.
46
+ */
47
+ function replaceOrClear(block, key, value) {
48
+ if (value === undefined)
49
+ delete block[key];
50
+ else
51
+ block[key] = value;
52
+ }
31
53
  /**
32
54
  * Build the partition key for the open-message map.
33
55
  *
@@ -82,6 +104,16 @@ export class Reducer {
82
104
  // path can degrade loudly (resync) instead of silently minting a phantom
83
105
  // turn for a key that was never actually opened.
84
106
  #openedTurns = new Set();
107
+ // D9 (draft.4 §5.0 INV-OWNER; bar wf_08cf78ac-c30, A tightened): every
108
+ // turnId the fold has seen opened — by turn.start, by subagent.start, or by a
109
+ // folded messages.snapshot (its `turns`, or a message's turnId) — mapped to
110
+ // the threadId it was opened on (undefined when the opener named none). A
111
+ // snapshot that carries `turns` resets it (see the messages.snapshot arm).
112
+ // Only a terminal for one of these folds onto a turn record, and a record it
113
+ // has to create takes that thread, never the turnId. Kept apart from
114
+ // #openedTurns (tool.done adoption) and never rebuilt from #turns, whose
115
+ // records non-terminal arms may have minted as stubs.
116
+ #seenOpened = new Map();
85
117
  // block/tool-call id → position in its owning message's content[], for REPLACE.
86
118
  #blockPos = new Map();
87
119
  // ── streaming scratch ──────────────────────────────────────────────────────
@@ -92,6 +124,12 @@ export class Reducer {
92
124
  // ── gap detection ──────────────────────────────────────────────────────────
93
125
  #lastSeq = -1;
94
126
  #resync = false;
127
+ // ── rd-14 INV-BLOCK (invoke-scoped) ─────────────────────────────────────────
128
+ // Block ids created in the current invoke, and toolCallIds whose FINAL
129
+ // (more-less) tool.done already landed. Both reset at the seq-0 restart, so a
130
+ // new invoke may reuse per-invoke ids.
131
+ #invokeBlockIds = new Set();
132
+ #finalToolDone = new Set();
95
133
  /**
96
134
  * Feed a single normalized AgEvent into the fold.
97
135
  * R1: lifecycle handlers (turn/message/subagent/step).
@@ -113,6 +151,12 @@ export class Reducer {
113
151
  if (this.#lastSeq >= 0 && ev.seq > this.#lastSeq + 1) {
114
152
  this.#resync = true;
115
153
  }
154
+ // rd-14 (founder: "Stall it, like a gap"): a repeated or backward seq ABOVE 0
155
+ // parks exactly like a forward gap. Only seq 0 (a new invoke's restart) may go
156
+ // backward (SPEC INV-SEQ), so a re-delivery can never fold twice.
157
+ if (this.#lastSeq >= 0 && ev.seq > 0 && ev.seq <= this.#lastSeq) {
158
+ this.#resync = true;
159
+ }
116
160
  // ── Park-gate (R9) ───────────────────────────────────────────────────────
117
161
  // While parked, process ONLY the two snapshot kinds; all else is ignored.
118
162
  // Both snapshots REPLACE + clear #resync inside their handlers.
@@ -128,6 +172,25 @@ export class Reducer {
128
172
  // Update #lastSeq for every processed event (including snapshots and
129
173
  // non-folding ext/live-only events — seq accounting is universal, see above).
130
174
  this.#lastSeq = ev.seq;
175
+ // A seq-0 restart opens a new invoke: the invoke-scoped INV-BLOCK sets reset.
176
+ if (ev.seq === 0) {
177
+ this.#invokeBlockIds.clear();
178
+ this.#finalToolDone.clear();
179
+ }
180
+ // Store-time isolation: the handlers below keep references into the event
181
+ // (a block, a providerMetadata or _meta bag, a tool result, an outcome, a
182
+ // state snapshot, a patch value, a memory value), so the fold works on its
183
+ // own copy. A host that reuses or mutates its event object after push() can
184
+ // never move the fold; result() clones on the way out, this on the way in.
185
+ // It runs before the ext guard below, which then narrows the copy. An event
186
+ // structuredClone cannot copy (a function-valued field) folds as pushed, as
187
+ // it always did, rather than throwing out of push().
188
+ try {
189
+ ev = structuredClone(ev);
190
+ }
191
+ catch {
192
+ // not cloneable: fold the event as pushed
193
+ }
131
194
  // Ext events (`ext.<vendor>.<key>`) are live-only / non-folding (§4/§12).
132
195
  // Rule them out HERE — after seq accounting above, so an ext event still
133
196
  // advances the gap check/#lastSeq — so the switch below sees the narrowed
@@ -140,6 +203,7 @@ export class Reducer {
140
203
  case "turn.start": {
141
204
  // Task 8c leg 3: a turn.start always counts as a legitimately opened turn.
142
205
  this.#openedTurns.add(ev.turnId);
206
+ this.#seenOpened.set(ev.turnId, ev.threadId);
143
207
  // Idempotent: if the turn already exists, merge defined fields only.
144
208
  const existing = this.#turns.get(ev.turnId);
145
209
  if (existing === undefined) {
@@ -159,6 +223,11 @@ export class Reducer {
159
223
  }
160
224
  // ── MESSAGE lifecycle ──────────────────────────────────────────────────
161
225
  case "message.start": {
226
+ // rd-14 INV-MSG: a message.start for a turn that already closed parks.
227
+ if (this.#closedTurns.has(this.#resolveTurnId(ev.turnId) ?? ev.turnId)) {
228
+ this.#resync = true;
229
+ break;
230
+ }
162
231
  const msg = {
163
232
  id: ev.id,
164
233
  role: ev.role,
@@ -200,8 +269,11 @@ export class Reducer {
200
269
  // opened turn, even on the idempotent-duplicate early return below.
201
270
  this.#openedTurns.add(ev.turnId);
202
271
  // Idempotent: if the nested turn already exists, skip (never duplicate).
203
- if (this.#turns.has(ev.turnId))
272
+ const existingNested = this.#turns.get(ev.turnId);
273
+ if (existingNested !== undefined) {
274
+ this.#seenOpened.set(ev.turnId, existingNested.threadId);
204
275
  break;
276
+ }
205
277
  // threadId is required on AgTurnRecord; inherit from the parent turn.
206
278
  // subagent.start does not carry threadId on the wire, so we look it up.
207
279
  const parentTurn = this.#turns.get(ev.parentTurnId);
@@ -229,6 +301,7 @@ export class Reducer {
229
301
  parentTurnId: ev.parentTurnId,
230
302
  threadId,
231
303
  });
304
+ this.#seenOpened.set(ev.turnId, threadId);
232
305
  break;
233
306
  }
234
307
  case "subagent.done": {
@@ -248,6 +321,8 @@ export class Reducer {
248
321
  }
249
322
  // ── TEXT blocks ───────────────────────────────────────────────────────────
250
323
  case "text.start": {
324
+ if (this.#dupBlock(ev.id))
325
+ break; // rd-14 INV-BLOCK
251
326
  const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
252
327
  if (msg === undefined) {
253
328
  this.#resync = true;
@@ -256,6 +331,7 @@ export class Reducer {
256
331
  const block = {
257
332
  type: "text",
258
333
  text: "", // REQUIRED field — mid-stream result() before any delta must parse
334
+ ...(ev.phase !== undefined ? { phase: ev.phase } : {}), // draft.4 open-string label
259
335
  ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
260
336
  ...(ev._meta !== undefined ? { _meta: ev._meta } : {}),
261
337
  };
@@ -271,16 +347,17 @@ export class Reducer {
271
347
  const msg = this.#messages.get(pos.messageId);
272
348
  if (msg === undefined)
273
349
  break;
274
- // INV-MSG (SPEC.md:745): a straggler delta into a sealed message parks.
275
- if (this.#sealed.has(msg.id)) {
350
+ // INV-MSG (SPEC.md:745): a straggler delta into a sealed message, or into
351
+ // any message of a closed turn (rd-14), parks.
352
+ if (this.#isClosedTarget(msg.id)) {
276
353
  this.#resync = true;
277
354
  break;
278
- }
355
+ } // INV-MSG delta guard
279
356
  const block = msg.content[pos.index];
280
357
  if (block === undefined || block.type !== "text")
281
358
  break;
282
359
  block.text += ev.delta;
283
- block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
360
+ setProviderMeta(block, ev.providerMetadata);
284
361
  break;
285
362
  }
286
363
  case "text.end": {
@@ -290,10 +367,20 @@ export class Reducer {
290
367
  const msg = this.#messages.get(pos.messageId);
291
368
  if (msg === undefined)
292
369
  break;
370
+ // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
371
+ // message, or into any message of a closed turn, parks like a delta.
372
+ if (this.#isClosedTarget(msg.id)) {
373
+ this.#resync = true;
374
+ break;
375
+ } // INV-MSG finalizer guard (E5)
293
376
  const block = msg.content[pos.index];
294
377
  if (block === undefined || block.type !== "text")
295
378
  break;
296
- block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
379
+ // draft.4 phase: a value on the end REPLACES the start one; absent keeps
380
+ // it; never filled once the owning message is sealed.
381
+ if (ev.phase !== undefined && !this.#sealed.has(msg.id))
382
+ block.phase = ev.phase;
383
+ setProviderMeta(block, ev.providerMetadata);
297
384
  // STREAMED-text citations carrier (audit M22): attach citations to the
298
385
  // sealed block named by `ev.id` — never re-emitted as a duplicate
299
386
  // supplement block.
@@ -303,6 +390,8 @@ export class Reducer {
303
390
  }
304
391
  // ── REASONING blocks ──────────────────────────────────────────────────────
305
392
  case "reasoning.start": {
393
+ if (this.#dupBlock(ev.id))
394
+ break; // rd-14 INV-BLOCK
306
395
  const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
307
396
  if (msg === undefined) {
308
397
  this.#resync = true;
@@ -311,6 +400,7 @@ export class Reducer {
311
400
  const block = {
312
401
  type: "reasoning",
313
402
  text: "", // seeded — mid-stream result() before any delta must parse
403
+ ...(ev.phase !== undefined ? { phase: ev.phase } : {}), // draft.4 open-string label
314
404
  ...(ev.providerMetadata !== undefined ? { providerMetadata: ev.providerMetadata } : {}),
315
405
  ...(ev._meta !== undefined ? { _meta: ev._meta } : {}),
316
406
  ...(ev.itemId !== undefined ? { itemId: ev.itemId } : {}),
@@ -327,17 +417,18 @@ export class Reducer {
327
417
  const msg = this.#messages.get(pos.messageId);
328
418
  if (msg === undefined)
329
419
  break;
330
- // INV-MSG (SPEC.md:745): a straggler delta into a sealed message parks.
331
- if (this.#sealed.has(msg.id)) {
420
+ // INV-MSG (SPEC.md:745): a straggler delta into a sealed message, or into
421
+ // any message of a closed turn (rd-14), parks.
422
+ if (this.#isClosedTarget(msg.id)) {
332
423
  this.#resync = true;
333
424
  break;
334
- }
425
+ } // INV-MSG delta guard
335
426
  const block = msg.content[pos.index];
336
427
  if (block === undefined || block.type !== "reasoning")
337
428
  break;
338
429
  // APPEND delta to text (in-order concat of parts)
339
430
  block.text = (block.text ?? "") + ev.delta;
340
- block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
431
+ setProviderMeta(block, ev.providerMetadata);
341
432
  break;
342
433
  }
343
434
  case "reasoning.end": {
@@ -347,10 +438,19 @@ export class Reducer {
347
438
  const msg = this.#messages.get(pos.messageId);
348
439
  if (msg === undefined)
349
440
  break;
441
+ // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
442
+ // message, or into any message of a closed turn, parks like a delta.
443
+ if (this.#isClosedTarget(msg.id)) {
444
+ this.#resync = true;
445
+ break;
446
+ } // INV-MSG finalizer guard (E5)
350
447
  const block = msg.content[pos.index];
351
448
  if (block === undefined || block.type !== "reasoning")
352
449
  break;
353
- block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
450
+ // draft.4 phase: same rule as text.end (end REPLACES, absent keeps, no post-seal fill).
451
+ if (ev.phase !== undefined && !this.#sealed.has(msg.id))
452
+ block.phase = ev.phase;
453
+ setProviderMeta(block, ev.providerMetadata);
354
454
  if (ev.provider !== undefined) {
355
455
  block.provider = ev.provider;
356
456
  }
@@ -362,10 +462,10 @@ export class Reducer {
362
462
  // parks. The block is resolved by id; with no known block the delta
363
463
  // stays scratch-only, as before.
364
464
  const opaquePos = this.#blockPos.get(ev.id);
365
- if (opaquePos !== undefined && this.#sealed.has(opaquePos.messageId)) {
465
+ if (opaquePos !== undefined && this.#isClosedTarget(opaquePos.messageId)) {
366
466
  this.#resync = true;
367
467
  break;
368
- }
468
+ } // INV-MSG delta guard
369
469
  const existing = this.#opaque.get(ev.id) ?? "";
370
470
  this.#opaque.set(ev.id, existing + ev.delta);
371
471
  break;
@@ -378,6 +478,12 @@ export class Reducer {
378
478
  const msg = this.#messages.get(pos.messageId);
379
479
  if (msg === undefined)
380
480
  break;
481
+ // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
482
+ // message, or into any message of a closed turn, parks like a delta.
483
+ if (this.#isClosedTarget(msg.id)) {
484
+ this.#resync = true;
485
+ break;
486
+ } // INV-MSG finalizer guard (E5)
381
487
  const block = msg.content[pos.index];
382
488
  if (block === undefined || block.type !== "reasoning")
383
489
  break;
@@ -397,6 +503,8 @@ export class Reducer {
397
503
  }
398
504
  // ── TOOL-CALL blocks ──────────────────────────────────────────────────────
399
505
  case "tool.start": {
506
+ if (this.#dupBlock(ev.toolCallId))
507
+ break; // rd-14 INV-BLOCK
400
508
  const msg = this.openMessage(ev.turnId, ev.candidateIndex ?? 0);
401
509
  if (msg === undefined) {
402
510
  this.#resync = true;
@@ -425,10 +533,10 @@ export class Reducer {
425
533
  // APPEND raw partial-JSON delta to scratch (NEVER authoritative input).
426
534
  // INV-MSG (SPEC.md:745): a straggler into a sealed message's tool call parks.
427
535
  const argsPos = this.#blockPos.get(ev.toolCallId);
428
- if (argsPos !== undefined && this.#sealed.has(argsPos.messageId)) {
536
+ if (argsPos !== undefined && this.#isClosedTarget(argsPos.messageId)) {
429
537
  this.#resync = true;
430
538
  break;
431
- }
539
+ } // INV-MSG delta guard
432
540
  const existing = this.#toolArgs.get(ev.toolCallId) ?? "";
433
541
  this.#toolArgs.set(ev.toolCallId, existing + ev.delta);
434
542
  break;
@@ -441,6 +549,12 @@ export class Reducer {
441
549
  const msg = this.#messages.get(pos.messageId);
442
550
  if (msg === undefined)
443
551
  break;
552
+ // INV-MSG (SPEC.md:745, draft.4 E5): a block-finalizing event into a sealed
553
+ // message, or into any message of a closed turn, parks like a delta.
554
+ if (this.#isClosedTarget(msg.id)) {
555
+ this.#resync = true;
556
+ break;
557
+ } // INV-MSG finalizer guard (E5)
444
558
  const block = msg.content[pos.index];
445
559
  if (block === undefined || block.type !== "tool-call")
446
560
  break;
@@ -454,19 +568,27 @@ export class Reducer {
454
568
  if (ev.toolMetadata !== undefined) {
455
569
  block.toolMetadata = ev.toolMetadata;
456
570
  }
457
- block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
571
+ setProviderMeta(block, ev.providerMetadata);
458
572
  // Clear scratch now that it's been superseded by the authoritative input.
459
573
  this.#toolArgs.delete(ev.toolCallId);
460
574
  break;
461
575
  }
462
576
  // ── TOOL-RESULT blocks ────────────────────────────────────────────────────
463
577
  case "tool.done": {
578
+ // rd-14 INV-BLOCK: a second FINAL (more-less) tool.done for one call parks.
579
+ if (ev.more !== true) {
580
+ if (this.#finalToolDone.has(ev.toolCallId)) {
581
+ this.#resync = true;
582
+ break;
583
+ }
584
+ this.#finalToolDone.add(ev.toolCallId);
585
+ }
464
586
  const resultKey = `result:${ev.toolCallId}`;
465
587
  const existingPos = this.#blockPos.get(resultKey);
466
588
  if (existingPos !== undefined) {
467
- // MERGE path: a preliminary tool-result block is already open for this
468
- // toolCallId. Replace its content with the incoming (final or next-preliminary)
469
- // content.
589
+ // MERGE path: a kept-open (more:true) tool-result block exists for this
590
+ // toolCallId; the incoming tool.done (final or next kept-open) folds onto it
591
+ // as a snapshot (draft.4 §5, below).
470
592
  const msg = this.#messages.get(existingPos.messageId);
471
593
  if (msg === undefined)
472
594
  break;
@@ -483,40 +605,41 @@ export class Reducer {
483
605
  this.#resync = true;
484
606
  break;
485
607
  }
608
+ // Snapshot fold (draft.4 §5; fold/flush P1, bar wf_2231e194-e31): while a
609
+ // result is kept open, every tool.done carries the FULL current result, so
610
+ // a later one REPLACES the payload as a unit. content, outcome, isError,
611
+ // structuredContent, uiData, sideData, errorText, errorCode and
612
+ // pendingInput take the later event's values, and a field it omits is
613
+ // CLEARED: an ok final no longer keeps a kept-open error's
614
+ // isError/errorText, and an error final no longer keeps a kept-open
615
+ // structuredContent. uiData is payload (founder ruling, bar
616
+ // wf_93a30c7b-cd0): a carried `uiData: null` is STORED as a value ("no
617
+ // view data"), never a retraction; a view's identity that must outlive a
618
+ // snapshot lives on `_meta.ui.resourceUri`, a descriptor below.
486
619
  block.content = ev.content;
487
- if (ev.outcome !== undefined)
488
- block.outcome = ev.outcome;
489
- if (ev.isError !== undefined)
490
- block.isError = ev.isError;
491
- if (ev.structuredContent !== undefined)
492
- block.structuredContent = ev.structuredContent;
493
- if (ev.uiData !== undefined)
494
- block.uiData = ev.uiData;
495
- if (ev.sideData !== undefined)
496
- block.sideData = ev.sideData;
497
- if (ev.errorText !== undefined)
498
- block.errorText = ev.errorText;
499
- if (ev.errorCode !== undefined)
500
- block.errorCode = ev.errorCode;
501
- // SPEC.md:799: tool.done lands toolMetadata and dynamic (the create
502
- // path always did); same guarded per-field merge as the rest.
620
+ replaceOrClear(block, "outcome", ev.outcome);
621
+ replaceOrClear(block, "isError", ev.isError);
622
+ replaceOrClear(block, "structuredContent", ev.structuredContent);
623
+ replaceOrClear(block, "uiData", ev.uiData);
624
+ replaceOrClear(block, "sideData", ev.sideData);
625
+ replaceOrClear(block, "errorText", ev.errorText);
626
+ replaceOrClear(block, "errorCode", ev.errorCode);
627
+ replaceOrClear(block, "pendingInput", ev.pendingInput);
628
+ // Descriptors are replaced only when the later event carries them:
629
+ // toolMetadata and dynamic (SPEC.md:799; as tool.args.assembled treats
630
+ // toolMetadata), and `_meta`, the §0.4 host side-channel, so a kept-open
631
+ // result's MCP-Apps/A2UI card bootstrap survives a final that omits its
632
+ // own (workspace#9). providerMetadata merges by key.
503
633
  if (ev.toolMetadata !== undefined)
504
634
  block.toolMetadata = ev.toolMetadata;
505
635
  if (ev.dynamic !== undefined)
506
636
  block.dynamic = ev.dynamic;
507
- if (ev.pendingInput !== undefined)
508
- block.pendingInput = ev.pendingInput;
509
- // workspace#9: the §0.4 host side-channel joins the merge like every
510
- // other result field — guarded, so a preliminary's `_meta` (the
511
- // MCP-Apps/A2UI card bootstrap) survives a final REPLACE that omits
512
- // its own. Mirrors the text.start/reasoning.start carriage.
513
637
  if (ev._meta !== undefined)
514
638
  block._meta = ev._meta;
515
- block.providerMetadata = mergeProviderMeta(block.providerMetadata, ev.providerMetadata);
639
+ setProviderMeta(block, ev.providerMetadata);
516
640
  // Typed preliminary flag mirrors the block's `more` state (audit M20):
517
- // more:true keeps it set (partial, kept open); the final more-less tool.done
518
- // REPLACES the result fields wholesale (merge = REPLACE, code-canonical) and
519
- // clears it, closing (removing from open tracking).
641
+ // more:true keeps it set (kept open); the final more-less tool.done
642
+ // clears it and closes the result (removed from open tracking).
520
643
  if (ev.more) {
521
644
  block.preliminary = true;
522
645
  }
@@ -654,8 +777,20 @@ export class Reducer {
654
777
  }
655
778
  // ── TURN-RECORD events (R5) ───────────────────────────────────────────────
656
779
  case "turn.done": {
657
- const turn = this.ensureTurn(ev.turnId);
780
+ // D9 (draft.4 §5.0 INV-OWNER): a terminal for a turn this fold never saw
781
+ // opened is not an unresolvable owner: it folds onto no turn record and
782
+ // does not park. A CORE client that ignores subagent.*, or a fold whose
783
+ // opener was dropped, sees exactly this; a producer's lone terminal fails
784
+ // the §10 producer turn-open leg instead of minting a stub record here.
785
+ if (!this.#seenOpened.has(ev.turnId))
786
+ break;
787
+ const turn = this.#seenTurnRecord(ev.turnId);
788
+ if (turn === undefined)
789
+ break;
658
790
  turn.finishReason = ev.finishReason;
791
+ // draft.4: the native finish value, verbatim, beside its mapped reason.
792
+ if (ev.finishReasonRaw !== undefined)
793
+ turn.finishReasonRaw = ev.finishReasonRaw;
659
794
  // Usage is recorded VERBATIM — NO de-cumulation (spec §8.4; normalizer duty).
660
795
  if (ev.usage !== undefined)
661
796
  turn.usage = ev.usage;
@@ -684,7 +819,13 @@ export class Reducer {
684
819
  }
685
820
  case "turn.error": {
686
821
  // Non-folding into content; sets outcome={type:"error",...} on the turn record.
687
- const turn = this.ensureTurn(ev.turnId);
822
+ // D9, as turn.done; only for a NAMED turnId (a turnId-less terminal keeps
823
+ // the INV-OWNER backfill below).
824
+ if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
825
+ break;
826
+ const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.ensureTurn(ev.turnId);
827
+ if (turn === undefined)
828
+ break;
688
829
  turn.outcome = {
689
830
  type: "error",
690
831
  message: ev.message,
@@ -702,7 +843,13 @@ export class Reducer {
702
843
  // Non-folding into content; sets a dedicated aborted outcome on the turn record
703
844
  // (symmetric with turn.error). taskState is verbatim-A2A only and is NEVER
704
845
  // reducer-invented (audit M29) — it stays whatever a prior turn.done left it as.
705
- const turn = this.ensureTurn(ev.turnId);
846
+ // D9, as turn.done; only for a NAMED turnId (a turnId-less terminal keeps
847
+ // the INV-OWNER backfill below).
848
+ if (ev.turnId !== undefined && !this.#seenOpened.has(ev.turnId))
849
+ break;
850
+ const turn = ev.turnId !== undefined ? this.#seenTurnRecord(ev.turnId) : this.ensureTurn(ev.turnId);
851
+ if (turn === undefined)
852
+ break;
706
853
  turn.outcome = { type: "aborted", ...(ev.reason !== undefined ? { reason: ev.reason } : {}) };
707
854
  // INV-MSG binding window: no blocks attach to a closed turn's messages.
708
855
  this.#closeTurnWindow(ev.turnId);
@@ -858,7 +1005,7 @@ export class Reducer {
858
1005
  // Apply patch to #state using a tightened discriminator:
859
1006
  //
860
1007
  // Array.isArray(patch) → RFC-6902 via applyPatch (R6)
861
- // typeof patch === "object" && != null → LangGraph node-keyed last-writer-wins merge
1008
+ // typeof patch === "object" && != null → key-replace: each top-level key set whole (draft.4, pkg-21)
862
1009
  // else (scalar / null) → explicit no-op
863
1010
  // (documented: a future third source may extend this discriminator;
864
1011
  // scalars are NOT an error and must NOT set #resync)
@@ -880,28 +1027,25 @@ export class Reducer {
880
1027
  this.#state = result.value;
881
1028
  }
882
1029
  else if (typeof patch === "object" && patch !== null) {
883
- // LangGraph node-keyed last-writer-wins merge:
884
- // patch = { nodeKey: { key: value, ... }, ... }
885
- // For each top-level node key, shallow-merge its sub-object into #state[node].
886
- // Creates #state as {} if undefined; creates the node sub-object if absent.
1030
+ // Key-replace (draft.4 §5, pkg-21, founder-ruled): each top-level key
1031
+ // of the patch REPLACES #state[key] whole, which is how ADK applies
1032
+ // a stateDelta (sessions/state.js State.set). draft.3 merged one
1033
+ // level deep: a write that rewrote part of an object-valued key kept
1034
+ // the stale members (state-fold-gemini38: {cfg:{a:1,b:2}} then
1035
+ // {cfg:{a:5}} folded to {cfg:{a:5,b:2}} where ADK holds {cfg:{a:5}}),
1036
+ // and two partial writes to one key could assemble an object neither
1037
+ // write held (DC-6). null is stored as a value. #state starts as {}
1038
+ // when it is absent or not an object.
1039
+ // Keys are DEFINED, never assigned, so an own `__proto__` key of a
1040
+ // hand-built patch never selects the state's prototype.
887
1041
  const base = this.#state !== undefined && typeof this.#state === "object" && !Array.isArray(this.#state)
888
1042
  ? { ...this.#state }
889
1043
  : {};
890
- for (const nodeKey of Object.keys(patch)) {
891
- const nodeUpdate = patch[nodeKey];
892
- if (typeof nodeUpdate === "object" && nodeUpdate !== null && !Array.isArray(nodeUpdate)) {
893
- // Shallow-merge the node's key-value pairs into base[nodeKey].
894
- const existing = base[nodeKey];
895
- const existingObj = typeof existing === "object" && existing !== null && !Array.isArray(existing)
896
- ? { ...existing }
897
- : {};
898
- base[nodeKey] = { ...existingObj, ...nodeUpdate };
899
- }
900
- else {
901
- // Non-object node value: replace the node entry wholesale.
902
- if (nodeUpdate !== undefined) {
903
- base[nodeKey] = nodeUpdate;
904
- }
1044
+ for (const key of Object.keys(patch)) {
1045
+ const value = patch[key];
1046
+ if (value !== undefined) {
1047
+ // Copy-isolated from the event, as the capstone C1/C2 fixes require.
1048
+ Object.defineProperty(base, key, { value: structuredClone(value), enumerable: true, writable: true, configurable: true });
905
1049
  }
906
1050
  }
907
1051
  this.#state = base;
@@ -1018,6 +1162,26 @@ export class Reducer {
1018
1162
  this.#openedTurns = ev.turns !== undefined
1019
1163
  ? new Set(ev.turns.map((t) => t.turnId))
1020
1164
  : new Set(this.#turns.keys());
1165
+ // D9 (bar wf_08cf78ac-c30): a snapshot that carries `turns` is
1166
+ // authoritative, so seen becomes exactly its turns plus its messages'
1167
+ // turns (a turn seen before it and absent from it is no longer seen);
1168
+ // one that omits `turns` keeps what was seen and adds its messages'
1169
+ // turns. Never rebuilt from #turns (a source/handoff/guardrail event
1170
+ // can have minted a stub record for a turn nobody opened). A
1171
+ // message-carried turn takes the thread of this snapshot's first
1172
+ // message with that turnId and a threadId, else none.
1173
+ if (ev.turns !== undefined)
1174
+ this.#seenOpened = new Map(ev.turns.map((t) => [t.turnId, t.threadId]));
1175
+ const snapshotTurnIds = new Set((ev.turns ?? []).map((t) => t.turnId));
1176
+ const messageThread = new Map();
1177
+ for (const m of ev.messages) {
1178
+ if (m.turnId === undefined || snapshotTurnIds.has(m.turnId))
1179
+ continue;
1180
+ if (messageThread.get(m.turnId) === undefined)
1181
+ messageThread.set(m.turnId, m.threadId);
1182
+ }
1183
+ for (const [turnId, threadId] of messageThread)
1184
+ this.#seenOpened.set(turnId, threadId);
1021
1185
  // Un-park.
1022
1186
  this.#resync = false;
1023
1187
  break;
@@ -1068,6 +1232,9 @@ export class Reducer {
1068
1232
  // because it corrupts batch AND incremental identically). (final-review M1)
1069
1233
  this.#toolArgs.delete(blockId);
1070
1234
  this.#opaque.delete(blockId);
1235
+ // INV-BLOCK is about ids PRESENT in the fold (SPEC INV-BLOCK): a removed
1236
+ // block's id is no longer present, so a later *.start may reuse it.
1237
+ this.#invokeBlockIds.delete(blockId);
1071
1238
  }
1072
1239
  }
1073
1240
  // Remove from #messages.
@@ -1165,6 +1332,22 @@ export class Reducer {
1165
1332
  * If omitted and exactly one turn is open, return that turn's id.
1166
1333
  * Otherwise return `undefined` (ambiguous / no turns open).
1167
1334
  */
1335
+ /** INV-MSG: true when the message is sealed or its turn has closed (rd-14 closed-turn half). */
1336
+ #isClosedTarget(messageId) {
1337
+ if (this.#sealed.has(messageId))
1338
+ return true;
1339
+ const turnId = this.#messages.get(messageId)?.turnId;
1340
+ return turnId !== undefined && this.#closedTurns.has(turnId);
1341
+ }
1342
+ /** rd-14 INV-BLOCK: a block-creating id seen twice in one invoke parks; else records it. */
1343
+ #dupBlock(id) {
1344
+ if (this.#invokeBlockIds.has(id)) {
1345
+ this.#resync = true;
1346
+ return true;
1347
+ }
1348
+ this.#invokeBlockIds.add(id);
1349
+ return false;
1350
+ }
1168
1351
  #resolveTurnId(turnId) {
1169
1352
  if (turnId !== undefined)
1170
1353
  return turnId;
@@ -1191,6 +1374,25 @@ export class Reducer {
1191
1374
  * AgTurnRecord requires `threadId`; when creating a defensive stub we use the
1192
1375
  * turnId itself as a placeholder (no threadId is available without turn.start).
1193
1376
  */
1377
+ /**
1378
+ * D9: the record a terminal for a SEEN turn folds onto — the existing one,
1379
+ * else one created on the thread the fold saw the turn opened on. With no
1380
+ * thread known it returns undefined and the terminal folds onto no record.
1381
+ * No other turn's thread is borrowed (that could adopt a subagent's parent
1382
+ * label as a threadId), and a D9 path never writes a threadId equal to its
1383
+ * turnId.
1384
+ */
1385
+ #seenTurnRecord(turnId) {
1386
+ const existing = this.#turns.get(turnId);
1387
+ if (existing !== undefined)
1388
+ return existing;
1389
+ const threadId = this.#seenOpened.get(turnId);
1390
+ if (threadId === undefined)
1391
+ return undefined;
1392
+ const record = { turnId, threadId };
1393
+ this.#turns.set(turnId, record);
1394
+ return record;
1395
+ }
1194
1396
  ensureTurn(turnId) {
1195
1397
  const resolved = this.#resolveTurnId(turnId) ?? turnId;
1196
1398
  const key = resolved ?? "unknown-turn";