@ai-matrx/content-ir 0.1.1 → 0.2.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,4484 @@
1
+ 'use strict';
2
+
3
+ var Ajv = require('ajv');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
8
+
9
+ // core/ir-types.ts
10
+ var IR_VERSION = 1;
11
+ var IR_ENVELOPE_KEY = "__ir";
12
+ function irPathKey(path) {
13
+ return path.map((segment) => String(segment)).join(".");
14
+ }
15
+ function irPathsEqual(left, right) {
16
+ if (left.length !== right.length) return false;
17
+ for (let i = 0; i < left.length; i++) {
18
+ if (left[i] !== right[i]) return false;
19
+ }
20
+ return true;
21
+ }
22
+ function irPathIsUnderOrEqual(path, prefix) {
23
+ if (path.length < prefix.length) return false;
24
+ for (let i = 0; i < prefix.length; i++) {
25
+ if (path[i] !== prefix[i]) return false;
26
+ }
27
+ return true;
28
+ }
29
+ function irPathLabel(path) {
30
+ if (path.length === 0) return "root";
31
+ const parts = [];
32
+ for (const segment of path) {
33
+ if (typeof segment === "number") {
34
+ parts[parts.length - 1] += `[${segment}]`;
35
+ } else {
36
+ parts.push(String(segment));
37
+ }
38
+ }
39
+ return parts.join(".");
40
+ }
41
+ function isEmptyResidue(residue) {
42
+ return (residue.extra === null || Object.keys(residue.extra).length === 0) && (residue.optionalMissing === null || residue.optionalMissing.length === 0) && (residue.notices === null || residue.notices.length === 0);
43
+ }
44
+
45
+ // core/kind-schema.types.ts
46
+ var KIND_KEY = "__kind";
47
+ function readObjectKind(value) {
48
+ const kind = value[KIND_KEY];
49
+ return typeof kind === "string" ? kind : null;
50
+ }
51
+ function isScalarArrayType(type) {
52
+ return type === "string[]" || type === "number[]" || type === "boolean[]";
53
+ }
54
+ function scalarArrayItemType(type) {
55
+ if (type === "number[]") return "number";
56
+ if (type === "boolean[]") return "boolean";
57
+ return "string";
58
+ }
59
+ function isJsonAnyField(field) {
60
+ return field.type === "json" || field.type === "json[]";
61
+ }
62
+
63
+ // core/discriminator.ts
64
+ var JSON_DISCRIMINATOR = {
65
+ format: "json",
66
+ key: KIND_KEY
67
+ };
68
+ function xmlDiscriminator(tag) {
69
+ return { format: "xml", tag };
70
+ }
71
+ function fenceDiscriminator(language) {
72
+ return { format: "fence", language };
73
+ }
74
+
75
+ // core/ir-tree.ts
76
+ function isRecord(value) {
77
+ return typeof value === "object" && value !== null && !Array.isArray(value);
78
+ }
79
+ function mergeWithoutLoss(prior, incoming) {
80
+ if (!isRecord(prior)) return { value: incoming, rescued: [] };
81
+ if (!isRecord(incoming)) {
82
+ if (incoming !== null && incoming !== void 0) {
83
+ return { value: incoming, rescued: [] };
84
+ }
85
+ return { value: prior, rescued: Object.keys(prior) };
86
+ }
87
+ const rescued = Object.keys(prior).filter((key) => !(key in incoming));
88
+ if (rescued.length === 0) return { value: incoming, rescued };
89
+ return { value: { ...prior, ...incoming }, rescued };
90
+ }
91
+ var IrTree = class {
92
+ nodes = /* @__PURE__ */ new Map();
93
+ rawPaths = /* @__PURE__ */ new Map();
94
+ // pathKey → reason
95
+ dirty = /* @__PURE__ */ new Set();
96
+ /**
97
+ * KIND PRESERVATION (streaming db/cloud kinds): pathKey → identified kind
98
+ * for nodes whose kind is KNOWN (kind_identified / pending_schema) but that
99
+ * have no snapshot node yet because the schema is still cold-fetching.
100
+ * Without this, the envelope reports `kind: ""` for the whole pending
101
+ * window and the render seam can only show raw JSON.
102
+ */
103
+ identifiedKinds = /* @__PURE__ */ new Map();
104
+ /** pathKeys currently waiting on a schema cold fetch. */
105
+ pendingSchemaPaths = /* @__PURE__ */ new Set();
106
+ /**
107
+ * Early top-level scalar fields (title, loading_message, …) captured for
108
+ * identified-but-schema-pending nodes — the loading-component fuel. Scalars
109
+ * only (no live parser references can escape through here). Superseded the
110
+ * moment a real snapshot node exists.
111
+ */
112
+ earlyFields = /* @__PURE__ */ new Map();
113
+ /**
114
+ * pathKey → identified kind preserved through a SCHEMA-AVAILABILITY raw
115
+ * fallback (parser stamped `kind` on the raw_object event). Structural raws
116
+ * (missing __kind, duplicate key, validation failure) never land here.
117
+ */
118
+ rawKinds = /* @__PURE__ */ new Map();
119
+ regionStatus = "streaming";
120
+ errorReason = null;
121
+ rootRawValue = null;
122
+ /** Notices for degrades that tried to erase already-published data. */
123
+ rescueNotices = [];
124
+ completedKind = "";
125
+ get status() {
126
+ return this.regionStatus;
127
+ }
128
+ applyEvent(event) {
129
+ switch (event.type) {
130
+ case "kind_identified": {
131
+ this.identifiedKinds.set(irPathKey(event.path), event.kind);
132
+ this.dirty.add(irPathKey(event.path));
133
+ return;
134
+ }
135
+ case "pending_schema": {
136
+ const pathKey = irPathKey(event.path);
137
+ this.identifiedKinds.set(pathKey, event.kind);
138
+ this.pendingSchemaPaths.add(pathKey);
139
+ this.dirty.add(pathKey);
140
+ return;
141
+ }
142
+ case "field": {
143
+ const parentKey = irPathKey(event.path.slice(0, -1));
144
+ if (this.nodes.has(parentKey)) return;
145
+ if (!this.identifiedKinds.has(parentKey)) return;
146
+ const v = event.value;
147
+ if (v !== null && typeof v === "object") return;
148
+ const bucket = this.earlyFields.get(parentKey) ?? {};
149
+ bucket[event.key] = v;
150
+ this.earlyFields.set(parentKey, bucket);
151
+ this.dirty.add(parentKey);
152
+ return;
153
+ }
154
+ case "block_snapshot": {
155
+ const pathKey = irPathKey(event.path);
156
+ this.pendingSchemaPaths.delete(pathKey);
157
+ this.earlyFields.delete(pathKey);
158
+ this.upsertNode(event.path, {
159
+ kind: event.kind,
160
+ value: event.value,
161
+ residue: event.residue,
162
+ complete: event.complete
163
+ });
164
+ return;
165
+ }
166
+ case "raw_object": {
167
+ const pathKey = irPathKey(event.path);
168
+ this.pendingSchemaPaths.delete(pathKey);
169
+ this.earlyFields.delete(pathKey);
170
+ if (event.kind) this.rawKinds.set(pathKey, event.kind);
171
+ this.markRaw(event.path, event.reason, event.value);
172
+ return;
173
+ }
174
+ case "complete": {
175
+ this.regionStatus = this.errorReason ? "error" : "complete";
176
+ this.completedKind = event.kind;
177
+ if (this.rawPaths.has("") && isRecord(event.value)) {
178
+ const merged = mergeWithoutLoss(this.rootRawValue, event.value);
179
+ this.recordRescue("", "complete", merged.rescued);
180
+ if (isRecord(merged.value)) this.rootRawValue = merged.value;
181
+ }
182
+ this.dirty.add("");
183
+ return;
184
+ }
185
+ case "error": {
186
+ this.errorReason = event.reason;
187
+ this.regionStatus = "error";
188
+ this.dirty.add("");
189
+ return;
190
+ }
191
+ default:
192
+ return;
193
+ }
194
+ }
195
+ getNode(pathKey) {
196
+ return this.nodes.get(pathKey) ?? null;
197
+ }
198
+ listNodes() {
199
+ return [...this.nodes.values()];
200
+ }
201
+ isRawPath(pathKey) {
202
+ return this.rawPaths.has(pathKey);
203
+ }
204
+ /** Dirty pathKeys since the last drain — the flush/notify unit. */
205
+ drainDirty() {
206
+ const drained = [...this.dirty];
207
+ this.dirty.clear();
208
+ return drained;
209
+ }
210
+ hasDirty() {
211
+ return this.dirty.size > 0;
212
+ }
213
+ // -------------------------------------------------------------------------
214
+ upsertNode(path, payload) {
215
+ const pathKey = irPathKey(path);
216
+ if (this.rawPaths.has(pathKey)) return;
217
+ const stabilized = this.stabilizeValue(
218
+ payload.value,
219
+ path,
220
+ pathKey
221
+ );
222
+ const prior = this.nodes.get(pathKey);
223
+ const node = {
224
+ kind: payload.kind,
225
+ kindState: payload.complete ? "resolved" : prior?.kindState ?? "resolved",
226
+ path,
227
+ pathKey,
228
+ value: stabilized,
229
+ residue: payload.residue,
230
+ complete: payload.complete,
231
+ version: (prior?.version ?? 0) + 1
232
+ };
233
+ this.nodes.set(pathKey, node);
234
+ this.dirty.add(pathKey);
235
+ this.propagateToAncestors(path, node.value);
236
+ }
237
+ /**
238
+ * Substitute kind-node children with their current tree values so sibling
239
+ * identities are stable; deep-copy everything else so no live parser
240
+ * reference ever escapes.
241
+ */
242
+ stabilizeValue(value, path, applyingPathKey) {
243
+ if (Array.isArray(value)) {
244
+ return value.map(
245
+ (item, index) => this.stabilizeValue(item, [...path, index], applyingPathKey)
246
+ );
247
+ }
248
+ if (isRecord(value)) {
249
+ const pathKey = irPathKey(path);
250
+ if (pathKey !== applyingPathKey) {
251
+ const childNode = this.nodes.get(pathKey);
252
+ if (childNode) return childNode.value;
253
+ }
254
+ const out = {};
255
+ for (const [key, child] of Object.entries(value)) {
256
+ out[key] = this.stabilizeValue(child, [...path, key], applyingPathKey);
257
+ }
258
+ return out;
259
+ }
260
+ return value;
261
+ }
262
+ /**
263
+ * COW spine rebuild: replace the child's slot in each ancestor kind-node's
264
+ * value, shallow-copying only the containers along the way. Siblings keep
265
+ * identity; every ancestor gets a new value identity + version bump.
266
+ */
267
+ propagateToAncestors(childPath, childValue) {
268
+ let currentPath = childPath;
269
+ let currentValue = childValue;
270
+ while (currentPath.length > 0) {
271
+ const ancestor = this.findNearestAncestorNode(currentPath);
272
+ if (!ancestor) return;
273
+ const relative = currentPath.slice(ancestor.path.length);
274
+ const rebuilt = this.cloneAlong(ancestor.value, relative, currentValue);
275
+ if (rebuilt === ancestor.value) return;
276
+ const updated = {
277
+ ...ancestor,
278
+ value: rebuilt,
279
+ version: ancestor.version + 1
280
+ };
281
+ this.nodes.set(ancestor.pathKey, updated);
282
+ this.dirty.add(ancestor.pathKey);
283
+ currentPath = ancestor.path;
284
+ currentValue = updated.value;
285
+ }
286
+ }
287
+ findNearestAncestorNode(path) {
288
+ for (let len = path.length - 1; len >= 0; len--) {
289
+ const node = this.nodes.get(irPathKey(path.slice(0, len)));
290
+ if (node) return node;
291
+ }
292
+ return null;
293
+ }
294
+ cloneAlong(container, relative, leaf) {
295
+ if (relative.length === 0) return leaf;
296
+ const [head, ...rest] = relative;
297
+ if (Array.isArray(container)) {
298
+ const index = typeof head === "number" ? head : Number(head);
299
+ const copy = container.slice();
300
+ while (copy.length <= index) copy.push(void 0);
301
+ copy[index] = this.cloneAlong(container[index], rest, leaf);
302
+ return copy;
303
+ }
304
+ if (isRecord(container)) {
305
+ const key = String(head);
306
+ return {
307
+ ...container,
308
+ [key]: this.cloneAlong(container[key], rest, leaf)
309
+ };
310
+ }
311
+ const built = typeof head === "number" ? this.cloneAlong([], relative, leaf) : this.cloneAlong({}, relative, leaf);
312
+ return built;
313
+ }
314
+ markRaw(path, reason, value) {
315
+ const pathKey = irPathKey(path);
316
+ const prior = path.length === 0 ? this.nodes.get("")?.value ?? this.rootRawValue : this.nodes.get(pathKey)?.value;
317
+ const merged = mergeWithoutLoss(prior, value);
318
+ this.recordRescue(pathKey, reason, merged.rescued);
319
+ this.rawPaths.set(pathKey, reason);
320
+ this.nodes.delete(pathKey);
321
+ this.dirty.add(pathKey);
322
+ if (path.length === 0) {
323
+ if (isRecord(merged.value)) this.rootRawValue = merged.value;
324
+ return;
325
+ }
326
+ this.propagateToAncestors(path, merged.value);
327
+ }
328
+ /**
329
+ * A rescue means a degrade tried to erase data a user could already see —
330
+ * an upstream defect. It rides the envelope as a notice so it surfaces in the
331
+ * Error Inspector instead of being silently absorbed (`core/` is a pure
332
+ * kernel: no console, no capture — the notice IS the alarm).
333
+ */
334
+ recordRescue(pathKey, reason, rescued) {
335
+ if (rescued.length === 0) return;
336
+ this.rescueNotices.push({
337
+ code: "degrade_data_rescued",
338
+ message: `degrade (${reason}) at path "${pathKey || "<root>"}" would have dropped: ${rescued.join(", ")}`
339
+ });
340
+ }
341
+ /**
342
+ * Assemble the canonical envelope. ONE code path for stream + one-shot.
343
+ * Callers supply the fingerprint (one-shot hashes the source; live sessions
344
+ * keep an incremental hasher so no per-flush re-hash happens).
345
+ */
346
+ buildEnvelope(fingerprint) {
347
+ const rootNode = this.nodes.get("");
348
+ const rootRawReason = this.rawPaths.get("") ?? null;
349
+ const notices = [];
350
+ if (this.errorReason) {
351
+ notices.push({ code: "parse_error", message: this.errorReason });
352
+ }
353
+ if (rootRawReason) {
354
+ notices.push({ code: "raw_fallback", message: rootRawReason });
355
+ }
356
+ notices.push(...this.rescueNotices);
357
+ const baseResidue = rootNode?.residue ?? null;
358
+ let residue = baseResidue;
359
+ if (notices.length > 0) {
360
+ residue = {
361
+ extra: baseResidue?.extra ?? null,
362
+ optionalMissing: baseResidue?.optionalMissing ?? null,
363
+ notices: [...baseResidue?.notices ?? [], ...notices]
364
+ };
365
+ }
366
+ const isRaw = rootRawReason !== null;
367
+ const identifiedKind = this.identifiedKinds.get("") ?? "";
368
+ const rootKind = isRaw ? this.rawKinds.get("") ?? "" : rootNode?.kind ?? (this.completedKind || identifiedKind);
369
+ const root = {
370
+ role: "structured",
371
+ kind: rootKind,
372
+ kindState: isRaw ? "raw" : rootNode ? rootNode.kindState : this.pendingSchemaPaths.has("") ? "pending_schema" : this.regionStatus === "streaming" ? identifiedKind ? "pending_schema" : "pending_kind" : "raw",
373
+ discriminator: JSON_DISCRIMINATOR,
374
+ path: [],
375
+ status: this.regionStatus,
376
+ value: rootNode?.value ?? this.rootRawValue ?? // Copy: the early-fields bucket keeps mutating as fields arrive; the
377
+ // envelope must be freezable (Redux dev-mode immutability).
378
+ (this.earlyFields.has("") ? { ...this.earlyFields.get("") } : {}),
379
+ residue
380
+ };
381
+ const nodeIndex = {};
382
+ for (const node of this.nodes.values()) {
383
+ if (node.pathKey === "") continue;
384
+ nodeIndex[node.pathKey] = {
385
+ kind: node.kind,
386
+ kindState: node.kindState,
387
+ status: node.complete ? "complete" : "streaming",
388
+ ...node.residue ? { residue: node.residue } : {}
389
+ };
390
+ }
391
+ for (const [pathKey] of this.rawPaths) {
392
+ if (pathKey === "") continue;
393
+ nodeIndex[pathKey] = { kind: "", kindState: "raw", status: "complete" };
394
+ }
395
+ return {
396
+ v: IR_VERSION,
397
+ engine: "fe-kind-parser",
398
+ fingerprint,
399
+ root,
400
+ ...Object.keys(nodeIndex).length > 0 ? { nodeIndex } : {}
401
+ };
402
+ }
403
+ };
404
+
405
+ // core/json-tokenizer.ts
406
+ var JsonStreamTokenizer = class {
407
+ constructor(onToken) {
408
+ this.onToken = onToken;
409
+ }
410
+ onToken;
411
+ mode = "normal";
412
+ pos = 0;
413
+ stringBuffer = "";
414
+ primitiveBuffer = "";
415
+ unicodeBuffer = "";
416
+ tokenStart = 0;
417
+ get position() {
418
+ return this.pos;
419
+ }
420
+ push(chunk) {
421
+ for (let i = 0; i < chunk.length; i++) {
422
+ const ch = chunk[i];
423
+ const at = this.pos;
424
+ this.pos += 1;
425
+ if (ch === void 0) continue;
426
+ if (this.mode === "primitive") {
427
+ if (this.isDelimiter(ch)) {
428
+ this.emitPrimitive();
429
+ this.handleNormalChar(ch, at);
430
+ } else {
431
+ this.primitiveBuffer += ch;
432
+ }
433
+ continue;
434
+ }
435
+ if (this.mode === "string") {
436
+ if (ch === '"') {
437
+ this.onToken({
438
+ type: "string",
439
+ value: this.stringBuffer,
440
+ at: this.tokenStart
441
+ });
442
+ this.stringBuffer = "";
443
+ this.mode = "normal";
444
+ continue;
445
+ }
446
+ if (ch === "\\") {
447
+ this.mode = "escape";
448
+ continue;
449
+ }
450
+ if (ch === "\n" || ch === "\r") {
451
+ throw new Error(`Invalid unescaped newline in JSON string at ${at}`);
452
+ }
453
+ this.stringBuffer += ch;
454
+ continue;
455
+ }
456
+ if (this.mode === "escape") {
457
+ if (ch === "u") {
458
+ this.unicodeBuffer = "";
459
+ this.mode = "unicode";
460
+ continue;
461
+ }
462
+ const escaped = {
463
+ '"': '"',
464
+ "\\": "\\",
465
+ "/": "/",
466
+ b: "\b",
467
+ f: "\f",
468
+ n: "\n",
469
+ r: "\r",
470
+ t: " "
471
+ };
472
+ if (!(ch in escaped)) {
473
+ throw new Error(`Invalid JSON escape sequence at ${at}`);
474
+ }
475
+ this.stringBuffer += escaped[ch];
476
+ this.mode = "string";
477
+ continue;
478
+ }
479
+ if (this.mode === "unicode") {
480
+ if (!/[0-9a-fA-F]/.test(ch)) {
481
+ throw new Error(`Invalid unicode escape at ${at}`);
482
+ }
483
+ this.unicodeBuffer += ch;
484
+ if (this.unicodeBuffer.length === 4) {
485
+ this.stringBuffer += String.fromCharCode(
486
+ parseInt(this.unicodeBuffer, 16)
487
+ );
488
+ this.unicodeBuffer = "";
489
+ this.mode = "string";
490
+ }
491
+ continue;
492
+ }
493
+ this.handleNormalChar(ch, at);
494
+ }
495
+ }
496
+ end() {
497
+ if (this.mode === "primitive") {
498
+ this.emitPrimitive();
499
+ return;
500
+ }
501
+ if (this.mode !== "normal") {
502
+ throw new Error(
503
+ `Stream ended while parsing JSON ${this.mode} at ${this.pos}`
504
+ );
505
+ }
506
+ }
507
+ handleNormalChar(ch, at) {
508
+ if (/\s/.test(ch)) return;
509
+ if (ch === "{" || ch === "}" || ch === "[" || ch === "]" || ch === ":" || ch === ",") {
510
+ this.onToken({ type: "punct", value: ch, at });
511
+ return;
512
+ }
513
+ if (ch === '"') {
514
+ this.mode = "string";
515
+ this.stringBuffer = "";
516
+ this.tokenStart = at;
517
+ return;
518
+ }
519
+ if (/[-0-9tfn]/.test(ch)) {
520
+ this.mode = "primitive";
521
+ this.primitiveBuffer = ch;
522
+ this.tokenStart = at;
523
+ return;
524
+ }
525
+ throw new Error(`Unexpected character "${ch}" at ${at}`);
526
+ }
527
+ emitPrimitive() {
528
+ const raw = this.primitiveBuffer;
529
+ const at = this.tokenStart;
530
+ this.primitiveBuffer = "";
531
+ this.mode = "normal";
532
+ let value;
533
+ try {
534
+ value = JSON.parse(raw);
535
+ } catch {
536
+ throw new Error(`Invalid JSON primitive "${raw}" at ${at}`);
537
+ }
538
+ if (typeof value === "number") {
539
+ this.onToken({ type: "number", value, at });
540
+ return;
541
+ }
542
+ if (typeof value === "boolean") {
543
+ this.onToken({ type: "boolean", value, at });
544
+ return;
545
+ }
546
+ if (value === null) {
547
+ this.onToken({ type: "null", value, at });
548
+ return;
549
+ }
550
+ throw new Error(`Unsupported JSON primitive "${raw}" at ${at}`);
551
+ }
552
+ isDelimiter(ch) {
553
+ return /\s/.test(ch) || ch === "{" || ch === "}" || ch === "[" || ch === "]" || ch === ":" || ch === ",";
554
+ }
555
+ };
556
+
557
+ // core/kind-snapshot.ts
558
+ function emptyValueForFieldSchema(field) {
559
+ if (field.nullable) return null;
560
+ switch (field.type) {
561
+ case "string":
562
+ return "";
563
+ case "number":
564
+ return 0;
565
+ case "boolean":
566
+ return false;
567
+ case "json":
568
+ return null;
569
+ case "string[]":
570
+ case "number[]":
571
+ case "boolean[]":
572
+ case "json[]":
573
+ case "array":
574
+ return [];
575
+ case "object":
576
+ case "inline_object":
577
+ case "record":
578
+ return {};
579
+ case "enum":
580
+ return "";
581
+ case "union":
582
+ if (field.scalars.includes("string")) return "";
583
+ if (field.scalars.includes("number")) return 0;
584
+ if (field.scalars.includes("boolean")) return false;
585
+ return {};
586
+ default:
587
+ return null;
588
+ }
589
+ }
590
+ function buildCompliantKindSnapshot(schema, partial) {
591
+ const value = {
592
+ [KIND_KEY]: schema.kind
593
+ };
594
+ const optionalMissing = [];
595
+ for (const [fieldName, fieldSchema] of Object.entries(schema.fields)) {
596
+ if (fieldName in partial && partial[fieldName] !== void 0) {
597
+ value[fieldName] = partial[fieldName];
598
+ } else if (fieldSchema.required) {
599
+ value[fieldName] = emptyValueForFieldSchema(fieldSchema);
600
+ } else {
601
+ optionalMissing.push(fieldName);
602
+ }
603
+ }
604
+ let extra = null;
605
+ for (const [fieldName, fieldValue] of Object.entries(partial)) {
606
+ if (fieldName === KIND_KEY) continue;
607
+ if (fieldName in schema.fields) continue;
608
+ if (extra === null) extra = {};
609
+ extra[fieldName] = fieldValue;
610
+ }
611
+ const residue = {
612
+ extra,
613
+ optionalMissing: optionalMissing.length > 0 ? optionalMissing : null,
614
+ notices: null
615
+ };
616
+ return { value, residue: isEmptyResidue(residue) ? null : residue };
617
+ }
618
+ function mergeResidueIntoValue(value, residue) {
619
+ if (!residue?.extra) return value;
620
+ return { ...value, ...residue.extra };
621
+ }
622
+
623
+ // core/kind-parser.ts
624
+ var jsonRootKeyLookup = null;
625
+ function setJsonRootKeyLookup(lookup) {
626
+ jsonRootKeyLookup = lookup;
627
+ }
628
+ function isSchemaResolver(source) {
629
+ return typeof source.get === "function";
630
+ }
631
+ function safeCopy(value) {
632
+ try {
633
+ return structuredClone(value);
634
+ } catch {
635
+ return value;
636
+ }
637
+ }
638
+ var KindStreamParser = class {
639
+ constructor(options) {
640
+ this.options = options;
641
+ this.resolver = isSchemaResolver(options.schemas) ? options.schemas : {
642
+ get: (kind) => options.schemas[kind]
643
+ };
644
+ this.tokenizer = new JsonStreamTokenizer(
645
+ (token) => this.handleToken(token)
646
+ );
647
+ }
648
+ options;
649
+ resolver;
650
+ stack = [];
651
+ objectKinds = /* @__PURE__ */ new Map();
652
+ inlineSchemas = /* @__PURE__ */ new Map();
653
+ recordSchemas = /* @__PURE__ */ new Map();
654
+ rawObjectPaths = /* @__PURE__ */ new Set();
655
+ /**
656
+ * Subtrees whose value domain is "any JSON" by schema (`json` / `json[]`
657
+ * fields, `record` with `values:"json"` members). OPAQUE by contract: no
658
+ * kind identification, no pending_kind, no raw_object degradation — unknown
659
+ * structure here is the declared shape, not a failure. Propagates to every
660
+ * descendant compound.
661
+ */
662
+ opaquePaths = /* @__PURE__ */ new Set();
663
+ deferredFields = /* @__PURE__ */ new Map();
664
+ awaitingKindPaths = /* @__PURE__ */ new Set();
665
+ /** Paths whose kind came from parent-schema prediction, unconfirmed so far. */
666
+ speculativeKinds = /* @__PURE__ */ new Set();
667
+ /**
668
+ * Kind named by the root object's FIRST key through the `json_root_key`
669
+ * surface registry — a candidate, adopted only at root finalize.
670
+ */
671
+ rootSurfaceKind = null;
672
+ /** kind → paths (by key) waiting for the resolver's cold fetch. */
673
+ pendingSchemaPaths = /* @__PURE__ */ new Map();
674
+ /** Pending-schema paths whose object already closed. */
675
+ closedPendingPaths = /* @__PURE__ */ new Set();
676
+ /** Schemas delivered via notifySchemaArrived (overlay over the resolver). */
677
+ arrivedSchemas = /* @__PURE__ */ new Map();
678
+ tokenizer;
679
+ root;
680
+ rootKind = "";
681
+ rootDone = false;
682
+ failed = false;
683
+ push(chunk) {
684
+ if (this.failed || this.rootDone) return;
685
+ try {
686
+ this.tokenizer.push(chunk);
687
+ } catch (error) {
688
+ this.fail(
689
+ error instanceof Error ? error.message : String(error),
690
+ this.tokenizer.position
691
+ );
692
+ }
693
+ }
694
+ end() {
695
+ if (this.failed) return;
696
+ try {
697
+ this.tokenizer.end();
698
+ } catch (error) {
699
+ this.fail(
700
+ error instanceof Error ? error.message : String(error),
701
+ this.tokenizer.position
702
+ );
703
+ return;
704
+ }
705
+ this.resolvePendingSchemasAsRaw();
706
+ if (!this.rootDone) {
707
+ this.fail(
708
+ "Stream ended before the root JSON object was complete.",
709
+ this.tokenizer.position
710
+ );
711
+ }
712
+ }
713
+ resolvePendingSchemasAsRaw() {
714
+ const at = this.tokenizer.position;
715
+ for (const [kind, paths] of [...this.pendingSchemaPaths]) {
716
+ this.pendingSchemaPaths.delete(kind);
717
+ for (const [pathKey, path] of paths) {
718
+ this.closedPendingPaths.delete(pathKey);
719
+ if (this.rawObjectPaths.has(pathKey)) continue;
720
+ const value = this.getLiveObjectValue(path) ?? this.getFinalizedObjectValue(path) ?? {};
721
+ this.emitRawObject(
722
+ path,
723
+ safeCopy(value),
724
+ `No block schema registered for "${kind}".`,
725
+ at,
726
+ kind
727
+ );
728
+ }
729
+ }
730
+ }
731
+ /** True once the root value has closed — the region is fully consumed. */
732
+ get isComplete() {
733
+ return this.rootDone;
734
+ }
735
+ get hasFailed() {
736
+ return this.failed;
737
+ }
738
+ /**
739
+ * Upgrade-in-place: the registry's cold fetch answered. Pending nodes for
740
+ * this kind validate and complete (closed nodes retroactively); a null
741
+ * schema (fetch miss) drops them to raw. Safe to call after end().
742
+ */
743
+ notifySchemaArrived(kind, schema) {
744
+ const waiting = this.pendingSchemaPaths.get(kind);
745
+ if (!waiting) return;
746
+ this.pendingSchemaPaths.delete(kind);
747
+ if (schema) {
748
+ this.arrivedSchemas.set(kind, schema);
749
+ }
750
+ const at = this.tokenizer.position;
751
+ for (const [pathKey, path] of waiting) {
752
+ if (this.rawObjectPaths.has(pathKey)) continue;
753
+ const value = this.getLiveObjectValue(path) ?? this.getFinalizedObjectValue(path);
754
+ if (!schema) {
755
+ this.emitRawObject(
756
+ path,
757
+ safeCopy(value ?? {}),
758
+ `No block schema registered for "${kind}".`,
759
+ at,
760
+ kind
761
+ );
762
+ this.closedPendingPaths.delete(pathKey);
763
+ continue;
764
+ }
765
+ if (this.closedPendingPaths.has(pathKey)) {
766
+ this.closedPendingPaths.delete(pathKey);
767
+ if (value) {
768
+ this.finalizeTypedObject(path, value, at);
769
+ }
770
+ } else {
771
+ this.emitBlockSnapshotForObject(path, at);
772
+ }
773
+ }
774
+ }
775
+ handleToken(token) {
776
+ if (this.failed) return;
777
+ if (this.rootDone) {
778
+ this.fail("Unexpected token after complete JSON object.", token.at);
779
+ return;
780
+ }
781
+ if (token.type === "punct") {
782
+ this.handlePunctuation(token);
783
+ return;
784
+ }
785
+ if (token.type === "string") {
786
+ this.handleString(token);
787
+ return;
788
+ }
789
+ this.beginScalar(token.value, token.at);
790
+ }
791
+ handleString(token) {
792
+ const frame = this.currentFrame();
793
+ if (frame?.kind === "object" && (frame.expecting === "keyOrEnd" || frame.expecting === "key")) {
794
+ this.acceptObjectKey(frame, token.value, token.at);
795
+ return;
796
+ }
797
+ this.beginScalar(token.value, token.at);
798
+ }
799
+ handlePunctuation(token) {
800
+ switch (token.value) {
801
+ case "{":
802
+ this.beginCompound("object", token.at);
803
+ return;
804
+ case "[":
805
+ this.beginCompound("array", token.at);
806
+ return;
807
+ case "}":
808
+ this.closeCompound("object", token.at);
809
+ return;
810
+ case "]":
811
+ this.closeCompound("array", token.at);
812
+ return;
813
+ case ":":
814
+ this.acceptColon(token.at);
815
+ return;
816
+ case ",":
817
+ this.acceptComma(token.at);
818
+ return;
819
+ }
820
+ }
821
+ beginCompound(kind, at) {
822
+ const value = kind === "object" ? {} : [];
823
+ const container = this.currentFrame();
824
+ const path = this.placeValue(value, kind, at, false);
825
+ if (!path || this.failed) return;
826
+ const opaque = container !== void 0 && this.opaquePaths.has(this.pathKey(container.path)) || this.isJsonAnyPlacement(path);
827
+ if (opaque) this.opaquePaths.add(this.pathKey(path));
828
+ if (kind === "object") {
829
+ this.emit({ type: "object_start", path, at });
830
+ if (opaque) {
831
+ this.stack.push({
832
+ kind: "object",
833
+ path,
834
+ value,
835
+ expecting: "keyOrEnd",
836
+ keyCount: 0
837
+ });
838
+ return;
839
+ }
840
+ this.registerObjectContext(path);
841
+ const pathKey = this.pathKey(path);
842
+ this.stack.push({
843
+ kind: "object",
844
+ path,
845
+ value,
846
+ expecting: "keyOrEnd",
847
+ keyCount: 0
848
+ });
849
+ if (this.inlineSchemas.has(pathKey) || this.recordSchemas.has(pathKey)) {
850
+ return;
851
+ }
852
+ const speculated = this.resolveSpeculativeKind(path);
853
+ if (speculated) {
854
+ this.objectKinds.set(pathKey, speculated);
855
+ this.speculativeKinds.add(pathKey);
856
+ if (path.length === 0) {
857
+ this.rootKind = speculated;
858
+ }
859
+ this.emit({
860
+ type: "kind_identified",
861
+ kind: speculated,
862
+ path,
863
+ speculative: true,
864
+ at
865
+ });
866
+ this.emitBlockSnapshotForObject(path, at);
867
+ return;
868
+ }
869
+ this.awaitingKindPaths.add(pathKey);
870
+ this.emit({ type: "pending_kind", path, at });
871
+ return;
872
+ }
873
+ const parentField = this.parentFieldName(path);
874
+ if (parentField) {
875
+ this.emit({ type: "array_start", path, field: parentField, at });
876
+ }
877
+ this.stack.push({
878
+ kind: "array",
879
+ path,
880
+ value,
881
+ expecting: "valueOrEnd",
882
+ nextIndex: 0
883
+ });
884
+ }
885
+ /**
886
+ * THE JSON-ROOT-KEY SURFACE — `content_ir.kind_surface` rows of type
887
+ * `json_root_key`, live at last (they were inert phantom rows until
888
+ * 2026-08-20).
889
+ *
890
+ * A legacy payload such as `{"quiz_title": ...}` carries no `__kind`, but
891
+ * the ONE surface registry knows exactly which kind that root key names —
892
+ * the same lookup the SERVER performs before adapting the payload
893
+ * (`aidream .../processing/blocks/envelope.py`). Consulting it HERE, in the
894
+ * shared parser core, is what makes one place decide it: both hosts — the
895
+ * one-shot `normalizeJsonRegion` (DB reload / reconcile) and the live
896
+ * `openParseSession` (streaming) — build their parser through
897
+ * `createKindStreamParser`, so neither passes an option and neither can
898
+ * drift from the other.
899
+ *
900
+ * Recorded at the first root key; ADOPTED only when the root object closes
901
+ * (`completeTypedObject`). That is the surface registry's complete-only
902
+ * convergence law, and every json_root_key row is `streaming:false` — these
903
+ * legacy shapes are recognised by their whole payload, so speculating
904
+ * mid-stream would flash a kind component over an object that may never
905
+ * satisfy the schema. An explicit `expectedRootKind` (an agent's declared
906
+ * output schema) is stronger context and always wins; an actual `__kind`
907
+ * still wins over both.
908
+ */
909
+ noteRootSurfaceKind(key) {
910
+ if (key === KIND_KEY) return;
911
+ if (this.options.expectedRootKind) return;
912
+ if (this.rootKind || this.objectKinds.has(this.pathKey([]))) return;
913
+ const kind = this.resolver.kindForJsonRootKey?.(key) ?? jsonRootKeyLookup?.(key);
914
+ if (!kind) return;
915
+ this.rootSurfaceKind = kind;
916
+ if (!this.lookupSchema(kind)) {
917
+ this.resolver.request?.(kind);
918
+ }
919
+ }
920
+ /**
921
+ * Prediction from the parent schema: object field → declared kind; array
922
+ * item → sole itemKind; root → expectedRootKind. Only when the schema is
923
+ * actually resolvable (a prediction we can't validate against is not a
924
+ * commitment worth making).
925
+ */
926
+ resolveSpeculativeKind(path) {
927
+ if (path.length === 0) {
928
+ const expected = this.options.expectedRootKind;
929
+ return expected && this.lookupObjectSchema(expected) ? expected : null;
930
+ }
931
+ const last = path[path.length - 1];
932
+ if (typeof last === "string") {
933
+ const fieldSchema2 = this.resolveParentFieldSchema(path);
934
+ if (fieldSchema2?.type === "object" && this.lookupObjectSchema(fieldSchema2.kind)) {
935
+ return fieldSchema2.kind;
936
+ }
937
+ return null;
938
+ }
939
+ const fieldName = this.parentFieldName(path);
940
+ if (!fieldName) return null;
941
+ const ownerPath = path.slice(0, -2);
942
+ const ownerKind = this.getObjectKindForPath(ownerPath);
943
+ if (!ownerKind) return null;
944
+ const fieldSchema = this.lookupSchema(ownerKind)?.fields[fieldName];
945
+ const soleItemKind = fieldSchema?.type === "array" && fieldSchema.itemKinds.length === 1 ? fieldSchema.itemKinds[0] : void 0;
946
+ if (soleItemKind !== void 0 && this.lookupObjectSchema(soleItemKind)) {
947
+ return soleItemKind;
948
+ }
949
+ return null;
950
+ }
951
+ /**
952
+ * A schema usable for OBJECT speculation/snapshots — root-form kinds
953
+ * (non-object data-only shapes) are never a valid object commitment.
954
+ */
955
+ lookupObjectSchema(kind) {
956
+ const schema = this.lookupSchema(kind);
957
+ return schema && !schema.root ? schema : void 0;
958
+ }
959
+ beginScalar(value, at) {
960
+ this.placeValue(value, "scalar", at, true);
961
+ }
962
+ placeValue(value, valueKind, at, finalizedImmediately) {
963
+ if (this.root === void 0) {
964
+ if (valueKind !== "object") {
965
+ this.fail("Root value must be a JSON object.", at);
966
+ return null;
967
+ }
968
+ this.root = value;
969
+ return [];
970
+ }
971
+ const parent = this.currentFrame();
972
+ if (!parent) {
973
+ this.fail("Unexpected value after root object.", at);
974
+ return null;
975
+ }
976
+ let path;
977
+ let fieldKey;
978
+ if (parent.kind === "object") {
979
+ if (parent.expecting !== "value") {
980
+ this.fail(
981
+ `Unexpected value inside object. Expected ${parent.expecting}.`,
982
+ at
983
+ );
984
+ return null;
985
+ }
986
+ if (parent.currentKey === void 0) {
987
+ this.fail("Internal parser error: missing object key.", at);
988
+ return null;
989
+ }
990
+ fieldKey = parent.currentKey;
991
+ path = [...parent.path, fieldKey];
992
+ const placementError = this.validateFieldPlacement(
993
+ parent,
994
+ fieldKey,
995
+ valueKind,
996
+ value
997
+ );
998
+ if (placementError) {
999
+ this.markNodeRaw(parent.path, parent.value, placementError, at);
1000
+ }
1001
+ parent.value[fieldKey] = value;
1002
+ parent.currentKey = void 0;
1003
+ parent.expecting = "commaOrEnd";
1004
+ } else {
1005
+ if (parent.expecting !== "valueOrEnd" && parent.expecting !== "value") {
1006
+ this.fail(
1007
+ `Unexpected value inside array. Expected ${parent.expecting}.`,
1008
+ at
1009
+ );
1010
+ return null;
1011
+ }
1012
+ const index = parent.nextIndex;
1013
+ path = [...parent.path, index];
1014
+ fieldKey = this.parentFieldName(path);
1015
+ parent.value.push(value);
1016
+ parent.nextIndex += 1;
1017
+ parent.expecting = "commaOrEnd";
1018
+ }
1019
+ if (finalizedImmediately) {
1020
+ this.onValueFinalized(path, value, at);
1021
+ }
1022
+ return path;
1023
+ }
1024
+ acceptObjectKey(frame, key, at) {
1025
+ if (frame.expecting !== "keyOrEnd" && frame.expecting !== "key") {
1026
+ this.fail(`Unexpected object key "${key}".`, at);
1027
+ return;
1028
+ }
1029
+ if (Object.prototype.hasOwnProperty.call(frame.value, key)) {
1030
+ this.markNodeRaw(
1031
+ frame.path,
1032
+ frame.value,
1033
+ `Duplicate key "${key}".`,
1034
+ at
1035
+ );
1036
+ }
1037
+ if (frame.path.length === 0 && frame.keyCount === 0) {
1038
+ this.noteRootSurfaceKind(key);
1039
+ }
1040
+ frame.currentKey = key;
1041
+ frame.keyCount += 1;
1042
+ frame.expecting = "colon";
1043
+ }
1044
+ acceptColon(at) {
1045
+ const frame = this.currentFrame();
1046
+ if (!frame || frame.kind !== "object" || frame.expecting !== "colon") {
1047
+ this.fail("Unexpected colon.", at);
1048
+ return;
1049
+ }
1050
+ frame.expecting = "value";
1051
+ }
1052
+ acceptComma(at) {
1053
+ const frame = this.currentFrame();
1054
+ if (!frame || frame.expecting !== "commaOrEnd") {
1055
+ this.fail("Unexpected comma.", at);
1056
+ return;
1057
+ }
1058
+ if (frame.kind === "object") {
1059
+ frame.expecting = "key";
1060
+ } else {
1061
+ frame.expecting = "value";
1062
+ }
1063
+ }
1064
+ closeCompound(kind, at) {
1065
+ const frame = this.currentFrame();
1066
+ if (!frame || frame.kind !== kind) {
1067
+ this.fail(
1068
+ `Unexpected closing ${kind === "object" ? "brace" : "bracket"}.`,
1069
+ at
1070
+ );
1071
+ return;
1072
+ }
1073
+ if (frame.kind === "object") {
1074
+ if (frame.expecting !== "keyOrEnd" && frame.expecting !== "commaOrEnd") {
1075
+ this.fail(`Object closed too early. Expected ${frame.expecting}.`, at);
1076
+ return;
1077
+ }
1078
+ } else if (frame.expecting !== "valueOrEnd" && frame.expecting !== "commaOrEnd") {
1079
+ this.fail(`Array closed too early. Expected ${frame.expecting}.`, at);
1080
+ return;
1081
+ }
1082
+ this.stack.pop();
1083
+ if (this.stack.length === 0) {
1084
+ this.rootDone = true;
1085
+ }
1086
+ this.onValueFinalized(frame.path, frame.value, at);
1087
+ }
1088
+ /**
1089
+ * True when a value placed at `path` sits directly under a json-any
1090
+ * placement: a `json`/`json[]` FIELD, or a member of a `record` whose
1091
+ * values are `"json"`. (Deeper descendants inherit via `opaquePaths`.)
1092
+ */
1093
+ isJsonAnyPlacement(path) {
1094
+ const fieldSchema = this.resolveParentFieldSchema(path);
1095
+ if (fieldSchema && isJsonAnyField(fieldSchema)) return true;
1096
+ const last = path[path.length - 1];
1097
+ if (typeof last === "string") {
1098
+ const parentKey = this.pathKey(path.slice(0, -1));
1099
+ if (this.recordSchemas.get(parentKey) === "json") return true;
1100
+ }
1101
+ return false;
1102
+ }
1103
+ onValueFinalized(path, value, at) {
1104
+ if (this.failed) return;
1105
+ const pathKey = this.pathKey(path);
1106
+ const parentIsOpaque = path.length > 0 && this.opaquePaths.has(this.pathKey(path.slice(0, -1)));
1107
+ if (this.opaquePaths.has(pathKey)) {
1108
+ if (!parentIsOpaque) this.emitFieldIfReady(path, value, at);
1109
+ return;
1110
+ }
1111
+ if (parentIsOpaque) return;
1112
+ if (this.isKindFieldPath(path)) {
1113
+ if (typeof value !== "string") {
1114
+ return;
1115
+ }
1116
+ this.onKindDiscriminatorArrived(path.slice(0, -1), value, at);
1117
+ return;
1118
+ }
1119
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
1120
+ const objectValue = value;
1121
+ const inlineFields = this.inlineSchemas.get(pathKey);
1122
+ if (inlineFields) {
1123
+ const inlineError = this.validateObjectAgainstFields(
1124
+ objectValue,
1125
+ inlineFields
1126
+ );
1127
+ if (inlineError.error) {
1128
+ this.emitRawObject(path, objectValue, inlineError.error, at);
1129
+ return;
1130
+ }
1131
+ this.inlineSchemas.delete(pathKey);
1132
+ this.emitSchemaNotices(path, "inline_object", inlineError, at);
1133
+ this.emit({
1134
+ type: "object_complete",
1135
+ kind: "inline_object",
1136
+ path,
1137
+ value: objectValue,
1138
+ at
1139
+ });
1140
+ } else {
1141
+ const recordValueType = this.recordSchemas.get(pathKey);
1142
+ if (recordValueType) {
1143
+ const recordError = this.validateRecordObject(
1144
+ objectValue,
1145
+ recordValueType
1146
+ );
1147
+ if (recordError) {
1148
+ this.emitRawObject(path, objectValue, recordError, at);
1149
+ return;
1150
+ }
1151
+ this.recordSchemas.delete(pathKey);
1152
+ this.emit({
1153
+ type: "object_complete",
1154
+ kind: "record",
1155
+ path,
1156
+ value: objectValue,
1157
+ at
1158
+ });
1159
+ } else {
1160
+ this.completeTypedObject(path, objectValue, at);
1161
+ }
1162
+ }
1163
+ }
1164
+ this.emitFieldIfReady(path, value, at);
1165
+ if (path.length === 0) {
1166
+ this.completeRoot(value, at);
1167
+ }
1168
+ }
1169
+ /** __kind arrived for an object — confirm speculation, identify, or backtrack. */
1170
+ onKindDiscriminatorArrived(objectPath, kind, at) {
1171
+ const objectPathKey = this.pathKey(objectPath);
1172
+ if (this.rawObjectPaths.has(objectPathKey)) return;
1173
+ const prior = this.objectKinds.get(objectPathKey);
1174
+ const wasSpeculative = this.speculativeKinds.has(objectPathKey);
1175
+ if (prior !== void 0 && wasSpeculative) {
1176
+ this.speculativeKinds.delete(objectPathKey);
1177
+ if (prior === kind) {
1178
+ this.emitBlockSnapshotForObject(objectPath, at);
1179
+ return;
1180
+ }
1181
+ if (this.lookupSchema(kind) && this.validateArrayItemKind(objectPath, kind) === null && this.speculativeRetagAllowed(objectPath, kind)) {
1182
+ this.objectKinds.set(objectPathKey, kind);
1183
+ if (objectPath.length === 0) {
1184
+ this.rootKind = kind;
1185
+ }
1186
+ this.emit({ type: "kind_identified", kind, path: objectPath, at });
1187
+ this.emitBlockSnapshotForObject(objectPath, at);
1188
+ return;
1189
+ }
1190
+ const live = this.getLiveObjectValue(objectPath);
1191
+ this.objectKinds.delete(objectPathKey);
1192
+ if (objectPath.length === 0) {
1193
+ this.rootKind = "";
1194
+ }
1195
+ this.emitRawObject(
1196
+ objectPath,
1197
+ safeCopy(live ?? {}),
1198
+ `Speculated kind "${prior}" contradicted by ${KIND_KEY} "${kind}".`,
1199
+ at
1200
+ );
1201
+ return;
1202
+ }
1203
+ this.objectKinds.set(objectPathKey, kind);
1204
+ this.emit({
1205
+ type: "kind_identified",
1206
+ kind,
1207
+ path: objectPath,
1208
+ at
1209
+ });
1210
+ this.clearKindWait(objectPath, "identified", at, kind);
1211
+ if (objectPath.length === 0) {
1212
+ this.rootKind = kind;
1213
+ }
1214
+ if (!this.lookupSchema(kind) && this.resolver.request) {
1215
+ this.addPendingSchemaPath(kind, objectPath);
1216
+ this.emit({ type: "pending_schema", kind, path: objectPath, at });
1217
+ this.resolver.request(kind);
1218
+ return;
1219
+ }
1220
+ this.flushDeferredFields(objectPath, kind, at);
1221
+ this.emitBlockSnapshotForObject(objectPath, at);
1222
+ }
1223
+ /** A contradicted speculation may re-tag only where the new kind is legal. */
1224
+ speculativeRetagAllowed(path, kind) {
1225
+ if (path.length === 0) {
1226
+ return true;
1227
+ }
1228
+ const last = path[path.length - 1];
1229
+ if (typeof last === "number") {
1230
+ const fieldName = this.parentFieldName(path);
1231
+ const ownerKind = this.getObjectKindForPath(path.slice(0, -2));
1232
+ if (!fieldName || !ownerKind) return false;
1233
+ const fieldSchema = this.lookupSchema(ownerKind)?.fields[fieldName];
1234
+ return fieldSchema?.type === "array" && fieldSchema.itemKinds.includes(kind);
1235
+ }
1236
+ return false;
1237
+ }
1238
+ addPendingSchemaPath(kind, path) {
1239
+ const pathKey = this.pathKey(path);
1240
+ const existing = this.pendingSchemaPaths.get(kind) ?? /* @__PURE__ */ new Map();
1241
+ existing.set(pathKey, path);
1242
+ this.pendingSchemaPaths.set(kind, existing);
1243
+ }
1244
+ completeTypedObject(path, objectValue, at) {
1245
+ const pathKey = this.pathKey(path);
1246
+ if (this.rawObjectPaths.has(pathKey)) return;
1247
+ const declaredKind = readObjectKind(objectValue);
1248
+ const committedKind = this.objectKinds.get(pathKey);
1249
+ if (committedKind && this.pendingSchemaPaths.get(committedKind)?.has(pathKey)) {
1250
+ this.closedPendingPaths.add(pathKey);
1251
+ return;
1252
+ }
1253
+ if (!declaredKind && committedKind && this.speculativeKinds.has(pathKey)) {
1254
+ this.speculativeKinds.delete(pathKey);
1255
+ this.finalizeSpeculatedObject(path, objectValue, committedKind, at);
1256
+ return;
1257
+ }
1258
+ if (path.length === 0 && !declaredKind && !committedKind && this.rootSurfaceKind) {
1259
+ const surfaceKind = this.rootSurfaceKind;
1260
+ this.rootSurfaceKind = null;
1261
+ this.objectKinds.set(pathKey, surfaceKind);
1262
+ this.rootKind = surfaceKind;
1263
+ this.emit({
1264
+ type: "kind_identified",
1265
+ kind: surfaceKind,
1266
+ path,
1267
+ speculative: true,
1268
+ at
1269
+ });
1270
+ this.clearKindWait(path, "identified", at, surfaceKind);
1271
+ this.finalizeSpeculatedObject(path, objectValue, surfaceKind, at);
1272
+ return;
1273
+ }
1274
+ if (!declaredKind) {
1275
+ this.emitRawObject(
1276
+ path,
1277
+ objectValue,
1278
+ `Object is missing "${KIND_KEY}".`,
1279
+ at
1280
+ );
1281
+ return;
1282
+ }
1283
+ this.speculativeKinds.delete(pathKey);
1284
+ this.finalizeTypedObject(path, objectValue, at);
1285
+ }
1286
+ /** Validate + complete an object whose value carries __kind. */
1287
+ finalizeTypedObject(path, objectValue, at) {
1288
+ const pathKey = this.pathKey(path);
1289
+ const kind = readObjectKind(objectValue);
1290
+ if (!kind) {
1291
+ this.emitRawObject(
1292
+ path,
1293
+ objectValue,
1294
+ `Object is missing "${KIND_KEY}".`,
1295
+ at
1296
+ );
1297
+ return;
1298
+ }
1299
+ const schema = this.lookupSchema(kind);
1300
+ if (!schema) {
1301
+ this.emitRawObject(
1302
+ path,
1303
+ objectValue,
1304
+ `No block schema registered for "${kind}".`,
1305
+ at,
1306
+ kind
1307
+ );
1308
+ return;
1309
+ }
1310
+ const arrayItemError = this.validateArrayItemKind(path, kind);
1311
+ if (arrayItemError) {
1312
+ this.emitRawObject(path, objectValue, arrayItemError, at);
1313
+ return;
1314
+ }
1315
+ const outcome = this.validateObjectAgainstSchema(objectValue, schema);
1316
+ if (outcome.error) {
1317
+ this.emitRawObject(path, objectValue, outcome.error, at);
1318
+ return;
1319
+ }
1320
+ this.objectKinds.set(pathKey, kind);
1321
+ this.emitSchemaNotices(path, kind, outcome, at);
1322
+ this.emitBlockSnapshotForObject(path, at, true);
1323
+ this.emit({
1324
+ type: "object_complete",
1325
+ kind,
1326
+ path,
1327
+ value: objectValue,
1328
+ at
1329
+ });
1330
+ }
1331
+ /** Validate + complete an object typed purely by parent prediction. */
1332
+ finalizeSpeculatedObject(path, objectValue, kind, at) {
1333
+ const schema = this.lookupSchema(kind);
1334
+ if (!schema) {
1335
+ this.emitRawObject(
1336
+ path,
1337
+ objectValue,
1338
+ `No block schema registered for "${kind}".`,
1339
+ at,
1340
+ kind
1341
+ );
1342
+ return;
1343
+ }
1344
+ const outcome = this.validateObjectAgainstSchema(
1345
+ { ...objectValue, [KIND_KEY]: kind },
1346
+ schema
1347
+ );
1348
+ if (outcome.error) {
1349
+ this.emitRawObject(path, objectValue, outcome.error, at);
1350
+ return;
1351
+ }
1352
+ this.emitSchemaNotices(path, kind, outcome, at);
1353
+ this.emitBlockSnapshotForObject(path, at, true);
1354
+ this.emit({
1355
+ type: "object_complete",
1356
+ kind,
1357
+ path,
1358
+ value: objectValue,
1359
+ at
1360
+ });
1361
+ }
1362
+ validateArrayItemKind(path, kind) {
1363
+ const last = path[path.length - 1];
1364
+ if (typeof last !== "number") return null;
1365
+ const fieldName = this.parentFieldName(path);
1366
+ if (!fieldName) return null;
1367
+ const ownerObjectPath = path.slice(0, -2);
1368
+ const parentKind = this.getObjectKindForPath(ownerObjectPath);
1369
+ if (!parentKind) return null;
1370
+ const fieldSchema = this.lookupSchema(parentKind)?.fields[fieldName];
1371
+ if (!fieldSchema || fieldSchema.type !== "array") return null;
1372
+ if (!fieldSchema.itemKinds.includes(kind)) {
1373
+ return `Kind "${kind}" is not allowed in "${fieldName}" on "${parentKind}" (expected one of: ${fieldSchema.itemKinds.join(", ")}).`;
1374
+ }
1375
+ return null;
1376
+ }
1377
+ completeRoot(rootObject, at) {
1378
+ const pathKey = this.pathKey([]);
1379
+ if (this.rawObjectPaths.has(pathKey)) {
1380
+ this.emit({
1381
+ type: "complete",
1382
+ kind: readObjectKind(rootObject) ?? "",
1383
+ value: rootObject,
1384
+ at
1385
+ });
1386
+ return;
1387
+ }
1388
+ const committedKind = this.objectKinds.get(pathKey);
1389
+ if (committedKind && this.pendingSchemaPaths.get(committedKind)?.has(pathKey)) {
1390
+ this.emit({
1391
+ type: "complete",
1392
+ kind: committedKind,
1393
+ value: rootObject,
1394
+ at
1395
+ });
1396
+ return;
1397
+ }
1398
+ this.emit({
1399
+ type: "complete",
1400
+ kind: this.objectKinds.get(pathKey) ?? readObjectKind(rootObject) ?? "",
1401
+ value: rootObject,
1402
+ at
1403
+ });
1404
+ }
1405
+ /** Mark a node raw (node-scoped failure) without killing the stream. */
1406
+ markNodeRaw(path, liveValue, reason, at) {
1407
+ const pathKey = this.pathKey(path);
1408
+ if (this.rawObjectPaths.has(pathKey)) return;
1409
+ this.speculativeKinds.delete(pathKey);
1410
+ this.emitRawObject(path, safeCopy(liveValue), reason, at);
1411
+ }
1412
+ emitRawObject(path, value, reason, at, identifiedKind) {
1413
+ const pathKey = this.pathKey(path);
1414
+ if (this.rawObjectPaths.has(pathKey)) return;
1415
+ this.rawObjectPaths.add(pathKey);
1416
+ this.clearKindWait(path, "raw_fallback", at, void 0, reason);
1417
+ this.emit({
1418
+ type: "raw_object",
1419
+ path,
1420
+ value,
1421
+ reason,
1422
+ ...identifiedKind !== void 0 && { kind: identifiedKind },
1423
+ at
1424
+ });
1425
+ }
1426
+ clearKindWait(path, outcome, at, kind, reason) {
1427
+ const pathKey = this.pathKey(path);
1428
+ if (!this.awaitingKindPaths.has(pathKey)) return;
1429
+ this.awaitingKindPaths.delete(pathKey);
1430
+ this.emit({
1431
+ type: "kind_wait_end",
1432
+ path,
1433
+ outcome,
1434
+ ...kind !== void 0 && { kind },
1435
+ ...reason !== void 0 && { reason },
1436
+ at
1437
+ });
1438
+ }
1439
+ emitFieldIfReady(path, value, at) {
1440
+ const fieldKey = this.fieldKeyFromPath(path);
1441
+ if (!fieldKey || fieldKey === KIND_KEY) return;
1442
+ const parentPath = path.slice(0, -1);
1443
+ const objectKind = this.getDirectObjectKind(parentPath);
1444
+ if (!objectKind) {
1445
+ const parentPathKey = this.pathKey(parentPath);
1446
+ const deferred = this.deferredFields.get(parentPathKey) ?? [];
1447
+ deferred.push({ key: fieldKey, value, at });
1448
+ this.deferredFields.set(parentPathKey, deferred);
1449
+ return;
1450
+ }
1451
+ const schemaResolved = this.lookupSchema(objectKind) !== void 0;
1452
+ if (schemaResolved && !this.isAllowedSchemaField(parentPath, fieldKey, objectKind)) {
1453
+ return;
1454
+ }
1455
+ this.emit({
1456
+ type: "field",
1457
+ kind: objectKind,
1458
+ path,
1459
+ key: fieldKey,
1460
+ value,
1461
+ at
1462
+ });
1463
+ this.emitBlockSnapshotForObject(parentPath, at);
1464
+ }
1465
+ flushDeferredFields(objectPath, kind, at) {
1466
+ const pathKey = this.pathKey(objectPath);
1467
+ const deferred = this.deferredFields.get(pathKey);
1468
+ if (!deferred) return;
1469
+ for (const entry of deferred) {
1470
+ if (entry.key === KIND_KEY) continue;
1471
+ if (!this.isAllowedSchemaField(objectPath, entry.key, kind)) continue;
1472
+ this.emit({
1473
+ type: "field",
1474
+ kind,
1475
+ path: [...objectPath, entry.key],
1476
+ key: entry.key,
1477
+ value: entry.value,
1478
+ at: entry.at
1479
+ });
1480
+ }
1481
+ this.deferredFields.delete(pathKey);
1482
+ this.emitBlockSnapshotForObject(objectPath, at);
1483
+ }
1484
+ getLiveObjectValue(path) {
1485
+ const pathKey = this.pathKey(path);
1486
+ for (let i = this.stack.length - 1; i >= 0; i--) {
1487
+ const frame = this.stack[i];
1488
+ if (!frame) continue;
1489
+ if (frame.kind === "object" && this.pathKey(frame.path) === pathKey) {
1490
+ return frame.value;
1491
+ }
1492
+ }
1493
+ return null;
1494
+ }
1495
+ emitBlockSnapshotForObject(objectPath, at, complete = false) {
1496
+ const pathKey = this.pathKey(objectPath);
1497
+ if (this.rawObjectPaths.has(pathKey)) return;
1498
+ const kind = this.getDirectObjectKind(objectPath);
1499
+ if (!kind) return;
1500
+ const schema = this.lookupObjectSchema(kind);
1501
+ if (!schema) return;
1502
+ const partial = complete ? this.getFinalizedObjectValue(objectPath) : this.getLiveObjectValue(objectPath);
1503
+ if (!partial) return;
1504
+ const { value, residue } = buildCompliantKindSnapshot(schema, partial);
1505
+ this.emit({
1506
+ type: "block_snapshot",
1507
+ kind,
1508
+ path: objectPath,
1509
+ value,
1510
+ residue,
1511
+ complete,
1512
+ at
1513
+ });
1514
+ }
1515
+ /**
1516
+ * On `complete` snapshots (and post-close schema upgrades) the frame has
1517
+ * already been popped — the finalized value lives in the root tree.
1518
+ */
1519
+ getFinalizedObjectValue(path) {
1520
+ const live = this.getLiveObjectValue(path);
1521
+ if (live) return live;
1522
+ if (path.length === 0) {
1523
+ return typeof this.root === "object" && this.root !== null && !Array.isArray(this.root) ? this.root : null;
1524
+ }
1525
+ let cursor = this.root;
1526
+ for (const segment of path) {
1527
+ if (cursor === null || typeof cursor !== "object") return null;
1528
+ cursor = cursor[segment];
1529
+ }
1530
+ return typeof cursor === "object" && cursor !== null && !Array.isArray(cursor) ? cursor : null;
1531
+ }
1532
+ validateFieldPlacement(parent, fieldKey, valueKind, value) {
1533
+ const parentPathKey = this.pathKey(parent.path);
1534
+ const inlineFields = this.inlineSchemas.get(parentPathKey);
1535
+ if (inlineFields) {
1536
+ const fieldSchema = inlineFields[fieldKey];
1537
+ if (!fieldSchema) {
1538
+ return null;
1539
+ }
1540
+ return this.validateValueAgainstField(
1541
+ fieldSchema,
1542
+ valueKind,
1543
+ value,
1544
+ fieldKey
1545
+ );
1546
+ }
1547
+ const recordValueType = this.recordSchemas.get(parentPathKey);
1548
+ if (recordValueType) {
1549
+ if (recordValueType === "json") return null;
1550
+ if (valueKind !== "scalar") {
1551
+ return `Record field "${fieldKey}" must be a scalar.`;
1552
+ }
1553
+ return this.validateRecordScalar(recordValueType, value, fieldKey);
1554
+ }
1555
+ return null;
1556
+ }
1557
+ emitSchemaNotices(path, kind, outcome, at) {
1558
+ for (const field of outcome.optionalMissing) {
1559
+ this.emit({
1560
+ type: "optional_field_missing",
1561
+ kind,
1562
+ path,
1563
+ field,
1564
+ at
1565
+ });
1566
+ }
1567
+ for (const field of outcome.extraFields) {
1568
+ this.emit({
1569
+ type: "extra_field",
1570
+ kind,
1571
+ path,
1572
+ field,
1573
+ at
1574
+ });
1575
+ }
1576
+ }
1577
+ validateObjectAgainstSchema(objectValue, schema) {
1578
+ const optionalMissing = [];
1579
+ const extraFields = [];
1580
+ const emptyOutcome = { optionalMissing, extraFields };
1581
+ if (schema.root) {
1582
+ return {
1583
+ error: `Kind "${schema.kind}" has a non-object root form and cannot be a "${KIND_KEY}" object.`,
1584
+ ...emptyOutcome
1585
+ };
1586
+ }
1587
+ const kind = readObjectKind(objectValue);
1588
+ if (kind !== schema.kind) {
1589
+ return {
1590
+ error: `Object "${KIND_KEY}" is "${kind ?? "missing"}", expected "${schema.kind}".`,
1591
+ ...emptyOutcome
1592
+ };
1593
+ }
1594
+ for (const [fieldName, fieldSchema] of Object.entries(schema.fields)) {
1595
+ if (fieldSchema.required) {
1596
+ if (!(fieldName in objectValue)) {
1597
+ return {
1598
+ error: `Kind "${schema.kind}" is missing required field "${fieldName}".`,
1599
+ ...emptyOutcome
1600
+ };
1601
+ }
1602
+ continue;
1603
+ }
1604
+ if (!(fieldName in objectValue)) {
1605
+ optionalMissing.push(fieldName);
1606
+ }
1607
+ }
1608
+ for (const [fieldName, fieldValue] of Object.entries(objectValue)) {
1609
+ if (fieldName === KIND_KEY) continue;
1610
+ const fieldSchema = schema.fields[fieldName];
1611
+ if (!fieldSchema) {
1612
+ extraFields.push(fieldName);
1613
+ continue;
1614
+ }
1615
+ const error = this.validateFinalFieldValue(
1616
+ fieldSchema,
1617
+ fieldValue,
1618
+ fieldName,
1619
+ schema.kind
1620
+ );
1621
+ if (error) {
1622
+ return { error, optionalMissing, extraFields };
1623
+ }
1624
+ }
1625
+ return { error: null, optionalMissing, extraFields };
1626
+ }
1627
+ validateFinalFieldValue(fieldSchema, value, fieldName, objectKind) {
1628
+ if (fieldSchema.type === "json") return null;
1629
+ if (fieldSchema.type === "json[]") {
1630
+ if (value === null) {
1631
+ return fieldSchema.nullable ? null : `Field "${fieldName}" on kind "${objectKind}" cannot be null.`;
1632
+ }
1633
+ if (!Array.isArray(value)) {
1634
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array.`;
1635
+ }
1636
+ return null;
1637
+ }
1638
+ if (isScalarArrayType(fieldSchema.type)) {
1639
+ if (!Array.isArray(value)) {
1640
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array.`;
1641
+ }
1642
+ const itemType = scalarArrayItemType(fieldSchema.type);
1643
+ if (!value.every((item) => typeof item === itemType)) {
1644
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array of ${itemType}s.`;
1645
+ }
1646
+ if (fieldSchema.type === "string[]" && fieldSchema.values !== void 0 && !fieldSchema.open) {
1647
+ const allowed = fieldSchema.values;
1648
+ const bad = value.find(
1649
+ (item) => typeof item === "string" && !allowed.includes(item)
1650
+ );
1651
+ if (bad !== void 0) {
1652
+ return `Field "${fieldName}" on kind "${objectKind}" items must be one of: ${allowed.join(", ")}.`;
1653
+ }
1654
+ }
1655
+ return null;
1656
+ }
1657
+ if (fieldSchema.type === "array") {
1658
+ if (!Array.isArray(value)) {
1659
+ return `Field "${fieldName}" on kind "${objectKind}" must be an array.`;
1660
+ }
1661
+ return null;
1662
+ }
1663
+ if (fieldSchema.type === "object") {
1664
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1665
+ return `Field "${fieldName}" on kind "${objectKind}" must be an object.`;
1666
+ }
1667
+ const nestedKind = readObjectKind(value);
1668
+ if (nestedKind !== fieldSchema.kind) {
1669
+ return `Field "${fieldName}" on kind "${objectKind}" must be kind "${fieldSchema.kind}".`;
1670
+ }
1671
+ const nestedSchema = this.lookupSchema(fieldSchema.kind);
1672
+ if (!nestedSchema) {
1673
+ return `Unknown nested kind "${fieldSchema.kind}" on field "${fieldName}".`;
1674
+ }
1675
+ return this.validateObjectAgainstSchema(
1676
+ value,
1677
+ nestedSchema
1678
+ ).error;
1679
+ }
1680
+ if (fieldSchema.type === "inline_object") {
1681
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1682
+ return `Field "${fieldName}" on kind "${objectKind}" must be an inline object.`;
1683
+ }
1684
+ return this.validateObjectAgainstFields(
1685
+ value,
1686
+ fieldSchema.fields
1687
+ ).error;
1688
+ }
1689
+ if (fieldSchema.type === "record") {
1690
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
1691
+ return `Field "${fieldName}" on kind "${objectKind}" must be a record object.`;
1692
+ }
1693
+ return this.validateRecordObject(
1694
+ value,
1695
+ fieldSchema.values
1696
+ );
1697
+ }
1698
+ if (fieldSchema.type === "union") {
1699
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
1700
+ const kinds = fieldSchema.kinds ?? [];
1701
+ if (kinds.length === 0) {
1702
+ return `Field "${fieldName}" on kind "${objectKind}" must be ${fieldSchema.scalars.join(" | ")}.`;
1703
+ }
1704
+ const memberKind = readObjectKind(value);
1705
+ if (!memberKind || !kinds.includes(memberKind)) {
1706
+ return `Field "${fieldName}" on kind "${objectKind}" must be one of kinds: ${kinds.join(", ")}.`;
1707
+ }
1708
+ const memberSchema = this.lookupSchema(memberKind);
1709
+ if (!memberSchema) {
1710
+ return `Unknown union member kind "${memberKind}" on field "${fieldName}".`;
1711
+ }
1712
+ return this.validateObjectAgainstSchema(
1713
+ value,
1714
+ memberSchema
1715
+ ).error;
1716
+ }
1717
+ return this.validateScalarField(fieldSchema, value, fieldName);
1718
+ }
1719
+ if (fieldSchema.type === "string" || fieldSchema.type === "number" || fieldSchema.type === "boolean" || fieldSchema.type === "enum") {
1720
+ return this.validateScalarField(fieldSchema, value, fieldName);
1721
+ }
1722
+ return `Unsupported field schema for "${fieldName}".`;
1723
+ }
1724
+ validateValueAgainstField(fieldSchema, valueKind, value, fieldName) {
1725
+ if (fieldSchema.type === "json") {
1726
+ return null;
1727
+ }
1728
+ if (fieldSchema.type === "array" || fieldSchema.type === "json[]") {
1729
+ return valueKind === "array" ? null : `Field "${fieldName}" must be an array.`;
1730
+ }
1731
+ if (fieldSchema.type === "object" || fieldSchema.type === "inline_object") {
1732
+ return valueKind === "object" ? null : `Field "${fieldName}" must be an object.`;
1733
+ }
1734
+ if (fieldSchema.type === "record") {
1735
+ return valueKind === "object" ? null : `Field "${fieldName}" must be a record object.`;
1736
+ }
1737
+ if (isScalarArrayType(fieldSchema.type)) {
1738
+ return valueKind === "array" ? null : `Field "${fieldName}" must be an array.`;
1739
+ }
1740
+ if (fieldSchema.type === "union" && (fieldSchema.kinds?.length ?? 0) > 0) {
1741
+ if (valueKind === "object") return null;
1742
+ }
1743
+ if (valueKind !== "scalar") {
1744
+ return `Field "${fieldName}" must be a scalar.`;
1745
+ }
1746
+ return this.validateScalarField(fieldSchema, value, fieldName);
1747
+ }
1748
+ validateScalarField(fieldSchema, value, fieldName) {
1749
+ if (value === null) {
1750
+ return fieldSchema.nullable ? null : `Field "${fieldName}" cannot be null.`;
1751
+ }
1752
+ if (fieldSchema.type === "enum") {
1753
+ if (typeof value !== "string") {
1754
+ return `Field "${fieldName}" must be a string.`;
1755
+ }
1756
+ if (!fieldSchema.open && !fieldSchema.values.includes(value)) {
1757
+ return `Field "${fieldName}" must be one of: ${fieldSchema.values.join(", ")}.`;
1758
+ }
1759
+ return null;
1760
+ }
1761
+ if (fieldSchema.type === "union") {
1762
+ const valueType = typeof value;
1763
+ if (valueType !== "string" && valueType !== "number" && valueType !== "boolean") {
1764
+ return `Field "${fieldName}" must be ${fieldSchema.scalars.join(" | ")}.`;
1765
+ }
1766
+ if (!fieldSchema.scalars.includes(
1767
+ valueType
1768
+ )) {
1769
+ return `Field "${fieldName}" must be ${fieldSchema.scalars.join(" | ")}.`;
1770
+ }
1771
+ return null;
1772
+ }
1773
+ if (fieldSchema.type === "string" || fieldSchema.type === "number" || fieldSchema.type === "boolean") {
1774
+ if (typeof value !== fieldSchema.type) {
1775
+ return `Field "${fieldName}" must be ${fieldSchema.type}.`;
1776
+ }
1777
+ if (fieldSchema.type === "number" && typeof value === "number") {
1778
+ if (fieldSchema.min !== void 0 && value < fieldSchema.min) {
1779
+ return `Field "${fieldName}" must be >= ${fieldSchema.min}.`;
1780
+ }
1781
+ if (fieldSchema.max !== void 0 && value > fieldSchema.max) {
1782
+ return `Field "${fieldName}" must be <= ${fieldSchema.max}.`;
1783
+ }
1784
+ }
1785
+ return null;
1786
+ }
1787
+ return `Field "${fieldName}" is not a scalar.`;
1788
+ }
1789
+ validateRecordScalar(valueType, value, fieldName) {
1790
+ if (valueType === "json") return null;
1791
+ if (typeof value !== valueType) {
1792
+ return `Record field "${fieldName}" must be ${valueType}.`;
1793
+ }
1794
+ return null;
1795
+ }
1796
+ validateRecordObject(objectValue, valueType) {
1797
+ if (valueType === "json") return null;
1798
+ for (const [key, entry] of Object.entries(objectValue)) {
1799
+ if (typeof entry !== valueType) {
1800
+ return `Record key "${key}" must be ${valueType}.`;
1801
+ }
1802
+ }
1803
+ return null;
1804
+ }
1805
+ validateObjectAgainstFields(objectValue, fields) {
1806
+ const optionalMissing = [];
1807
+ const extraFields = [];
1808
+ const emptyOutcome = { optionalMissing, extraFields };
1809
+ for (const [fieldName, fieldSchema] of Object.entries(fields)) {
1810
+ if (fieldSchema.required) {
1811
+ if (!(fieldName in objectValue)) {
1812
+ return {
1813
+ error: `Inline object is missing required field "${fieldName}".`,
1814
+ ...emptyOutcome
1815
+ };
1816
+ }
1817
+ continue;
1818
+ }
1819
+ if (!(fieldName in objectValue)) {
1820
+ optionalMissing.push(fieldName);
1821
+ }
1822
+ }
1823
+ for (const [fieldName, fieldValue] of Object.entries(objectValue)) {
1824
+ const fieldSchema = fields[fieldName];
1825
+ if (!fieldSchema) {
1826
+ extraFields.push(fieldName);
1827
+ continue;
1828
+ }
1829
+ const error = this.validateFinalFieldValue(
1830
+ fieldSchema,
1831
+ fieldValue,
1832
+ fieldName,
1833
+ "inline_object"
1834
+ );
1835
+ if (error) {
1836
+ return { error, optionalMissing, extraFields };
1837
+ }
1838
+ }
1839
+ return { error: null, optionalMissing, extraFields };
1840
+ }
1841
+ registerObjectContext(path) {
1842
+ const fieldSchema = this.resolveParentFieldSchema(path);
1843
+ if (!fieldSchema) return;
1844
+ const pathKey = this.pathKey(path);
1845
+ if (fieldSchema.type === "inline_object") {
1846
+ this.inlineSchemas.set(pathKey, fieldSchema.fields);
1847
+ }
1848
+ if (fieldSchema.type === "record") {
1849
+ this.recordSchemas.set(pathKey, fieldSchema.values);
1850
+ }
1851
+ }
1852
+ resolveParentFieldSchema(path) {
1853
+ const fieldKey = this.fieldKeyFromPath(path);
1854
+ if (!fieldKey) return void 0;
1855
+ const parentPath = path.slice(0, -1);
1856
+ const parentKind = this.getObjectKindForPath(parentPath);
1857
+ if (!parentKind) return void 0;
1858
+ return this.lookupSchema(parentKind)?.fields[fieldKey];
1859
+ }
1860
+ getObjectKindForPath(path) {
1861
+ return this.objectKinds.get(this.pathKey(path)) ?? (path.length === 0 ? this.rootKind || null : null);
1862
+ }
1863
+ getDirectObjectKind(objectPath) {
1864
+ if (objectPath.length === 0) {
1865
+ return this.rootKind || null;
1866
+ }
1867
+ return this.objectKinds.get(this.pathKey(objectPath)) ?? null;
1868
+ }
1869
+ isAllowedSchemaField(objectPath, fieldKey, objectKind) {
1870
+ const pathKey = this.pathKey(objectPath);
1871
+ const inlineFields = this.inlineSchemas.get(pathKey);
1872
+ if (inlineFields) {
1873
+ return fieldKey in inlineFields;
1874
+ }
1875
+ if (this.recordSchemas.has(pathKey)) {
1876
+ return true;
1877
+ }
1878
+ const schema = this.lookupSchema(objectKind);
1879
+ return !!schema?.fields[fieldKey];
1880
+ }
1881
+ parentFieldName(path) {
1882
+ if (path.length === 0) return void 0;
1883
+ const parent = path[path.length - 2];
1884
+ return typeof parent === "string" ? parent : void 0;
1885
+ }
1886
+ fieldKeyFromPath(path) {
1887
+ const last = path[path.length - 1];
1888
+ return typeof last === "string" ? last : null;
1889
+ }
1890
+ isKindFieldPath(path) {
1891
+ return path[path.length - 1] === KIND_KEY;
1892
+ }
1893
+ pathKey(path) {
1894
+ return path.map((segment) => String(segment)).join(".");
1895
+ }
1896
+ lookupSchema(kind) {
1897
+ return this.resolver.get(kind) ?? this.arrivedSchemas.get(kind);
1898
+ }
1899
+ fail(reason, at) {
1900
+ if (this.failed) return;
1901
+ this.failed = true;
1902
+ this.emit({ type: "error", reason, at });
1903
+ }
1904
+ emit(event) {
1905
+ this.options.onEvent(event);
1906
+ }
1907
+ currentFrame() {
1908
+ return this.stack[this.stack.length - 1];
1909
+ }
1910
+ };
1911
+ function createKindStreamParser(options) {
1912
+ return new KindStreamParser(options);
1913
+ }
1914
+
1915
+ // core/fingerprint.ts
1916
+ var SEED_A = 2166136261;
1917
+ var SEED_B = 16777619;
1918
+ function fnv1aStep(hash, input) {
1919
+ let h = hash >>> 0;
1920
+ for (let i = 0; i < input.length; i++) {
1921
+ h ^= input.charCodeAt(i);
1922
+ h = h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24)) >>> 0;
1923
+ }
1924
+ return h >>> 0;
1925
+ }
1926
+ function createFingerprinter() {
1927
+ let a = SEED_A;
1928
+ let b = SEED_B;
1929
+ let length = 0;
1930
+ return {
1931
+ push(chunk) {
1932
+ a = fnv1aStep(a, chunk);
1933
+ b = fnv1aStep(b, chunk);
1934
+ length += chunk.length;
1935
+ },
1936
+ current() {
1937
+ return `${length.toString(36)}-${a.toString(36)}${b.toString(36)}`;
1938
+ }
1939
+ };
1940
+ }
1941
+ function fingerprintText(source) {
1942
+ const hasher = createFingerprinter();
1943
+ hasher.push(source);
1944
+ return hasher.current();
1945
+ }
1946
+
1947
+ // core/normalize.ts
1948
+ function isCanonicalBlockIR(value) {
1949
+ if (typeof value !== "object" || value === null) return false;
1950
+ const candidate = value;
1951
+ return candidate.v === IR_VERSION && typeof candidate.fingerprint === "string" && typeof candidate.engine === "string" && typeof candidate.root === "object" && candidate.root !== null && candidate.root.role === "structured";
1952
+ }
1953
+ function reuseEnvelopeIfCurrent(source, candidate) {
1954
+ if (!isCanonicalBlockIR(candidate)) return null;
1955
+ return candidate.fingerprint === fingerprintText(source) ? candidate : null;
1956
+ }
1957
+ function envelopeFromCompleteValue(value, kind, options) {
1958
+ return {
1959
+ v: IR_VERSION,
1960
+ engine: "fe-kind-parser",
1961
+ fingerprint: fingerprintText(JSON.stringify(value)),
1962
+ root: {
1963
+ role: "structured",
1964
+ kind,
1965
+ kindState: "resolved",
1966
+ discriminator: options?.discriminator ?? { format: "json", key: KIND_KEY },
1967
+ path: [],
1968
+ status: "complete",
1969
+ value,
1970
+ residue: null
1971
+ }
1972
+ };
1973
+ }
1974
+ function normalizeJsonRegion(source, options) {
1975
+ const reused = reuseEnvelopeIfCurrent(source, options.existing);
1976
+ if (reused) return reused;
1977
+ const tree = new IrTree();
1978
+ const parser = createKindStreamParser({
1979
+ schemas: options.schemas,
1980
+ ...options.expectedRootKind !== void 0 && {
1981
+ expectedRootKind: options.expectedRootKind
1982
+ },
1983
+ onEvent(event) {
1984
+ tree.applyEvent(event);
1985
+ }
1986
+ });
1987
+ parser.push(source);
1988
+ parser.end();
1989
+ return tree.buildEnvelope(fingerprintText(source));
1990
+ }
1991
+
1992
+ // core/envelope-cache.ts
1993
+ var IR_ENVELOPE_CACHE_VERSION = 1;
1994
+ function isRecord2(value) {
1995
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1996
+ }
1997
+ function isIrEnvelopeCache(value) {
1998
+ if (!isRecord2(value)) return false;
1999
+ if (value.v !== IR_ENVELOPE_CACHE_VERSION) return false;
2000
+ if (!isRecord2(value.blocks)) return false;
2001
+ const entries = Object.entries(value.blocks);
2002
+ if (entries.length === 0) return false;
2003
+ for (const [fingerprint, envelope] of entries) {
2004
+ if (!isCanonicalBlockIR(envelope)) return false;
2005
+ if (envelope.fingerprint !== fingerprint) return false;
2006
+ if (envelope.root.status !== "complete") return false;
2007
+ }
2008
+ return true;
2009
+ }
2010
+ function envelopeCacheFromEnvelopes(envelopes) {
2011
+ let blocks = null;
2012
+ for (const envelope of envelopes) {
2013
+ if (!isCanonicalBlockIR(envelope)) continue;
2014
+ if (envelope.root.status !== "complete") continue;
2015
+ (blocks ??= {})[envelope.fingerprint] = envelope;
2016
+ }
2017
+ return blocks ? { v: IR_ENVELOPE_CACHE_VERSION, blocks } : null;
2018
+ }
2019
+
2020
+ // core/envelope-read.ts
2021
+ function readEnvelope(metadata) {
2022
+ const candidate = metadata?.[IR_ENVELOPE_KEY];
2023
+ return isCanonicalBlockIR(candidate) ? candidate : null;
2024
+ }
2025
+ function classifyInboundEnvelopeMetadata(metadata) {
2026
+ if (!metadata || !(IR_ENVELOPE_KEY in metadata)) {
2027
+ return { outcome: "absent", metadata: metadata ?? void 0 };
2028
+ }
2029
+ const candidate = metadata[IR_ENVELOPE_KEY];
2030
+ if (isCanonicalBlockIR(candidate)) {
2031
+ return { outcome: "valid", metadata, envelope: candidate };
2032
+ }
2033
+ const engine = typeof candidate === "object" && candidate !== null && typeof candidate.engine === "string" ? candidate.engine : "unknown";
2034
+ const { [IR_ENVELOPE_KEY]: _dropped, ...rest } = metadata;
2035
+ return { outcome: "malformed", metadata: rest, engine, raw: candidate };
2036
+ }
2037
+ function sanitizeInboundEnvelopeMetadata(metadata, context, hooks = {}) {
2038
+ const verdict = classifyInboundEnvelopeMetadata(metadata);
2039
+ if (verdict.outcome === "valid") {
2040
+ hooks.seedEnvelope?.(verdict.envelope);
2041
+ return verdict.metadata;
2042
+ }
2043
+ if (verdict.outcome === "malformed") {
2044
+ hooks.reportMalformed?.({
2045
+ blockId: context.blockId,
2046
+ engine: verdict.engine,
2047
+ raw: verdict.raw
2048
+ });
2049
+ return verdict.metadata;
2050
+ }
2051
+ return verdict.metadata;
2052
+ }
2053
+
2054
+ // core/envelope-value.ts
2055
+ function isRecord3(value) {
2056
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2057
+ }
2058
+ function reconstructRegionValue(envelope) {
2059
+ const cloned = structuredClone(envelope.root.value);
2060
+ const applyExtras = (target, extras) => {
2061
+ if (!extras) return;
2062
+ for (const [key, value] of Object.entries(extras)) {
2063
+ target[key] = structuredClone(value);
2064
+ }
2065
+ };
2066
+ applyExtras(cloned, envelope.root.residue?.extra);
2067
+ for (const [pathKey, meta] of Object.entries(envelope.nodeIndex ?? {})) {
2068
+ const residue = meta.residue;
2069
+ if (!residue || isEmptyResidue(residue) || !residue.extra) continue;
2070
+ const segments = pathKey.split(".");
2071
+ let cursor = cloned;
2072
+ for (const segment of segments) {
2073
+ if (Array.isArray(cursor)) {
2074
+ cursor = cursor[Number(segment)];
2075
+ } else if (isRecord3(cursor)) {
2076
+ cursor = cursor[segment];
2077
+ } else {
2078
+ cursor = void 0;
2079
+ break;
2080
+ }
2081
+ }
2082
+ if (isRecord3(cursor)) {
2083
+ applyExtras(cursor, residue.extra);
2084
+ }
2085
+ }
2086
+ return cloned;
2087
+ }
2088
+ function stripKindDeep(value) {
2089
+ if (Array.isArray(value)) {
2090
+ return value.map(stripKindDeep);
2091
+ }
2092
+ if (isRecord3(value)) {
2093
+ const out = {};
2094
+ for (const [key, child] of Object.entries(value)) {
2095
+ if (key === KIND_KEY) continue;
2096
+ out[key] = stripKindDeep(child);
2097
+ }
2098
+ return out;
2099
+ }
2100
+ return value;
2101
+ }
2102
+
2103
+ // utils/text-case-converter.ts
2104
+ var DEFAULT_WORD_REPLACEMENTS = {
2105
+ // Acronyms & initialisms
2106
+ "api": "API",
2107
+ "apis": "APIs",
2108
+ "ui": "UI",
2109
+ "ux": "UX",
2110
+ "id": "ID",
2111
+ "ids": "IDs",
2112
+ "qr": "QR",
2113
+ "ssr": "SSR",
2114
+ "csr": "CSR",
2115
+ "ssg": "SSG",
2116
+ "isr": "ISR",
2117
+ "spa": "SPA",
2118
+ "pwa": "PWA",
2119
+ "sdk": "SDK",
2120
+ "sdks": "SDKs",
2121
+ "cli": "CLI",
2122
+ "tty": "TTY",
2123
+ "repl": "REPL",
2124
+ "ci": "CI",
2125
+ "cd": "CD",
2126
+ "cpu": "CPU",
2127
+ "cpus": "CPUs",
2128
+ "gpu": "GPU",
2129
+ "gpus": "GPUs",
2130
+ "ram": "RAM",
2131
+ "rom": "ROM",
2132
+ "ssd": "SSD",
2133
+ "ssds": "SSDs",
2134
+ "hdd": "HDD",
2135
+ "hdds": "HDDs",
2136
+ "kpi": "KPI",
2137
+ "kpis": "KPIs",
2138
+ "sla": "SLA",
2139
+ "slas": "SLAs",
2140
+ "slo": "SLO",
2141
+ "slos": "SLOs",
2142
+ "sli": "SLI",
2143
+ "slis": "SLIs",
2144
+ "dom": "DOM",
2145
+ // Web, formats, protocols
2146
+ "url": "URL",
2147
+ "urls": "URLs",
2148
+ "uri": "URI",
2149
+ "uris": "URIs",
2150
+ "http": "HTTP",
2151
+ "https": "HTTPS",
2152
+ "html": "HTML",
2153
+ "css": "CSS",
2154
+ "json": "JSON",
2155
+ "yaml": "YAML",
2156
+ "yml": "YML",
2157
+ "toml": "TOML",
2158
+ "csv": "CSV",
2159
+ "pdf": "PDF",
2160
+ "tsv": "TSV",
2161
+ "jpg": "JPG",
2162
+ "jpeg": "JPEG",
2163
+ "png": "PNG",
2164
+ "gif": "GIF",
2165
+ "webp": "WebP",
2166
+ "heic": "HEIC",
2167
+ "heif": "HEIF",
2168
+ "bmp": "BMP",
2169
+ "tiff": "TIFF",
2170
+ "ico": "ICO",
2171
+ "xml": "XML",
2172
+ "sql": "SQL",
2173
+ "db": "DB",
2174
+ "dbs": "DBs",
2175
+ "nosql": "NoSQL",
2176
+ "graphql": "GraphQL",
2177
+ "grpc": "gRPC",
2178
+ "rest": "REST",
2179
+ "restful": "RESTful",
2180
+ "websocket": "WebSocket",
2181
+ "websockets": "WebSockets",
2182
+ "webrtc": "WebRTC",
2183
+ // Networking
2184
+ "ip": "IP",
2185
+ "ipv4": "IPv4",
2186
+ "ipv6": "IPv6",
2187
+ "dns": "DNS",
2188
+ "dhcp": "DHCP",
2189
+ "nat": "NAT",
2190
+ "tcp": "TCP",
2191
+ "udp": "UDP",
2192
+ "icmp": "ICMP",
2193
+ "ttl": "TTL",
2194
+ "lan": "LAN",
2195
+ "wan": "WAN",
2196
+ "vlan": "VLAN",
2197
+ "cdn": "CDN",
2198
+ "ftp": "FTP",
2199
+ "ssh": "SSH",
2200
+ "tls": "TLS",
2201
+ "ssl": "SSL",
2202
+ // Security & crypto
2203
+ "jwt": "JWT",
2204
+ "jws": "JWS",
2205
+ "jwe": "JWE",
2206
+ "hmac": "HMAC",
2207
+ "rsa": "RSA",
2208
+ "ecdsa": "ECDSA",
2209
+ "aes": "AES",
2210
+ "pbkdf2": "PBKDF2",
2211
+ "argon2": "Argon2",
2212
+ "scrypt": "scrypt",
2213
+ "totp": "TOTP",
2214
+ "hotp": "HOTP",
2215
+ "mfa": "MFA",
2216
+ "2fa": "2FA",
2217
+ "csrf": "CSRF",
2218
+ "xss": "XSS",
2219
+ "ssrf": "SSRF",
2220
+ "rce": "RCE",
2221
+ "dos": "DoS",
2222
+ "ddos": "DDoS",
2223
+ "mitm": "MITM",
2224
+ "csp": "CSP",
2225
+ "cors": "CORS",
2226
+ "pii": "PII",
2227
+ "phi": "PHI",
2228
+ "gdpr": "GDPR",
2229
+ "ccpa": "CCPA",
2230
+ "hipaa": "HIPAA",
2231
+ "rfc": "RFC",
2232
+ // Platforms, langs, tools (single-token)
2233
+ "javascript": "JavaScript",
2234
+ "typescript": "TypeScript",
2235
+ "jsx": "JSX",
2236
+ "tsx": "TSX",
2237
+ "node": "Node",
2238
+ // (used when tokenized alone)
2239
+ "deno": "Deno",
2240
+ "bun": "Bun",
2241
+ "react": "React",
2242
+ "nextjs": "Next.js",
2243
+ // if your tokenizer drops dots, keep this
2244
+ "nodejs": "Node.js",
2245
+ "postgresql": "PostgreSQL",
2246
+ "postgres": "Postgres",
2247
+ "mysql": "MySQL",
2248
+ "sqlite": "SQLite",
2249
+ "redis": "Redis",
2250
+ "supabase": "Supabase",
2251
+ "docker": "Docker",
2252
+ "kubernetes": "Kubernetes",
2253
+ "k8s": "Kubernetes",
2254
+ "helm": "Helm",
2255
+ "npm": "npm",
2256
+ "pnpm": "pnpm",
2257
+ "yarn": "Yarn",
2258
+ "eslint": "ESLint",
2259
+ "prettier": "Prettier",
2260
+ "vite": "Vite",
2261
+ "webpack": "Webpack",
2262
+ "babel": "Babel",
2263
+ // OS & vendors
2264
+ "macos": "macOS",
2265
+ "ios": "iOS",
2266
+ "ipados": "iPadOS",
2267
+ "watchos": "watchOS",
2268
+ "tvos": "tvOS",
2269
+ "windows": "Windows",
2270
+ "linux": "Linux",
2271
+ "ubuntu": "Ubuntu",
2272
+ "github": "GitHub",
2273
+ "gitlab": "GitLab",
2274
+ "bitbucket": "Bitbucket",
2275
+ // Data & analytics
2276
+ "etl": "ETL",
2277
+ "elt": "ELT",
2278
+ "olap": "OLAP",
2279
+ "oltp": "OLTP",
2280
+ "bi": "BI",
2281
+ // Time & locales
2282
+ "utc": "UTC",
2283
+ "gmt": "GMT",
2284
+ "pst": "PST",
2285
+ "pdt": "PDT",
2286
+ "pt": "PT",
2287
+ // Common “small words” to keep lowercase (unless first/last word)
2288
+ "or": "or",
2289
+ "and": "and",
2290
+ "the": "the",
2291
+ "of": "of",
2292
+ "in": "in",
2293
+ "to": "to",
2294
+ "with": "with",
2295
+ "as": "as",
2296
+ "by": "by",
2297
+ "for": "for",
2298
+ "on": "on",
2299
+ "at": "at",
2300
+ "up": "up",
2301
+ "a": "a",
2302
+ "an": "an",
2303
+ "is": "is",
2304
+ "are": "are",
2305
+ "was": "was",
2306
+ "were": "were",
2307
+ "be": "be",
2308
+ "but": "but",
2309
+ "nor": "nor",
2310
+ "so": "so",
2311
+ "yet": "yet",
2312
+ "per": "per",
2313
+ "via": "via",
2314
+ // Latin abbreviations (tokenized as words in some pipelines)
2315
+ "eg": "e.g.",
2316
+ "ie": "i.e.",
2317
+ "etc": "etc.",
2318
+ "aka": "aka",
2319
+ "vs": "vs.",
2320
+ "v": "v.",
2321
+ // Client abbreviations
2322
+ "CIC": "CIC",
2323
+ "AGR": "AGR",
2324
+ "AGER": "AGER",
2325
+ "DD": "DD",
2326
+ "TS": "TS",
2327
+ "TM": "TM",
2328
+ "arman": "Arman"
2329
+ };
2330
+ var DEFAULT_OPTIONS = {
2331
+ textCase: "title",
2332
+ wordReplacements: DEFAULT_WORD_REPLACEMENTS,
2333
+ trim: true
2334
+ };
2335
+ function formatText(text, options = {}) {
2336
+ const opts = { ...DEFAULT_OPTIONS, ...options };
2337
+ if (!text) return "";
2338
+ let normalized = text.replace(/_/g, " ").replace(/-/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/\s+/g, " ");
2339
+ if (opts.trim) {
2340
+ normalized = normalized.trim();
2341
+ }
2342
+ let caseTransformed = normalized;
2343
+ switch (opts.textCase) {
2344
+ case "title":
2345
+ caseTransformed = normalized.replace(
2346
+ /\w\S*/g,
2347
+ (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
2348
+ );
2349
+ break;
2350
+ case "sentence":
2351
+ if (normalized.length > 0) {
2352
+ caseTransformed = normalized.charAt(0).toUpperCase() + normalized.slice(1).toLowerCase();
2353
+ }
2354
+ break;
2355
+ case "lower":
2356
+ caseTransformed = normalized.toLowerCase();
2357
+ break;
2358
+ case "upper":
2359
+ caseTransformed = normalized.toUpperCase();
2360
+ break;
2361
+ }
2362
+ let result = caseTransformed;
2363
+ if (opts.wordReplacements) {
2364
+ Object.entries(opts.wordReplacements).forEach(([key, value]) => {
2365
+ const regex = new RegExp(`\\b${key}\\b`, "gi");
2366
+ result = result.replace(regex, value);
2367
+ });
2368
+ }
2369
+ return result;
2370
+ }
2371
+
2372
+ // core/schema-structure.ts
2373
+ function formatBlockLabel(key) {
2374
+ return formatText(key, { textCase: "title" });
2375
+ }
2376
+ function schemaStructureDepth(schema, allSchemas, visiting = /* @__PURE__ */ new Set()) {
2377
+ if (visiting.has(schema.kind)) return 0;
2378
+ visiting.add(schema.kind);
2379
+ let max = 0;
2380
+ for (const field of Object.values(schema.fields)) {
2381
+ max = Math.max(max, fieldStructureDepth(field, allSchemas, visiting));
2382
+ }
2383
+ visiting.delete(schema.kind);
2384
+ return max;
2385
+ }
2386
+ function fieldStructureDepth(field, allSchemas, visiting) {
2387
+ switch (field.type) {
2388
+ case "array": {
2389
+ let itemMax = 0;
2390
+ for (const itemKind of field.itemKinds) {
2391
+ const itemSchema = allSchemas[itemKind];
2392
+ itemMax = Math.max(
2393
+ itemMax,
2394
+ itemSchema ? 1 + schemaStructureDepth(itemSchema, allSchemas, visiting) : 1
2395
+ );
2396
+ }
2397
+ return itemMax;
2398
+ }
2399
+ case "object": {
2400
+ const ref = allSchemas[field.kind];
2401
+ return ref ? 1 + schemaStructureDepth(ref, allSchemas, visiting) : 1;
2402
+ }
2403
+ case "inline_object": {
2404
+ let nested = 0;
2405
+ for (const child of Object.values(field.fields)) {
2406
+ nested = Math.max(
2407
+ nested,
2408
+ fieldStructureDepth(child, allSchemas, visiting)
2409
+ );
2410
+ }
2411
+ return nested > 0 ? 1 + nested : 1;
2412
+ }
2413
+ default:
2414
+ return 0;
2415
+ }
2416
+ }
2417
+ function schemaLayoutMode(schema, allSchemas) {
2418
+ const depth = schemaStructureDepth(schema, allSchemas);
2419
+ if (depth <= 0) return "flat";
2420
+ if (depth === 1) return "grid";
2421
+ return "nested";
2422
+ }
2423
+
2424
+ // session/parse-session.ts
2425
+ var ParseSession = class {
2426
+ identity;
2427
+ parser;
2428
+ tree = new IrTree();
2429
+ listeners = /* @__PURE__ */ new Map();
2430
+ anyListeners = /* @__PURE__ */ new Set();
2431
+ unsubscribeSchemaArrivals;
2432
+ fingerprinter = createFingerprinter();
2433
+ ended = false;
2434
+ constructor(options) {
2435
+ this.identity = options.identity;
2436
+ this.parser = createKindStreamParser({
2437
+ schemas: options.schemas,
2438
+ ...options.expectedRootKind !== void 0 && {
2439
+ expectedRootKind: options.expectedRootKind
2440
+ },
2441
+ onEvent: (event) => {
2442
+ this.tree.applyEvent(event);
2443
+ options.onEvent?.(event);
2444
+ }
2445
+ });
2446
+ this.unsubscribeSchemaArrivals = options.onSchemaArrived?.((kind, schema) => {
2447
+ this.parser.notifySchemaArrived(kind, schema);
2448
+ this.flushNotify();
2449
+ }) ?? null;
2450
+ }
2451
+ /** The single writer's input. Does NOT notify — host flushes on its cadence. */
2452
+ write(chunk) {
2453
+ this.fingerprinter.push(chunk);
2454
+ this.parser.push(chunk);
2455
+ }
2456
+ end() {
2457
+ if (this.ended) return;
2458
+ this.ended = true;
2459
+ this.parser.end();
2460
+ }
2461
+ get isEnded() {
2462
+ return this.ended;
2463
+ }
2464
+ get status() {
2465
+ return this.tree.status;
2466
+ }
2467
+ getNode(pathKey) {
2468
+ return this.tree.getNode(pathKey);
2469
+ }
2470
+ listNodes() {
2471
+ return this.tree.listNodes();
2472
+ }
2473
+ isRawPath(pathKey) {
2474
+ return this.tree.isRawPath(pathKey);
2475
+ }
2476
+ subscribe(pathKey, listener) {
2477
+ const set = this.listeners.get(pathKey) ?? /* @__PURE__ */ new Set();
2478
+ set.add(listener);
2479
+ this.listeners.set(pathKey, set);
2480
+ return () => {
2481
+ set.delete(listener);
2482
+ if (set.size === 0) this.listeners.delete(pathKey);
2483
+ };
2484
+ }
2485
+ /** Structural subscription: fires when ANY node changes (mount lists). */
2486
+ subscribeAny(listener) {
2487
+ this.anyListeners.add(listener);
2488
+ return () => {
2489
+ this.anyListeners.delete(listener);
2490
+ };
2491
+ }
2492
+ /** Publish dirty paths to their readers. Host-cadence, coalesced. */
2493
+ flushNotify() {
2494
+ if (!this.tree.hasDirty()) return;
2495
+ const dirty = this.tree.drainDirty();
2496
+ for (const pathKey of dirty) {
2497
+ const set = this.listeners.get(pathKey);
2498
+ if (!set) continue;
2499
+ for (const listener of set) listener();
2500
+ }
2501
+ if (this.anyListeners.size > 0) {
2502
+ for (const listener of this.anyListeners) listener();
2503
+ }
2504
+ }
2505
+ buildEnvelope() {
2506
+ return this.tree.buildEnvelope(this.fingerprinter.current());
2507
+ }
2508
+ dispose() {
2509
+ this.unsubscribeSchemaArrivals?.();
2510
+ this.listeners.clear();
2511
+ this.anyListeners.clear();
2512
+ }
2513
+ };
2514
+
2515
+ // session/session-manager.ts
2516
+ var sessions = /* @__PURE__ */ new Map();
2517
+ function openParseSession(options) {
2518
+ const existing = sessions.get(options.identity);
2519
+ if (existing && !existing.isEnded) {
2520
+ throw new Error(
2521
+ `content-ir: a writer is already open for identity "${options.identity}". One writer per stream identity \u2014 everyone else reads.`
2522
+ );
2523
+ }
2524
+ existing?.dispose();
2525
+ const session = new ParseSession(options);
2526
+ sessions.set(options.identity, session);
2527
+ return session;
2528
+ }
2529
+ function getParseSession(identity) {
2530
+ return sessions.get(identity) ?? null;
2531
+ }
2532
+ function disposeParseSession(identity) {
2533
+ const session = sessions.get(identity);
2534
+ if (!session) return;
2535
+ session.dispose();
2536
+ sessions.delete(identity);
2537
+ }
2538
+
2539
+ // registry/kind-storage-transform.ts
2540
+ var ROOT_STORAGE_NAME = "__root";
2541
+ var KindStorageError = class extends Error {
2542
+ constructor(message) {
2543
+ super(message);
2544
+ this.name = "KindStorageError";
2545
+ }
2546
+ };
2547
+ var PATH_SEP = ".";
2548
+ function base(field) {
2549
+ const out = {
2550
+ name: ""
2551
+ };
2552
+ if (field.required) out.required = true;
2553
+ if (field.nullable) out.nullable = true;
2554
+ if (field.description !== void 0) out.description = field.description;
2555
+ if (field.default !== void 0) out.default = field.default;
2556
+ return out;
2557
+ }
2558
+ function storeField(name, field, path, edges) {
2559
+ const b = { ...base(field), name };
2560
+ switch (field.type) {
2561
+ case "string":
2562
+ case "boolean":
2563
+ case "number[]":
2564
+ case "boolean[]":
2565
+ case "json":
2566
+ case "json[]":
2567
+ return { ...b, type: field.type };
2568
+ case "number":
2569
+ return {
2570
+ ...b,
2571
+ type: "number",
2572
+ ...field.min !== void 0 ? { min: field.min } : {},
2573
+ ...field.max !== void 0 ? { max: field.max } : {},
2574
+ ...field.step !== void 0 ? { step: field.step } : {}
2575
+ };
2576
+ case "string[]":
2577
+ return {
2578
+ ...b,
2579
+ type: "string[]",
2580
+ ...field.values !== void 0 ? { values: [...field.values] } : {},
2581
+ ...field.open ? { open: true } : {}
2582
+ };
2583
+ case "record":
2584
+ return { ...b, type: "record", values: field.values };
2585
+ case "enum":
2586
+ return {
2587
+ ...b,
2588
+ type: "enum",
2589
+ values: [...field.values],
2590
+ ...field.open ? { open: true } : {}
2591
+ };
2592
+ case "union": {
2593
+ if (field.kinds && field.kinds.length > 0) {
2594
+ field.kinds.forEach((childKind, position) => {
2595
+ edges.push({ fieldPath: path, childKind, position });
2596
+ });
2597
+ return { ...b, type: "union", scalars: [...field.scalars], hasKinds: true };
2598
+ }
2599
+ return { ...b, type: "union", scalars: [...field.scalars] };
2600
+ }
2601
+ case "object":
2602
+ edges.push({ fieldPath: path, childKind: field.kind, position: null });
2603
+ return { ...b, type: "object" };
2604
+ case "array":
2605
+ field.itemKinds.forEach((childKind, position) => {
2606
+ edges.push({ fieldPath: path, childKind, position });
2607
+ });
2608
+ return { ...b, type: "array" };
2609
+ case "inline_object": {
2610
+ const fields = [];
2611
+ for (const [childName, childField] of Object.entries(field.fields)) {
2612
+ fields.push(
2613
+ storeField(
2614
+ childName,
2615
+ childField,
2616
+ `${path}${PATH_SEP}${childName}`,
2617
+ edges
2618
+ )
2619
+ );
2620
+ }
2621
+ return field.open ? { ...b, type: "inline_object", fields, open: true } : { ...b, type: "inline_object", fields };
2622
+ }
2623
+ }
2624
+ }
2625
+ function kindSchemaToStorage(schema) {
2626
+ const data = [];
2627
+ const edges = [];
2628
+ if (schema.root) {
2629
+ if (Object.keys(schema.fields).length > 0) {
2630
+ throw new KindStorageError(
2631
+ `kind "${schema.kind}": root form and a non-empty fields map are mutually exclusive.`
2632
+ );
2633
+ }
2634
+ data.push(storeField(ROOT_STORAGE_NAME, schema.root, ROOT_STORAGE_NAME, edges));
2635
+ return { data, edges };
2636
+ }
2637
+ for (const [name, field] of Object.entries(schema.fields)) {
2638
+ if (name === ROOT_STORAGE_NAME) {
2639
+ throw new KindStorageError(
2640
+ `kind "${schema.kind}": field name "${ROOT_STORAGE_NAME}" is reserved for the non-object root form.`
2641
+ );
2642
+ }
2643
+ data.push(storeField(name, field, name, edges));
2644
+ }
2645
+ return { data, edges };
2646
+ }
2647
+ function indexEdges(edges) {
2648
+ const byPath = /* @__PURE__ */ new Map();
2649
+ for (const edge of edges) {
2650
+ const list = byPath.get(edge.fieldPath);
2651
+ if (list) list.push(edge);
2652
+ else byPath.set(edge.fieldPath, [edge]);
2653
+ }
2654
+ return byPath;
2655
+ }
2656
+ function restoreField(element, path, byPath) {
2657
+ const b = {};
2658
+ if (element.required) b.required = true;
2659
+ if (element.nullable) b.nullable = true;
2660
+ if (element.description !== void 0) b.description = element.description;
2661
+ if (element.default !== void 0) b.default = element.default;
2662
+ switch (element.type) {
2663
+ case "string":
2664
+ case "boolean":
2665
+ case "number[]":
2666
+ case "boolean[]":
2667
+ case "json":
2668
+ case "json[]":
2669
+ return { ...b, type: element.type };
2670
+ case "number":
2671
+ return {
2672
+ ...b,
2673
+ type: "number",
2674
+ ...element.min !== void 0 ? { min: element.min } : {},
2675
+ ...element.max !== void 0 ? { max: element.max } : {},
2676
+ ...element.step !== void 0 ? { step: element.step } : {}
2677
+ };
2678
+ case "string[]":
2679
+ return {
2680
+ ...b,
2681
+ type: "string[]",
2682
+ ...element.values !== void 0 ? { values: [...element.values] } : {},
2683
+ ...element.open ? { open: true } : {}
2684
+ };
2685
+ case "record":
2686
+ return { ...b, type: "record", values: element.values };
2687
+ case "enum":
2688
+ return {
2689
+ ...b,
2690
+ type: "enum",
2691
+ values: [...element.values],
2692
+ ...element.open ? { open: true } : {}
2693
+ };
2694
+ case "union": {
2695
+ const list = byPath.get(path) ?? [];
2696
+ if (element.hasKinds) {
2697
+ if (list.length === 0) {
2698
+ throw new KindStorageError(
2699
+ `union field "${path}" declares kind members (hasKinds) but has no edges.`
2700
+ );
2701
+ }
2702
+ const kinds = [...list].sort((a, z) => (a.position ?? 0) - (z.position ?? 0)).map((e) => e.childKind);
2703
+ return { ...b, type: "union", scalars: [...element.scalars], kinds };
2704
+ }
2705
+ if (list.length > 0) {
2706
+ throw new KindStorageError(
2707
+ `union field "${path}" has ${list.length} edge(s) but does not declare hasKinds.`
2708
+ );
2709
+ }
2710
+ return { ...b, type: "union", scalars: [...element.scalars] };
2711
+ }
2712
+ case "object": {
2713
+ const list = byPath.get(path) ?? [];
2714
+ if (list.length !== 1) {
2715
+ throw new KindStorageError(
2716
+ `object field "${path}" must have exactly one edge, found ${list.length}.`
2717
+ );
2718
+ }
2719
+ const [edge] = list;
2720
+ if (!edge) {
2721
+ throw new KindStorageError(
2722
+ `object field "${path}" must have exactly one edge, found 0.`
2723
+ );
2724
+ }
2725
+ return { ...b, type: "object", kind: edge.childKind };
2726
+ }
2727
+ case "array": {
2728
+ const list = byPath.get(path) ?? [];
2729
+ if (list.length === 0) {
2730
+ throw new KindStorageError(
2731
+ `array field "${path}" must have at least one edge.`
2732
+ );
2733
+ }
2734
+ const itemKinds = [...list].sort((a, z) => (a.position ?? 0) - (z.position ?? 0)).map((e) => e.childKind);
2735
+ return { ...b, type: "array", itemKinds };
2736
+ }
2737
+ case "inline_object": {
2738
+ const fields = {};
2739
+ for (const child of element.fields) {
2740
+ fields[child.name] = restoreField(
2741
+ child,
2742
+ `${path}${PATH_SEP}${child.name}`,
2743
+ byPath
2744
+ );
2745
+ }
2746
+ return element.open ? { ...b, type: "inline_object", fields, open: true } : { ...b, type: "inline_object", fields };
2747
+ }
2748
+ }
2749
+ }
2750
+ function storageToKindSchema(kind, shape) {
2751
+ const byPath = indexEdges(shape.edges);
2752
+ const [first] = shape.data;
2753
+ if (first && first.name === ROOT_STORAGE_NAME) {
2754
+ if (shape.data.length !== 1) {
2755
+ throw new KindStorageError(
2756
+ `kind "${kind}": a "${ROOT_STORAGE_NAME}" element must be the only data element (found ${shape.data.length}).`
2757
+ );
2758
+ }
2759
+ return {
2760
+ kind,
2761
+ fields: {},
2762
+ root: restoreField(first, ROOT_STORAGE_NAME, byPath)
2763
+ };
2764
+ }
2765
+ const fields = {};
2766
+ for (const element of shape.data) {
2767
+ if (element.name === ROOT_STORAGE_NAME) {
2768
+ throw new KindStorageError(
2769
+ `kind "${kind}": "${ROOT_STORAGE_NAME}" must be the first and only data element.`
2770
+ );
2771
+ }
2772
+ fields[element.name] = restoreField(element, element.name, byPath);
2773
+ }
2774
+ return { kind, fields };
2775
+ }
2776
+ var ajv = new Ajv__default.default({ allErrors: true, strict: false });
2777
+ function stripKind(value) {
2778
+ if (Array.isArray(value)) return value.map(stripKind);
2779
+ if (value && typeof value === "object") {
2780
+ const out = {};
2781
+ for (const [k, v] of Object.entries(value)) {
2782
+ if (k === KIND_KEY) continue;
2783
+ out[k] = stripKind(v);
2784
+ }
2785
+ return out;
2786
+ }
2787
+ return value;
2788
+ }
2789
+ function validateStructuralLeg(sample, emittedJsonSchema) {
2790
+ let validate;
2791
+ try {
2792
+ validate = ajv.compile(emittedJsonSchema);
2793
+ } catch (err) {
2794
+ return {
2795
+ ok: false,
2796
+ detail: `emitted_json_schema failed to compile: ${err instanceof Error ? err.message : String(err)}`
2797
+ };
2798
+ }
2799
+ const ok = validate(stripKind(sample));
2800
+ if (ok) return { ok: true };
2801
+ const errors = (validate.errors ?? []).map((e) => `${e.instancePath || "(root)"} ${e.message ?? ""}`.trim()).slice(0, 8);
2802
+ return { ok: false, detail: `sample failed schema: ${errors.join("; ")}` };
2803
+ }
2804
+ var SERVER_DATA_ANNOTATION_KEYS = /* @__PURE__ */ new Set(["language"]);
2805
+ var SUBSTANCE_DEPTH_LIMIT = 8;
2806
+ function isSubstantiveValue(value, depth = 0) {
2807
+ if (value === null || value === void 0) return false;
2808
+ if (typeof value === "string") return value.trim().length > 0;
2809
+ if (typeof value === "number") return Number.isFinite(value);
2810
+ if (typeof value === "boolean") return true;
2811
+ if (depth >= SUBSTANCE_DEPTH_LIMIT) return true;
2812
+ if (Array.isArray(value)) {
2813
+ return value.some((entry) => isSubstantiveValue(entry, depth + 1));
2814
+ }
2815
+ if (typeof value === "object") {
2816
+ return Object.values(value).some(
2817
+ (entry) => isSubstantiveValue(entry, depth + 1)
2818
+ );
2819
+ }
2820
+ return false;
2821
+ }
2822
+ function describeUnrenderableBridgeOutput(serverData) {
2823
+ if (serverData === void 0 || serverData === null) {
2824
+ return "bridge returned no serverData (undefined)";
2825
+ }
2826
+ if (typeof serverData !== "object") {
2827
+ return `bridge returned a non-object serverData (${typeof serverData})`;
2828
+ }
2829
+ if (Array.isArray(serverData)) {
2830
+ return "bridge returned an array, not a serverData record";
2831
+ }
2832
+ const record = serverData;
2833
+ const keys = Object.keys(record);
2834
+ if (keys.length === 0) return "bridge returned an empty object ({})";
2835
+ const contentKeys = keys.filter((key) => !SERVER_DATA_ANNOTATION_KEYS.has(key));
2836
+ if (contentKeys.length === 0) {
2837
+ return `bridge returned only annotation keys [${keys.join(", ")}] \u2014 that is the raw code-region annotation, not kind data`;
2838
+ }
2839
+ if (!contentKeys.some((key) => isSubstantiveValue(record[key]))) {
2840
+ return `bridge returned serverData whose every content value is empty (keys: ${contentKeys.join(", ")}) \u2014 structurally present, semantically empty`;
2841
+ }
2842
+ return null;
2843
+ }
2844
+ function validateRender(kind, sample, definition, resolvedComponent, dataOnly) {
2845
+ if (dataOnly) {
2846
+ return {
2847
+ ok: true,
2848
+ detail: "data-only contract kind \u2014 render leg is structurally inapplicable (n/a)"
2849
+ };
2850
+ }
2851
+ if (!definition && !resolvedComponent?.isActive) {
2852
+ return {
2853
+ ok: false,
2854
+ detail: `kind "${kind}" has no component (not in the compiled registry, and no active role='output' kind_component row) \u2014 nothing to render`
2855
+ };
2856
+ }
2857
+ if (definition && !definition.legacyBlockType && !definition.component && !definition.toLegacyServerData && !resolvedComponent?.isActive) {
2858
+ return {
2859
+ ok: false,
2860
+ detail: `kind "${kind}" has no component (no compiled legacyBlockType/component facet, and no active role='output' kind_component row) \u2014 nothing to render`
2861
+ };
2862
+ }
2863
+ if (definition?.toLegacyServerData) {
2864
+ let serverData;
2865
+ try {
2866
+ serverData = definition.toLegacyServerData(
2867
+ envelopeFromCompleteValue(sample, kind)
2868
+ );
2869
+ } catch (err) {
2870
+ return {
2871
+ ok: false,
2872
+ detail: `toLegacyServerData threw: ${err instanceof Error ? err.message : String(err)}`
2873
+ };
2874
+ }
2875
+ const problem = describeUnrenderableBridgeOutput(serverData);
2876
+ if (problem) {
2877
+ return {
2878
+ ok: false,
2879
+ detail: `${problem} (the "No ${kind} available" failure)`
2880
+ };
2881
+ }
2882
+ return { ok: true };
2883
+ }
2884
+ const satisfier = definition?.legacyBlockType ? `compiled component "${definition.legacyBlockType}"` : definition?.component ? "compiled component facet" : resolvedComponent ? `resolved ${resolvedComponent.source} component "${resolvedComponent.componentKey}"` : "component";
2885
+ return {
2886
+ ok: true,
2887
+ detail: `bridgeless kind \u2014 ${satisfier} parses content itself; full DOM render check deferred to an RTL harness`
2888
+ };
2889
+ }
2890
+ function runKindDualGate(input) {
2891
+ const structural = validateStructuralLeg(input.sample, input.emittedJsonSchema);
2892
+ const render = validateRender(
2893
+ input.kind,
2894
+ input.sample,
2895
+ input.definition,
2896
+ input.resolvedComponent,
2897
+ input.dataOnly
2898
+ );
2899
+ return { isActive: structural.ok && render.ok, structural, render };
2900
+ }
2901
+ function describeDualGateFailure(kind, result) {
2902
+ if (result.isActive) return "";
2903
+ const parts = [];
2904
+ if (!result.structural.ok) {
2905
+ parts.push(`structural(Pydantic): ${result.structural.detail ?? "failed"}`);
2906
+ }
2907
+ if (!result.render.ok) {
2908
+ parts.push(`render(UI): ${result.render.detail ?? "failed"}`);
2909
+ }
2910
+ return `kind "${kind}" failed the dual gate \u2014 ${parts.join(" | ")}`;
2911
+ }
2912
+
2913
+ // convert/openai-schema-converter.ts
2914
+ function requiredNullableFlags(required, nullable) {
2915
+ return {
2916
+ ...required ? { required: true } : {},
2917
+ ...nullable ? { nullable: true } : {}
2918
+ };
2919
+ }
2920
+ var METADATA_KEYS = /* @__PURE__ */ new Set([
2921
+ "description",
2922
+ "title",
2923
+ "default",
2924
+ "examples",
2925
+ "format",
2926
+ "minimum",
2927
+ "maximum",
2928
+ "multipleOf",
2929
+ "exclusiveMinimum",
2930
+ "exclusiveMaximum",
2931
+ "minLength",
2932
+ "maxLength",
2933
+ "minItems",
2934
+ "maxItems",
2935
+ "pattern",
2936
+ "const",
2937
+ "$schema",
2938
+ "$id",
2939
+ "deprecated",
2940
+ "readOnly",
2941
+ "writeOnly"
2942
+ ]);
2943
+ function isRecord4(value) {
2944
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2945
+ }
2946
+ function deepClone(value) {
2947
+ return JSON.parse(JSON.stringify(value));
2948
+ }
2949
+ function fieldSchemaSummary(field) {
2950
+ if (field.type === "enum") {
2951
+ return `enum(${field.values.join("|")}${field.open ? "|+any" : ""})${field.required ? "*" : ""}`;
2952
+ }
2953
+ if (field.type === "array") {
2954
+ return `array<${field.itemKinds.join("|")}>${field.required ? "*" : ""}`;
2955
+ }
2956
+ if (field.type === "inline_object") {
2957
+ return `inline{${Object.keys(field.fields).join(",")}}${field.required ? "*" : ""}`;
2958
+ }
2959
+ if (field.type === "object") {
2960
+ return `object:${field.kind}${field.required ? "*" : ""}`;
2961
+ }
2962
+ if (field.type === "union") {
2963
+ const members = [...field.scalars, ...field.kinds ?? []];
2964
+ return `union(${members.join("|")})${field.required ? "*" : ""}`;
2965
+ }
2966
+ if (field.type === "record") {
2967
+ return `record(${field.values})${field.required ? "*" : ""}`;
2968
+ }
2969
+ return `${field.type}${field.required ? "*" : ""}${field.nullable ? "?" : ""}`;
2970
+ }
2971
+ function resolvePrimaryType(node) {
2972
+ const raw = node.type;
2973
+ if (typeof raw === "string") {
2974
+ return { type: raw === "integer" ? "number" : raw, nullable: false };
2975
+ }
2976
+ if (Array.isArray(raw)) {
2977
+ const types = raw.filter((t) => typeof t === "string");
2978
+ const nullable = types.includes("null");
2979
+ const primary = types.find((t) => t !== "null") ?? (nullable && types.length === 1 ? "null" : null);
2980
+ if (primary === "integer") {
2981
+ return { type: "number", nullable };
2982
+ }
2983
+ return { type: primary ?? null, nullable };
2984
+ }
2985
+ if (node.enum) return { type: "string", nullable: false };
2986
+ if (node.properties) return { type: "object", nullable: false };
2987
+ if (node.items) return { type: "array", nullable: false };
2988
+ return { type: null, nullable: false };
2989
+ }
2990
+ function carriedMetadataKeys(field) {
2991
+ if (field === null) return /* @__PURE__ */ new Set();
2992
+ const carried = /* @__PURE__ */ new Set(["description", "default"]);
2993
+ if (field.type === "number") {
2994
+ carried.add("minimum");
2995
+ carried.add("maximum");
2996
+ carried.add("multipleOf");
2997
+ }
2998
+ return carried;
2999
+ }
3000
+ function collectDropped(node, path, carriedField = null) {
3001
+ const carried = carriedMetadataKeys(carriedField);
3002
+ const dropped = {};
3003
+ for (const [key, value] of Object.entries(node)) {
3004
+ if (METADATA_KEYS.has(key) && !carried.has(key)) {
3005
+ dropped[key] = value;
3006
+ }
3007
+ }
3008
+ if (Object.keys(dropped).length > 0) {
3009
+ return [{ path, dropped }];
3010
+ }
3011
+ return [];
3012
+ }
3013
+ function attachNodeMetadata(node, field) {
3014
+ let out = field;
3015
+ if (typeof node.description === "string" && out.description === void 0) {
3016
+ out = { ...out, description: node.description };
3017
+ }
3018
+ if (node.default !== void 0 && out.default === void 0) {
3019
+ out = { ...out, default: node.default };
3020
+ }
3021
+ if (out.type === "number") {
3022
+ const bounds = {};
3023
+ if (typeof node.minimum === "number" && out.min === void 0) {
3024
+ bounds.min = node.minimum;
3025
+ }
3026
+ if (typeof node.maximum === "number" && out.max === void 0) {
3027
+ bounds.max = node.maximum;
3028
+ }
3029
+ if (typeof node.multipleOf === "number" && out.step === void 0) {
3030
+ bounds.step = node.multipleOf;
3031
+ }
3032
+ if (Object.keys(bounds).length > 0) out = { ...out, ...bounds };
3033
+ }
3034
+ return out;
3035
+ }
3036
+ function synthesizeItemKindSlug(schemaName, fieldName) {
3037
+ const base2 = fieldName.endsWith("ies") ? `${fieldName.slice(0, -3)}y` : fieldName.endsWith("s") ? fieldName.slice(0, -1) : fieldName;
3038
+ return `${schemaName}_${base2}`;
3039
+ }
3040
+ function makeKindJsonSchemaProperty(kindSlug, strict) {
3041
+ const base2 = {
3042
+ type: "string",
3043
+ description: "Block discriminator for render pipeline."
3044
+ };
3045
+ if (strict) {
3046
+ return { ...base2, const: kindSlug };
3047
+ }
3048
+ return { ...base2, enum: [kindSlug] };
3049
+ }
3050
+ function injectKindIntoObjectSchema(objectSchema, kindSlug, strict) {
3051
+ const clone = deepClone(objectSchema);
3052
+ const properties = isRecord4(clone.properties) ? { ...clone.properties } : {};
3053
+ properties[KIND_KEY] = makeKindJsonSchemaProperty(kindSlug, strict);
3054
+ const required = Array.isArray(clone.required) ? clone.required.filter((k) => typeof k === "string") : [];
3055
+ const nextRequired = required.includes(KIND_KEY) ? required : [KIND_KEY, ...required];
3056
+ return {
3057
+ ...clone,
3058
+ properties,
3059
+ required: nextRequired,
3060
+ ...strict ? { additionalProperties: false } : {}
3061
+ };
3062
+ }
3063
+ function injectKindsIntoRootSchema(rootSchema, rootKindSlug, arrayBindings, strict) {
3064
+ let updated = injectKindIntoObjectSchema(rootSchema, rootKindSlug, strict);
3065
+ if (!isRecord4(updated.properties)) {
3066
+ return updated;
3067
+ }
3068
+ const properties = { ...updated.properties };
3069
+ for (const binding of arrayBindings) {
3070
+ const fieldNode = properties[binding.arrayField];
3071
+ if (!isRecord4(fieldNode)) continue;
3072
+ const items = fieldNode.items;
3073
+ const itemNode = Array.isArray(items) ? items[0] : items;
3074
+ if (!isRecord4(itemNode)) continue;
3075
+ const updatedItem = injectKindIntoObjectSchema(
3076
+ itemNode,
3077
+ binding.itemKindSlug,
3078
+ strict
3079
+ );
3080
+ properties[binding.arrayField] = {
3081
+ ...fieldNode,
3082
+ items: updatedItem
3083
+ };
3084
+ }
3085
+ return { ...updated, properties };
3086
+ }
3087
+ function buildAgentSchemaWithRenderBlockSupport(input, rootKindSlug, arrayBindings, strict) {
3088
+ if (!isRecord4(input)) return null;
3089
+ const normalized = normalizeAiSchemaInput(input);
3090
+ if (!normalized.rootSchema) return null;
3091
+ if (normalized.rootSchema.type !== "object" && !isRecord4(normalized.rootSchema.properties)) {
3092
+ return deepClone(input);
3093
+ }
3094
+ const updatedRoot = injectKindsIntoRootSchema(
3095
+ normalized.rootSchema,
3096
+ rootKindSlug,
3097
+ arrayBindings,
3098
+ strict
3099
+ );
3100
+ if (isRecord4(input.schema) && typeof input.name === "string") {
3101
+ return {
3102
+ ...deepClone(input),
3103
+ schema: updatedRoot
3104
+ };
3105
+ }
3106
+ if (isRecord4(input.json_schema)) {
3107
+ const inner = buildAgentSchemaWithRenderBlockSupport(
3108
+ input.json_schema,
3109
+ rootKindSlug,
3110
+ arrayBindings,
3111
+ strict
3112
+ );
3113
+ return inner ? { ...deepClone(input), json_schema: inner } : null;
3114
+ }
3115
+ if (typeof input.name === "string") {
3116
+ return {
3117
+ ...deepClone(input),
3118
+ schema: updatedRoot
3119
+ };
3120
+ }
3121
+ return updatedRoot;
3122
+ }
3123
+ function isAnyValueSchema(node) {
3124
+ return node.type === void 0 && node.enum === void 0 && node.const === void 0 && node.properties === void 0 && node.items === void 0 && node.additionalProperties === void 0 && node.anyOf === void 0 && node.oneOf === void 0 && node.allOf === void 0 && node.$ref === void 0;
3125
+ }
3126
+ function registerDeclaredKindDraft(declaredKind, objectNode, path, ctx) {
3127
+ if (ctx.blockSchemas.some((draft) => draft.slug === declaredKind)) return;
3128
+ if (!isRecord4(objectNode.properties)) return;
3129
+ const memberRequired = new Set(
3130
+ Array.isArray(objectNode.required) ? objectNode.required.filter((k) => typeof k === "string") : []
3131
+ );
3132
+ const fields = {};
3133
+ for (const [propName, propNode] of Object.entries(objectNode.properties)) {
3134
+ if (!isRecord4(propNode)) continue;
3135
+ if (propName === KIND_KEY) continue;
3136
+ const converted = convertProperty(
3137
+ propName,
3138
+ propNode,
3139
+ memberRequired.has(propName),
3140
+ `${path}.${propName}`,
3141
+ ctx
3142
+ );
3143
+ if (converted) fields[propName] = converted;
3144
+ }
3145
+ ctx.blockSchemas.push({
3146
+ slug: declaredKind,
3147
+ label: formatBlockLabel(declaredKind),
3148
+ fields
3149
+ });
3150
+ }
3151
+ function convertProperty(fieldName, node, required, path, ctx) {
3152
+ const core = convertPropertyCore(fieldName, node, required, path, ctx);
3153
+ const field = core === null ? null : attachNodeMetadata(node, core);
3154
+ ctx.droppedMetadata.push(...collectDropped(node, path, field));
3155
+ return field;
3156
+ }
3157
+ function convertPropertyCore(fieldName, node, required, path, ctx) {
3158
+ if (typeof node.$ref === "string") {
3159
+ ctx.problems.push({
3160
+ severity: "error",
3161
+ path,
3162
+ message: `$ref is not supported ("${node.$ref}"). Inline the schema manually.`
3163
+ });
3164
+ return null;
3165
+ }
3166
+ if (Array.isArray(node.anyOf) || Array.isArray(node.oneOf)) {
3167
+ const variants = node.anyOf ?? node.oneOf;
3168
+ const scalarTypes = /* @__PURE__ */ new Set();
3169
+ const enumVariantSets = [];
3170
+ const memberKinds = [];
3171
+ const anonymousObjects = [];
3172
+ let sawNull = false;
3173
+ let unsupported = false;
3174
+ for (const variant of variants) {
3175
+ if (!isRecord4(variant)) {
3176
+ unsupported = true;
3177
+ continue;
3178
+ }
3179
+ if (typeof variant.$ref === "string") {
3180
+ ctx.problems.push({
3181
+ severity: "error",
3182
+ path,
3183
+ message: `$ref inside anyOf/oneOf is not supported ("${variant.$ref}"). Inline the schema manually.`
3184
+ });
3185
+ unsupported = true;
3186
+ continue;
3187
+ }
3188
+ const { type: type2, nullable: nullable2 } = resolvePrimaryType(variant);
3189
+ if (nullable2) sawNull = true;
3190
+ if (type2 === "null") {
3191
+ sawNull = true;
3192
+ continue;
3193
+ }
3194
+ if (type2 === "string" && Array.isArray(variant.enum)) {
3195
+ enumVariantSets.push(
3196
+ variant.enum.filter((v) => typeof v === "string")
3197
+ );
3198
+ continue;
3199
+ }
3200
+ if (type2 === "string" || type2 === "number" || type2 === "boolean") {
3201
+ scalarTypes.add(type2);
3202
+ continue;
3203
+ }
3204
+ if (type2 === "object" && isRecord4(variant.properties)) {
3205
+ const declared = readBlockKindFromProperties(variant.properties);
3206
+ if (declared) {
3207
+ memberKinds.push(declared);
3208
+ registerDeclaredKindDraft(declared, variant, `${path}<${declared}>`, ctx);
3209
+ } else {
3210
+ anonymousObjects.push(variant);
3211
+ }
3212
+ continue;
3213
+ }
3214
+ unsupported = true;
3215
+ }
3216
+ if (unsupported) {
3217
+ ctx.problems.push({
3218
+ severity: "error",
3219
+ path,
3220
+ message: "anyOf/oneOf with unsupported variants cannot be converted automatically."
3221
+ });
3222
+ return null;
3223
+ }
3224
+ if (enumVariantSets.length > 0 && anonymousObjects.length === 0 && memberKinds.length === 0 && [...scalarTypes].every((s) => s === "string")) {
3225
+ const values = [...new Set(enumVariantSets.flat())];
3226
+ const open = scalarTypes.has("string");
3227
+ return {
3228
+ ...requiredNullableFlags(required, sawNull),
3229
+ type: "enum",
3230
+ values,
3231
+ ...open ? { open: true } : {}
3232
+ };
3233
+ }
3234
+ if (enumVariantSets.length > 0) {
3235
+ ctx.problems.push({
3236
+ severity: "warning",
3237
+ path,
3238
+ message: "anyOf/oneOf mixes an enum variant with non-string members \u2014 enum widened to string within the union."
3239
+ });
3240
+ scalarTypes.add("string");
3241
+ }
3242
+ if (anonymousObjects.length === 1 && scalarTypes.size === 0 && memberKinds.length === 0) {
3243
+ const [sole] = anonymousObjects;
3244
+ const converted = sole ? convertProperty(fieldName, sole, required, path, ctx) : null;
3245
+ if (!converted) return null;
3246
+ return sawNull ? { ...converted, nullable: true } : converted;
3247
+ }
3248
+ if (anonymousObjects.length > 0) {
3249
+ ctx.problems.push({
3250
+ severity: "error",
3251
+ path,
3252
+ message: "anyOf/oneOf mixing anonymous objects with other variants cannot be converted \u2014 declare __kind on each object variant."
3253
+ });
3254
+ return null;
3255
+ }
3256
+ if (scalarTypes.size === 1 && memberKinds.length === 0) {
3257
+ const [scalar] = [...scalarTypes];
3258
+ if (scalar) {
3259
+ return { ...requiredNullableFlags(required, sawNull), type: scalar };
3260
+ }
3261
+ }
3262
+ if (scalarTypes.size > 0 || memberKinds.length > 0) {
3263
+ ctx.problems.push({
3264
+ severity: "warning",
3265
+ path,
3266
+ message: `Converted anyOf/oneOf to union of: ${[
3267
+ ...scalarTypes,
3268
+ ...memberKinds
3269
+ ].join(", ")}.`
3270
+ });
3271
+ return {
3272
+ ...requiredNullableFlags(required, sawNull),
3273
+ type: "union",
3274
+ scalars: [...scalarTypes],
3275
+ ...memberKinds.length > 0 ? { kinds: memberKinds } : {}
3276
+ };
3277
+ }
3278
+ ctx.problems.push({
3279
+ severity: "warning",
3280
+ path,
3281
+ message: "anyOf/oneOf carried only null variants \u2014 widened to json (any value)."
3282
+ });
3283
+ return { ...requiredNullableFlags(required), type: "json" };
3284
+ }
3285
+ if (Array.isArray(node.allOf)) {
3286
+ ctx.problems.push({
3287
+ severity: "warning",
3288
+ path,
3289
+ message: "allOf merged using first object branch only."
3290
+ });
3291
+ const objectBranch = node.allOf.find(
3292
+ (b) => b.properties
3293
+ );
3294
+ if (objectBranch) {
3295
+ return convertProperty(fieldName, objectBranch, required, path, ctx);
3296
+ }
3297
+ }
3298
+ if (isAnyValueSchema(node)) {
3299
+ ctx.problems.push({
3300
+ severity: "info",
3301
+ path,
3302
+ message: `Typeless schema at "${path || "(root)"}" \u2014 any JSON value (json).`
3303
+ });
3304
+ return { ...requiredNullableFlags(required), type: "json" };
3305
+ }
3306
+ const { type, nullable } = resolvePrimaryType(node);
3307
+ if (type === "string") {
3308
+ if (Array.isArray(node.enum)) {
3309
+ const values = node.enum.filter(
3310
+ (v) => typeof v === "string"
3311
+ );
3312
+ if (values.length !== node.enum.length) {
3313
+ ctx.problems.push({
3314
+ severity: "warning",
3315
+ path,
3316
+ message: "Enum contains non-string values; non-strings dropped."
3317
+ });
3318
+ }
3319
+ return {
3320
+ ...requiredNullableFlags(required, nullable),
3321
+ type: "enum",
3322
+ values
3323
+ };
3324
+ }
3325
+ return {
3326
+ ...requiredNullableFlags(required, nullable),
3327
+ type: "string"
3328
+ };
3329
+ }
3330
+ if (type === "number") {
3331
+ return {
3332
+ ...requiredNullableFlags(required, nullable),
3333
+ type: "number"
3334
+ };
3335
+ }
3336
+ if (type === "boolean") {
3337
+ return {
3338
+ ...requiredNullableFlags(required, nullable),
3339
+ type: "boolean"
3340
+ };
3341
+ }
3342
+ if (type === "array") {
3343
+ const items = node.items;
3344
+ if (!items) {
3345
+ ctx.problems.push({
3346
+ severity: "error",
3347
+ path,
3348
+ message: "Array field is missing items schema."
3349
+ });
3350
+ return null;
3351
+ }
3352
+ const itemNode = Array.isArray(items) ? items[0] : items;
3353
+ if (!isRecord4(itemNode)) {
3354
+ ctx.problems.push({
3355
+ severity: "error",
3356
+ path,
3357
+ message: "Array items schema must be an object."
3358
+ });
3359
+ return null;
3360
+ }
3361
+ if (isAnyValueSchema(itemNode)) {
3362
+ return {
3363
+ ...requiredNullableFlags(required, nullable),
3364
+ type: "json[]"
3365
+ };
3366
+ }
3367
+ const itemVariants = Array.isArray(itemNode.anyOf) ? itemNode.anyOf : Array.isArray(itemNode.oneOf) ? itemNode.oneOf : null;
3368
+ if (itemVariants) {
3369
+ const itemEnumSets = [];
3370
+ let itemPlainString = false;
3371
+ let itemsAllString = true;
3372
+ for (const variant of itemVariants) {
3373
+ if (!isRecord4(variant) || resolvePrimaryType(variant).type !== "string") {
3374
+ itemsAllString = false;
3375
+ break;
3376
+ }
3377
+ if (Array.isArray(variant.enum)) {
3378
+ itemEnumSets.push(
3379
+ variant.enum.filter((v) => typeof v === "string")
3380
+ );
3381
+ } else {
3382
+ itemPlainString = true;
3383
+ }
3384
+ }
3385
+ if (itemsAllString && itemEnumSets.length > 0) {
3386
+ return {
3387
+ ...requiredNullableFlags(required, nullable),
3388
+ type: "string[]",
3389
+ values: [...new Set(itemEnumSets.flat())],
3390
+ ...itemPlainString ? { open: true } : {}
3391
+ };
3392
+ }
3393
+ const itemKinds = [];
3394
+ for (const variant of itemVariants) {
3395
+ if (!isRecord4(variant) || !isRecord4(variant.properties)) {
3396
+ ctx.problems.push({
3397
+ severity: "error",
3398
+ path: `${path}[]`,
3399
+ message: "Array items anyOf/oneOf variants must be inline objects declaring __kind."
3400
+ });
3401
+ return null;
3402
+ }
3403
+ const declared = readBlockKindFromProperties(variant.properties);
3404
+ if (!declared) {
3405
+ ctx.problems.push({
3406
+ severity: "error",
3407
+ path: `${path}[]`,
3408
+ message: "Array items anyOf/oneOf variant is missing a __kind const/enum declaration."
3409
+ });
3410
+ return null;
3411
+ }
3412
+ itemKinds.push(declared);
3413
+ registerDeclaredKindDraft(declared, variant, `${path}[]<${declared}>`, ctx);
3414
+ ctx.arrayBindings.push({ arrayField: fieldName, itemKindSlug: declared });
3415
+ }
3416
+ return {
3417
+ ...requiredNullableFlags(required, nullable),
3418
+ type: "array",
3419
+ itemKinds
3420
+ };
3421
+ }
3422
+ const itemType = resolvePrimaryType(itemNode).type;
3423
+ if (itemType === "string") {
3424
+ if (Array.isArray(itemNode.enum)) {
3425
+ return {
3426
+ ...requiredNullableFlags(required, nullable),
3427
+ type: "string[]",
3428
+ values: itemNode.enum.filter(
3429
+ (v) => typeof v === "string"
3430
+ )
3431
+ };
3432
+ }
3433
+ return {
3434
+ ...requiredNullableFlags(required, nullable),
3435
+ type: "string[]"
3436
+ };
3437
+ }
3438
+ if (itemType === "number") {
3439
+ return {
3440
+ ...requiredNullableFlags(required, nullable),
3441
+ type: "number[]"
3442
+ };
3443
+ }
3444
+ if (itemType === "boolean") {
3445
+ return {
3446
+ ...requiredNullableFlags(required, nullable),
3447
+ type: "boolean[]"
3448
+ };
3449
+ }
3450
+ if (itemType === "object" && isRecord4(itemNode.properties)) {
3451
+ const declaredItemKind = readBlockKindFromProperties(itemNode.properties);
3452
+ const itemKindSlug = declaredItemKind ?? synthesizeItemKindSlug(ctx.schemaName, fieldName);
3453
+ const itemRequired = new Set(
3454
+ Array.isArray(itemNode.required) ? itemNode.required.filter((k) => typeof k === "string") : []
3455
+ );
3456
+ const itemFields = {};
3457
+ for (const [propName, propNode] of Object.entries(itemNode.properties)) {
3458
+ if (!isRecord4(propNode)) continue;
3459
+ if (propName === KIND_KEY) continue;
3460
+ const converted = convertProperty(
3461
+ propName,
3462
+ propNode,
3463
+ itemRequired.has(propName),
3464
+ `${path}[].${propName}`,
3465
+ ctx
3466
+ );
3467
+ if (converted) {
3468
+ itemFields[propName] = converted;
3469
+ }
3470
+ }
3471
+ const alreadyHasBlockKind = propNameIsBlockKind(itemNode.properties) || itemRequired.has(KIND_KEY);
3472
+ ctx.arrayBindings.push({
3473
+ arrayField: fieldName,
3474
+ itemKindSlug
3475
+ });
3476
+ if (!ctx.blockSchemas.some((draft) => draft.slug === itemKindSlug)) {
3477
+ ctx.blockSchemas.push({
3478
+ slug: itemKindSlug,
3479
+ label: declaredItemKind ? formatBlockLabel(itemKindSlug) : formatBlockLabel(`${ctx.schemaName}_${fieldName}_item`),
3480
+ fields: itemFields
3481
+ });
3482
+ }
3483
+ if (!alreadyHasBlockKind) {
3484
+ ctx.problems.push({
3485
+ severity: "warning",
3486
+ path: `${path}[]`,
3487
+ message: `Array "${fieldName}" items need __kind:"${itemKindSlug}" at runtime (OPTION 1: server injects, OPTION 2: use agent schema with __kind).`
3488
+ });
3489
+ }
3490
+ return {
3491
+ ...requiredNullableFlags(required, nullable),
3492
+ type: "array",
3493
+ itemKinds: [itemKindSlug]
3494
+ };
3495
+ }
3496
+ ctx.problems.push({
3497
+ severity: "error",
3498
+ path,
3499
+ message: `Unsupported array items type "${itemType ?? "unknown"}".`
3500
+ });
3501
+ return null;
3502
+ }
3503
+ if (type === "object") {
3504
+ const ap = node.additionalProperties;
3505
+ const apIsOpen = ap === true || isRecord4(ap) && isAnyValueSchema(ap);
3506
+ if (isRecord4(node.properties)) {
3507
+ const nestedRequired = new Set(
3508
+ Array.isArray(node.required) ? node.required.filter((k) => typeof k === "string") : []
3509
+ );
3510
+ const nestedFields = {};
3511
+ for (const [propName, propNode] of Object.entries(node.properties)) {
3512
+ if (!isRecord4(propNode)) continue;
3513
+ if (propName === KIND_KEY) continue;
3514
+ const converted = convertProperty(
3515
+ propName,
3516
+ propNode,
3517
+ nestedRequired.has(propName),
3518
+ `${path}.${propName}`,
3519
+ ctx
3520
+ );
3521
+ if (converted) {
3522
+ nestedFields[propName] = converted;
3523
+ }
3524
+ }
3525
+ const referencedKind = readBlockKindFromProperties(node.properties);
3526
+ if (referencedKind) {
3527
+ return {
3528
+ ...requiredNullableFlags(required, nullable),
3529
+ type: "object",
3530
+ kind: referencedKind
3531
+ };
3532
+ }
3533
+ let open = apIsOpen;
3534
+ if (!apIsOpen && isRecord4(ap)) {
3535
+ ctx.problems.push({
3536
+ severity: "warning",
3537
+ path,
3538
+ message: "Typed additionalProperties alongside declared properties is not representable \u2014 treated as an OPEN object (extra values unconstrained)."
3539
+ });
3540
+ open = true;
3541
+ } else if (ap === false) {
3542
+ ctx.droppedMetadata.push({
3543
+ path,
3544
+ dropped: { additionalProperties: false }
3545
+ });
3546
+ }
3547
+ return {
3548
+ ...requiredNullableFlags(required, nullable),
3549
+ type: "inline_object",
3550
+ fields: nestedFields,
3551
+ ...open ? { open: true } : {}
3552
+ };
3553
+ }
3554
+ if (apIsOpen || ap === void 0) {
3555
+ if (ap === void 0) {
3556
+ ctx.problems.push({
3557
+ severity: "info",
3558
+ path,
3559
+ message: `Bare object schema at "${path || "(root)"}" \u2014 record of any JSON values.`
3560
+ });
3561
+ }
3562
+ return {
3563
+ ...requiredNullableFlags(required, nullable),
3564
+ type: "record",
3565
+ values: "json"
3566
+ };
3567
+ }
3568
+ if (isRecord4(ap)) {
3569
+ const apType = resolvePrimaryType(ap).type;
3570
+ if (apType === "string" || apType === "number" || apType === "boolean") {
3571
+ return {
3572
+ ...requiredNullableFlags(required, nullable),
3573
+ type: "record",
3574
+ values: apType
3575
+ };
3576
+ }
3577
+ ctx.problems.push({
3578
+ severity: "warning",
3579
+ path,
3580
+ message: `Record value schema at "${path}" is not scalar \u2014 widened to record of any JSON values.`
3581
+ });
3582
+ return {
3583
+ ...requiredNullableFlags(required, nullable),
3584
+ type: "record",
3585
+ values: "json"
3586
+ };
3587
+ }
3588
+ return {
3589
+ ...requiredNullableFlags(required, nullable),
3590
+ type: "inline_object",
3591
+ fields: {}
3592
+ };
3593
+ }
3594
+ ctx.problems.push({
3595
+ severity: "error",
3596
+ path,
3597
+ message: `Unsupported or missing JSON Schema type at "${path}".`
3598
+ });
3599
+ return null;
3600
+ }
3601
+ function propNameIsBlockKind(properties) {
3602
+ return KIND_KEY in properties;
3603
+ }
3604
+ function readBlockKindFromProperties(properties) {
3605
+ const kindProp = properties[KIND_KEY];
3606
+ if (!isRecord4(kindProp)) return null;
3607
+ if (typeof kindProp.const === "string") return kindProp.const;
3608
+ if (Array.isArray(kindProp.enum) && typeof kindProp.enum[0] === "string") {
3609
+ return kindProp.enum[0];
3610
+ }
3611
+ return null;
3612
+ }
3613
+ function normalizeAiSchemaInput(input) {
3614
+ const parseErrors = [];
3615
+ if (!isRecord4(input)) {
3616
+ return {
3617
+ name: null,
3618
+ strict: null,
3619
+ rootSchema: null,
3620
+ parseErrors: ["Input must be a JSON object."]
3621
+ };
3622
+ }
3623
+ if (isRecord4(input.json_schema)) {
3624
+ return normalizeAiSchemaInput(input.json_schema);
3625
+ }
3626
+ if (isRecord4(input.schema) && typeof input.name === "string") {
3627
+ return {
3628
+ name: input.name,
3629
+ strict: typeof input.strict === "boolean" ? input.strict : null,
3630
+ rootSchema: input.schema,
3631
+ parseErrors: []
3632
+ };
3633
+ }
3634
+ if (typeof input.type === "string" || Array.isArray(input.type) || input.properties || input.items) {
3635
+ const name = typeof input.name === "string" ? input.name : typeof input.title === "string" ? input.title : null;
3636
+ return {
3637
+ name,
3638
+ strict: typeof input.strict === "boolean" ? input.strict : null,
3639
+ rootSchema: input,
3640
+ parseErrors: []
3641
+ };
3642
+ }
3643
+ parseErrors.push(
3644
+ "Expected OpenAI output_schema shape { name, schema } or a root JSON Schema object."
3645
+ );
3646
+ return { name: null, strict: null, rootSchema: null, parseErrors };
3647
+ }
3648
+ function convertAiSchemaToBlockFields(schemaName, rootSchema, strict) {
3649
+ const ctx = {
3650
+ schemaName,
3651
+ problems: [],
3652
+ droppedMetadata: [],
3653
+ blockSchemas: [],
3654
+ arrayBindings: []
3655
+ };
3656
+ ctx.droppedMetadata.push(...collectDropped(rootSchema, ""));
3657
+ const rootAp = rootSchema.additionalProperties;
3658
+ const rootIsOpen = rootAp === true || isRecord4(rootAp) && isAnyValueSchema(rootAp);
3659
+ const properties = rootSchema.properties;
3660
+ if (!isRecord4(properties) || rootIsOpen) {
3661
+ const rootField = convertProperty("$root", rootSchema, false, "$root", ctx);
3662
+ if (!rootField) {
3663
+ ctx.problems.push({
3664
+ severity: "error",
3665
+ path: "",
3666
+ message: "Root schema could not be converted (see problems above) \u2014 expected an object with properties, a scalar/array/json root, or an open object."
3667
+ });
3668
+ return emptyConversionResult(schemaName, strict, ctx);
3669
+ }
3670
+ ctx.blockSchemas.unshift({
3671
+ slug: schemaName,
3672
+ label: formatBlockLabel(schemaName),
3673
+ fields: {},
3674
+ root: rootField
3675
+ });
3676
+ return {
3677
+ schemaName,
3678
+ strict,
3679
+ blockSchemas: ctx.blockSchemas,
3680
+ problems: ctx.problems,
3681
+ droppedMetadata: ctx.droppedMetadata
3682
+ };
3683
+ }
3684
+ const required = new Set(
3685
+ Array.isArray(rootSchema.required) ? rootSchema.required.filter((k) => typeof k === "string") : []
3686
+ );
3687
+ const convertedFields = {};
3688
+ for (const [fieldName, fieldNode] of Object.entries(properties)) {
3689
+ if (!isRecord4(fieldNode)) continue;
3690
+ if (fieldName === KIND_KEY) continue;
3691
+ const converted = convertProperty(
3692
+ fieldName,
3693
+ fieldNode,
3694
+ required.has(fieldName),
3695
+ fieldName,
3696
+ ctx
3697
+ );
3698
+ if (converted) {
3699
+ convertedFields[fieldName] = converted;
3700
+ }
3701
+ }
3702
+ const rootHasKind = propNameIsBlockKind(properties) || required.has(KIND_KEY);
3703
+ if (!rootHasKind) {
3704
+ ctx.problems.push({
3705
+ severity: "warning",
3706
+ path: "",
3707
+ message: `Root object needs __kind:"${schemaName}" at runtime (OPTION 1: server injects, OPTION 2: use agent schema with __kind).`
3708
+ });
3709
+ }
3710
+ const rootDraft = {
3711
+ slug: schemaName,
3712
+ label: formatBlockLabel(schemaName),
3713
+ fields: convertedFields
3714
+ };
3715
+ ctx.blockSchemas.unshift(rootDraft);
3716
+ if (typeof rootSchema.additionalProperties === "boolean") {
3717
+ ctx.droppedMetadata.push({
3718
+ path: "",
3719
+ dropped: { additionalProperties: rootSchema.additionalProperties }
3720
+ });
3721
+ }
3722
+ if (strict) {
3723
+ ctx.droppedMetadata.push({
3724
+ path: "",
3725
+ dropped: { strict }
3726
+ });
3727
+ }
3728
+ return {
3729
+ schemaName,
3730
+ strict,
3731
+ blockSchemas: ctx.blockSchemas,
3732
+ problems: ctx.problems,
3733
+ droppedMetadata: ctx.droppedMetadata
3734
+ };
3735
+ }
3736
+ function emptyConversionResult(schemaName, strict, ctx) {
3737
+ return {
3738
+ schemaName,
3739
+ strict,
3740
+ blockSchemas: ctx.blockSchemas,
3741
+ problems: ctx.problems,
3742
+ droppedMetadata: ctx.droppedMetadata
3743
+ };
3744
+ }
3745
+ function compareFieldSchemas(aiField, blockField, fieldName) {
3746
+ const aiPresent = aiField !== void 0;
3747
+ const blockPresent = blockField !== void 0;
3748
+ const aiSummary = aiField ? fieldSchemaSummary(aiField) : null;
3749
+ const blockSummary = blockField ? fieldSchemaSummary(blockField) : null;
3750
+ if (aiPresent && blockPresent) {
3751
+ if (aiSummary === blockSummary) {
3752
+ return {
3753
+ field: fieldName,
3754
+ aiPresent,
3755
+ blockPresent,
3756
+ aiSummary,
3757
+ blockSummary,
3758
+ status: "match"
3759
+ };
3760
+ }
3761
+ const aiRicher = aiField?.type === "enum" && blockField?.type === "string" || aiField?.type === "inline_object" && blockField?.type !== "inline_object";
3762
+ const blockRicher = blockField?.type === "enum" && aiField?.type === "string" || blockField?.required && !aiField?.required;
3763
+ return {
3764
+ field: fieldName,
3765
+ aiPresent,
3766
+ blockPresent,
3767
+ aiSummary,
3768
+ blockSummary,
3769
+ status: aiRicher ? "ai_richer" : blockRicher ? "block_richer" : "type_mismatch",
3770
+ ...aiSummary !== blockSummary && {
3771
+ detail: `${aiSummary} vs ${blockSummary}`
3772
+ }
3773
+ };
3774
+ }
3775
+ if (aiPresent) {
3776
+ return {
3777
+ field: fieldName,
3778
+ aiPresent,
3779
+ blockPresent,
3780
+ aiSummary,
3781
+ blockSummary,
3782
+ status: "ai_only"
3783
+ };
3784
+ }
3785
+ return {
3786
+ field: fieldName,
3787
+ aiPresent,
3788
+ blockPresent,
3789
+ aiSummary,
3790
+ blockSummary,
3791
+ status: "block_only"
3792
+ };
3793
+ }
3794
+ function compareWithExistingKindSchema(convertedFields, existing) {
3795
+ if (!existing) return [];
3796
+ const allFields = /* @__PURE__ */ new Set([
3797
+ ...Object.keys(convertedFields),
3798
+ ...Object.keys(existing.fields)
3799
+ ]);
3800
+ return [...allFields].sort().map(
3801
+ (field) => compareFieldSchemas(
3802
+ convertedFields[field],
3803
+ existing.fields[field],
3804
+ field
3805
+ )
3806
+ );
3807
+ }
3808
+ function runSchemaConversion(input, existingSchemas) {
3809
+ const normalized = normalizeAiSchemaInput(input);
3810
+ if (!normalized.rootSchema || !normalized.name) {
3811
+ return {
3812
+ schemaName: normalized.name,
3813
+ strict: normalized.strict,
3814
+ blockSchemas: [],
3815
+ agentSchemaWithKinds: null,
3816
+ problems: [],
3817
+ droppedMetadata: [],
3818
+ comparisons: [],
3819
+ parseErrors: normalized.parseErrors.length ? normalized.parseErrors : ["Schema name and root schema are required."]
3820
+ };
3821
+ }
3822
+ const strict = normalized.strict ?? false;
3823
+ const core = convertAiSchemaToBlockFields(
3824
+ normalized.name,
3825
+ normalized.rootSchema,
3826
+ strict
3827
+ );
3828
+ const existing = existingSchemas[normalized.name] ?? null;
3829
+ const rootDraft = core.blockSchemas[0];
3830
+ const comparisons = rootDraft ? compareWithExistingKindSchema(rootDraft.fields, existing) : [];
3831
+ const problems = [...core.problems];
3832
+ if (!existing) {
3833
+ problems.push({
3834
+ severity: "info",
3835
+ path: "",
3836
+ message: `No existing block schema with slug "${normalized.name}".`
3837
+ });
3838
+ }
3839
+ const agentSchemaWithKinds = buildAgentSchemaWithRenderBlockSupport(
3840
+ input,
3841
+ normalized.name,
3842
+ collectArrayBindingsFromDrafts(core.blockSchemas, normalized.name),
3843
+ strict
3844
+ );
3845
+ return {
3846
+ ...core,
3847
+ agentSchemaWithKinds,
3848
+ comparisons,
3849
+ problems,
3850
+ parseErrors: []
3851
+ };
3852
+ }
3853
+ function collectArrayBindingsFromDrafts(drafts, rootSlug) {
3854
+ const root = drafts.find((d) => d.slug === rootSlug);
3855
+ if (!root) return [];
3856
+ const bindings = [];
3857
+ for (const [fieldName, field] of Object.entries(root.fields)) {
3858
+ if (field.type !== "array") continue;
3859
+ for (const itemKind of field.itemKinds) {
3860
+ bindings.push({ arrayField: fieldName, itemKindSlug: itemKind });
3861
+ }
3862
+ }
3863
+ return bindings;
3864
+ }
3865
+ function validateBlockSchemaSavePlan(blockSchemas, existingSlugs, hasConversionErrors) {
3866
+ const errors = [];
3867
+ const normalizedExisting = new Set(
3868
+ existingSlugs.map((s) => s.trim().toLowerCase())
3869
+ );
3870
+ const batchSlugs = /* @__PURE__ */ new Set();
3871
+ const itemKindRefs = [];
3872
+ for (const draft of blockSchemas) {
3873
+ const slug = draft.slug.trim();
3874
+ const normalized = slug.toLowerCase();
3875
+ if (!slug) {
3876
+ errors.push("Every block schema must have a non-empty slug.");
3877
+ continue;
3878
+ }
3879
+ if (batchSlugs.has(normalized)) {
3880
+ errors.push(`Duplicate slug in conversion batch: "${slug}".`);
3881
+ }
3882
+ batchSlugs.add(normalized);
3883
+ }
3884
+ const entries = blockSchemas.map((draft) => {
3885
+ const existsInDb = normalizedExisting.has(draft.slug.trim().toLowerCase());
3886
+ return {
3887
+ draft,
3888
+ existsInDb,
3889
+ willSave: !existsInDb
3890
+ };
3891
+ });
3892
+ for (const draft of blockSchemas) {
3893
+ for (const [fieldName, field] of Object.entries(draft.fields)) {
3894
+ if (field.type !== "array") continue;
3895
+ for (const itemKind of field.itemKinds) {
3896
+ const inBatch = batchSlugs.has(itemKind.trim().toLowerCase());
3897
+ const inDb = normalizedExisting.has(itemKind.trim().toLowerCase());
3898
+ const satisfied = inBatch || inDb;
3899
+ itemKindRefs.push({
3900
+ parentSlug: draft.slug,
3901
+ field: fieldName,
3902
+ itemKind,
3903
+ satisfied,
3904
+ source: inBatch ? "batch" : inDb ? "database" : "missing"
3905
+ });
3906
+ if (!satisfied) {
3907
+ errors.push(
3908
+ `"${draft.slug}".${fieldName} references itemKind "${itemKind}" \u2014 not in this batch and not in DB.`
3909
+ );
3910
+ }
3911
+ }
3912
+ }
3913
+ }
3914
+ const newCount = entries.filter((e) => e.willSave).length;
3915
+ if (newCount === 0 && blockSchemas.length > 0) {
3916
+ errors.push("All block schema slugs already exist in the database.");
3917
+ }
3918
+ if (hasConversionErrors) {
3919
+ errors.push("Resolve conversion errors before saving.");
3920
+ }
3921
+ return {
3922
+ entries,
3923
+ itemKindRefs,
3924
+ newCount,
3925
+ canSave: errors.length === 0 && newCount > 0,
3926
+ errors
3927
+ };
3928
+ }
3929
+ function fieldsToDbPayload(fields) {
3930
+ return JSON.parse(JSON.stringify(fields));
3931
+ }
3932
+ function isDuplicateBlockSlug(slug, entries) {
3933
+ const normalized = slug.trim().toLowerCase();
3934
+ return entries.some((e) => e.slug.trim().toLowerCase() === normalized);
3935
+ }
3936
+
3937
+ // convert/kind-to-json-schema.ts
3938
+ function collectReferencedKinds(fields) {
3939
+ const out = [];
3940
+ const seen = /* @__PURE__ */ new Set();
3941
+ const add = (kind) => {
3942
+ if (!seen.has(kind)) {
3943
+ seen.add(kind);
3944
+ out.push(kind);
3945
+ }
3946
+ };
3947
+ const visit = (field) => {
3948
+ if (field.type === "object") {
3949
+ add(field.kind);
3950
+ } else if (field.type === "array") {
3951
+ field.itemKinds.forEach(add);
3952
+ } else if (field.type === "union") {
3953
+ (field.kinds ?? []).forEach(add);
3954
+ } else if (field.type === "inline_object") {
3955
+ Object.values(field.fields).forEach(visit);
3956
+ }
3957
+ };
3958
+ Object.values(fields).forEach(visit);
3959
+ return out;
3960
+ }
3961
+ function collectSchemaReferencedKinds(schema) {
3962
+ if (!schema.root) return collectReferencedKinds(schema.fields);
3963
+ return collectReferencedKinds({ [ROOT_REF_FIELD]: schema.root });
3964
+ }
3965
+ var ROOT_REF_FIELD = "__root";
3966
+ function kindSchemaToJsonSchema(kind, resolve, options = {}) {
3967
+ const strict = options.strict ?? false;
3968
+ const injectKind = options.injectKind ?? true;
3969
+ const rootSchema = resolve(kind);
3970
+ if (!rootSchema) return null;
3971
+ const visited = /* @__PURE__ */ new Set([kind]);
3972
+ const defsOrder = [];
3973
+ const resolvedDefs = /* @__PURE__ */ new Map();
3974
+ const unresolved = [];
3975
+ const queue = collectSchemaReferencedKinds(rootSchema);
3976
+ while (queue.length > 0) {
3977
+ const next = queue.shift();
3978
+ if (visited.has(next)) continue;
3979
+ visited.add(next);
3980
+ defsOrder.push(next);
3981
+ const schema = resolve(next);
3982
+ if (!schema) {
3983
+ unresolved.push(next);
3984
+ continue;
3985
+ }
3986
+ resolvedDefs.set(next, schema);
3987
+ queue.push(...collectSchemaReferencedKinds(schema));
3988
+ }
3989
+ const refFor = (slug) => slug === kind ? { $ref: "#" } : { $ref: `#/$defs/${slug}` };
3990
+ const withNull = (type, nullable) => nullable ? [type, "null"] : type;
3991
+ function fieldToJsonSchema(field) {
3992
+ const node = fieldToJsonSchemaCore(field);
3993
+ if (field.description !== void 0) node.description = field.description;
3994
+ if (field.default !== void 0) node.default = field.default;
3995
+ return node;
3996
+ }
3997
+ function fieldToJsonSchemaCore(field) {
3998
+ switch (field.type) {
3999
+ case "string":
4000
+ case "boolean":
4001
+ return { type: withNull(field.type, field.nullable) };
4002
+ case "number":
4003
+ return {
4004
+ type: withNull("number", field.nullable),
4005
+ ...!strict && field.min !== void 0 ? { minimum: field.min } : {},
4006
+ ...!strict && field.max !== void 0 ? { maximum: field.max } : {},
4007
+ ...!strict && field.step !== void 0 ? { multipleOf: field.step } : {}
4008
+ };
4009
+ case "json":
4010
+ return {};
4011
+ case "string[]": {
4012
+ const items = field.values === void 0 ? { type: "string" } : field.open ? {
4013
+ anyOf: [
4014
+ { type: "string", enum: [...field.values] },
4015
+ { type: "string" }
4016
+ ]
4017
+ } : { type: "string", enum: [...field.values] };
4018
+ return { type: withNull("array", field.nullable), items };
4019
+ }
4020
+ case "number[]":
4021
+ case "boolean[]":
4022
+ return {
4023
+ type: withNull("array", field.nullable),
4024
+ items: { type: scalarArrayItemType(field.type) }
4025
+ };
4026
+ case "json[]":
4027
+ return {
4028
+ type: withNull("array", field.nullable),
4029
+ items: {}
4030
+ };
4031
+ case "enum": {
4032
+ if (!field.open) {
4033
+ return {
4034
+ type: withNull("string", field.nullable),
4035
+ enum: [...field.values]
4036
+ };
4037
+ }
4038
+ const variants = [
4039
+ { type: "string", enum: [...field.values] },
4040
+ { type: "string" }
4041
+ ];
4042
+ if (field.nullable) variants.push({ type: "null" });
4043
+ return { anyOf: variants };
4044
+ }
4045
+ case "union": {
4046
+ const variants = field.scalars.map((scalar) => ({
4047
+ type: scalar
4048
+ }));
4049
+ for (const memberKind of field.kinds ?? []) {
4050
+ variants.push(refFor(memberKind));
4051
+ }
4052
+ if (field.nullable) variants.push({ type: "null" });
4053
+ return { anyOf: variants };
4054
+ }
4055
+ case "record":
4056
+ return {
4057
+ type: withNull("object", field.nullable),
4058
+ additionalProperties: field.values === "json" ? true : { type: field.values }
4059
+ };
4060
+ case "inline_object": {
4061
+ const properties = {};
4062
+ const required = [];
4063
+ for (const [name, child] of Object.entries(field.fields)) {
4064
+ properties[name] = fieldToJsonSchema(child);
4065
+ if (child.required) required.push(name);
4066
+ }
4067
+ return {
4068
+ type: withNull("object", field.nullable),
4069
+ properties,
4070
+ required,
4071
+ ...field.open ? { additionalProperties: true } : strict ? { additionalProperties: false } : {}
4072
+ };
4073
+ }
4074
+ case "object":
4075
+ return field.nullable ? { anyOf: [refFor(field.kind), { type: "null" }] } : refFor(field.kind);
4076
+ case "array": {
4077
+ const [soleItemKind] = field.itemKinds;
4078
+ const items = field.itemKinds.length === 1 && soleItemKind !== void 0 ? refFor(soleItemKind) : { anyOf: field.itemKinds.map(refFor) };
4079
+ return { type: withNull("array", field.nullable), items };
4080
+ }
4081
+ }
4082
+ }
4083
+ function kindObjectSchema(schema) {
4084
+ if (schema.root) {
4085
+ return fieldToJsonSchema(schema.root);
4086
+ }
4087
+ const properties = {};
4088
+ const required = [];
4089
+ for (const [name, field] of Object.entries(schema.fields)) {
4090
+ properties[name] = fieldToJsonSchema(field);
4091
+ if (field.required) required.push(name);
4092
+ }
4093
+ const node = {
4094
+ type: "object",
4095
+ properties,
4096
+ required,
4097
+ ...strict ? { additionalProperties: false } : {}
4098
+ };
4099
+ return injectKind ? injectKindIntoObjectSchema(node, schema.kind, strict) : node;
4100
+ }
4101
+ function unresolvedStub(slug) {
4102
+ const node = {
4103
+ type: "object",
4104
+ description: `Unresolved kind "${slug}" \u2014 schema not available at export time.`
4105
+ };
4106
+ return injectKind ? injectKindIntoObjectSchema(node, slug, false) : node;
4107
+ }
4108
+ const rootNode = kindObjectSchema(rootSchema);
4109
+ if (defsOrder.length === 0) {
4110
+ return { name: kind, schema: rootNode, strict, unresolved };
4111
+ }
4112
+ const defs = {};
4113
+ for (const slug of defsOrder) {
4114
+ const schema = resolvedDefs.get(slug);
4115
+ defs[slug] = schema ? kindObjectSchema(schema) : unresolvedStub(slug);
4116
+ }
4117
+ return { name: kind, schema: { ...rootNode, $defs: defs }, strict, unresolved };
4118
+ }
4119
+
4120
+ // wire/partial-kind.ts
4121
+ var IR_PARTIAL_KEY = "__ir_partial";
4122
+ var PARTIAL_STATES = [
4123
+ "partial",
4124
+ "superseded",
4125
+ "retracted"
4126
+ ];
4127
+ function isRecord5(value) {
4128
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4129
+ }
4130
+ function readPath(value) {
4131
+ if (!Array.isArray(value)) return null;
4132
+ return value.every(
4133
+ (segment) => typeof segment === "string" || typeof segment === "number"
4134
+ ) ? value : null;
4135
+ }
4136
+ function readDiscriminator(value) {
4137
+ if (!isRecord5(value)) return null;
4138
+ if (value.format === "json" && value.key === "__kind") {
4139
+ return { format: "json", key: "__kind" };
4140
+ }
4141
+ if (value.format === "xml" && typeof value.tag === "string") {
4142
+ return { format: "xml", tag: value.tag };
4143
+ }
4144
+ if (value.format === "fence" && typeof value.language === "string") {
4145
+ return { format: "fence", language: value.language };
4146
+ }
4147
+ return null;
4148
+ }
4149
+ function readResidue(value) {
4150
+ if (value === null) return null;
4151
+ if (!isRecord5(value)) return void 0;
4152
+ const extra = value.extra;
4153
+ const optionalMissing = value.optionalMissing;
4154
+ const notices = value.notices;
4155
+ if (extra !== null && !isRecord5(extra)) return void 0;
4156
+ if (optionalMissing !== null && (!Array.isArray(optionalMissing) || !optionalMissing.every((item) => typeof item === "string"))) {
4157
+ return void 0;
4158
+ }
4159
+ if (notices !== null && (!Array.isArray(notices) || !notices.every(
4160
+ (notice) => isRecord5(notice) && typeof notice.code === "string" && typeof notice.message === "string" && (notice.at === void 0 || typeof notice.at === "number")
4161
+ ))) {
4162
+ return void 0;
4163
+ }
4164
+ return { extra, optionalMissing, notices };
4165
+ }
4166
+ function readPartialKindEvent(metadata) {
4167
+ if (!isRecord5(metadata)) return null;
4168
+ const candidate = metadata[IR_PARTIAL_KEY];
4169
+ if (!isRecord5(candidate)) return null;
4170
+ if (candidate.v !== IR_VERSION) return null;
4171
+ if (typeof candidate.engine !== "string") return null;
4172
+ if (typeof candidate.seq !== "number" || !Number.isFinite(candidate.seq)) {
4173
+ return null;
4174
+ }
4175
+ const state = candidate.state;
4176
+ if (typeof state !== "string") return null;
4177
+ if (!PARTIAL_STATES.includes(state)) return null;
4178
+ if (state === "partial") {
4179
+ const root = candidate.root;
4180
+ if (!isRecord5(root)) return null;
4181
+ if (root.role !== "structured") return null;
4182
+ if (root.status !== "streaming") return null;
4183
+ if (root.kindState !== "speculative") return null;
4184
+ if (typeof root.kind !== "string" || !root.kind) return null;
4185
+ if (!isRecord5(root.value)) return null;
4186
+ const discriminator = readDiscriminator(root.discriminator);
4187
+ const path = readPath(root.path);
4188
+ const residue = readResidue(root.residue);
4189
+ if (discriminator === null || path === null || residue === void 0) {
4190
+ return null;
4191
+ }
4192
+ return {
4193
+ v: IR_VERSION,
4194
+ engine: candidate.engine,
4195
+ state: "partial",
4196
+ seq: candidate.seq,
4197
+ fingerprint: typeof candidate.fingerprint === "string" ? candidate.fingerprint : "",
4198
+ root: {
4199
+ role: "structured",
4200
+ kind: root.kind,
4201
+ kindState: "speculative",
4202
+ discriminator,
4203
+ path,
4204
+ status: "streaming",
4205
+ value: root.value,
4206
+ residue
4207
+ }
4208
+ };
4209
+ }
4210
+ if (typeof candidate.kind !== "string" || !candidate.kind) return null;
4211
+ if (state === "superseded") {
4212
+ return {
4213
+ v: IR_VERSION,
4214
+ engine: candidate.engine,
4215
+ state: "superseded",
4216
+ seq: candidate.seq,
4217
+ kind: candidate.kind
4218
+ };
4219
+ }
4220
+ if (typeof candidate.reason !== "string" || !candidate.reason) return null;
4221
+ if (candidate.becameKind !== null && typeof candidate.becameKind !== "string") {
4222
+ return null;
4223
+ }
4224
+ if (candidate.becameBlockType !== null && typeof candidate.becameBlockType !== "string") {
4225
+ return null;
4226
+ }
4227
+ return {
4228
+ v: IR_VERSION,
4229
+ engine: candidate.engine,
4230
+ state: "retracted",
4231
+ seq: candidate.seq,
4232
+ kind: candidate.kind,
4233
+ reason: candidate.reason,
4234
+ becameKind: candidate.becameKind,
4235
+ becameBlockType: candidate.becameBlockType
4236
+ };
4237
+ }
4238
+ function sanitizeInboundPartialKindMetadata(metadata, context, hooks = {}) {
4239
+ if (!isRecord5(metadata) || !(IR_PARTIAL_KEY in metadata)) {
4240
+ return metadata ?? void 0;
4241
+ }
4242
+ if (readPartialKindEvent(metadata) !== null) return metadata;
4243
+ const { [IR_PARTIAL_KEY]: raw, ...rest } = metadata;
4244
+ hooks.reportMalformed?.({ blockId: context.blockId, raw });
4245
+ return rest;
4246
+ }
4247
+ function isProvisionalKind(event) {
4248
+ return event !== null && event.state === "partial";
4249
+ }
4250
+ function isTerminalKindEvent(event) {
4251
+ return event !== null && (event.state === "superseded" || event.state === "retracted");
4252
+ }
4253
+ function advancePartialKind(seen, blockId, event) {
4254
+ if (event === null) return null;
4255
+ const last = seen[blockId];
4256
+ if (last !== void 0 && event.seq <= last) return null;
4257
+ return event;
4258
+ }
4259
+ function makePartialKindStalenessGate() {
4260
+ const seen = {};
4261
+ const lastAccepted = {};
4262
+ const terminated = {};
4263
+ return (blockId, metadata) => {
4264
+ if (!isRecord5(metadata)) return metadata;
4265
+ if (!(IR_PARTIAL_KEY in metadata)) {
4266
+ const open = lastAccepted[blockId];
4267
+ if (terminated[blockId] || open === void 0) return metadata;
4268
+ return { ...metadata, [IR_PARTIAL_KEY]: open };
4269
+ }
4270
+ const parsed = readPartialKindEvent(metadata);
4271
+ if (parsed === null) return metadata;
4272
+ if (advancePartialKind(seen, blockId, parsed) !== null) {
4273
+ seen[blockId] = parsed.seq;
4274
+ lastAccepted[blockId] = metadata[IR_PARTIAL_KEY];
4275
+ if (isTerminalKindEvent(parsed)) terminated[blockId] = true;
4276
+ return metadata;
4277
+ }
4278
+ const carried = lastAccepted[blockId];
4279
+ if (carried === void 0 || carried === metadata[IR_PARTIAL_KEY]) {
4280
+ return metadata;
4281
+ }
4282
+ return { ...metadata, [IR_PARTIAL_KEY]: carried };
4283
+ };
4284
+ }
4285
+
4286
+ // wire/runtime-wrapper.ts
4287
+ var NODE_OUTCOME_KIND = "node_outcome";
4288
+ var RUN_RESULT_KIND = "run_result";
4289
+ function isRecord6(value) {
4290
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4291
+ }
4292
+ function str(source, key) {
4293
+ const value = source[key];
4294
+ return typeof value === "string" && value.length > 0 ? value : null;
4295
+ }
4296
+ function num(source, key) {
4297
+ const value = source[key];
4298
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
4299
+ }
4300
+ function bool(source, key) {
4301
+ const value = source[key];
4302
+ return typeof value === "boolean" ? value : null;
4303
+ }
4304
+ function strings(source, key) {
4305
+ const value = source[key];
4306
+ if (!Array.isArray(value)) return null;
4307
+ const out = value.filter((item) => typeof item === "string");
4308
+ return out.length > 0 ? out : null;
4309
+ }
4310
+ function readOutputRef(frame, ref) {
4311
+ let cursor = frame;
4312
+ for (const segment of ref.split(".")) {
4313
+ if (!isRecord6(cursor)) return void 0;
4314
+ if (!(segment in cursor)) return void 0;
4315
+ cursor = cursor[segment];
4316
+ }
4317
+ return cursor;
4318
+ }
4319
+ function rehydrateNodeOutcome(raw, frame) {
4320
+ if (!isRecord6(raw)) return null;
4321
+ if (raw[KIND_KEY] !== NODE_OUTCOME_KIND) return null;
4322
+ const ref = str(raw, "output_ref");
4323
+ const resolved = ref === null ? void 0 : readOutputRef(frame, ref);
4324
+ return readNodeOutcomeValue(
4325
+ resolved === void 0 ? raw : { ...raw, output: resolved }
4326
+ );
4327
+ }
4328
+ function readNodeOutcomeValue(raw) {
4329
+ if (!isRecord6(raw)) return null;
4330
+ const runId = str(raw, "run_id");
4331
+ const nodeId = str(raw, "node_id");
4332
+ if (!runId || !nodeId) return null;
4333
+ const output = raw.output ?? null;
4334
+ return {
4335
+ __kind: NODE_OUTCOME_KIND,
4336
+ run_id: runId,
4337
+ node_id: nodeId,
4338
+ workflow_id: str(raw, "workflow_id"),
4339
+ step: num(raw, "step"),
4340
+ attempt: num(raw, "attempt") ?? 1,
4341
+ status: str(raw, "status") ?? "completed",
4342
+ started_at: str(raw, "started_at"),
4343
+ ended_at: str(raw, "ended_at"),
4344
+ duration_ms: num(raw, "duration_ms"),
4345
+ output_kind: str(raw, "output_kind"),
4346
+ output_kind_ok: bool(raw, "output_kind_ok"),
4347
+ output_kind_errors: strings(raw, "output_kind_errors"),
4348
+ output
4349
+ };
4350
+ }
4351
+ function rehydrateRunResult(raw, frame) {
4352
+ if (!isRecord6(raw)) return null;
4353
+ if (raw[KIND_KEY] !== RUN_RESULT_KIND) return null;
4354
+ const ref = str(raw, "output_ref");
4355
+ const resolved = ref === null ? void 0 : readOutputRef(frame, ref);
4356
+ const outputs = Array.isArray(raw.outputs) ? raw.outputs.map((child) => rehydrateNodeOutcome(child, frame) ?? child) : [];
4357
+ return readRunResultValue({
4358
+ ...raw,
4359
+ ...resolved === void 0 ? {} : { output: resolved },
4360
+ outputs
4361
+ });
4362
+ }
4363
+ function readRunResultValue(raw) {
4364
+ if (!isRecord6(raw)) return null;
4365
+ const runId = str(raw, "run_id");
4366
+ if (!runId) return null;
4367
+ const output = raw.output ?? null;
4368
+ const outputs = Array.isArray(raw.outputs) ? raw.outputs.map((child) => readNodeOutcomeValue(child)).filter((child) => child !== null) : [];
4369
+ return {
4370
+ __kind: RUN_RESULT_KIND,
4371
+ run_id: runId,
4372
+ workflow_id: str(raw, "workflow_id"),
4373
+ status: str(raw, "status") ?? "completed",
4374
+ started_at: str(raw, "started_at"),
4375
+ ended_at: str(raw, "ended_at"),
4376
+ duration_ms: num(raw, "duration_ms"),
4377
+ output_kind: str(raw, "output_kind"),
4378
+ output,
4379
+ outputs
4380
+ };
4381
+ }
4382
+ function kindVerdictOf(wrapper) {
4383
+ if (wrapper.output_kind_ok === true) return "passed";
4384
+ if (wrapper.output_kind_ok === false) return "failed";
4385
+ return "unchecked";
4386
+ }
4387
+
4388
+ // wire/emit-payload.ts
4389
+ function withRootKind(kind, value) {
4390
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4391
+ return { [KIND_KEY]: kind, ...value };
4392
+ }
4393
+ return value;
4394
+ }
4395
+ function emitPayloadJson(kind, value) {
4396
+ return JSON.stringify(withRootKind(kind, value), null, 2);
4397
+ }
4398
+ function emitPayloadFence(kind, value) {
4399
+ return "```json\n" + emitPayloadJson(kind, value) + "\n```";
4400
+ }
4401
+
4402
+ exports.IR_ENVELOPE_CACHE_VERSION = IR_ENVELOPE_CACHE_VERSION;
4403
+ exports.IR_ENVELOPE_KEY = IR_ENVELOPE_KEY;
4404
+ exports.IR_PARTIAL_KEY = IR_PARTIAL_KEY;
4405
+ exports.IR_VERSION = IR_VERSION;
4406
+ exports.IrTree = IrTree;
4407
+ exports.JSON_DISCRIMINATOR = JSON_DISCRIMINATOR;
4408
+ exports.JsonStreamTokenizer = JsonStreamTokenizer;
4409
+ exports.KIND_KEY = KIND_KEY;
4410
+ exports.KindStorageError = KindStorageError;
4411
+ exports.KindStreamParser = KindStreamParser;
4412
+ exports.NODE_OUTCOME_KIND = NODE_OUTCOME_KIND;
4413
+ exports.ParseSession = ParseSession;
4414
+ exports.ROOT_STORAGE_NAME = ROOT_STORAGE_NAME;
4415
+ exports.RUN_RESULT_KIND = RUN_RESULT_KIND;
4416
+ exports.advancePartialKind = advancePartialKind;
4417
+ exports.buildAgentSchemaWithRenderBlockSupport = buildAgentSchemaWithRenderBlockSupport;
4418
+ exports.buildCompliantKindSnapshot = buildCompliantKindSnapshot;
4419
+ exports.classifyInboundEnvelopeMetadata = classifyInboundEnvelopeMetadata;
4420
+ exports.collectReferencedKinds = collectReferencedKinds;
4421
+ exports.collectSchemaReferencedKinds = collectSchemaReferencedKinds;
4422
+ exports.compareWithExistingKindSchema = compareWithExistingKindSchema;
4423
+ exports.convertAiSchemaToBlockFields = convertAiSchemaToBlockFields;
4424
+ exports.createFingerprinter = createFingerprinter;
4425
+ exports.createKindStreamParser = createKindStreamParser;
4426
+ exports.describeDualGateFailure = describeDualGateFailure;
4427
+ exports.disposeParseSession = disposeParseSession;
4428
+ exports.emitPayloadFence = emitPayloadFence;
4429
+ exports.emitPayloadJson = emitPayloadJson;
4430
+ exports.emptyValueForFieldSchema = emptyValueForFieldSchema;
4431
+ exports.envelopeCacheFromEnvelopes = envelopeCacheFromEnvelopes;
4432
+ exports.envelopeFromCompleteValue = envelopeFromCompleteValue;
4433
+ exports.fenceDiscriminator = fenceDiscriminator;
4434
+ exports.fieldsToDbPayload = fieldsToDbPayload;
4435
+ exports.fingerprintText = fingerprintText;
4436
+ exports.formatBlockLabel = formatBlockLabel;
4437
+ exports.getParseSession = getParseSession;
4438
+ exports.injectKindIntoObjectSchema = injectKindIntoObjectSchema;
4439
+ exports.irPathIsUnderOrEqual = irPathIsUnderOrEqual;
4440
+ exports.irPathKey = irPathKey;
4441
+ exports.irPathLabel = irPathLabel;
4442
+ exports.irPathsEqual = irPathsEqual;
4443
+ exports.isCanonicalBlockIR = isCanonicalBlockIR;
4444
+ exports.isDuplicateBlockSlug = isDuplicateBlockSlug;
4445
+ exports.isEmptyResidue = isEmptyResidue;
4446
+ exports.isIrEnvelopeCache = isIrEnvelopeCache;
4447
+ exports.isJsonAnyField = isJsonAnyField;
4448
+ exports.isProvisionalKind = isProvisionalKind;
4449
+ exports.isScalarArrayType = isScalarArrayType;
4450
+ exports.isTerminalKindEvent = isTerminalKindEvent;
4451
+ exports.kindSchemaToJsonSchema = kindSchemaToJsonSchema;
4452
+ exports.kindSchemaToStorage = kindSchemaToStorage;
4453
+ exports.kindVerdictOf = kindVerdictOf;
4454
+ exports.makePartialKindStalenessGate = makePartialKindStalenessGate;
4455
+ exports.mergeResidueIntoValue = mergeResidueIntoValue;
4456
+ exports.normalizeAiSchemaInput = normalizeAiSchemaInput;
4457
+ exports.normalizeJsonRegion = normalizeJsonRegion;
4458
+ exports.openParseSession = openParseSession;
4459
+ exports.readEnvelope = readEnvelope;
4460
+ exports.readNodeOutcomeValue = readNodeOutcomeValue;
4461
+ exports.readObjectKind = readObjectKind;
4462
+ exports.readOutputRef = readOutputRef;
4463
+ exports.readPartialKindEvent = readPartialKindEvent;
4464
+ exports.readRunResultValue = readRunResultValue;
4465
+ exports.reconstructRegionValue = reconstructRegionValue;
4466
+ exports.rehydrateNodeOutcome = rehydrateNodeOutcome;
4467
+ exports.rehydrateRunResult = rehydrateRunResult;
4468
+ exports.reuseEnvelopeIfCurrent = reuseEnvelopeIfCurrent;
4469
+ exports.runKindDualGate = runKindDualGate;
4470
+ exports.runSchemaConversion = runSchemaConversion;
4471
+ exports.sanitizeInboundEnvelopeMetadata = sanitizeInboundEnvelopeMetadata;
4472
+ exports.sanitizeInboundPartialKindMetadata = sanitizeInboundPartialKindMetadata;
4473
+ exports.scalarArrayItemType = scalarArrayItemType;
4474
+ exports.schemaLayoutMode = schemaLayoutMode;
4475
+ exports.schemaStructureDepth = schemaStructureDepth;
4476
+ exports.setJsonRootKeyLookup = setJsonRootKeyLookup;
4477
+ exports.storageToKindSchema = storageToKindSchema;
4478
+ exports.stripKindDeep = stripKindDeep;
4479
+ exports.validateBlockSchemaSavePlan = validateBlockSchemaSavePlan;
4480
+ exports.validateStructuralLeg = validateStructuralLeg;
4481
+ exports.withRootKind = withRootKind;
4482
+ exports.xmlDiscriminator = xmlDiscriminator;
4483
+ //# sourceMappingURL=index.cjs.map
4484
+ //# sourceMappingURL=index.cjs.map