@silverprotocol/core 0.6.7 → 0.7.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 +55 -7
- package/dist/agjson.d.ts +29 -8
- package/dist/agjson.d.ts.map +1 -1
- package/dist/agjson.js +28 -7
- package/dist/agjson.js.map +1 -1
- package/dist/atomic-push.d.ts +51 -0
- package/dist/atomic-push.d.ts.map +1 -0
- package/dist/atomic-push.js +188 -0
- package/dist/atomic-push.js.map +1 -0
- package/dist/copy-json.d.ts +12 -0
- package/dist/copy-json.d.ts.map +1 -0
- package/dist/copy-json.js +21 -0
- package/dist/copy-json.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +41 -5
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +53 -30
- package/dist/ingest.js.map +1 -1
- package/dist/input-check.d.ts +51 -0
- package/dist/input-check.d.ts.map +1 -0
- package/dist/input-check.js +113 -0
- package/dist/input-check.js.map +1 -0
- package/dist/record.d.ts +68 -0
- package/dist/record.d.ts.map +1 -0
- package/dist/record.js +112 -0
- package/dist/record.js.map +1 -0
- package/dist/reduce.d.ts +0 -14
- package/dist/reduce.d.ts.map +1 -1
- package/dist/reduce.js +270 -68
- package/dist/reduce.js.map +1 -1
- package/dist/stream-assembler.d.ts +54 -5
- package/dist/stream-assembler.d.ts.map +1 -1
- package/dist/stream-assembler.js +62 -5
- package/dist/stream-assembler.js.map +1 -1
- package/dist/wire.d.ts +96 -0
- package/dist/wire.d.ts.map +1 -1
- package/dist/wire.js +309 -0
- package/dist/wire.js.map +1 -1
- package/package.json +1 -1
- package/src/agjson.ts +33 -10
- package/src/atomic-push.ts +217 -0
- package/src/copy-json.ts +27 -0
- package/src/index.ts +3 -0
- package/src/ingest.ts +71 -26
- package/src/input-check.ts +124 -0
- package/src/record.ts +132 -0
- package/src/reduce.ts +234 -56
- package/src/stream-assembler.ts +82 -10
- package/src/wire.ts +303 -0
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* atomic-push.ts — per-native atomicity for a Normalizer (the fleet guard
|
|
3
|
+
* ruling, 2026-09-24, binding; sp-main approved sp-openai's option B).
|
|
4
|
+
*
|
|
5
|
+
* A Normalizer MUST NOT throw out of push() (SPEC.md §8.0). When handling
|
|
6
|
+
* one native throws anyway, the events it had already produced must be
|
|
7
|
+
* discarded WITHOUT consuming seq (INV-SEQ), and no turn, message or block it
|
|
8
|
+
* half-opened may survive. The assembler stamps seq at emit and the facet
|
|
9
|
+
* holds its own state, so the wrapper restores both by construction: it
|
|
10
|
+
* rebuilds the inner Normalizer from its factory and re-drives every native it
|
|
11
|
+
* accepted so far, output dropped. That relies on facets being deterministic
|
|
12
|
+
* (no clock, no randomness inside the factory; capture a random id stem OUTSIDE
|
|
13
|
+
* `createInner`).
|
|
14
|
+
*
|
|
15
|
+
* A facet whose live natives are class instances it recognizes by class
|
|
16
|
+
* (e.g. an Error it tests with `instanceof`, which any JSON-shaped copy
|
|
17
|
+
* loses) should not normalize at entry, and cannot journal a faithful copy.
|
|
18
|
+
* It can use StreamAssembler.checkpoint()/rollback() plus its own state
|
|
19
|
+
* snapshot instead (the vercel-ai facet does).
|
|
20
|
+
*/
|
|
21
|
+
import type { AgEvent, JsonValue } from "./agjson.js";
|
|
22
|
+
import type { Normalizer } from "./stream-assembler.js";
|
|
23
|
+
import { isJsonValue, toJsonValue, toJsonValueSafe } from "./wire.js";
|
|
24
|
+
|
|
25
|
+
/** The constant `message` of the guard's core `error` event. */
|
|
26
|
+
export const NORMALIZER_ERROR_MESSAGE = "normalizer error";
|
|
27
|
+
|
|
28
|
+
/** The guard's `code`: the thrown value's constructor NAME only, never its
|
|
29
|
+
* message (a SyntaxError quotes its input) and never the native. */
|
|
30
|
+
export function normalizerErrorCode(err: unknown): string {
|
|
31
|
+
try {
|
|
32
|
+
if (err instanceof Error) return err.constructor.name || "Error";
|
|
33
|
+
} catch {
|
|
34
|
+
return "Error";
|
|
35
|
+
}
|
|
36
|
+
return "NonError";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface AtomicPushOptions {
|
|
40
|
+
/** Run {@link toJsonValueSafe} on each native before the inner push (default
|
|
41
|
+
* true). With it the journal holds a JSON deep copy of what the inner saw,
|
|
42
|
+
* so a host mutating a pushed native later cannot skew a rebuild. With
|
|
43
|
+
* `false` a native that is already plain JSON is still journaled as a deep
|
|
44
|
+
* copy; any other native (a class instance, a Date, a cycle) is journaled
|
|
45
|
+
* BY REFERENCE, so the caller must pass values it owns and never mutate one
|
|
46
|
+
* after pushing it. */
|
|
47
|
+
normalize?: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Wrap a Normalizer factory so each push() (and flush()) is atomic:
|
|
52
|
+
* - Success: the inner's events are returned (by reference; unchanged until a
|
|
53
|
+
* throw has happened), and the native joins the journal.
|
|
54
|
+
* - Throw: the partial batch is discarded, the inner is rebuilt and re-driven
|
|
55
|
+
* from the journal with its output dropped (a throw during that re-drive is
|
|
56
|
+
* caught too), and ONE core `error {message: "normalizer error", code}`
|
|
57
|
+
* takes the next seq. Its `turnId` is the owner INV-OWNER backfills
|
|
58
|
+
* (SPEC.md:766), resolved exactly as StreamAssembler.emit() resolves it:
|
|
59
|
+
* the last-opened turn, restored to the parent when a subagent turn
|
|
60
|
+
* closes, so after the last turn closed it is still that turn, and before
|
|
61
|
+
* any turn there is none. It is replayed from the delivered events, which
|
|
62
|
+
* show every move of the assembler's last turn except one: a facet
|
|
63
|
+
* re-calling openTurn() on an already-seen turn, which emits nothing. The
|
|
64
|
+
* e2e corpus leg asserts no committed native reaches that move
|
|
65
|
+
* (atomic-guard.corpus.test.ts).
|
|
66
|
+
* From then on every inner event is
|
|
67
|
+
* renumbered by +1 per error emitted, so seq stays ascending and gap-free
|
|
68
|
+
* and no seq repeats.
|
|
69
|
+
* - flush() throwing: inner.flush() is NOT retried (so it cannot throw a
|
|
70
|
+
* second time). The wrapper rebuilds, emits the same `error`, then
|
|
71
|
+
* synthesizes the INV-FLUSH closes from its own tracker of what the
|
|
72
|
+
* consumer has seen open: a message.end for each open message, then
|
|
73
|
+
* turn.abort{stream-truncated} for each open turn, innermost first.
|
|
74
|
+
*
|
|
75
|
+
* Costs, by design (caps deferred):
|
|
76
|
+
* - Memory: O(invoke). The journal keeps a COPY of every accepted native (a
|
|
77
|
+
* JSON deep copy when normalizing, never the host's reference) for the life
|
|
78
|
+
* of the instance, i.e. one invoke, since hosts build a fresh Normalizer per
|
|
79
|
+
* invoke (§8.0 obligation 3).
|
|
80
|
+
* - Time: O(bad × prefix). Each throw re-drives the invoke so far, output
|
|
81
|
+
* dropped. Nothing is paid when nothing throws, beyond the copy.
|
|
82
|
+
*/
|
|
83
|
+
export function withAtomicPush(createInner: () => Normalizer, opts: AtomicPushOptions = {}): Normalizer {
|
|
84
|
+
const normalize = opts.normalize ?? true;
|
|
85
|
+
let inner = createInner();
|
|
86
|
+
const journal: unknown[] = [];
|
|
87
|
+
let offset = 0; // errors emitted so far = the seq shift applied to inner output
|
|
88
|
+
let lastSeq = -1; // the last seq returned to the caller
|
|
89
|
+
// What the consumer has seen open, for flush()'s fallback INV-FLUSH close.
|
|
90
|
+
const openMessages = new Map<string, true>();
|
|
91
|
+
const openTurns = new Set<string>();
|
|
92
|
+
let lastTurn: string | undefined;
|
|
93
|
+
|
|
94
|
+
// The guard error's owner, per INV-OWNER (SPEC.md:766: every emit path,
|
|
95
|
+
// the generic emit() included, applies the same owner backfill): the
|
|
96
|
+
// StreamAssembler's last-turn rule (#resolveTurnId, stream-assembler.ts),
|
|
97
|
+
// replayed from the events the consumer has seen. turn.start and
|
|
98
|
+
// message.start set it, subagent.start saves it and moves in,
|
|
99
|
+
// subagent.done restores the saved one (the parent), and no close clears it.
|
|
100
|
+
let ownerTurn: string | undefined;
|
|
101
|
+
const ownerStack: (string | undefined)[] = [];
|
|
102
|
+
const trackOwner = (ev: AgEvent): void => {
|
|
103
|
+
const turnId = (ev as { turnId?: string }).turnId;
|
|
104
|
+
switch (ev.type) {
|
|
105
|
+
case "turn.start":
|
|
106
|
+
case "message.start":
|
|
107
|
+
if (turnId !== undefined) ownerTurn = turnId;
|
|
108
|
+
break;
|
|
109
|
+
case "subagent.start":
|
|
110
|
+
ownerStack.push(ownerTurn);
|
|
111
|
+
ownerTurn = turnId;
|
|
112
|
+
break;
|
|
113
|
+
case "subagent.done":
|
|
114
|
+
ownerTurn = ownerStack.length > 0 ? ownerStack.pop() : (ev as { parentTurnId?: string }).parentTurnId;
|
|
115
|
+
break;
|
|
116
|
+
default:
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const track = (ev: AgEvent): void => {
|
|
122
|
+
trackOwner(ev);
|
|
123
|
+
const turnId = (ev as { turnId?: string }).turnId;
|
|
124
|
+
const id = (ev as { id?: string }).id;
|
|
125
|
+
switch (ev.type) {
|
|
126
|
+
case "message.start":
|
|
127
|
+
if (id !== undefined) openMessages.set(id, true);
|
|
128
|
+
break;
|
|
129
|
+
case "message.end":
|
|
130
|
+
if (id !== undefined) openMessages.delete(id);
|
|
131
|
+
break;
|
|
132
|
+
case "turn.start":
|
|
133
|
+
case "subagent.start":
|
|
134
|
+
if (turnId !== undefined) {
|
|
135
|
+
openTurns.add(turnId);
|
|
136
|
+
lastTurn = turnId;
|
|
137
|
+
}
|
|
138
|
+
break;
|
|
139
|
+
case "turn.done":
|
|
140
|
+
case "turn.error":
|
|
141
|
+
case "turn.abort": {
|
|
142
|
+
const closed = turnId ?? lastTurn;
|
|
143
|
+
if (closed !== undefined) openTurns.delete(closed);
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
case "subagent.done":
|
|
147
|
+
if (turnId !== undefined) openTurns.delete(turnId);
|
|
148
|
+
break;
|
|
149
|
+
default:
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const deliver = (evs: AgEvent[]): AgEvent[] => {
|
|
155
|
+
const out = offset === 0 ? evs : evs.map((ev): AgEvent => ({ ...ev, seq: ev.seq + offset }));
|
|
156
|
+
for (const ev of out) {
|
|
157
|
+
lastSeq = ev.seq;
|
|
158
|
+
track(ev);
|
|
159
|
+
}
|
|
160
|
+
return out;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const rebuild = (): void => {
|
|
164
|
+
try {
|
|
165
|
+
inner = createInner();
|
|
166
|
+
for (const n of journal) inner.push(n);
|
|
167
|
+
} catch {
|
|
168
|
+
// Double fault: keep the partly rebuilt inner; the error is still emitted.
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const guardError = (err: unknown): AgEvent => {
|
|
173
|
+
const turnId = ownerTurn;
|
|
174
|
+
// Key order as StreamAssembler.emit() builds it ({...ev, turnId, seq}), so
|
|
175
|
+
// this error serializes byte-for-byte like an assembler-emitted guard
|
|
176
|
+
// error (vercel-ai's, and google-adk's in 0.6.x).
|
|
177
|
+
const ev: AgEvent = {
|
|
178
|
+
type: "error",
|
|
179
|
+
message: NORMALIZER_ERROR_MESSAGE,
|
|
180
|
+
code: normalizerErrorCode(err),
|
|
181
|
+
...(turnId !== undefined ? { turnId } : {}),
|
|
182
|
+
seq: lastSeq + 1,
|
|
183
|
+
};
|
|
184
|
+
lastSeq = ev.seq;
|
|
185
|
+
offset += 1;
|
|
186
|
+
return ev;
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
push(native: unknown): AgEvent[] {
|
|
191
|
+
try {
|
|
192
|
+
const n: unknown = normalize ? toJsonValueSafe(native) : native;
|
|
193
|
+
const evs = inner.push(n);
|
|
194
|
+
journal.push(normalize || isJsonValue(n) ? toJsonValue(n as JsonValue) : n);
|
|
195
|
+
return deliver(evs);
|
|
196
|
+
} catch (err) {
|
|
197
|
+
rebuild();
|
|
198
|
+
return [guardError(err)];
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
flush(): AgEvent[] {
|
|
202
|
+
try {
|
|
203
|
+
return deliver(inner.flush());
|
|
204
|
+
} catch (err) {
|
|
205
|
+
rebuild();
|
|
206
|
+
const out: AgEvent[] = [guardError(err)];
|
|
207
|
+
for (const id of openMessages.keys()) out.push({ type: "message.end", seq: ++lastSeq, id });
|
|
208
|
+
for (const turnId of [...openTurns].reverse()) {
|
|
209
|
+
out.push({ type: "turn.abort", seq: ++lastSeq, turnId, reason: "stream-truncated" });
|
|
210
|
+
}
|
|
211
|
+
openMessages.clear();
|
|
212
|
+
openTurns.clear();
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
package/src/copy-json.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* copy-json.ts — INTERNAL (not re-exported from index.ts).
|
|
3
|
+
*
|
|
4
|
+
* The one own-property deep copy every consumer-side reader in core uses, so
|
|
5
|
+
* the §13 rule on `__proto__` has a single code path: stage-1 ingest
|
|
6
|
+
* (ingest.ts), the stored-record readers (record.ts) and the input check
|
|
7
|
+
* (input-check.ts).
|
|
8
|
+
*/
|
|
9
|
+
import type { JsonValue } from "./agjson.js";
|
|
10
|
+
|
|
11
|
+
/** Own-property deep copy of a JSON value, dropping `__proto__` at every depth. */
|
|
12
|
+
export function copyJson(v: JsonValue): JsonValue {
|
|
13
|
+
if (Array.isArray(v)) return v.map(copyJson);
|
|
14
|
+
if (v === null || typeof v !== "object") return v;
|
|
15
|
+
const out: { [k: string]: JsonValue } = {};
|
|
16
|
+
for (const k of Object.keys(v)) {
|
|
17
|
+
if (k === "__proto__") continue;
|
|
18
|
+
// DEFINED, never assigned (belt and braces with the skip above).
|
|
19
|
+
Object.defineProperty(out, k, {
|
|
20
|
+
value: copyJson((v as { [k: string]: JsonValue })[k]!),
|
|
21
|
+
enumerable: true,
|
|
22
|
+
writable: true,
|
|
23
|
+
configurable: true,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
return out;
|
|
27
|
+
}
|
package/src/index.ts
CHANGED
package/src/ingest.ts
CHANGED
|
@@ -10,46 +10,91 @@
|
|
|
10
10
|
* depth (SPEC.md:27 does not limit "untouched" to the top level). After a
|
|
11
11
|
* successful `AgEvent.safeParse`, the returned event is an own-property deep
|
|
12
12
|
* copy of the RAW input, not zod's validated output, which strips unknown
|
|
13
|
-
* nested keys. The copy
|
|
14
|
-
* agjson.ts rewrites values (no transform/
|
|
15
|
-
* preprocess); ingest.test.ts guards that.
|
|
13
|
+
* nested keys. The copy carries the same keys and values as the validated
|
|
14
|
+
* value only because no schema in agjson.ts rewrites values (no transform/
|
|
15
|
+
* default/coerce/catch/pipe/preprocess); ingest.test.ts guards that. It is
|
|
16
|
+
* NOT byte-identical to it: nested objects keep the PRODUCER's key order,
|
|
17
|
+
* where zod's output (and so 0.6.4's ingest) used the schema's. Over the
|
|
18
|
+
* 0.6.5 corpus that reordered 64 of 1,103 events, all inside `usage`.
|
|
16
19
|
*
|
|
17
20
|
* One exception, at every depth: a key named `__proto__` is dropped, never
|
|
18
21
|
* copied. A consumer must not let wire data select the prototype of any object
|
|
19
22
|
* it materialises (JSON.parse keeps such a key as an own property, and
|
|
20
23
|
* assigning it would run Object.prototype's setter).
|
|
24
|
+
*
|
|
25
|
+
* Forward-compatible ingest (draft.4 §0.2, workspace#20 stage 2). Every input
|
|
26
|
+
* lands in exactly one of three places:
|
|
27
|
+
* - a WELL-FORMED ENVELOPE (a JSON object whose `type` is a string and whose
|
|
28
|
+
* `seq` is a finite number) that validates → the event, as above;
|
|
29
|
+
* - a well-formed envelope that does NOT validate (an undefined type, an
|
|
30
|
+
* unknown enum value or block, a malformed known type) → IN PLACE, the
|
|
31
|
+
* stub `{type: "ext.agjson.ignored", seq, ignoredType, raw}`. It is a
|
|
32
|
+
* typed ext event: it never folds, but a Reducer counts its `seq` slot,
|
|
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;
|
|
35
|
+
* - anything else (not an object, a non-string `type`, a missing or
|
|
36
|
+
* non-number `seq`) → not an event and occupies no slot: returns
|
|
37
|
+
* undefined and is reported through the optional `onReject` callback.
|
|
38
|
+
* ingestAgEvent/ingestAgEvents never throw, even if `onReject` does.
|
|
21
39
|
*/
|
|
22
40
|
import { AgEvent, type JsonValue } from "./agjson.js";
|
|
41
|
+
import { copyJson } from "./copy-json.js";
|
|
23
42
|
|
|
24
|
-
/**
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
configurable: true,
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
return out;
|
|
43
|
+
/** Why an input is not a well-formed envelope (draft.4 §0.2). */
|
|
44
|
+
export type AgIngestRejectReason = "not-object" | "type-not-string" | "seq-not-number";
|
|
45
|
+
|
|
46
|
+
/** A non-envelope input, reported through `IngestOptions.onReject`. */
|
|
47
|
+
export interface AgIngestReject {
|
|
48
|
+
input: JsonValue;
|
|
49
|
+
reason: AgIngestRejectReason;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface IngestOptions {
|
|
53
|
+
/** Called once per non-envelope input. It occupies no seq slot. A throw is swallowed. */
|
|
54
|
+
onReject?: (reject: AgIngestReject) => void;
|
|
40
55
|
}
|
|
41
56
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
57
|
+
/** The in-place report for an ignored well-formed envelope. `raw` is live-only. */
|
|
58
|
+
export interface AgIgnoredEvent {
|
|
59
|
+
type: "ext.agjson.ignored";
|
|
60
|
+
seq: number;
|
|
61
|
+
ignoredType: string;
|
|
62
|
+
raw: JsonValue;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function envelopeProblem(v: JsonValue): AgIngestRejectReason | undefined {
|
|
66
|
+
if (v === null || typeof v !== "object" || Array.isArray(v)) return "not-object";
|
|
67
|
+
if (typeof v["type"] !== "string") return "type-not-string";
|
|
68
|
+
const seq = v["seq"];
|
|
69
|
+
if (typeof seq !== "number" || !Number.isFinite(seq)) return "seq-not-number";
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function ingestAgEvent(v: JsonValue, opts?: IngestOptions): AgEvent | undefined {
|
|
74
|
+
const problem = envelopeProblem(v);
|
|
75
|
+
if (problem !== undefined) {
|
|
76
|
+
try {
|
|
77
|
+
opts?.onReject?.({ input: v, reason: problem });
|
|
78
|
+
} catch {
|
|
79
|
+
// never-throw contract: a host callback bug must not break ingest
|
|
80
|
+
}
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
const env = v as { [k: string]: JsonValue };
|
|
84
|
+
if (AgEvent.safeParse(v).success) return copyJson(v) as unknown as AgEvent;
|
|
85
|
+
const stub: AgIgnoredEvent = {
|
|
86
|
+
type: "ext.agjson.ignored",
|
|
87
|
+
seq: env["seq"] as number,
|
|
88
|
+
ignoredType: env["type"] as string,
|
|
89
|
+
raw: copyJson(v),
|
|
90
|
+
};
|
|
91
|
+
return stub as unknown as AgEvent;
|
|
47
92
|
}
|
|
48
93
|
|
|
49
|
-
export function ingestAgEvents(vs: JsonValue[]): AgEvent[] {
|
|
94
|
+
export function ingestAgEvents(vs: JsonValue[], opts?: IngestOptions): AgEvent[] {
|
|
50
95
|
const out: AgEvent[] = [];
|
|
51
96
|
for (const v of vs) {
|
|
52
|
-
const e = ingestAgEvent(v);
|
|
97
|
+
const e = ingestAgEvent(v, opts);
|
|
53
98
|
if (e !== undefined) out.push(e);
|
|
54
99
|
}
|
|
55
100
|
return out;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* input-check.ts — the reference AgInput receiver check (draft.4 §0.2,
|
|
3
|
+
* workspace#20 decision 6: option 1 "omit the element, reject the input";
|
|
4
|
+
* input classes per the founder's ALT-1 ruling, bar wf_a8a31902-fb5).
|
|
5
|
+
*
|
|
6
|
+
* A receiver passes unknown object fields through untouched, and REJECTS THE
|
|
7
|
+
* WHOLE INPUT, before acting on any part of it, when the input fails this
|
|
8
|
+
* specification's schema in any way other than an unknown field. The
|
|
9
|
+
* rejection names ONE path and ONE class:
|
|
10
|
+
*
|
|
11
|
+
* - `major-mismatch`, at `["version"]`: `version` differs in MAJOR (§12);
|
|
12
|
+
* - `unknown-value`: the value at the path is a STRING that the closed set
|
|
13
|
+
* there does not define (an `AgInput.kind`, an `AgHitlAnswer.status`, a
|
|
14
|
+
* reasoning `effort`, an `AgBlock` `type`, …). zod's codes alone cannot
|
|
15
|
+
* tell this from malformed, so the rule reads the raw value (bar CB-6);
|
|
16
|
+
* - `malformed`: every other failure — a missing value, a value of the wrong
|
|
17
|
+
* JSON type, a value that breaks a stated constraint, a non-JSON input, or
|
|
18
|
+
* a `protocol` other than `"agjson"` (it names the protocol; it is not a
|
|
19
|
+
* closed set). An input that is not a JSON object is malformed at `[]`.
|
|
20
|
+
*
|
|
21
|
+
* Order and scope: `protocol` is judged first, then `version`, then the rest.
|
|
22
|
+
* The `AgInputEnvelope` members are checked whatever the `kind`; a member that
|
|
23
|
+
* only an undefined `kind` would select is not checked, nor any other member of
|
|
24
|
+
* an `AgBlock` whose `type` is undefined. When the rest has both malformed and
|
|
25
|
+
* unknown-value problems, the class is malformed, at the path of the first
|
|
26
|
+
* malformed problem in the reference's order; otherwise the first
|
|
27
|
+
* unknown-value. Inside a plain union, only a branch whose shape fits the
|
|
28
|
+
* value's JSON type is read (a string against an enum branch, an object
|
|
29
|
+
* against an object branch).
|
|
30
|
+
*
|
|
31
|
+
* An accepted input comes back as an own-property deep copy of the RAW value,
|
|
32
|
+
* so unknown fields stay intact at every depth (`__proto__` dropped, as
|
|
33
|
+
* ingest). A sender that receives `unknown-value` at a path inside an
|
|
34
|
+
* `AgBlock[]` MAY resend without that element.
|
|
35
|
+
*/
|
|
36
|
+
import { AGJSON_VERSION, AgInput, AgInputEnvelope, type JsonValue } from "./agjson.js";
|
|
37
|
+
import { copyJson } from "./copy-json.js";
|
|
38
|
+
import { isJsonValue } from "./wire.js";
|
|
39
|
+
|
|
40
|
+
export type AgInputCheckCode = "unknown-value" | "malformed" | "major-mismatch";
|
|
41
|
+
|
|
42
|
+
export type AgInputCheck =
|
|
43
|
+
| { ok: true; input: AgInput }
|
|
44
|
+
| { ok: false; code: AgInputCheckCode; path: (string | number)[] };
|
|
45
|
+
|
|
46
|
+
type Path = (string | number)[];
|
|
47
|
+
type Problem = { code: "unknown-value" | "malformed"; path: Path };
|
|
48
|
+
|
|
49
|
+
/** A zod issue, as far as this check reads it. */
|
|
50
|
+
interface Issue {
|
|
51
|
+
code: string;
|
|
52
|
+
path: PropertyKey[];
|
|
53
|
+
values?: readonly unknown[];
|
|
54
|
+
options?: readonly unknown[];
|
|
55
|
+
errors?: Issue[][];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The raw value at `path`, read through own properties only. */
|
|
59
|
+
function at(root: unknown, path: Path): unknown {
|
|
60
|
+
let v: unknown = root;
|
|
61
|
+
for (const k of path) {
|
|
62
|
+
if (v === null || typeof v !== "object" || !Object.hasOwn(v, k)) return undefined;
|
|
63
|
+
v = (v as Record<string | number, unknown>)[k];
|
|
64
|
+
}
|
|
65
|
+
return v;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const toPath = (p: PropertyKey[]): Path => p.filter((k): k is string | number => typeof k !== "symbol");
|
|
69
|
+
const samePath = (a: Path, b: Path) => a.length === b.length && a.every((k, i) => k === b[i]);
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Every problem one issue stands for. `unknown-value` iff the raw value at its
|
|
73
|
+
* path is a string outside the closed set there (an enum's `values`, a
|
|
74
|
+
* discriminator's `options`); a plain union is read through the branch that
|
|
75
|
+
* fits the value's JSON type; anything else is `malformed`.
|
|
76
|
+
*/
|
|
77
|
+
function problemsOf(root: unknown, issue: Issue, prefix: Path): Problem[] {
|
|
78
|
+
const path = [...prefix, ...toPath(issue.path)];
|
|
79
|
+
const raw = at(root, path);
|
|
80
|
+
const set = issue.code === "invalid_value" ? issue.values : issue.code === "invalid_union" ? issue.options : undefined;
|
|
81
|
+
if (set !== undefined && typeof raw === "string" && !set.includes(raw)) return [{ code: "unknown-value", path }];
|
|
82
|
+
if (issue.code === "invalid_union" && issue.errors !== undefined && issue.errors.length > 0) {
|
|
83
|
+
// A branch that is malformed AT the union's own path does not fit the
|
|
84
|
+
// value's JSON type (a string branch against an array, an enum against an
|
|
85
|
+
// object); the first branch that fits is the one the value was meant for.
|
|
86
|
+
const fitting = issue.errors
|
|
87
|
+
.map((branch) => branch.flatMap((i) => problemsOf(root, i, path)))
|
|
88
|
+
.filter((ps) => ps.length > 0 && !ps.some((p) => p.code === "malformed" && samePath(p.path, path)));
|
|
89
|
+
return fitting[0] ?? [{ code: "malformed", path }];
|
|
90
|
+
}
|
|
91
|
+
return [{ code: "malformed", path }];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const MAJOR = AGJSON_VERSION.split(".")[0];
|
|
95
|
+
const reject = (code: AgInputCheckCode, path: Path): AgInputCheck => ({ ok: false, code, path });
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Check a received AgInput (draft.4 §0.2). Returns the input, unknown fields
|
|
99
|
+
* intact, or a typed rejection naming one path and one class.
|
|
100
|
+
*/
|
|
101
|
+
export function checkAgInput(raw: unknown): AgInputCheck {
|
|
102
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return reject("malformed", []);
|
|
103
|
+
// protocol first: it names the protocol, so anything but "agjson" is not AgJSON at all.
|
|
104
|
+
if (!Object.hasOwn(raw, "protocol") || (raw as { protocol?: unknown }).protocol !== "agjson") return reject("malformed", ["protocol"]);
|
|
105
|
+
// then version: another major is major-mismatch; any other version problem is malformed.
|
|
106
|
+
const version = Object.hasOwn(raw, "version") ? (raw as { version?: unknown }).version : undefined;
|
|
107
|
+
if (typeof version !== "string" || !/^\d+\./.test(version)) return reject("malformed", ["version"]);
|
|
108
|
+
if (version.split(".")[0] !== MAJOR) return reject("major-mismatch", ["version"]);
|
|
109
|
+
// then the rest.
|
|
110
|
+
if (!isJsonValue(raw)) return reject("malformed", []);
|
|
111
|
+
const parsed = AgInput.safeParse(raw);
|
|
112
|
+
if (parsed.success) return { ok: true, input: copyJson(raw as JsonValue) as unknown as AgInput };
|
|
113
|
+
const issues = parsed.error.issues as unknown as Issue[];
|
|
114
|
+
const problems: Problem[] = [];
|
|
115
|
+
// An undefined kind stops zod at the discriminator: judge the envelope
|
|
116
|
+
// members anyway, and never the members only that kind would select.
|
|
117
|
+
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, []));
|
|
120
|
+
}
|
|
121
|
+
for (const i of issues) problems.push(...problemsOf(raw, i, []));
|
|
122
|
+
const pick = problems.find((p) => p.code === "malformed") ?? problems.find((p) => p.code === "unknown-value");
|
|
123
|
+
return pick === undefined ? reject("malformed", []) : reject(pick.code, pick.path);
|
|
124
|
+
}
|
package/src/record.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* record.ts — lenient readers for STORED records (draft.4 §0.2, workspace#20
|
|
3
|
+
* decision 6, founder ruling 2026-09-23: option 1, "omit the element, reject
|
|
4
|
+
* the input").
|
|
5
|
+
*
|
|
6
|
+
* §0.2's consumer posture also binds a reader of a stored `AgMessage` or
|
|
7
|
+
* `AgMemoryRecord` it did not receive inside an event. These readers
|
|
8
|
+
* implement it:
|
|
9
|
+
*
|
|
10
|
+
* - A stored `AgMessage` is materialized only when its `id` is a string, its
|
|
11
|
+
* `role` an `AgRole`, its `content` an array and its other defined fields
|
|
12
|
+
* valid. Otherwise there is no value, and ONE report carries the whole record
|
|
13
|
+
* verbatim.
|
|
14
|
+
* - An element of `content[]` that fails `AgBlock` at any depth (an undefined
|
|
15
|
+
* `type`, or an undefined value in a closed set inside a known block) is
|
|
16
|
+
* omitted WHOLE and reported with its index and verbatim value. A
|
|
17
|
+
* tool-result is omitted, never altered. The remaining elements keep their
|
|
18
|
+
* order.
|
|
19
|
+
* - In an array of stored records, a record that fails is omitted and
|
|
20
|
+
* reported with its index. Nothing is ever coerced.
|
|
21
|
+
* - Unknown object fields pass through untouched at every depth: every value
|
|
22
|
+
* returned is an own-property deep copy of the RAW input, never zod's output
|
|
23
|
+
* (which strips unknown keys). A key named `__proto__` is dropped at every
|
|
24
|
+
* depth (the shared copy stage-1 ingest uses). The input is never mutated.
|
|
25
|
+
* - Inserting each report's `raw` at its reported index reproduces the stored
|
|
26
|
+
* record or array.
|
|
27
|
+
*
|
|
28
|
+
* What a reader returns is a VIEW. It MUST NOT be persisted in place of the
|
|
29
|
+
* stored record: a component that persists or forwards a record keeps it as
|
|
30
|
+
* received.
|
|
31
|
+
*
|
|
32
|
+
* Records carried by EVENTS are out of scope: they keep the whole-event rule
|
|
33
|
+
* (ingest.ts). Disclosed, not fixed: a `messages.snapshot` holding one unknown
|
|
34
|
+
* block fails `AgEvent`, becomes an `ext.agjson.ignored` stub and so cannot
|
|
35
|
+
* un-park a live fold, while the same message read here from storage keeps its
|
|
36
|
+
* readable blocks. That stays so until decision 5's snapshot leg is ruled.
|
|
37
|
+
*/
|
|
38
|
+
import { AgBlock, AgMemoryRecord, AgMessage, type JsonValue } from "./agjson.js";
|
|
39
|
+
import { copyJson } from "./copy-json.js";
|
|
40
|
+
import { isJsonValue, toJsonValueSafe } from "./wire.js";
|
|
41
|
+
|
|
42
|
+
/** One omitted element or record: where it was, its type when it had one, and its verbatim value. */
|
|
43
|
+
export interface AgRecordReport {
|
|
44
|
+
/** From the value passed to the reader: `[]` for the whole record, `["content", i]` for an element, `[i]` or `[i, "content", j]` inside an array. */
|
|
45
|
+
path: (string | number)[];
|
|
46
|
+
/** The omitted element's `type`, when it is a string (a content element's block type). */
|
|
47
|
+
ignoredType?: string;
|
|
48
|
+
/** The omitted value, verbatim (an own-property copy; `__proto__` dropped). */
|
|
49
|
+
raw: JsonValue;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The result of reading one stored record: a value when it was materialized, and every omission. */
|
|
53
|
+
export interface AgRecordRead<T> {
|
|
54
|
+
value?: T;
|
|
55
|
+
reports: AgRecordReport[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The result of reading an array of stored records. */
|
|
59
|
+
export interface AgRecordsRead<T> {
|
|
60
|
+
value: T[];
|
|
61
|
+
reports: AgRecordReport[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
type JsonObject = { [k: string]: JsonValue };
|
|
65
|
+
|
|
66
|
+
const isObject = (v: JsonValue): v is JsonObject => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
67
|
+
|
|
68
|
+
/** A value as a report can carry it: a JSON value is copied verbatim; a
|
|
69
|
+
* non-JSON one (never read from JSON storage) is made JSON-safe. */
|
|
70
|
+
const reportRaw = (v: unknown): JsonValue => (isJsonValue(v) ? copyJson(v) : toJsonValueSafe(v));
|
|
71
|
+
|
|
72
|
+
function report(path: (string | number)[], raw: unknown, ignoredType?: string): AgRecordReport {
|
|
73
|
+
return { path, ...(ignoredType !== undefined ? { ignoredType } : {}), raw: reportRaw(raw) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Read one stored `AgMessage` (draft.4 §0.2). Omits and reports each
|
|
78
|
+
* unreadable `content[]` element; a record that cannot be materialized has no
|
|
79
|
+
* `value` and one report at path `[]`.
|
|
80
|
+
*/
|
|
81
|
+
export function readStoredAgMessage(raw: unknown): AgRecordRead<AgMessage> {
|
|
82
|
+
if (!isJsonValue(raw) || !isObject(raw) || !Array.isArray(raw["content"])) return { reports: [report([], raw)] };
|
|
83
|
+
const kept: JsonValue[] = [];
|
|
84
|
+
const reports: AgRecordReport[] = [];
|
|
85
|
+
raw["content"].forEach((element, i) => {
|
|
86
|
+
if (AgBlock.safeParse(element).success) {
|
|
87
|
+
kept.push(copyJson(element));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const type = isObject(element) && typeof element["type"] === "string" ? element["type"] : undefined;
|
|
91
|
+
reports.push(report(["content", i], element, type));
|
|
92
|
+
});
|
|
93
|
+
// The copy keeps the stored key order, with the readable elements in place of content.
|
|
94
|
+
const view: JsonObject = {};
|
|
95
|
+
for (const k of Object.keys(raw)) {
|
|
96
|
+
if (k === "__proto__") continue;
|
|
97
|
+
Object.defineProperty(view, k, {
|
|
98
|
+
value: k === "content" ? kept : copyJson(raw[k]!),
|
|
99
|
+
enumerable: true,
|
|
100
|
+
writable: true,
|
|
101
|
+
configurable: true,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
// Every other defined field must be valid; else the whole record is reported.
|
|
105
|
+
if (!AgMessage.safeParse(view).success) return { reports: [report([], raw)] };
|
|
106
|
+
return { value: view as unknown as AgMessage, reports };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Read an array of stored `AgMessage`s: each unreadable message or element is omitted and reported, prefixed with its index. */
|
|
110
|
+
export function readStoredAgMessages(raws: readonly unknown[]): AgRecordsRead<AgMessage> {
|
|
111
|
+
if (!Array.isArray(raws)) return { value: [], reports: [report([], raws)] };
|
|
112
|
+
const value: AgMessage[] = [];
|
|
113
|
+
const reports: AgRecordReport[] = [];
|
|
114
|
+
raws.forEach((raw, i) => {
|
|
115
|
+
const r = readStoredAgMessage(raw);
|
|
116
|
+
if (r.value !== undefined) value.push(r.value);
|
|
117
|
+
for (const rep of r.reports) reports.push({ ...rep, path: [i, ...rep.path] });
|
|
118
|
+
});
|
|
119
|
+
return { value, reports };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Read an array of stored `AgMemoryRecord`s: a record that fails (an undefined `scope`, a missing `value`, …) is omitted and reported at `[i]`. */
|
|
123
|
+
export function readStoredAgMemoryRecords(raws: readonly unknown[]): AgRecordsRead<AgMemoryRecord> {
|
|
124
|
+
if (!Array.isArray(raws)) return { value: [], reports: [report([], raws)] };
|
|
125
|
+
const value: AgMemoryRecord[] = [];
|
|
126
|
+
const reports: AgRecordReport[] = [];
|
|
127
|
+
raws.forEach((raw, i) => {
|
|
128
|
+
if (isJsonValue(raw) && isObject(raw) && AgMemoryRecord.safeParse(raw).success) value.push(copyJson(raw) as unknown as AgMemoryRecord);
|
|
129
|
+
else reports.push(report([i], raw));
|
|
130
|
+
});
|
|
131
|
+
return { value, reports };
|
|
132
|
+
}
|