@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
@@ -4,8 +4,7 @@
4
4
  * turn, emits subagent lifecycle, and enforces turn-scoped monotonic seq. Used by
5
5
  * the stateful `Normalizer` implementations in `@silverprotocol/<framework>` packages.
6
6
  *
7
- * Generalised from the guuey-side `backend/services/nocode-runtime/src/stream-assembler.ts`
8
- * (spec §8.2 / §16). The guuey-side version will be deleted in T5.
7
+ * Generalised from a reference host's stream assembler (spec §8.2 / §16).
9
8
  *
10
9
  * Invariants enforced:
11
10
  * I1 – `turn.start` synthesized when `openMessage` is called for an unseen turnId
@@ -18,6 +17,7 @@
18
17
  */
19
18
 
20
19
  import type { AgEvent, AgClosedEventType, AgTrigger, AgUsage, AgRole, AgNoticeSource, AgBlock, AgOpaqueKind, AgProviderMeta, AgCitation, JsonValue } from "./agjson.js";
20
+ import { withoutOwnProtoMember } from "./copy-json.js";
21
21
 
22
22
  // Extracted closed-event arm types (no `as` casts — Extract keeps types typed at source).
23
23
  type TurnStartEvent = Extract<AgClosedEventType, { type: "turn.start" }>;
@@ -156,7 +156,7 @@ export class StreamAssembler {
156
156
  // turnIds currently OPEN (opened, not yet closed) — insertion order (JS Sets
157
157
  // iterate in insertion order). Bookkept in the single emit funnel `#emit` so
158
158
  // EVERY turn-lifecycle event (sugar primitives + raw `emit()`) keeps it correct.
159
- // Drives `flush()`'s INV-FLUSH turn.abort closure (audit M21).
159
+ // Drives `flush()`'s INV-FLUSH turn.abort closure.
160
160
  #openTurns = new Set<string>();
161
161
 
162
162
  // turnIds whose terminal (turn.done / turn.error / turn.abort, or a nested
@@ -172,17 +172,17 @@ export class StreamAssembler {
172
172
 
173
173
  // messageId → turnId map (populated in openMessage): used by content/tool events
174
174
  // to backfill turnId from the owning message when the event carries no turnId.
175
- // Mirrors the guuey-side StreamAssembler #msgTurn.
175
+ // Mirrors a reference host's StreamAssembler #msgTurn.
176
176
  #msgTurn = new Map<string, string>();
177
177
 
178
178
  // The most recent turnId introduced by any turn-opening event (openTurn,
179
179
  // openMessage, subagentStart). Fallback for content events that carry neither
180
- // turnId nor messageId (e.g. an orphan tool.done). Mirrors guuey #lastTurn.
180
+ // turnId nor messageId (e.g. an orphan tool.done). Mirrors a reference host's #lastTurn.
181
181
  #lastTurn: string | undefined = undefined;
182
182
 
183
183
  // Stack of #lastTurn snapshots, one pushed per subagentStart and popped by
184
- // the matching subagentDone (Task 8c leg 1 — guuey capstone finding A). The
185
- // OLD owner-fallback reused the wire-visible `parentTurnId` argument directly
184
+ // the matching subagentDone. The OLD owner-fallback (a reference host found
185
+ // its defect) reused the wire-visible `parentTurnId` argument directly
186
186
  // as the restored owner, but a facet's `parentTurnId` label (e.g. claude's
187
187
  // synthetic `turn_${toolCallId}` Task-tool cross-ref) MAY never have been
188
188
  // opened as a real turn — reusing it fabricated a phantom turn and corrupted
@@ -209,7 +209,7 @@ export class StreamAssembler {
209
209
 
210
210
  /** Emit one closed event into the buffer. */
211
211
  #emit(ev: AgClosedEventType): void {
212
- // Turn-lifecycle bookkeeping (INV-TURN / INV-FLUSH; audit M21). `#emit` is the
212
+ // Turn-lifecycle bookkeeping (INV-TURN / INV-FLUSH). `#emit` is the
213
213
  // single funnel every primitive (and the raw `emit()` base primitive) routes
214
214
  // through, so this is the one place that can never miss a turn open/close.
215
215
  switch (ev.type) {
@@ -234,12 +234,15 @@ export class StreamAssembler {
234
234
  default:
235
235
  break;
236
236
  }
237
- this.#buffer.push(ev);
237
+ // §13.7: an emitted event holds no own `__proto__` member at any depth. The
238
+ // copy rebuilds only when a node holds one, and never mutates the caller's
239
+ // values; a class instance rides by reference.
240
+ this.#buffer.push(withoutOwnProtoMember(ev));
238
241
  }
239
242
 
240
243
  /** Emit one AgExtEvent into the buffer (open template-literal type). */
241
244
  #emitExt(ev: AgEvent): void {
242
- this.#buffer.push(ev);
245
+ this.#buffer.push(withoutOwnProtoMember(ev));
243
246
  }
244
247
 
245
248
  /** Ensure a turn.start has been emitted for `turnId`. If not seen, synthesize one. */
@@ -259,7 +262,7 @@ export class StreamAssembler {
259
262
  /**
260
263
  * Resolve a turnId for a content/tool event: explicit field → owning message's
261
264
  * turnId (#msgTurn) → current open turn (#lastTurn).
262
- * Mirrors the guuey-side `withTurnId` + `#msgTurn`/`#lastTurn` resolution order.
265
+ * Mirrors a reference host's `withTurnId` + `#msgTurn`/`#lastTurn` resolution order.
263
266
  */
264
267
  #resolveTurnId(explicitTurnId: string | undefined, messageId: string | undefined): string | undefined {
265
268
  if (explicitTurnId !== undefined) return explicitTurnId;
@@ -366,7 +369,7 @@ export class StreamAssembler {
366
369
  * `turn.start` (fix: subagent-turn-double-open / subagent-turnstart-ordering).
367
370
  */
368
371
  subagentStart(turnId: string, parentTurnId: string): void {
369
- // Task 8c leg 1: snapshot the CURRENT owner before switching into the
372
+ // Snapshot the CURRENT owner before switching into the
370
373
  // nested turn, so the matching subagentDone can restore it verbatim —
371
374
  // never the (possibly synthetic) `parentTurnId` wire label.
372
375
  this.#turnStack.push(this.#lastTurn);
@@ -390,7 +393,7 @@ export class StreamAssembler {
390
393
  parentTurnId,
391
394
  };
392
395
  this.#emit(ev);
393
- // INV-OWNER (Task 8c leg 1 — supersedes audit B10's parentTurnId reuse):
396
+ // INV-OWNER (this supersedes the earlier reuse of the parentTurnId argument):
394
397
  // restored to the ENCLOSING turn that was current when the subagent
395
398
  // opened — never the wire parentTurnId label, which MAY be a synthetic
396
399
  // cross-ref (e.g. claude's `turn_${toolCallId}`) that was never opened as
@@ -438,7 +441,7 @@ export class StreamAssembler {
438
441
 
439
442
  /**
440
443
  * Emit `text.end` for a finished text content stream. `fields.citations` is the
441
- * STREAMED-text citations carrier (audit M22): a normalizer passes citations for
444
+ * STREAMED-text citations carrier: a normalizer passes citations for
442
445
  * this block here — never as a duplicate id-less supplement block — and `reduce()`
443
446
  * attaches them to the sealed block named by `id`.
444
447
  */
@@ -483,7 +486,7 @@ export class StreamAssembler {
483
486
  * prior buffer. `opts.providerMetadata` rides the delta verbatim — the home
484
487
  * for a provider's per-chunk, replay-load-bearing reasoning metadata; absent
485
488
  * ⇒ no key. Host-only telemetry does NOT belong here: e.g. the Claude CLI's
486
- * per-delta `estimated_tokens` rides `_meta` (X5). This sugar has no `_meta`
489
+ * per-delta `estimated_tokens` rides `_meta`. This sugar has no `_meta`
487
490
  * option, so a facet raw-emits the delta for that case.
488
491
  */
489
492
  reasoningDelta(
@@ -643,7 +646,7 @@ export class StreamAssembler {
643
646
  /**
644
647
  * Emit an open `ext.<vendor>.<key>` event (lossless vendor extension channel).
645
648
  * The type field is the only constraint: `ext.` + vendor + `.` + key.
646
- * M49: the lossless vendor channel never drops payload bytes. Non-object
649
+ * The lossless vendor channel never drops payload bytes. Non-object
647
650
  * payloads ride under `value`; reserved-envelope collisions relocate under
648
651
  * `shadowed` (the envelope stays engine-owned — ratified anti-clobber).
649
652
  * Payload's own `value` key wins the top-level slot when no wrapper is
@@ -710,7 +713,7 @@ export class StreamAssembler {
710
713
  * A restorable snapshot of this assembler's whole state: the seq counter,
711
714
  * the turn / message trackers, the turn stack, the cumulative-delta
712
715
  * buffers and how many events sit undrained. It exists for a facet's
713
- * per-native transaction (the fleet guard ruling, 2026-09-24): take a
716
+ * per-native transaction (the no-throw guard ruling, 2026-09-24): take a
714
717
  * checkpoint before driving one native, and {@link rollback} to it if
715
718
  * driving throws. The discarded partial batch then consumes no seq
716
719
  * (INV-SEQ), and no turn, message or block it half-opened survives.
@@ -770,7 +773,7 @@ export class StreamAssembler {
770
773
  * Flush per INV-FLUSH (SPEC §5.0): (1) synthetic `message.end` for each
771
774
  * still-open message in insertion order; (2) `turn.abort{stream-truncated}`
772
775
  * for each still-open turn, innermost (latest-opened) first — NEVER a
773
- * success close (audit M21); (3) nothing else.
776
+ * success close; (3) nothing else.
774
777
  */
775
778
  flush(): AgEvent[] {
776
779
  for (const [id] of this.#openMessages) {
package/src/wire.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Wire projection (audit D5-a). SPEC §0.1 asserts every AgEvent is a plain
2
+ * Wire projection. SPEC §0.1 asserts every AgEvent is a plain
3
3
  * JSON value, but TypeScript cannot PROVE `AgEvent extends JsonValue`
4
4
  * (structural interfaces like AgUsage lack index signatures). These helpers
5
5
  * are the single sanctioned crossing: a JSON round-trip typed at the
@@ -41,6 +41,22 @@ export const JSON_SAFE_MAX_DEPTH_MARK = "[MaxDepth]";
41
41
  * @beta
42
42
  */
43
43
  export const JSON_SAFE_MAX_DEPTH = 1000;
44
+ /**
45
+ * The levels an event's own members may add above a carried value that
46
+ * {@link toJsonValueSafe} capped at {@link JSON_SAFE_MAX_DEPTH}.
47
+ *
48
+ * @beta
49
+ */
50
+ export const AG_EVENT_DEPTH_ALLOWANCE = 16;
51
+ /**
52
+ * The deepest node an event may hold, counted from the event root: the root is
53
+ * at depth 0 and a node's depth is the number of containers above it.
54
+ * {@link JSON_SAFE_MAX_DEPTH} plus {@link AG_EVENT_DEPTH_ALLOWANCE}. A consuming
55
+ * ingest rejects a deeper event, and a reducer parks on one.
56
+ *
57
+ * @beta
58
+ */
59
+ export const AG_EVENT_MAX_DEPTH = JSON_SAFE_MAX_DEPTH + AG_EVENT_DEPTH_ALLOWANCE;
44
60
 
45
61
  /**
46
62
  * Why {@link toJsonValueSafe} had to degrade a node that `JSON.stringify` would have thrown on.
@@ -77,6 +93,17 @@ export interface JsonSafeIssue {
77
93
  * @beta
78
94
  */
79
95
  export function isJsonValue(v: unknown): v is JsonValue {
96
+ return jsonWalk(v, false);
97
+ }
98
+
99
+ /** {@link isJsonValue} where every object also has the ordinary prototype
100
+ * (`Object.prototype`, or `Array.prototype` for an array): no null-prototype
101
+ * node. The fast path of {@link toJsonValueSafeWithIssues} uses it. */
102
+ function isOrdinaryJsonValue(v: unknown): v is JsonValue {
103
+ return jsonWalk(v, true);
104
+ }
105
+
106
+ function jsonWalk(v: unknown, ordinaryOnly: boolean): boolean {
80
107
  const ancestors: object[] = [];
81
108
  const walk = (x: unknown, depth: number): boolean => {
82
109
  if (x === null) return true;
@@ -96,13 +123,14 @@ export function isJsonValue(v: unknown): v is JsonValue {
96
123
  ancestors.push(o);
97
124
  try {
98
125
  if (Array.isArray(o)) {
126
+ if (ordinaryOnly && Object.getPrototypeOf(o) !== Array.prototype) return false;
99
127
  for (let i = 0; i < o.length; i++) {
100
128
  if (!(i in o) || !walk(o[i], depth + 1)) return false;
101
129
  }
102
130
  return true;
103
131
  }
104
132
  const proto: unknown = Object.getPrototypeOf(o);
105
- if (proto !== Object.prototype && proto !== null) return false;
133
+ if (proto !== Object.prototype && (ordinaryOnly || proto !== null)) return false;
106
134
  if (typeof (o as { toJSON?: unknown }).toJSON === "function") return false;
107
135
  for (const k in o) {
108
136
  if (!Object.prototype.hasOwnProperty.call(o, k)) continue;
@@ -135,8 +163,10 @@ export function isJsonValue(v: unknown): v is JsonValue {
135
163
  * Normalizer MUST NOT throw out of `push()` (SPEC.md §8.0). Keep
136
164
  * `JsonValue.parse` for validating data that is already JSON.
137
165
  *
138
- * Plain JSON input (see {@link isJsonValue}) is returned UNCHANGED, as the same
139
- * reference, with no copy. Anything else is rebuilt as a fresh value that
166
+ * Plain JSON input (see {@link isJsonValue}) whose every object has the
167
+ * ordinary prototype is returned UNCHANGED, as the same reference, with no
168
+ * copy. Anything else, a null-prototype node included, is rebuilt as a fresh
169
+ * value whose every object has the ordinary prototype and that
140
170
  * applies `JSON.stringify`'s own rules per node, so for JSON-able input the
141
171
  * result serializes identically to `toJsonValue(v)`:
142
172
  * - `toJSON` is honoured once per node, with the member key (a `Date` becomes
@@ -208,7 +238,7 @@ function isErrorObject(o: object): boolean {
208
238
  * @beta
209
239
  */
210
240
  export function toJsonValueSafeWithIssues(v: unknown): { value: JsonValue; issues: readonly JsonSafeIssue[] } {
211
- if (isJsonValue(v)) return { value: v, issues: [] };
241
+ if (isOrdinaryJsonValue(v)) return { value: v, issues: [] };
212
242
  const issues: JsonSafeIssue[] = [];
213
243
  const ancestors: object[] = [];
214
244
  const OMIT = Symbol("omit");
@@ -257,7 +287,7 @@ export function toJsonValueSafeWithIssues(v: unknown): { value: JsonValue; issue
257
287
  return JSON_SAFE_MAX_DEPTH_MARK;
258
288
  }
259
289
  if (isErrorObject(obj)) {
260
- // Deliberate extension beyond JSON (sp-main, 2026-09-24): an Error's
290
+ // Deliberate extension beyond JSON (ruled 2026-09-24): an Error's
261
291
  // `name` and `message` are not enumerable own data, so JSON drops them
262
292
  // and a live error part loses its text. Map it to {name, message, …own
263
293
  // enumerable props}, and NEVER `stack` (it holds local file paths).