@silverprotocol/core 0.12.4 → 0.12.6

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.
@@ -108,15 +108,27 @@ export function checkAgInput(raw: unknown): AgInputCheck {
108
108
  if (version.split(".")[0] !== MAJOR) return reject("major-mismatch", ["version"]);
109
109
  // then the rest.
110
110
  if (!isJsonValue(raw)) return reject("malformed", []);
111
- const parsed = AgInput.safeParse(raw);
111
+ // A throw from the parse (a getter, a schema recursing past the call stack)
112
+ // is a malformed input, never a throw out of the check.
113
+ let parsed: ReturnType<typeof AgInput.safeParse>;
114
+ try {
115
+ parsed = AgInput.safeParse(raw);
116
+ } catch {
117
+ return reject("malformed", []);
118
+ }
112
119
  if (parsed.success) return { ok: true, input: copyJson(raw as JsonValue) as unknown as AgInput };
113
120
  const issues = parsed.error.issues as unknown as Issue[];
114
121
  const problems: Problem[] = [];
115
122
  // An undefined kind stops zod at the discriminator: judge the envelope
116
123
  // members anyway, and never the members only that kind would select.
117
124
  if (issues.some((i) => i.code === "invalid_union" && i.options !== undefined && samePath(toPath(i.path), ["kind"]))) {
118
- const envelope = AgInputEnvelope.safeParse(raw);
119
- if (!envelope.success) for (const i of envelope.error.issues as unknown as Issue[]) problems.push(...problemsOf(raw, i, []));
125
+ let envelope: ReturnType<typeof AgInputEnvelope.safeParse> | undefined;
126
+ try {
127
+ envelope = AgInputEnvelope.safeParse(raw);
128
+ } catch {
129
+ envelope = undefined;
130
+ }
131
+ if (envelope !== undefined && !envelope.success) for (const i of envelope.error.issues as unknown as Issue[]) problems.push(...problemsOf(raw, i, []));
120
132
  }
121
133
  for (const i of issues) problems.push(...problemsOf(raw, i, []));
122
134
  const pick = problems.find((p) => p.code === "malformed") ?? problems.find((p) => p.code === "unknown-value");
package/src/json-patch.ts CHANGED
@@ -16,6 +16,10 @@ import type { JsonValue } from "./agjson.js";
16
16
  // RFC-6901 pointer parsing:
17
17
  // • split on "/"; unescape "~1" → "/" then "~0" → "~" (ORDER MATTERS).
18
18
  // • "" (empty pointer) = the whole document (root replacement).
19
+ //
20
+ // Member resolution: a token names an object member only when the object holds
21
+ // it as its OWN member; an inherited name (toString, constructor, …) is absent.
22
+ // `add` of such a name still creates it as an own member (RFC 6902 §4.1).
19
23
  // ─────────────────────────────────────────────────────────────────────────────
20
24
 
21
25
  /** Result type returned by applyPatch. */
@@ -63,6 +67,11 @@ function parsePointer(ptr: string): string[] | null {
63
67
  .map((tok) => tok.replace(/~1/g, "/").replace(/~0/g, "~"));
64
68
  }
65
69
 
70
+ /** The object's OWN member `tok`, or undefined when it holds none (inherited names included). */
71
+ function ownMember(node: { [k: string]: JsonValue }, tok: string): JsonValue | undefined {
72
+ return Object.hasOwn(node, tok) ? node[tok] : undefined;
73
+ }
74
+
66
75
  /**
67
76
  * Resolve a JSON Pointer in a document, returning { parent, key, value } on
68
77
  * success, or null on failure (absent path, wrong type at an intermediate node).
@@ -90,7 +99,7 @@ function resolve(
90
99
  if (child === undefined) return null;
91
100
  node = child;
92
101
  } else if (isJsonObject(node)) {
93
- const child = node[tok];
102
+ const child = ownMember(node, tok);
94
103
  if (child === undefined) return null;
95
104
  node = child;
96
105
  } else {
@@ -108,7 +117,7 @@ function resolve(
108
117
  if (value === undefined) return null;
109
118
  return { parent: node, key: String(idx), value };
110
119
  } else if (isJsonObject(node)) {
111
- const value = node[lastTok];
120
+ const value = ownMember(node, lastTok);
112
121
  if (value === undefined) return null;
113
122
  return { parent: node, key: lastTok, value };
114
123
  }
@@ -177,7 +186,7 @@ function pointerSet(
177
186
  return { ok: true, doc: copy };
178
187
  } else if (isJsonObject(doc)) {
179
188
  // Object: add creates/replaces; replace requires the key to exist.
180
- if (!isAdd && !(tok in doc)) return POINTER_FAIL; // replace: key must exist
189
+ if (!isAdd && !Object.hasOwn(doc, tok)) return POINTER_FAIL; // replace: own key must exist
181
190
  return { ok: true, doc: { ...doc, [tok]: value } };
182
191
  }
183
192
  return POINTER_FAIL; // scalar — cannot descend
@@ -199,7 +208,7 @@ function pointerSet(
199
208
  copy[idx] = childResult.doc;
200
209
  return { ok: true, doc: copy };
201
210
  } else if (isJsonObject(doc)) {
202
- const child = doc[tok];
211
+ const child = ownMember(doc, tok);
203
212
  if (child === undefined) return POINTER_FAIL;
204
213
  const childResult = pointerSet(child, rest, value, isAdd);
205
214
  if (!childResult.ok) return POINTER_FAIL;
@@ -232,7 +241,7 @@ function pointerRemove(doc: JsonValue, tokens: string[]): PointerResult {
232
241
  copy.splice(idx, 1);
233
242
  return { ok: true, doc: copy };
234
243
  } else if (isJsonObject(doc)) {
235
- if (!(tok in doc)) return POINTER_FAIL;
244
+ if (!Object.hasOwn(doc, tok)) return POINTER_FAIL;
236
245
  const { [tok]: _removed, ...rest } = doc;
237
246
  return { ok: true, doc: rest };
238
247
  }
@@ -255,7 +264,7 @@ function pointerRemove(doc: JsonValue, tokens: string[]): PointerResult {
255
264
  copy[idx] = childResult.doc;
256
265
  return { ok: true, doc: copy };
257
266
  } else if (isJsonObject(doc)) {
258
- const child = doc[tok];
267
+ const child = ownMember(doc, tok);
259
268
  if (child === undefined) return POINTER_FAIL;
260
269
  const childResult = pointerRemove(child, rest);
261
270
  if (!childResult.ok) return POINTER_FAIL;
@@ -287,7 +296,7 @@ function deepEqual(a: JsonValue, b: JsonValue): boolean {
287
296
  const bKeys = Object.keys(b);
288
297
  if (aKeys.length !== bKeys.length) return false;
289
298
  for (const k of aKeys) {
290
- if (!(k in b)) return false;
299
+ if (!Object.hasOwn(b, k)) return false;
291
300
  const av = a[k];
292
301
  const bv = b[k];
293
302
  if (av === undefined || bv === undefined) return false;
package/src/record.ts CHANGED
@@ -36,7 +36,26 @@
36
36
  */
37
37
  import { AgBlock, AgMemoryRecord, AgMessage, type JsonValue } from "./agjson.js";
38
38
  import { copyJson } from "./copy-json.js";
39
- import { isJsonValue, toJsonValueSafe } from "./wire.js";
39
+ import { toJsonValueSafe } from "./wire.js";
40
+ import { AG_EVENT_DEPTH_ALLOWANCE, AG_EVENT_MAX_DEPTH, isJsonValueWithin } from "./depth.js";
41
+
42
+ /**
43
+ * The deepest node a stored record may hold, from its root. The fold places a
44
+ * block's members a few levels deeper in its message than in the event that
45
+ * carried them (a tool result's content, a tool call's input), so a record
46
+ * the fold built from events inside AG_EVENT_MAX_DEPTH reads back within
47
+ * this bound.
48
+ */
49
+ const STORED_RECORD_MAX_DEPTH = AG_EVENT_MAX_DEPTH + AG_EVENT_DEPTH_ALLOWANCE;
50
+ const isStoredJson = (v: unknown): v is JsonValue => isJsonValueWithin(v, STORED_RECORD_MAX_DEPTH);
51
+ /** Whether `v` validates against `schema`; a throw from the parse is a failure, never a throw out of the reader. */
52
+ const passes = (schema: { safeParse(v: unknown): { success: boolean } }, v: unknown): boolean => {
53
+ try {
54
+ return schema.safeParse(v).success;
55
+ } catch {
56
+ return false;
57
+ }
58
+ };
40
59
 
41
60
  /** One omitted element or record: where it was, its type when it had one, and its verbatim value. */
42
61
  export interface AgRecordReport {
@@ -66,7 +85,7 @@ const isObject = (v: JsonValue): v is JsonObject => v !== null && typeof v === "
66
85
 
67
86
  /** A value as a report can carry it: a JSON value is copied verbatim; a
68
87
  * non-JSON one (never read from JSON storage) is made JSON-safe. */
69
- const reportRaw = (v: unknown): JsonValue => (isJsonValue(v) ? copyJson(v) : toJsonValueSafe(v));
88
+ const reportRaw = (v: unknown): JsonValue => (isStoredJson(v) ? copyJson(v) : toJsonValueSafe(v));
70
89
 
71
90
  function report(path: (string | number)[], raw: unknown, ignoredType?: string): AgRecordReport {
72
91
  return { path, ...(ignoredType !== undefined ? { ignoredType } : {}), raw: reportRaw(raw) };
@@ -78,11 +97,11 @@ function report(path: (string | number)[], raw: unknown, ignoredType?: string):
78
97
  * `value` and one report at path `[]`.
79
98
  */
80
99
  export function readStoredAgMessage(raw: unknown): AgRecordRead<AgMessage> {
81
- if (!isJsonValue(raw) || !isObject(raw) || !Array.isArray(raw["content"])) return { reports: [report([], raw)] };
100
+ if (!isStoredJson(raw) || !isObject(raw) || !Array.isArray(raw["content"])) return { reports: [report([], raw)] };
82
101
  const kept: JsonValue[] = [];
83
102
  const reports: AgRecordReport[] = [];
84
103
  raw["content"].forEach((element, i) => {
85
- if (AgBlock.safeParse(element).success) {
104
+ if (passes(AgBlock, element)) {
86
105
  kept.push(copyJson(element));
87
106
  return;
88
107
  }
@@ -101,7 +120,7 @@ export function readStoredAgMessage(raw: unknown): AgRecordRead<AgMessage> {
101
120
  });
102
121
  }
103
122
  // Every other defined field must be valid; else the whole record is reported.
104
- if (!AgMessage.safeParse(view).success) return { reports: [report([], raw)] };
123
+ if (!passes(AgMessage, view)) return { reports: [report([], raw)] };
105
124
  return { value: view as unknown as AgMessage, reports };
106
125
  }
107
126
 
@@ -124,7 +143,7 @@ export function readStoredAgMemoryRecords(raws: readonly unknown[]): AgRecordsRe
124
143
  const value: AgMemoryRecord[] = [];
125
144
  const reports: AgRecordReport[] = [];
126
145
  raws.forEach((raw, i) => {
127
- if (isJsonValue(raw) && isObject(raw) && AgMemoryRecord.safeParse(raw).success) value.push(copyJson(raw) as unknown as AgMemoryRecord);
146
+ if (isStoredJson(raw) && isObject(raw) && passes(AgMemoryRecord, raw)) value.push(copyJson(raw) as unknown as AgMemoryRecord);
128
147
  else reports.push(report([i], raw));
129
148
  });
130
149
  return { value, reports };
package/src/reduce.ts CHANGED
@@ -14,6 +14,7 @@ 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
18
 
18
19
  // ─────────────────────────────────────────────────────────────────────────────
19
20
  // Reducer — the normative event→state fold (spec §5).
@@ -108,6 +109,13 @@ function isClosedEvent(ev: AgEvent): ev is AgClosedEventType {
108
109
  const HELD_TURNS_CAP = 64;
109
110
  const HELD_LANDINGS_CAP = 1024;
110
111
 
112
+ /**
113
+ * The deepest node of a state or memory value a patch may leave, counted from
114
+ * the value's root: the depth at which a state.snapshot's `snapshot` or a
115
+ * memory.write's `value` sits below its event root is 1.
116
+ */
117
+ const STORED_VALUE_MAX_DEPTH = AG_EVENT_MAX_DEPTH - 1;
118
+
111
119
  export class Reducer {
112
120
  // ── keyed accumulators ──────────────────────────────────────────────────────
113
121
  // Messages, keyed by message id (insertion-ordered).
@@ -185,6 +193,13 @@ export class Reducer {
185
193
  * R3–R10 fill remaining content types.
186
194
  */
187
195
  push(ev: AgEvent): void {
196
+ // 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.
201
+ const scan = scanDepth(ev, AG_EVENT_MAX_DEPTH);
202
+
188
203
  // ── Seq-gap detection (R9) ────────────────────────────────────────────────
189
204
  // Seq accounting is UNIVERSAL (INV-SEQ: "gap-free ordinal" over the whole
190
205
  // per-invoke stream) — EVERY well-formed event with a numeric seq advances
@@ -226,6 +241,7 @@ export class Reducer {
226
241
  this.#invokeBlockIds.clear();
227
242
  this.#finalToolDone.clear();
228
243
  }
244
+ if (scan.tooDeep) return;
229
245
 
230
246
  // Store-time isolation: the handlers below keep references into the event
231
247
  // (a block, a providerMetadata or _meta bag, a tool result, an outcome, a
@@ -1060,8 +1076,9 @@ export class Reducer {
1060
1076
  break;
1061
1077
  }
1062
1078
  const result = applyPatch(this.#state, patch);
1063
- if (!result.ok) {
1064
- // applyPatch failed — signal resync; leave #state unchanged.
1079
+ if (!result.ok || exceedsDepth(result.value, STORED_VALUE_MAX_DEPTH)) {
1080
+ // applyPatch failed, or its result nests deeper than a
1081
+ // state.snapshot could carry — signal resync; leave #state unchanged.
1065
1082
  this.#resync = true;
1066
1083
  break;
1067
1084
  }
@@ -1122,8 +1139,9 @@ export class Reducer {
1122
1139
  break;
1123
1140
  }
1124
1141
  const result = applyPatch(existing.value, ev.patch);
1125
- if (!result.ok) {
1126
- // applyPatch failed — set resync flag and leave record unchanged.
1142
+ if (!result.ok || exceedsDepth(result.value, STORED_VALUE_MAX_DEPTH)) {
1143
+ // applyPatch failed, or its result nests deeper than a memory.write
1144
+ // value could — set resync flag and leave record unchanged.
1127
1145
  this.#resync = true;
1128
1146
  break;
1129
1147
  }