@silverprotocol/core 0.12.4 → 1.0.0-rc.1
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.
- package/README.md +17 -9
- package/dist/agjson.d.ts +594 -594
- package/dist/agjson.d.ts.map +1 -1
- package/dist/agjson.js +132 -17
- package/dist/agjson.js.map +1 -1
- package/dist/atomic-push.js.map +1 -1
- package/dist/copy-json.d.ts +31 -4
- package/dist/copy-json.d.ts.map +1 -1
- package/dist/copy-json.js +147 -15
- package/dist/copy-json.js.map +1 -1
- package/dist/depth.d.ts +34 -0
- package/dist/depth.d.ts.map +1 -0
- package/dist/depth.js +141 -0
- package/dist/depth.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +7 -2
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +36 -4
- package/dist/ingest.js.map +1 -1
- package/dist/input-check.d.ts.map +1 -1
- package/dist/input-check.js +17 -3
- package/dist/input-check.js.map +1 -1
- package/dist/json-patch.d.ts.map +1 -1
- package/dist/json-patch.js +17 -9
- package/dist/json-patch.js.map +1 -1
- package/dist/persist.js.map +1 -1
- package/dist/record.d.ts.map +1 -1
- package/dist/record.js +25 -6
- package/dist/record.js.map +1 -1
- package/dist/reduce.d.ts +1 -1
- package/dist/reduce.d.ts.map +1 -1
- package/dist/reduce.js +293 -112
- package/dist/reduce.js.map +1 -1
- package/dist/stream-assembler.d.ts +6 -7
- package/dist/stream-assembler.d.ts.map +1 -1
- package/dist/stream-assembler.js +21 -18
- package/dist/stream-assembler.js.map +1 -1
- package/dist/wire.d.ts +21 -3
- package/dist/wire.d.ts.map +1 -1
- package/dist/wire.js +34 -5
- package/dist/wire.js.map +1 -1
- package/package.json +1 -1
- package/src/agjson.ts +128 -28
- package/src/atomic-push.ts +2 -2
- package/src/copy-json.ts +143 -17
- package/src/depth.ts +138 -0
- package/src/index.ts +1 -0
- package/src/ingest.ts +35 -4
- package/src/input-check.ts +15 -3
- package/src/json-patch.ts +21 -8
- package/src/record.ts +25 -6
- package/src/reduce.ts +273 -111
- package/src/stream-assembler.ts +21 -18
- package/src/wire.ts +36 -6
package/src/depth.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* depth.ts — INTERNAL (not re-exported from index.ts).
|
|
3
|
+
*
|
|
4
|
+
* The nesting check run before a value reaches a recursive reader (the schema
|
|
5
|
+
* parse, structuredClone, a JSON Patch application), so that a value nested
|
|
6
|
+
* past a bound is turned away instead of overflowing the call stack.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { JsonValue } from "./agjson.js";
|
|
10
|
+
|
|
11
|
+
/** What one scan of a value found: a node past the bound, and an own `__proto__` member. */
|
|
12
|
+
export interface DepthScan {
|
|
13
|
+
tooDeep: boolean;
|
|
14
|
+
hasOwnProto: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The objects the fast walk visits before it hands the value to the walk that
|
|
19
|
+
* remembers each node. A JSON-parsed value shares no node, so the memory is
|
|
20
|
+
* overhead for it; a value that shares nodes can make the fast walk revisit
|
|
21
|
+
* them without end, and the budget turns that into the remembering walk.
|
|
22
|
+
*/
|
|
23
|
+
const SCAN_NODE_BUDGET = 50_000;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One iterative pass: whether some node sits deeper than `max` (the root at
|
|
27
|
+
* depth 0, a node's depth the number of containers above it), and whether any
|
|
28
|
+
* object other than an array holds an own `__proto__` member. It visits every
|
|
29
|
+
* object and array, as deleteOwnProtoMember does. With `remember`, a node
|
|
30
|
+
* reached again is walked again only when it is reached deeper than before;
|
|
31
|
+
* without, it returns undefined once it has visited SCAN_NODE_BUDGET objects.
|
|
32
|
+
*/
|
|
33
|
+
function scanPass(v: unknown, max: number, remember: boolean): DepthScan | undefined {
|
|
34
|
+
const deepest = remember ? new WeakMap<object, number>() : undefined;
|
|
35
|
+
let visits = 0;
|
|
36
|
+
let hasOwnProto = false;
|
|
37
|
+
const nodes: unknown[] = [v];
|
|
38
|
+
const depths: number[] = [0];
|
|
39
|
+
while (nodes.length > 0) {
|
|
40
|
+
const x = nodes.pop();
|
|
41
|
+
const depth = depths.pop()!;
|
|
42
|
+
if (depth > max) return { tooDeep: true, hasOwnProto };
|
|
43
|
+
if (x === null || typeof x !== "object") continue;
|
|
44
|
+
if (deepest !== undefined) {
|
|
45
|
+
const seen = deepest.get(x);
|
|
46
|
+
if (seen !== undefined && seen >= depth) continue;
|
|
47
|
+
deepest.set(x, depth);
|
|
48
|
+
} else if (++visits > SCAN_NODE_BUDGET) {
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
if (Array.isArray(x)) {
|
|
52
|
+
for (let i = 0; i < x.length; i++) {
|
|
53
|
+
nodes.push(x[i]);
|
|
54
|
+
depths.push(depth + 1);
|
|
55
|
+
}
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (Object.hasOwn(x, "__proto__")) hasOwnProto = true;
|
|
59
|
+
for (const k of Object.keys(x)) {
|
|
60
|
+
nodes.push((x as Record<string, unknown>)[k]);
|
|
61
|
+
depths.push(depth + 1);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return { tooDeep: false, hasOwnProto };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Scan `v` once, never throwing: the fast pass, then, when it runs past its
|
|
69
|
+
* budget, the pass that remembers each node, so a cycle is too deep and a
|
|
70
|
+
* large value is still scanned whole (never turned away for its size). A
|
|
71
|
+
* value it cannot read (a getter or proxy trap that throws) answers not too
|
|
72
|
+
* deep and holding the member, leaving it to the paths that handled it before.
|
|
73
|
+
*/
|
|
74
|
+
export function scanDepth(v: unknown, max: number): DepthScan {
|
|
75
|
+
try {
|
|
76
|
+
return scanPass(v, max, false) ?? scanPass(v, max, true)!;
|
|
77
|
+
} catch {
|
|
78
|
+
return { tooDeep: false, hasOwnProto: true };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** True when some node of `v` sits deeper than `max`; see {@link scanDepth}. */
|
|
83
|
+
export function exceedsDepth(v: unknown, max: number): boolean {
|
|
84
|
+
return scanDepth(v, max).tooDeep;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* isJsonValue's test with a caller's depth bound in place of
|
|
89
|
+
* JSON_SAFE_MAX_DEPTH: true when `v` is a plain JSON value (null, a string, a
|
|
90
|
+
* boolean, a finite number other than -0, an array with no holes, or a plain
|
|
91
|
+
* or null-prototype object without an own toJSON, of such values) whose
|
|
92
|
+
* deepest node sits no deeper than `max`, the root at depth 0. Iterative, so
|
|
93
|
+
* it never overflows the stack; a cycle is too deep. Never throws: a value it
|
|
94
|
+
* cannot read answers false.
|
|
95
|
+
*/
|
|
96
|
+
export function isJsonValueWithin(v: unknown, max: number): v is JsonValue {
|
|
97
|
+
try {
|
|
98
|
+
const deepest = new WeakMap<object, number>();
|
|
99
|
+
const stack: Array<[unknown, number]> = [[v, 0]];
|
|
100
|
+
while (stack.length > 0) {
|
|
101
|
+
const [x, depth] = stack.pop()!;
|
|
102
|
+
if (depth > max) return false;
|
|
103
|
+
if (x === null) continue;
|
|
104
|
+
switch (typeof x) {
|
|
105
|
+
case "string":
|
|
106
|
+
case "boolean":
|
|
107
|
+
continue;
|
|
108
|
+
case "number":
|
|
109
|
+
if (!Number.isFinite(x) || Object.is(x, -0)) return false;
|
|
110
|
+
continue;
|
|
111
|
+
case "object":
|
|
112
|
+
break;
|
|
113
|
+
default:
|
|
114
|
+
return false; // undefined, function, symbol, bigint
|
|
115
|
+
}
|
|
116
|
+
const o = x as object;
|
|
117
|
+
const seen = deepest.get(o);
|
|
118
|
+
if (seen !== undefined && seen >= depth) continue;
|
|
119
|
+
deepest.set(o, depth);
|
|
120
|
+
if (Array.isArray(o)) {
|
|
121
|
+
for (let i = 0; i < o.length; i++) {
|
|
122
|
+
if (!(i in o)) return false;
|
|
123
|
+
stack.push([o[i], depth + 1]);
|
|
124
|
+
}
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const proto: unknown = Object.getPrototypeOf(o);
|
|
128
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
129
|
+
if (typeof (o as { toJSON?: unknown }).toJSON === "function") return false;
|
|
130
|
+
for (const k in o) {
|
|
131
|
+
if (Object.prototype.hasOwnProperty.call(o, k)) stack.push([(o as Record<string, unknown>)[k], depth + 1]);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
} catch {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
package/src/index.ts
CHANGED
package/src/ingest.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Consumer-ingestion posture (SPEC §0.2 / §12
|
|
2
|
+
* Consumer-ingestion posture (SPEC §0.2 / §12).
|
|
3
3
|
*
|
|
4
4
|
* A consumer validating incoming events MUST parse-known-else-skip and pass
|
|
5
5
|
* unknown fields through, so additive-minor spec revisions survive. This is
|
|
@@ -31,7 +31,12 @@
|
|
|
31
31
|
* stub `{type: "ext.agjson.ignored", seq, ignoredType, raw}`. It is a
|
|
32
32
|
* typed ext event: it never folds, but a Reducer counts its `seq` slot,
|
|
33
33
|
* so an ignored event can no longer open a false gap. `raw` is the
|
|
34
|
-
* original frame (same copy rules) and is LIVE-ONLY: never persist it
|
|
34
|
+
* original frame (same copy rules) and is LIVE-ONLY: never persist it.
|
|
35
|
+
* An envelope holding a node deeper than AG_EVENT_MAX_DEPTH becomes the
|
|
36
|
+
* same stub without being parsed, since the schema parse's recursion
|
|
37
|
+
* would overflow on it; its `raw` is the frame as toJsonValueSafe
|
|
38
|
+
* renders it, cut off at JSON_SAFE_MAX_DEPTH, so the stub itself stays
|
|
39
|
+
* within the bound;
|
|
35
40
|
* - anything else (not an object, a non-string `type`, a missing or
|
|
36
41
|
* non-number `seq`) → not an event and occupies no slot: returns
|
|
37
42
|
* undefined and is reported through the optional `onReject` callback.
|
|
@@ -39,6 +44,8 @@
|
|
|
39
44
|
*/
|
|
40
45
|
import { AgEvent, type JsonValue } from "./agjson.js";
|
|
41
46
|
import { copyJson } from "./copy-json.js";
|
|
47
|
+
import { exceedsDepth } from "./depth.js";
|
|
48
|
+
import { AG_EVENT_MAX_DEPTH, JSON_SAFE_MAX_DEPTH_MARK, toJsonValueSafe } from "./wire.js";
|
|
42
49
|
|
|
43
50
|
/** Why an input is not a well-formed envelope (draft.4 §0.2). */
|
|
44
51
|
export type AgIngestRejectReason = "not-object" | "type-not-string" | "seq-not-number";
|
|
@@ -70,6 +77,20 @@ function envelopeProblem(v: JsonValue): AgIngestRejectReason | undefined {
|
|
|
70
77
|
return undefined;
|
|
71
78
|
}
|
|
72
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Whether `v` validates as an AgEvent. A throw from the parse (a getter, a
|
|
82
|
+
* schema recursing past the call stack) is a failure like any other, so the
|
|
83
|
+
* envelope becomes the stub in its slot and ingest keeps its never-throw
|
|
84
|
+
* contract.
|
|
85
|
+
*/
|
|
86
|
+
function validates(v: JsonValue): boolean {
|
|
87
|
+
try {
|
|
88
|
+
return AgEvent.safeParse(v).success;
|
|
89
|
+
} catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
73
94
|
export function ingestAgEvent(v: JsonValue, opts?: IngestOptions): AgEvent | undefined {
|
|
74
95
|
const problem = envelopeProblem(v);
|
|
75
96
|
if (problem !== undefined) {
|
|
@@ -81,12 +102,22 @@ export function ingestAgEvent(v: JsonValue, opts?: IngestOptions): AgEvent | und
|
|
|
81
102
|
return undefined;
|
|
82
103
|
}
|
|
83
104
|
const env = v as { [k: string]: JsonValue };
|
|
84
|
-
|
|
105
|
+
const tooDeep = exceedsDepth(v, AG_EVENT_MAX_DEPTH);
|
|
106
|
+
if (!tooDeep && validates(v)) return copyJson(v) as unknown as AgEvent;
|
|
107
|
+
// toJsonValueSafe recurses once per level up to its cut-off, so under a deep
|
|
108
|
+
// enough host stack even the cut-off copy can throw; the stub then carries
|
|
109
|
+
// the depth mark as its raw and still takes the event's slot.
|
|
110
|
+
let raw: JsonValue;
|
|
111
|
+
try {
|
|
112
|
+
raw = copyJson(tooDeep ? toJsonValueSafe(v) : v);
|
|
113
|
+
} catch {
|
|
114
|
+
raw = JSON_SAFE_MAX_DEPTH_MARK;
|
|
115
|
+
}
|
|
85
116
|
const stub: AgIgnoredEvent = {
|
|
86
117
|
type: "ext.agjson.ignored",
|
|
87
118
|
seq: env["seq"] as number,
|
|
88
119
|
ignoredType: env["type"] as string,
|
|
89
|
-
raw
|
|
120
|
+
raw,
|
|
90
121
|
};
|
|
91
122
|
return stub as unknown as AgEvent;
|
|
92
123
|
}
|
package/src/input-check.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
119
|
-
|
|
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,11 @@ 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
|
+
// • A reference token "__proto__" fails the operation (path or from).
|
|
20
|
+
//
|
|
21
|
+
// Member resolution: a token names an object member only when the object holds
|
|
22
|
+
// it as its OWN member; an inherited name (toString, constructor, …) is absent.
|
|
23
|
+
// `add` of such a name still creates it as an own member (RFC 6902 §4.1).
|
|
19
24
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
20
25
|
|
|
21
26
|
/** Result type returned by applyPatch. */
|
|
@@ -57,10 +62,18 @@ function isJsonArray(v: JsonValue): v is JsonValue[] {
|
|
|
57
62
|
function parsePointer(ptr: string): string[] | null {
|
|
58
63
|
if (ptr === "") return [];
|
|
59
64
|
if (!ptr.startsWith("/")) return null; // malformed — must start with "/"
|
|
60
|
-
|
|
65
|
+
const tokens = ptr
|
|
61
66
|
.slice(1)
|
|
62
67
|
.split("/")
|
|
63
68
|
.map((tok) => tok.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
69
|
+
// A "__proto__" token never names a member: the operation fails.
|
|
70
|
+
if (tokens.includes("__proto__")) return null;
|
|
71
|
+
return tokens;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The object's OWN member `tok`, or undefined when it holds none (inherited names included). */
|
|
75
|
+
function ownMember(node: { [k: string]: JsonValue }, tok: string): JsonValue | undefined {
|
|
76
|
+
return Object.hasOwn(node, tok) ? node[tok] : undefined;
|
|
64
77
|
}
|
|
65
78
|
|
|
66
79
|
/**
|
|
@@ -90,7 +103,7 @@ function resolve(
|
|
|
90
103
|
if (child === undefined) return null;
|
|
91
104
|
node = child;
|
|
92
105
|
} else if (isJsonObject(node)) {
|
|
93
|
-
const child = node
|
|
106
|
+
const child = ownMember(node, tok);
|
|
94
107
|
if (child === undefined) return null;
|
|
95
108
|
node = child;
|
|
96
109
|
} else {
|
|
@@ -108,7 +121,7 @@ function resolve(
|
|
|
108
121
|
if (value === undefined) return null;
|
|
109
122
|
return { parent: node, key: String(idx), value };
|
|
110
123
|
} else if (isJsonObject(node)) {
|
|
111
|
-
const value = node
|
|
124
|
+
const value = ownMember(node, lastTok);
|
|
112
125
|
if (value === undefined) return null;
|
|
113
126
|
return { parent: node, key: lastTok, value };
|
|
114
127
|
}
|
|
@@ -177,7 +190,7 @@ function pointerSet(
|
|
|
177
190
|
return { ok: true, doc: copy };
|
|
178
191
|
} else if (isJsonObject(doc)) {
|
|
179
192
|
// Object: add creates/replaces; replace requires the key to exist.
|
|
180
|
-
if (!isAdd && !(tok
|
|
193
|
+
if (!isAdd && !Object.hasOwn(doc, tok)) return POINTER_FAIL; // replace: own key must exist
|
|
181
194
|
return { ok: true, doc: { ...doc, [tok]: value } };
|
|
182
195
|
}
|
|
183
196
|
return POINTER_FAIL; // scalar — cannot descend
|
|
@@ -199,7 +212,7 @@ function pointerSet(
|
|
|
199
212
|
copy[idx] = childResult.doc;
|
|
200
213
|
return { ok: true, doc: copy };
|
|
201
214
|
} else if (isJsonObject(doc)) {
|
|
202
|
-
const child = doc
|
|
215
|
+
const child = ownMember(doc, tok);
|
|
203
216
|
if (child === undefined) return POINTER_FAIL;
|
|
204
217
|
const childResult = pointerSet(child, rest, value, isAdd);
|
|
205
218
|
if (!childResult.ok) return POINTER_FAIL;
|
|
@@ -232,7 +245,7 @@ function pointerRemove(doc: JsonValue, tokens: string[]): PointerResult {
|
|
|
232
245
|
copy.splice(idx, 1);
|
|
233
246
|
return { ok: true, doc: copy };
|
|
234
247
|
} else if (isJsonObject(doc)) {
|
|
235
|
-
if (!(tok
|
|
248
|
+
if (!Object.hasOwn(doc, tok)) return POINTER_FAIL;
|
|
236
249
|
const { [tok]: _removed, ...rest } = doc;
|
|
237
250
|
return { ok: true, doc: rest };
|
|
238
251
|
}
|
|
@@ -255,7 +268,7 @@ function pointerRemove(doc: JsonValue, tokens: string[]): PointerResult {
|
|
|
255
268
|
copy[idx] = childResult.doc;
|
|
256
269
|
return { ok: true, doc: copy };
|
|
257
270
|
} else if (isJsonObject(doc)) {
|
|
258
|
-
const child = doc
|
|
271
|
+
const child = ownMember(doc, tok);
|
|
259
272
|
if (child === undefined) return POINTER_FAIL;
|
|
260
273
|
const childResult = pointerRemove(child, rest);
|
|
261
274
|
if (!childResult.ok) return POINTER_FAIL;
|
|
@@ -287,7 +300,7 @@ function deepEqual(a: JsonValue, b: JsonValue): boolean {
|
|
|
287
300
|
const bKeys = Object.keys(b);
|
|
288
301
|
if (aKeys.length !== bKeys.length) return false;
|
|
289
302
|
for (const k of aKeys) {
|
|
290
|
-
if (!(k
|
|
303
|
+
if (!Object.hasOwn(b, k)) return false;
|
|
291
304
|
const av = a[k];
|
|
292
305
|
const bv = b[k];
|
|
293
306
|
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 {
|
|
39
|
+
import { AG_EVENT_DEPTH_ALLOWANCE, AG_EVENT_MAX_DEPTH, toJsonValueSafe } from "./wire.js";
|
|
40
|
+
import { 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 => (
|
|
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 (!
|
|
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
|
|
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
|
|
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 (
|
|
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 };
|