@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/wire.js CHANGED
@@ -6,4 +6,313 @@ export function toJsonValue(v) {
6
6
  const w = JSON.parse(JSON.stringify(v));
7
7
  return w;
8
8
  }
9
+ /** The value a cycle is replaced with by {@link toJsonValueSafe} (at the repeated node only). */
10
+ export const JSON_SAFE_CIRCULAR = "[Circular]";
11
+ /** The value a node nested deeper than {@link JSON_SAFE_MAX_DEPTH} is replaced with. */
12
+ export const JSON_SAFE_MAX_DEPTH_MARK = "[MaxDepth]";
13
+ /** The nesting depth past which the helpers stop descending (never reached by real data). */
14
+ export const JSON_SAFE_MAX_DEPTH = 1000;
15
+ /**
16
+ * True when `v` is ALREADY a plain JSON value, i.e. exactly what a JSON
17
+ * round-trip of it would produce: `null`, a string, a boolean, a finite
18
+ * number other than `-0`, an array with no holes, or a plain object (prototype
19
+ * `Object.prototype` or `null`, no own `toJSON`) of such values, acyclic and
20
+ * shallower than {@link JSON_SAFE_MAX_DEPTH}. Never throws (a throwing getter
21
+ * or proxy trap answers `false`). The walk allocates nothing per node beyond
22
+ * an ancestor stack, so a facet can afford it on every native event.
23
+ */
24
+ export function isJsonValue(v) {
25
+ const ancestors = [];
26
+ const walk = (x, depth) => {
27
+ if (x === null)
28
+ return true;
29
+ switch (typeof x) {
30
+ case "string":
31
+ case "boolean":
32
+ return true;
33
+ case "number":
34
+ return Number.isFinite(x) && !Object.is(x, -0);
35
+ case "object":
36
+ break;
37
+ default:
38
+ return false; // undefined, function, symbol, bigint
39
+ }
40
+ const o = x;
41
+ if (depth >= JSON_SAFE_MAX_DEPTH || ancestors.includes(o))
42
+ return false;
43
+ ancestors.push(o);
44
+ try {
45
+ if (Array.isArray(o)) {
46
+ for (let i = 0; i < o.length; i++) {
47
+ if (!(i in o) || !walk(o[i], depth + 1))
48
+ return false;
49
+ }
50
+ return true;
51
+ }
52
+ const proto = Object.getPrototypeOf(o);
53
+ if (proto !== Object.prototype && proto !== null)
54
+ return false;
55
+ if (typeof o.toJSON === "function")
56
+ return false;
57
+ for (const k in o) {
58
+ if (!Object.prototype.hasOwnProperty.call(o, k))
59
+ continue;
60
+ if (!walk(o[k], depth + 1))
61
+ return false;
62
+ }
63
+ return true;
64
+ }
65
+ finally {
66
+ ancestors.pop();
67
+ }
68
+ };
69
+ try {
70
+ return walk(v, 0);
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ }
76
+ /**
77
+ * Materialize ANY live value as a `JsonValue`, and never throw.
78
+ *
79
+ * TOTAL by contract: for every input it returns a `JsonValue`. It never
80
+ * throws and never returns anything that is not JSON; the degraded forms below
81
+ * are themselves JSON (a string, or an omitted member).
82
+ *
83
+ * For a facet at a LIVE boundary (in practice once, on the whole native, at
84
+ * `push()` entry): a framework hands over in-process objects that may hold
85
+ * `undefined`, a `Date`, `NaN`, a `BigInt`, a function, a cycle or a throwing
86
+ * getter. `JsonValue.parse` is a validator, and it throws on those;
87
+ * `toJsonValue` (a JSON round-trip) throws on a BigInt or a cycle. A
88
+ * Normalizer MUST NOT throw out of `push()` (SPEC.md §8.0). Keep
89
+ * `JsonValue.parse` for validating data that is already JSON.
90
+ *
91
+ * Plain JSON input (see {@link isJsonValue}) is returned UNCHANGED, as the same
92
+ * reference, with no copy. Anything else is rebuilt as a fresh value that
93
+ * applies `JSON.stringify`'s own rules per node, so for JSON-able input the
94
+ * result serializes identically to `toJsonValue(v)`:
95
+ * - `toJSON` is honoured once per node, with the member key (a `Date` becomes
96
+ * its ISO string; a class instance defining `toJSON` becomes its result);
97
+ * - boxed `Number` / `String` / `Boolean` / `BigInt` are unwrapped;
98
+ * - `NaN` and ±`Infinity` become `null`, and `-0` becomes `0`;
99
+ * - an `undefined`, function or symbol member is omitted from an object, and
100
+ * becomes `null` in an array (a hole too);
101
+ * - an object contributes its own enumerable string keys, in `Object.keys`
102
+ * order (a `Map` or `Set` therefore becomes `{}`, as in JSON).
103
+ *
104
+ * Where `JSON.stringify` would throw, it degrades per node instead and keeps
105
+ * every JSON-able sibling:
106
+ * - a `BigInt` becomes its decimal string;
107
+ * - a cycle becomes {@link JSON_SAFE_CIRCULAR} at the node that repeats an
108
+ * ancestor. A value shared by two branches but not its own ancestor is
109
+ * serialized in full each time, as JSON does;
110
+ * - a throwing `toJSON` or getter omits that member (`null` in an array and
111
+ * for the top-level value);
112
+ * - a node whose keys cannot be enumerated (e.g. a proxy trap throws) is
113
+ * omitted likewise;
114
+ * - nesting past {@link JSON_SAFE_MAX_DEPTH} levels becomes
115
+ * {@link JSON_SAFE_MAX_DEPTH_MARK}, so a pathological structure cannot
116
+ * overflow the stack.
117
+ *
118
+ * One deliberate extension beyond JSON: an `Error` instance (whose `name` and
119
+ * `message` are not enumerable, so JSON would reduce it to its enumerable
120
+ * props) becomes `{name, message, …own enumerable props}`, recursively
121
+ * converted, and NEVER `stack`, which holds local file paths. The rule is the
122
+ * google-adk 0.6.x facet's (c6ecc1c) exactly, so 0.6.7 and 0.7.0 map an Error
123
+ * the same way: detection is `instanceof Error`, and `cause` or
124
+ * AggregateError `errors` ride only when a host made them enumerable.
125
+ *
126
+ * A `__proto__` key is kept as an ordinary own data member on BOTH paths (as
127
+ * `JSON.parse` does), never as a prototype. The helper does not strip it: a
128
+ * consumer that must drop it does so downstream (ingest's copy does, and the
129
+ * facets' scrub/allowlist paths skip it explicitly). A top-level value that
130
+ * JSON would drop (`undefined`, a function, a symbol) returns `null`. To learn
131
+ * WHICH nodes degraded, use {@link toJsonValueSafeWithIssues}.
132
+ *
133
+ * ALIASING: unlike `toJsonValue` (which always deep-copies through a JSON
134
+ * round-trip), plain input is returned BY REFERENCE, so its nodes can end up
135
+ * inside emitted events. A caller that needs isolation copies the result
136
+ * ({@link isJsonValue} is the cheap check). A facet must neither mutate the
137
+ * returned value nor retain it past the `push()` that produced it.
138
+ */
139
+ export function toJsonValueSafe(v) {
140
+ return toJsonValueSafeWithIssues(v).value;
141
+ }
142
+ /** `instanceof Error`, exactly as the google-adk 0.6.x facet decides it
143
+ * (c6ecc1c), so 0.6.7 and 0.7.0 map the same values. An Error from another
144
+ * realm is not one, and converts as a plain object. */
145
+ function isErrorObject(o) {
146
+ try {
147
+ return o instanceof Error;
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ }
153
+ /**
154
+ * {@link toJsonValueSafe}, plus the list of nodes it had to degrade (empty when
155
+ * the input was JSON-able). A consumer that must not forward an invented value
156
+ * can branch on `issues.length > 0` instead of using `value`.
157
+ */
158
+ export function toJsonValueSafeWithIssues(v) {
159
+ if (isJsonValue(v))
160
+ return { value: v, issues: [] };
161
+ const issues = [];
162
+ const ancestors = [];
163
+ const OMIT = Symbol("omit");
164
+ const child = (path, key, inArray) => (inArray ? `${path}[${key}]` : `${path}.${key}`);
165
+ const convert = (value, key, path, depth) => {
166
+ let x = value;
167
+ try {
168
+ if (x !== null && (typeof x === "object" || typeof x === "bigint") && typeof x.toJSON === "function") {
169
+ x = x.toJSON(key);
170
+ }
171
+ }
172
+ catch {
173
+ issues.push({ path, kind: "throwing-toJSON" });
174
+ return OMIT;
175
+ }
176
+ if (typeof x === "object" && x !== null) {
177
+ if (x instanceof Number)
178
+ x = Number(x);
179
+ else if (x instanceof String)
180
+ x = String(x);
181
+ else if (x instanceof Boolean)
182
+ x = x.valueOf();
183
+ else if (Object.prototype.toString.call(x) === "[object BigInt]")
184
+ x = x.valueOf();
185
+ }
186
+ if (x === null)
187
+ return null;
188
+ switch (typeof x) {
189
+ case "string":
190
+ case "boolean":
191
+ return x;
192
+ case "number":
193
+ return Number.isFinite(x) ? (Object.is(x, -0) ? 0 : x) : null;
194
+ case "bigint":
195
+ issues.push({ path, kind: "bigint" });
196
+ return x.toString();
197
+ case "undefined":
198
+ case "function":
199
+ case "symbol":
200
+ return OMIT;
201
+ default:
202
+ break;
203
+ }
204
+ const obj = x;
205
+ if (ancestors.includes(obj)) {
206
+ issues.push({ path, kind: "circular" });
207
+ return JSON_SAFE_CIRCULAR;
208
+ }
209
+ if (depth >= JSON_SAFE_MAX_DEPTH) {
210
+ issues.push({ path, kind: "max-depth" });
211
+ return JSON_SAFE_MAX_DEPTH_MARK;
212
+ }
213
+ if (isErrorObject(obj)) {
214
+ // Deliberate extension beyond JSON (sp-main, 2026-09-24): an Error's
215
+ // `name` and `message` are not enumerable own data, so JSON drops them
216
+ // and a live error part loses its text. Map it to {name, message, …own
217
+ // enumerable props}, and NEVER `stack` (it holds local file paths).
218
+ ancestors.push(obj);
219
+ try {
220
+ const out = {};
221
+ const put = (k, read) => {
222
+ let item;
223
+ try {
224
+ item = read();
225
+ }
226
+ catch {
227
+ issues.push({ path: child(path, k, false), kind: "throwing-getter" });
228
+ return;
229
+ }
230
+ const c = convert(item, k, child(path, k, false), depth + 1);
231
+ if (c !== OMIT)
232
+ Object.defineProperty(out, k, { value: c, enumerable: true, writable: true, configurable: true });
233
+ };
234
+ put("name", () => obj.name);
235
+ put("message", () => obj.message);
236
+ let keys = [];
237
+ try {
238
+ keys = Object.keys(obj);
239
+ }
240
+ catch {
241
+ issues.push({ path, kind: "throwing-keys" });
242
+ }
243
+ for (const k of keys) {
244
+ // As c6ecc1c: an own enumerable name/message is read again here and
245
+ // that read wins, keeping its first position.
246
+ if (k === "stack")
247
+ continue;
248
+ put(k, () => obj[k]);
249
+ }
250
+ return out;
251
+ }
252
+ finally {
253
+ ancestors.pop();
254
+ }
255
+ }
256
+ ancestors.push(obj);
257
+ try {
258
+ if (Array.isArray(obj)) {
259
+ let length;
260
+ try {
261
+ length = obj.length;
262
+ }
263
+ catch {
264
+ issues.push({ path, kind: "throwing-keys" });
265
+ return OMIT;
266
+ }
267
+ const out = [];
268
+ for (let i = 0; i < length; i++) {
269
+ const p = child(path, String(i), true);
270
+ let item;
271
+ try {
272
+ item = obj[i];
273
+ }
274
+ catch {
275
+ issues.push({ path: p, kind: "throwing-getter" });
276
+ out.push(null);
277
+ continue;
278
+ }
279
+ const c = convert(item, String(i), p, depth + 1);
280
+ out.push(c === OMIT ? null : c);
281
+ }
282
+ return out;
283
+ }
284
+ let keys;
285
+ try {
286
+ keys = Object.keys(obj);
287
+ }
288
+ catch {
289
+ issues.push({ path, kind: "throwing-keys" });
290
+ return OMIT;
291
+ }
292
+ const out = {};
293
+ for (const k of keys) {
294
+ const p = child(path, k, false);
295
+ let item;
296
+ try {
297
+ item = obj[k];
298
+ }
299
+ catch {
300
+ issues.push({ path: p, kind: "throwing-getter" });
301
+ continue;
302
+ }
303
+ const c = convert(item, k, p, depth + 1);
304
+ if (c === OMIT)
305
+ continue;
306
+ // A data property, never a prototype write, even for "__proto__".
307
+ Object.defineProperty(out, k, { value: c, enumerable: true, writable: true, configurable: true });
308
+ }
309
+ return out;
310
+ }
311
+ finally {
312
+ ancestors.pop();
313
+ }
314
+ };
315
+ const top = convert(v, "", "$", 0);
316
+ return { value: top === OMIT ? null : top, issues };
317
+ }
9
318
  //# sourceMappingURL=wire.js.map
package/dist/wire.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,MAAM,CAAC,CAAU;IAC/B,MAAM,CAAC,GAAc,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACnD,OAAO,CAAC,CAAC;AACX,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,CAAU;IACpC,MAAM,CAAC,GAAc,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;IACnD,OAAO,CAAC,CAAC;AACX,CAAC"}
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,MAAM,CAAC,CAAU;IAC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AAC;oBACP,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAC;oBAClD,SAAS;gBACX,CAAC;gBACD,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;gBACzC,IAAI,CAAC,KAAK,IAAI;oBAAE,SAAS;gBACzB,kEAAkE;gBAClE,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;YACpG,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;gBAAS,CAAC;YACT,SAAS,CAAC,GAAG,EAAE,CAAC;QAClB,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,GAAG,GAAG,OAAO,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IACnC,OAAO,EAAE,KAAK,EAAE,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,CAAC;AACtD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silverprotocol/core",
3
- "version": "0.6.7",
3
+ "version": "0.7.0",
4
4
  "description": "AgJSON core — the typed schema (AgInput / AgEvent / AgMessage), the Normalizer interface, and the normative reduce().",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/agjson.ts CHANGED
@@ -300,11 +300,19 @@ export type AgHitlAnswerValidation =
300
300
  | "grant-mode-undeclared"
301
301
  | "grant-mode-without-declaration"
302
302
  | "grant-mode-on-nonresolved"
303
- | "request-state-mismatch";
303
+ | "request-state-mismatch"
304
+ | "unknown-status";
304
305
  message: string;
305
306
  };
306
307
 
307
308
  export function validateHitlAnswer(ask: AgPausedAsk, answer: AgHitlAnswer): AgHitlAnswerValidation {
309
+ // draft.4 §0.2 (workspace#20 decision 6): an undefined status is rejected
310
+ // before dispatch, never read as a grant. The typed path already fails at
311
+ // parse; this closes the fail-open for a raw or hand-built answer.
312
+ const statuses: readonly unknown[] = AgHitlAnswer.shape.status.options;
313
+ if (!statuses.includes(answer.status)) {
314
+ return { ok: false, code: "unknown-status", message: `status ${JSON.stringify(answer.status) ?? "undefined"} is not a defined AgHitlAnswer status (spec §0.2, §7)` };
315
+ }
308
316
  if (answer.askId !== ask.askId) {
309
317
  return { ok: false, code: "ask-id-mismatch", message: `answer.askId ${JSON.stringify(answer.askId)} does not name ask ${JSON.stringify(ask.askId)}` };
310
318
  }
@@ -354,7 +362,7 @@ type BlockMeta = {
354
362
  _meta?: AgMeta;
355
363
  };
356
364
  export type AgBlock =
357
- | ({ type: "text"; text: string; citations?: AgCitation[] } & BlockMeta)
365
+ | ({ type: "text"; text: string; citations?: AgCitation[]; phase?: string } & BlockMeta)
358
366
  | ({ type: "image"; source: AgSource } & BlockMeta)
359
367
  | ({ type: "audio"; source: AgSource } & BlockMeta)
360
368
  | ({ type: "file"; source: AgSource; filename?: string } & BlockMeta)
@@ -374,6 +382,7 @@ export type AgBlock =
374
382
  | ({
375
383
  type: "reasoning";
376
384
  text?: string;
385
+ phase?: string; // draft.4 open-string label (§2), folded from reasoning.start/end
377
386
  opaque?: AgOpaque;
378
387
  provider?: string;
379
388
  providerDetails?: JsonValue;
@@ -415,7 +424,7 @@ export type AgBlock =
415
424
  structuredContent?: JsonValue; // MODEL-facing structured result (base MCP outputSchema; §2.1)
416
425
  uiData?: JsonValue; // surface/view, MODEL-HIDDEN (MCP Apps structuredContent / OpenAI Apps component data; §2.1)
417
426
  sideData?: JsonValue; // app-only side data (LangChain ToolMessage.artifact; §2.1)
418
- errorText?: string; // free-form error message (Vercel tool-output-error); present iff outcome==="error"
427
+ errorText?: string; // free-form error message (Vercel tool-output-error); set only when outcome==="error", may be absent on an error (§2.2)
419
428
  errorCode?: string; // structured server-tool error code (Anthropic web_search_tool_result_error.error_code)
420
429
  toolMetadata?: AgMeta; // per-tool metadata bag (Vercel)
421
430
  dynamic?: boolean; // Vercel dynamic-vs-static tool distinction
@@ -449,6 +458,7 @@ export const AgBlock: z.ZodType<AgBlock> = z.lazy(() =>
449
458
  type: z.literal("text"),
450
459
  text: z.string(),
451
460
  citations: z.array(AgCitation).optional(),
461
+ phase: z.string().optional(), // draft.4: OPEN string, never z.enum (a closed value would drop the event)
452
462
  }),
453
463
  z.object({ ...blockMeta, type: z.literal("image"), source: AgSource }),
454
464
  z.object({ ...blockMeta, type: z.literal("audio"), source: AgSource }),
@@ -467,6 +477,7 @@ export const AgBlock: z.ZodType<AgBlock> = z.lazy(() =>
467
477
  ...blockMeta,
468
478
  type: z.literal("reasoning"),
469
479
  text: z.string().optional(),
480
+ phase: z.string().optional(), // draft.4: OPEN string, never z.enum
470
481
  opaque: AgOpaque.optional(),
471
482
  provider: z.string().optional(),
472
483
  providerDetails: JsonValue.optional(),
@@ -651,6 +662,7 @@ export const AgTurnRecord = z.object({
651
662
  threadId: z.string(),
652
663
  outcome: AgOutcome.optional(),
653
664
  finishReason: AgFinishReason.optional(),
665
+ finishReasonRaw: z.string().optional(), // the native finish value verbatim, folded from turn.done (§2, draft.4)
654
666
  usage: AgUsage.optional(),
655
667
  safety: z.array(AgSafety).optional(),
656
668
  handoffs: z.array(AgHandoffRecord).optional(),
@@ -733,6 +745,7 @@ export const AgClientCapabilities = z.object({
733
745
  .object({
734
746
  catalogs: z.array(z.string()).optional(),
735
747
  htmlResources: z.boolean().optional(),
748
+ viewMessageTurns: z.boolean().optional(), // draft.4: view ui/message + sendFollowUpMessage delivered as a later kind:"start" turn (spec §6)
736
749
  })
737
750
  .optional(),
738
751
  state: z.object({ jsonPatch: z.boolean().optional() }).optional(),
@@ -809,7 +822,7 @@ export type AgRunConfig = z.infer<typeof AgRunConfig>;
809
822
 
810
823
  // The spec version this SDK implements (SPEC.md status line + §12). Consumers
811
824
  // reject a MAJOR mismatch and accept any same-major version (§12 negotiation).
812
- export const AGJSON_VERSION = "1.0.0-draft.3";
825
+ export const AGJSON_VERSION = "1.0.0-draft.4";
813
826
 
814
827
  const agjsonWireVersion = z
815
828
  .string()
@@ -1002,10 +1015,14 @@ export type AgOpenAiWidgetAction = z.infer<typeof AgOpenAiWidgetAction>;
1002
1015
  // The surface-interaction union (spec §3 / §6). Element type of
1003
1016
  // resume.uiActions[]. Discriminated on `surface`; the three A2UI legs narrow
1004
1017
  // further on the inner `a2uiMessage` discriminant.
1005
- export const AgSurfaceInteraction = z.union([
1006
- AgA2uiSurfaceAction,
1007
- AgA2uiFunctionResponse,
1008
- AgA2uiError,
1018
+ // Discriminated on `surface` FIRST, then each surface's own discriminant
1019
+ // (a2uiMessage / method), so a validation issue names the member that is
1020
+ // actually wrong: a plain z.union let every non-matching branch report its
1021
+ // own `surface` literal, and the input check (input-check.ts) misclassified
1022
+ // e.g. an mcp-app ui/open-link with a non-string url (CB-9). Same members,
1023
+ // same literals, same accepted values; only the failure path is exact.
1024
+ export const AgSurfaceInteraction = z.discriminatedUnion("surface", [
1025
+ z.discriminatedUnion("a2uiMessage", [AgA2uiSurfaceAction, AgA2uiFunctionResponse, AgA2uiError]),
1009
1026
  AgMcpAppViewMessage,
1010
1027
  AgOpenAiWidgetAction,
1011
1028
  ]);
@@ -1074,7 +1091,7 @@ export const AgSurfaceError = z.object({
1074
1091
  });
1075
1092
  export type AgSurfaceError = z.infer<typeof AgSurfaceError>;
1076
1093
 
1077
- // Event base (spec §4): `seq` = global monotonic ordinal; `turnId` names the owning turn;
1094
+ // Event base (spec §4): `seq` = per-invoke gap-free ordinal from 0 (INV-SEQ: backward only as a new invoke's 0-restart); `turnId` names the owning turn;
1078
1095
  // `messageId` (when present) names the open message the event attaches to.
1079
1096
  // Spread FIRST in each arm so an arm's required field overrides the optional base field.
1080
1097
  const base = {
@@ -1099,6 +1116,7 @@ export const AgClosedEvent = z.discriminatedUnion("type", [
1099
1116
  turnId: z.string(),
1100
1117
  outcome: AgOutcome,
1101
1118
  finishReason: AgFinishReason,
1119
+ finishReasonRaw: z.string().optional(), // the native finish value verbatim, e.g. when finishReason is "other"/"unknown" (§4, draft.4)
1102
1120
  usage: AgUsage.optional(), // EXTENDED — per-turn usage (spec §4)
1103
1121
  safety: z.array(AgSafety).optional(), // EXTENDED — safety signals (spec §4)
1104
1122
  messageId: z.string().optional(),
@@ -1143,6 +1161,7 @@ export const AgClosedEvent = z.discriminatedUnion("type", [
1143
1161
  type: z.literal("text.start"),
1144
1162
  id: z.string(),
1145
1163
  role: z.literal("assistant").optional(),
1164
+ phase: z.string().optional(), // draft.4 open-string label, folds onto the block
1146
1165
  index: z.number().optional(),
1147
1166
  previousPartKind: z.string().optional(),
1148
1167
  providerMetadata: AgProviderMeta.optional(),
@@ -1159,6 +1178,7 @@ export const AgClosedEvent = z.discriminatedUnion("type", [
1159
1178
  ...base,
1160
1179
  type: z.literal("text.end"),
1161
1180
  id: z.string(),
1181
+ phase: z.string().optional(), // draft.4: REPLACES the start value when present
1162
1182
  providerMetadata: AgProviderMeta.optional(),
1163
1183
  // STREAMED-text citations carrier (audit M22): citations for a streamed text
1164
1184
  // block arrive here (not as a duplicate id-less supplement block) and attach
@@ -1237,6 +1257,7 @@ export const AgClosedEvent = z.discriminatedUnion("type", [
1237
1257
  type: z.literal("reasoning.start"),
1238
1258
  id: z.string(),
1239
1259
  mode: z.enum(["summarized", "full"]).optional(),
1260
+ phase: z.string().optional(), // draft.4 open-string label, folds onto the block
1240
1261
  partIndex: z.number().optional(),
1241
1262
  previousPartKind: z.string().optional(),
1242
1263
  providerMetadata: AgProviderMeta.optional(),
@@ -1256,6 +1277,7 @@ export const AgClosedEvent = z.discriminatedUnion("type", [
1256
1277
  type: z.literal("reasoning.end"),
1257
1278
  id: z.string(),
1258
1279
  provider: z.string().optional(),
1280
+ phase: z.string().optional(), // draft.4: REPLACES the start value when present
1259
1281
  providerMetadata: AgProviderMeta.optional(),
1260
1282
  }),
1261
1283
  // REPLACE — sets `opaque` on the reasoning block named by `id` (replay-load-bearing).
@@ -1370,7 +1392,8 @@ export const AgClosedEvent = z.discriminatedUnion("type", [
1370
1392
  // ── OPAQUE / ADVANCED STATE PASSTHROUGH (LangGraph values/updates) ──
1371
1393
  // `snapshot` = full graph-state dict ("values" stream mode); REPLACE on fold (§5).
1372
1394
  z.object({ ...base, type: z.literal("state.snapshot"), snapshot: JsonValue }),
1373
- // `patch` = LangGraph "updates" ({node:{key:value}}) OR an RFC-6902 JSON Patch — both opaque.
1395
+ // `patch` = an RFC-6902 JSON Patch array OR a key-replace object (each top-level key
1396
+ // replaces the state's key whole, draft.4 §5; ADK's actions.stateDelta is one).
1374
1397
  z.object({ ...base, type: z.literal("state.delta"), patch: JsonValue }),
1375
1398
  // ── STREAMED ARTIFACTS (A2A) — side-channel landing (§5) ──
1376
1399
  z.object({