@pipelex/mthds-form 0.2.0 → 0.3.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.
@@ -55,9 +55,8 @@ var HTML_CONCEPTS = nativeSet("HTML");
55
55
  var DOCUMENT_CONCEPTS = nativeSet("Document");
56
56
  var PAGE_CONCEPTS = nativeSet("Page");
57
57
  var IMAGE_CONCEPTS = nativeSet("Image");
58
- var INTEGER_CONCEPTS = nativeSet("Integer");
59
- var NUMBER_CONCEPTS = nativeSet("Number", "Float");
60
- var BOOLEAN_CONCEPTS = nativeSet("Boolean");
58
+ var NUMBER_CONCEPTS = nativeSet("Number");
59
+ var YES_NO_CONCEPTS = nativeSet("YesNo");
61
60
  var FIELD_TEXT_CONCEPTS = /* @__PURE__ */ new Set([
62
61
  ...TEXT_CONCEPTS,
63
62
  ...DATE_CONCEPTS
@@ -231,6 +230,14 @@ function isDocumentObject(schema) {
231
230
  const props = schema.properties;
232
231
  return Boolean(props?.url);
233
232
  }
233
+ function scalarWrapper(schema, ctx) {
234
+ const props = schema.properties;
235
+ const entries = props ? Object.entries(props) : [];
236
+ const only = entries.length === 1 ? entries[0] : void 0;
237
+ if (!only) return void 0;
238
+ const [key, propSchema] = only;
239
+ return { key, schema: collapseNullable(derefSchema(propSchema ?? {}, ctx.defs)) };
240
+ }
234
241
  function mapSchema(name, conceptRef, rawSchema, required, ctx) {
235
242
  const schema = collapseNullable(derefSchema(rawSchema, ctx.defs));
236
243
  const common = {
@@ -252,25 +259,25 @@ function mapSchema(name, conceptRef, rawSchema, required, ctx) {
252
259
  if (FIELD_DOCUMENT_CONCEPTS.has(base))
253
260
  return { ...common, kind: "document", accept: "PDF, DOCX, TXT" };
254
261
  if (IMAGE_CONCEPTS.has(base)) return { ...common, kind: "image", accept: "PNG, JPG, WEBP" };
255
- if (FIELD_TEXT_CONCEPTS.has(base) || HTML_CONCEPTS.has(base))
256
- return ctx.depth === 0 ? { ...common, kind: "prose" } : { ...common, kind: "text" };
257
- if (INTEGER_CONCEPTS.has(base))
258
- return {
259
- ...common,
260
- kind: "number",
261
- integer: true,
262
- min: numOrUndef(schema.minimum),
263
- max: numOrUndef(schema.maximum)
264
- };
262
+ const wrapper = scalarWrapper(schema, ctx);
263
+ if (FIELD_TEXT_CONCEPTS.has(base) || HTML_CONCEPTS.has(base)) {
264
+ const contentKey = wrapper?.key ?? (TEXT_WRAPPER_CONCEPTS.has(base) ? "text" : void 0);
265
+ return ctx.depth === 0 ? { ...common, contentKey, kind: "prose" } : { ...common, contentKey, kind: "text" };
266
+ }
265
267
  if (NUMBER_CONCEPTS.has(base))
266
268
  return {
267
269
  ...common,
270
+ contentKey: wrapper?.key,
268
271
  kind: "number",
272
+ // `NumberContent.number` is `int | float`, an unresolvable union, so the
273
+ // control stays a float input. Constraints are read off the WRAPPED
274
+ // property - the wrapper object never carries them, which is why the
275
+ // outer schema always answered `undefined`.
269
276
  integer: false,
270
- min: numOrUndef(schema.minimum),
271
- max: numOrUndef(schema.maximum)
277
+ min: numOrUndef(wrapper?.schema.minimum ?? schema.minimum),
278
+ max: numOrUndef(wrapper?.schema.maximum ?? schema.maximum)
272
279
  };
273
- if (BOOLEAN_CONCEPTS.has(base)) return { ...common, kind: "boolean" };
280
+ if (YES_NO_CONCEPTS.has(base)) return { ...common, contentKey: wrapper?.key, kind: "boolean" };
274
281
  }
275
282
  if (isDocumentObject(schema)) {
276
283
  return { ...common, kind: "document", accept: "PDF, DOCX, TXT" };
@@ -438,21 +445,15 @@ function validateRunInputsSchema(data, schema) {
438
445
  function toRunInputError(e) {
439
446
  const { instancePath, keyword, schemaPath, parentSchema } = e;
440
447
  const params = e.params;
441
- let message = e.message ?? "";
448
+ const message = e.message ?? "";
442
449
  let property = instancePath.replace(/\//g, ".");
443
450
  let stack = `${property} ${message}`.trim();
444
- const rawPropertyNames = [
451
+ const namesAProperty = [
445
452
  ...typeof params.deps === "string" ? params.deps.split(", ") : [],
446
453
  params.missingProperty,
447
454
  params.property
448
- ].filter((item) => typeof item === "string" && item.length > 0);
449
- if (rawPropertyNames.length > 0) {
450
- for (const currentProperty of rawPropertyNames) {
451
- const title = parentSchema?.properties?.[currentProperty]?.title;
452
- if (typeof title === "string" && title) {
453
- message = message.replace(`'${currentProperty}'`, `'${title}'`);
454
- }
455
- }
455
+ ].some((item) => typeof item === "string" && item.length > 0);
456
+ if (namesAProperty) {
456
457
  stack = message;
457
458
  } else {
458
459
  const parentTitle = parentSchema?.title;
@@ -618,6 +619,10 @@ function healStringWrappers(value, rawSchema, defs) {
618
619
  }
619
620
  return value;
620
621
  }
622
+ function isEmptyAfterPruning(value) {
623
+ if (value === "" || value === null || value === void 0) return true;
624
+ return typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
625
+ }
621
626
  function pruneEmptyOptionals(value, rawSchema, defs) {
622
627
  if (!rawSchema || value == null) return value;
623
628
  const allDefs = defs ?? collectSchemaDefs(rawSchema, {}, { traverseArrays: false });
@@ -639,8 +644,7 @@ function pruneEmptyOptionals(value, rawSchema, defs) {
639
644
  continue;
640
645
  }
641
646
  const pruned = pruneEmptyOptionals(raw, propSchema, allDefs);
642
- const isEmpty = pruned === "" || pruned === null || pruned === void 0;
643
- if (isEmpty && !required.has(key)) continue;
647
+ if (isEmptyAfterPruning(pruned) && !required.has(key)) continue;
644
648
  out[key] = pruned;
645
649
  }
646
650
  return out;
@@ -755,9 +759,14 @@ function apiInputsFromSchemaData(preparedData, inputs) {
755
759
  }
756
760
 
757
761
  // src/core/values.ts
758
- function isTextWrapperConcept(conceptRef) {
759
- const { base } = splitListConcept(conceptRef);
760
- return base !== void 0 && TEXT_WRAPPER_CONCEPTS.has(base);
762
+ function wrapContent(field, value) {
763
+ return field.contentKey === void 0 ? value : { [field.contentKey]: value };
764
+ }
765
+ function unwrapContent(field, value) {
766
+ const key = field.contentKey;
767
+ if (key === void 0 || !value || typeof value !== "object" || Array.isArray(value))
768
+ return value;
769
+ return value[key];
761
770
  }
762
771
  var MAX_UNWRAP_DEPTH = 8;
763
772
  function textFromStored(value, depth = 0) {
@@ -775,6 +784,19 @@ function fromRjsf(field, value) {
775
784
  case "text":
776
785
  case "prose":
777
786
  return textFromStored(value);
787
+ case "number": {
788
+ const raw = unwrapContent(field, value);
789
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : void 0;
790
+ if (typeof raw === "string" && raw.trim() !== "") {
791
+ const parsed = Number(raw);
792
+ return Number.isFinite(parsed) ? parsed : void 0;
793
+ }
794
+ return void 0;
795
+ }
796
+ case "boolean": {
797
+ const raw = unwrapContent(field, value);
798
+ return typeof raw === "boolean" ? raw : void 0;
799
+ }
778
800
  case "unknown":
779
801
  if (typeof value === "string") return value;
780
802
  if (value == null) return void 0;
@@ -808,13 +830,15 @@ function fromRjsf(field, value) {
808
830
  return value;
809
831
  }
810
832
  }
811
- function toRjsf(field, value) {
833
+ function toRjsf(field, value, collapseEmpty = true) {
812
834
  switch (field.kind) {
813
835
  case "text":
814
- case "prose": {
815
- const str = typeof value === "string" ? value : "";
816
- return isTextWrapperConcept(field.conceptRef) ? { text: str } : str;
817
- }
836
+ case "prose":
837
+ return wrapContent(field, typeof value === "string" ? value : "");
838
+ case "number":
839
+ return typeof value === "number" && Number.isFinite(value) ? wrapContent(field, value) : void 0;
840
+ case "boolean":
841
+ return typeof value === "boolean" ? wrapContent(field, value) : void 0;
818
842
  case "unknown":
819
843
  return typeof value === "string" ? value : "";
820
844
  case "document":
@@ -827,11 +851,11 @@ function toRjsf(field, value) {
827
851
  const obj = value && typeof value === "object" ? value : {};
828
852
  const out = {};
829
853
  for (const child of field.fields) out[child.name] = toRjsf(child, obj[child.name]);
830
- return out;
854
+ return collapseEmpty && !isFilled(out) ? void 0 : out;
831
855
  }
832
856
  case "list": {
833
857
  const arr = Array.isArray(value) ? value : [];
834
- return arr.map((item) => toRjsf(field.item, item));
858
+ return arr.map((item) => toRjsf(field.item, item, false));
835
859
  }
836
860
  default:
837
861
  return value;
@@ -962,5 +986,5 @@ function describeValidationError(error, t, formData) {
962
986
  }
963
987
 
964
988
  export { apiInputsFromRunValues, apiInputsFromSchemaData, asCalendarDate, buildPipeRef, buildRunFields, buildRunInputsSchema, collapseNullable, collectSchemaDefs, computeReadiness, conceptCategory, dayWithinDateTime, deflateAllInputs, deflateInput, derefSchema, describeValidationError, displayValue, fieldFilled, fieldsForContract, flattenAnyOf, getPipeIOContract, healStringWrappers, hoistDefsToRoot, inflateAllInputs, inflateInput, inputDataFromWorkingMemory, inputMustBeFilled, isAcceptableDate, isAcceptableDateTime, isFilled, isPluralInput, mustBeFilled, normalizeSchemaForRjsf, outputsFromPipeOutput, prepareRunInputs, prepareSchemaForRjsf, pruneEmptyOptionals, resolveConceptCode, resolveSchemaIndirection, rjsfDataFromRunValues, runValuesFromStore, schemaTypeOf, setValueAtPath, storeInputDataFromRunValues, toDateInputValue, toStoredDateValue, validateRunInputs, validateRunInputsSchema, valueAtProperty };
965
- //# sourceMappingURL=chunk-YWMUM7BC.js.map
966
- //# sourceMappingURL=chunk-YWMUM7BC.js.map
989
+ //# sourceMappingURL=chunk-S6KOTTGD.js.map
990
+ //# sourceMappingURL=chunk-S6KOTTGD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/descriptor.ts","../src/core/contracts.ts","../src/core/native-concepts.ts","../src/core/schema-utils.ts","../src/core/derive.ts","../src/core/readiness.ts","../src/core/date-format.ts","../src/core/gate-validator.ts","../src/core/wire-format.ts","../src/core/normalize-schema.ts","../src/core/gate.ts","../src/core/values.ts","../src/core/validation-message.ts"],"names":[],"mappings":";;;;AAuIO,SAAS,gBAAgB,KAAA,EAAkC;AAChE,EAAA,QAAQ,MAAM,IAAA;AAAM,IAClB,KAAK,MAAA;AAAA,IACL,KAAK,OAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,MAAA;AACH,MAAA,OAAO,MAAA;AAAA,IACT,KAAK,UAAA;AACH,MAAA,OAAO,UAAA;AAAA,IACT,KAAK,OAA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,+BAAA,EAAiC,EAAE,OAAO,CAAA;AAEvE,IAAA,MAAM,GAAA,GAAM,WAAW,MAAA,IAAU,OAAO,UAAU,QAAA,GAAW,iBAAA,CAAkB,KAAK,CAAA,GAAI,IAAA;AACxF,IAAA,IAAI,GAAA,KAAQ,IAAA,EAAM,OAAO,CAAA,CAAE,4BAAA,EAA8B,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,GAAA,EAAK,CAAA;AACrF,IAAA,OAAO,EAAE,0BAAA,EAA4B,EAAE,KAAA,EAAO,KAAA,EAAO,OAAO,CAAA;AAAA,EAC9D;AAEA,EAAA,MAAM,QAAQ,KAAA,CAAM,KAAA,IAAS,KAAA,CAAM,OAAA,IAAW,EAAE,yBAAyB,CAAA;AACzE,EAAA,OAAO,KAAA,KAAU,OAAO,KAAA,GAAQ,CAAA,CAAE,mCAAmC,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,CAAA;AAC9F","file":"chunk-S6KOTTGD.js","sourcesContent":["/**\n * The `RunField` descriptor - the consumer-facing currency of the form kernel.\n *\n * A method's inputs arrive from the API as a map of variable name →\n * `PipeInputContract` ({ concept_ref, json_schema }). That JSON Schema is rich\n * (Pydantic-generated) and not pleasant to render directly. `buildRunFields`\n * (in `derive.ts`) normalizes it once into a flat, recursive `RunField[]`\n * descriptor that the presentational field components consume - so the\n * components never touch raw JSON Schema, and stories can describe any input\n * shape declaratively.\n *\n * Pure module: no React, no API calls. Trivially unit-testable.\n */\n\nexport type RunFieldKind =\n | 'text' // short single-line string\n | 'prose' // long free-text (textarea)\n | 'date' // a calendar date (schema `format: date` or `date-time`)\n | 'number' // integer or float\n | 'boolean' // true/false\n | 'enum' // pick one of a fixed set\n | 'document' // a file (PDF, docx…) by upload or URL\n | 'image' // a file rendered with a preview\n | 'object' // a structured concept with nested fields\n | 'list' // an array of one element type\n | 'unknown'; // anything we can't map → raw JSON escape hatch\n\nexport interface RunFieldCommon {\n /** The variable identifier as written in the method (rendered in mono). */\n name: string;\n /** Human label; falls back to `name` when absent. */\n title?: string;\n /** The concept this input carries, e.g. `native.Document`, `demo.Invoice`. */\n conceptRef?: string;\n /** One-line helper text shown under the label. */\n description?: string;\n /** Required inputs always show; optional ones can collapse. */\n required: boolean;\n /**\n * Whether Run waits for this input - set on TOP-LEVEL fields only, straight\n * from `inputMustBeFilled` (see `mustBeFilled` in `readiness.ts` for why this\n * is not the same question as `required`). Nested fields leave it undefined;\n * they are gated through their parent's `fieldFilled`.\n */\n gating?: boolean;\n /**\n * The single property this field's value sits inside on the wire, when its\n * concept declares a scalar content model: `native.Text` is `TextContent\n * {text}`, `native.Number` is `NumberContent {number}`, `native.YesNo` is\n * `YesNoContent {yes_no}`. The control still holds the plain scalar; the\n * value bridge wraps into this property on the way out and unwraps on the way\n * back in.\n *\n * A property NAME, never a schema - the descriptor stays the only currency\n * and `buildRunFields` stays the only reader of JSON Schema. Absent whenever\n * the value is already the whole content (a structured concept, a file, a\n * child property of a structure): wrapping those would double-nest them.\n */\n contentKey?: string;\n}\n\nexport interface TextRunField extends RunFieldCommon {\n kind: 'text';\n placeholder?: string;\n}\n\nexport interface ProseRunField extends RunFieldCommon {\n kind: 'prose';\n placeholder?: string;\n}\n\nexport interface DateRunField extends RunFieldCommon {\n kind: 'date';\n /**\n * True when the backing schema is `format: date-time`: the stored value is a\n * full RFC 3339 timestamp (`2026-07-06T00:00:00Z`) so it passes the API's\n * `date-time` validation, even though the control only asks for a day. False\n * for a bare `format: date`, where the value stays `YYYY-MM-DD`.\n */\n datetime: boolean;\n}\n\nexport interface NumberRunField extends RunFieldCommon {\n kind: 'number';\n integer: boolean;\n min?: number;\n max?: number;\n}\n\nexport interface BooleanRunField extends RunFieldCommon {\n kind: 'boolean';\n}\n\nexport interface EnumRunField extends RunFieldCommon {\n kind: 'enum';\n options: string[];\n}\n\nexport interface FileRunField extends RunFieldCommon {\n kind: 'document' | 'image';\n /** Accept hint shown to the user, e.g. \"PDF, PNG, JPG\". */\n accept?: string;\n}\n\nexport interface ObjectRunField extends RunFieldCommon {\n kind: 'object';\n fields: RunField[];\n}\n\nexport interface ListRunField extends RunFieldCommon {\n kind: 'list';\n /** The element descriptor (its `name` is unused; the index labels items). */\n item: RunField;\n}\n\nexport interface UnknownRunField extends RunFieldCommon {\n kind: 'unknown';\n}\n\nexport type RunField =\n | TextRunField\n | ProseRunField\n | DateRunField\n | NumberRunField\n | BooleanRunField\n | EnumRunField\n | FileRunField\n | ObjectRunField\n | ListRunField\n | UnknownRunField;\n\n/** The short, friendly category label for a concept_ref (drives the pill dot). */\nexport type ConceptCategory =\n 'text' | 'date' | 'document' | 'image' | 'number' | 'boolean' | 'choice' | 'structured' | 'list';\n\nexport function conceptCategory(field: RunField): ConceptCategory {\n switch (field.kind) {\n case 'text':\n case 'prose':\n return 'text';\n case 'date':\n return 'date';\n case 'document':\n return 'document';\n case 'image':\n return 'image';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'enum':\n return 'choice';\n case 'list':\n return 'list';\n default:\n return 'structured';\n }\n}\n","/**\n * The typed `pipe_io_contracts` mirror and its gating predicates.\n *\n * Mirrors pipelex's `PipeIOContract` (pipelex/pipeline/pipe_io_contracts.py).\n * The SDK deliberately keeps `pipe_io_contracts` opaque, so the kernel is the\n * canonical TS home for this shape until the D-track specs it.\n *\n * The map itself is keyed by namespaced pipe ref (`<domain>.<pipe_code>`),\n * NOT bare pipe code - use `getPipeIOContract` to look entries up by the bare\n * codes the UI tracks.\n */\n\nexport interface PipeInputContract {\n concept_ref: string;\n json_schema: Record<string, unknown>;\n /**\n * `true` when the input is declared optional (`?`) - the caller may omit it\n * and the pipe handles the absence itself. Plain and force (`!`) inputs\n * report `false`. Absent on contracts persisted before the API carried the\n * flag, so read it as \"optional only when explicitly true\".\n */\n optional?: boolean;\n}\n\nexport interface PipeOutputContract {\n concept_ref: string;\n multiplicity: 'single' | 'variable';\n /** `true` when the output is declared optional (`?`) - the pipe may resolve\n * it as a recorded absence instead of a value. */\n optional?: boolean;\n}\n\nexport interface PipeIOContract {\n inputs: Record<string, PipeInputContract>;\n output: PipeOutputContract;\n}\n\n/** The `pipe_io_contracts` map: namespaced `pipe_ref` → IO contract. */\nexport type PipeIOContracts = Record<string, PipeIOContract>;\n\n/** Namespaced pipe ref (`<domain>.<pipe_code>`) - the identity convention the\n * validate artifacts key on. */\nexport function buildPipeRef(domain: string, pipeCode: string): string {\n return `${domain}.${pipeCode}`;\n}\n\n/**\n * Look up a pipe's IO contract by pipe code, tolerant of both key conventions.\n *\n * The map may be keyed by namespaced `pipe_ref` (`<domain>.<code>`, the\n * canonical convention) OR by bare pipe code - the current hosted `/validate`\n * keys `pipe_structures` by bare code, and methods persisted before the\n * pipe_ref re-keying also carry bare-code keys. Try the namespaced ref first\n * (when the caller supplies a domain), then fall back to the bare code.\n * Returns `undefined` (never crashes) when neither matches.\n */\nexport function getPipeIOContract(\n pipeIoContracts: PipeIOContracts | null | undefined,\n domain: string | null | undefined,\n pipeCode: string | null | undefined,\n): PipeIOContract | undefined {\n if (!pipeIoContracts || !pipeCode) return undefined;\n if (domain) {\n const byRef = pipeIoContracts[buildPipeRef(domain, pipeCode)];\n if (byRef) return byRef;\n }\n return pipeIoContracts[pipeCode];\n}\n\n/**\n * True when the input carries a plural concept (`Image[]`): its JSON Schema is\n * an array wrapper. A plural slot is never \"absent\" in MTHDS - its empty form\n * IS the empty list - so the UI must treat \"nothing entered\" as a real value.\n */\nexport function isPluralInput(input: PipeInputContract): boolean {\n return (input.json_schema as { type?: unknown } | undefined)?.type === 'array';\n}\n\n/**\n * True when the user MUST put a value in before a run can start.\n *\n * Two declarations relieve an input of that duty, for different reasons:\n * - **optional (`?`)** - the method itself states the caller may omit it;\n * - **plural (`[]`)** - the empty list is a legitimate value and no method can\n * declare \"at least one\", so gating on it would invent a constraint the\n * method never made.\n *\n * Everything else (plain and force `!`) still gates: that is the whole point of\n * the Run button telling you what is missing.\n */\nexport function inputMustBeFilled(input: PipeInputContract): boolean {\n return input.optional !== true && !isPluralInput(input);\n}\n","/**\n * The native-concept taxonomy, stated ONCE - with each call path's historical\n * view exported explicitly, because the three copies this consolidates had\n * DRIFTED and K1 preserved each path's observable behavior exactly (see\n * `concept-taxonomy-characterization.test.ts`).\n *\n * The sets below spell the codes MTHDS actually defines (the `native` domain of\n * the language spec). That is not pedantry: a set that named a concept the\n * language does not have is what broke `native.Number`, because the render path\n * knew the concept and the value path did not.\n *\n * The drift, recorded for M1 (where the server-derived descriptor retires this\n * module entirely):\n *\n * | concept | field mapper (render) | wire format (deflate/inflate) | value bridge (content wrapper) |\n * | ------- | ------------------------- | ----------------------------- | ------------------------------ |\n * | Text | text/prose | bare string | `{text}`, from `TextContent` |\n * | Number | number | `{concept, content}` | `{number}`, from `NumberContent` |\n * | YesNo | boolean | `{concept, content}` | `{yes_no}`, from `YesNoContent` |\n * | Date | text/prose (NOT a picker) | CUSTOM `{concept, content}` | `{text}` - WRONG, see below |\n * | Html | nested object | `{concept, content}` | - |\n * | Page | document | document-like (bare URL) | - |\n *\n * A `Date` input therefore ships as `{concept: \"native.Date\", content: {text}}`\n * today - consistent end-to-end, but not `DateContent {date, time}`. Changing\n * that is a wire-visible fix and belongs to M1, not here.\n *\n * `HTML_CONCEPTS` below spells the code `HTML`; the language spells it `Html`\n * (`NativeConceptCode.HTML = \"Html\"`), so the set matches nothing a real\n * contract carries and `native.Html` falls through to the generic object\n * dispatch - a nested card over `HtmlContent {inner_html, css_class}`, which\n * round-trips correctly. Correcting the spelling would route `native.Html` into\n * the prose-plus-`{text}` drift above and BREAK inputs that work today, so the\n * spelling is left alone deliberately and goes with the Date fix at M1.\n */\n\n/** Both spellings a concept ref uses: bare (`Text`) and namespaced (`native.Text`). */\nfunction nativeSet(...names: string[]): ReadonlySet<string> {\n return new Set(names.flatMap((n) => [n, `native.${n}`]));\n}\n\nexport const TEXT_CONCEPTS = nativeSet('Text');\nexport const DATE_CONCEPTS = nativeSet('Date');\n/** Deliberately the code the language does NOT use - see the header. */\nexport const HTML_CONCEPTS = nativeSet('HTML');\nexport const DOCUMENT_CONCEPTS = nativeSet('Document');\nexport const PAGE_CONCEPTS = nativeSet('Page');\nexport const IMAGE_CONCEPTS = nativeSet('Image');\nexport const NUMBER_CONCEPTS = nativeSet('Number');\nexport const YES_NO_CONCEPTS = nativeSet('YesNo');\n\n// ─── The field mapper's view (field-model.ts) ───────────────────────────────\n\n/** Concepts the mapper renders as text/prose - `Date` deliberately included\n * (a `native.Date` input renders as prose today, not as a date picker). */\nexport const FIELD_TEXT_CONCEPTS: ReadonlySet<string> = new Set([\n ...TEXT_CONCEPTS,\n ...DATE_CONCEPTS,\n]);\n\n/** Concepts the mapper renders as a document upload - `Page` folded in. */\nexport const FIELD_DOCUMENT_CONCEPTS: ReadonlySet<string> = new Set([\n ...DOCUMENT_CONCEPTS,\n ...PAGE_CONCEPTS,\n]);\n\n// ─── The wire format's view (input-format.ts) ───────────────────────────────\n\n/** True when the simplified wire form is a bare string (`{text} ↔ \"...\"`).\n * `Date` is NOT here: it travels through the custom-concept `{concept,\n * content}` branch (the drift the header records). */\nexport function isWireTextConcept(concept: string): boolean {\n return TEXT_CONCEPTS.has(concept);\n}\n\n/** True when the simplified wire form is a bare URL string. */\nexport function isWireDocumentLikeConcept(concept: string): boolean {\n return (\n DOCUMENT_CONCEPTS.has(concept) || IMAGE_CONCEPTS.has(concept) || PAGE_CONCEPTS.has(concept)\n );\n}\n\n// ─── The value bridge's view (run-values.ts) ────────────────────────────────\n\n/**\n * The FALLBACK text wrapper, for a text concept whose contract declares no\n * single-property content model to read the wrapper name off.\n *\n * The wrapper property is normally derived from the declared schema, in\n * `derive.ts`, and travels on the descriptor as `RunField.contentKey` - so the\n * value bridge wraps by name and holds no taxonomy of its own. This set is what\n * answers when that derivation finds nothing:\n *\n * - `native.Text` with a degenerate contract (a bare `{type: 'object'}`, or a\n * bare `{type: 'string'}`) still wraps as `{text}`, as it always has;\n * - `native.Date` declares `DateContent {date, time}` - two properties, so no\n * single wrapper - and this set is what keeps it wrapping as `{text}`. That\n * is the recorded drift, preserved on purpose until M1.\n */\nexport const TEXT_WRAPPER_CONCEPTS: ReadonlySet<string> = new Set([\n ...TEXT_CONCEPTS,\n ...DATE_CONCEPTS,\n ...HTML_CONCEPTS,\n]);\n\n// ─── List refs ──────────────────────────────────────────────────────────────\n\n/** A concept ref like `native.Document[]` → base `native.Document`, isList true. */\nexport function splitListConcept(conceptRef: string | undefined): {\n base?: string;\n isList: boolean;\n} {\n if (!conceptRef) return { isList: false };\n if (conceptRef.endsWith('[]')) return { base: conceptRef.slice(0, -2), isList: true };\n return { base: conceptRef, isList: false };\n}\n","/**\n * The ONE place JSON-Schema plumbing lives for the run form kernel: nullable\n * `anyOf` collapsing, `$defs` collection/hoisting, `$ref` resolution, and type\n * extraction. Consolidated from three drifted private copies (`field-model.ts`,\n * `normalize-schema.ts`, `input-format.ts`) during the form-kernel extraction.\n *\n * Two collapse engines are exported ON PURPOSE - their semantics genuinely\n * differ, and each caller's observable behavior is characterized and preserved\n * (see `schema-utils-characterization.test.ts`):\n *\n * - `collapseNullable` (the field mapper's rule): collapse ONLY when exactly one\n * non-null branch remains, dropping the null. A multi-branch union stays an\n * `anyOf` and maps to the raw-JSON escape hatch.\n * - `flattenAnyOf` (the RJSF/ajv rule): a union of simple primitives becomes a\n * `type` ARRAY (null preserved as a type entry - ajv validates `type:\n * [\"number\",\"null\"]` natively); a 2-branch nullable non-primitive drops the\n * null branch.\n *\n * Whether these converge (and which semantics win) is an M1 question, decided\n * when the descriptor derivation moves server-side - not silently here.\n */\n\nexport type JsonSchema = Record<string, unknown>;\n\n// ─── anyOf collapsing ────────────────────────────────────────────────────────\n\n/** Pydantic emits `anyOf: [T, {type:'null'}]` for Optional[T]; collapse to T.\n * Collapses ONLY when exactly one non-null branch remains; the branch merges\n * OVER the outer schema (its constraints win). */\nexport function collapseNullable(schema: JsonSchema): JsonSchema {\n const anyOf = schema.anyOf;\n if (!Array.isArray(anyOf)) return schema;\n const branches = anyOf as JsonSchema[];\n const nonNull = branches.filter((b) => b?.type !== 'null');\n if (nonNull.length === 1) return { ...stripAnyOf(schema), ...nonNull[0] };\n return schema;\n}\n\nconst PRIMITIVE_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null']);\n\n/**\n * An `anyOf` entry that is a simple primitive with no constraints:\n * `{type: \"string\"}` is simple, `{type: \"string\", maxLength: 10}` is not.\n */\nfunction isSimplePrimitive(schema: JsonSchema): boolean {\n const type = schema.type;\n if (typeof type !== 'string' || !PRIMITIVE_TYPES.has(type)) return false;\n const allowedKeys = new Set(['type', 'default', 'description', 'title']);\n return Object.keys(schema).every((key) => allowedKeys.has(key));\n}\n\n/**\n * The RJSF/ajv collapse: a union of simple primitives flattens to a `type`\n * array (`anyOf: [{string},{null}]` → `type: [\"string\",\"null\"]`, which RJSF\n * renders as a plain input instead of a sub-schema picker); an exactly-two\n * `[T, {null}]` union of anything else drops the null branch and merges T over\n * the outer schema. Anything else passes through unchanged.\n */\nexport function flattenAnyOf(schema: JsonSchema): JsonSchema {\n const anyOf = schema.anyOf;\n if (!Array.isArray(anyOf)) return schema;\n\n const branches = anyOf as JsonSchema[];\n\n // Case 1: all branches are simple primitives → type array.\n if (\n branches.every(\n (branch) => typeof branch === 'object' && branch !== null && isSimplePrimitive(branch),\n )\n ) {\n const types: string[] = [];\n let mergedDefault: unknown = undefined;\n for (const branch of branches) {\n types.push(branch.type as string);\n if (branch.default !== undefined) mergedDefault = branch.default;\n }\n const { anyOf: _, ...rest } = schema;\n const result: JsonSchema = { ...rest, type: types };\n if (mergedDefault !== undefined && result.default === undefined) {\n result.default = mergedDefault;\n }\n return result;\n }\n\n // Case 2: exactly [T, {type: \"null\"}] - nullable non-primitive → drop null.\n if (branches.length === 2) {\n const nullBranch = branches.find(\n (b) => typeof b === 'object' && b !== null && b.type === 'null',\n );\n const otherBranch = branches.find((b) => b !== nullBranch);\n if (nullBranch && otherBranch && typeof otherBranch === 'object') {\n const { anyOf: _, ...rest } = schema;\n return { ...rest, ...otherBranch };\n }\n }\n\n return schema;\n}\n\nfunction stripAnyOf(schema: JsonSchema): JsonSchema {\n const { anyOf: _drop, ...rest } = schema;\n return rest;\n}\n\n// ─── Type & $ref helpers ─────────────────────────────────────────────────────\n\n/** The schema's non-null type: a bare `type` string, or the first non-null\n * entry of a `type` array (`[\"number\",\"null\"]` → `\"number\"`). */\nexport function schemaTypeOf(schema: JsonSchema): string | undefined {\n const t = schema.type;\n if (typeof t === 'string') return t;\n if (Array.isArray(t)) return t.find((x) => x !== 'null') as string | undefined;\n return undefined;\n}\n\n/** Resolve `{ $ref: \"#/$defs/Foo\" }` against a collected `$defs` map. Sibling\n * keys on the referencing schema override the definition's. */\nexport function derefSchema(schema: JsonSchema, defs: Record<string, JsonSchema>): JsonSchema {\n const ref = schema.$ref;\n if (typeof ref === 'string' && ref.startsWith('#/$defs/')) {\n const resolved = defs[ref.slice('#/$defs/'.length)];\n if (resolved) return { ...resolved, ...stripRef(schema) };\n }\n return schema;\n}\n\nfunction stripRef(schema: JsonSchema): JsonSchema {\n const { $ref: _drop, ...rest } = schema;\n return rest;\n}\n\n/**\n * Resolve the indirection layers pydantic puts in front of a value schema - a\n * `#/$defs/...` ref, a nullable `anyOf: [T, {null}]` wrapper, or a stack of\n * both - until a plain schema remains. This is the resolver `healStringWrappers`\n * and `pruneEmptyOptionals` apply before reading `type`. Unlike `derefSchema`\n * it REPLACES the schema with the definition (no sibling merge) - exactly what\n * the callers did inline.\n */\nexport function resolveSchemaIndirection(\n schema: JsonSchema,\n defs: Record<string, JsonSchema>,\n): JsonSchema {\n let current = schema;\n for (;;) {\n const ref = current.$ref;\n if (typeof ref === 'string' && ref.startsWith('#/$defs/')) {\n const resolved = defs[ref.slice('#/$defs/'.length)];\n if (resolved) {\n current = resolved;\n continue;\n }\n }\n if (Array.isArray(current.anyOf)) {\n const nonNull = (current.anyOf as JsonSchema[]).filter((b) => b?.type !== 'null');\n if (nonNull.length === 1) {\n current = nonNull[0]!;\n continue;\n }\n }\n return current;\n }\n}\n\n// ─── $defs collection ────────────────────────────────────────────────────────\n\nexport interface CollectDefsOptions {\n /**\n * Whether the walk descends into JSON arrays (`anyOf`/`allOf` branches,\n * tuple `items`). The field mapper always has (so a def declared inside an\n * `anyOf` branch resolves); the wire-format heal path historically has NOT -\n * both behaviors are characterized, and each caller states its mode\n * explicitly until M1 retires the difference.\n */\n traverseArrays: boolean;\n}\n\n/**\n * Collect every nested `$defs` entry into one flat map so `#/$defs/...` refs\n * resolve from anywhere. First definition of a name wins. The input schema is\n * NOT modified (see `hoistDefsToRoot` for the stripping variant).\n */\nexport function collectSchemaDefs(\n schema: JsonSchema,\n into: Record<string, JsonSchema>,\n options: CollectDefsOptions,\n): Record<string, JsonSchema> {\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$defs' && value && typeof value === 'object' && !Array.isArray(value)) {\n for (const [name, def] of Object.entries(value as Record<string, JsonSchema>)) {\n if (!(name in into) && def && typeof def === 'object') {\n into[name] = def;\n collectSchemaDefs(def, into, options);\n }\n }\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n collectSchemaDefs(value as JsonSchema, into, options);\n } else if (options.traverseArrays && Array.isArray(value)) {\n // Any object item recurses - including a nested array, whose indices then\n // walk as keys (matches the historical field-model walker exactly).\n for (const item of value) {\n if (item && typeof item === 'object') {\n collectSchemaDefs(item as JsonSchema, into, options);\n }\n }\n }\n }\n return into;\n}\n\n// ─── $defs hoisting (the RJSF wrapper-schema case) ──────────────────────────\n\n/**\n * Walk a schema, collect every `$defs` entry into `collected`, and return the\n * schema with those nested `$defs` STRIPPED. Cycle-safe: a def name is claimed\n * (placeholder) before its body is walked.\n */\nfunction walkAndCollectDefs(schema: JsonSchema, collected: JsonSchema): JsonSchema {\n const out: JsonSchema = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$defs' && value && typeof value === 'object' && !Array.isArray(value)) {\n for (const [defName, defValue] of Object.entries(value as JsonSchema)) {\n if (!(defName in collected) && defValue && typeof defValue === 'object') {\n collected[defName] = {};\n collected[defName] = walkAndCollectDefs(defValue as JsonSchema, collected);\n }\n }\n // Don't copy `$defs` into out - it's hoisted to the root.\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n out[key] = walkAndCollectDefs(value as JsonSchema, collected);\n } else if (Array.isArray(value)) {\n out[key] = value.map((item) =>\n item && typeof item === 'object' && !Array.isArray(item)\n ? walkAndCollectDefs(item as JsonSchema, collected)\n : item,\n );\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Hoist every nested `$defs` to the schema root, so a wrapper schema composed\n * from several pydantic sub-schemas keeps its `#/$defs/...` refs resolvable.\n * (Pydantic emits one `$defs` per model; composing models as properties of a\n * wrapper object leaves those maps below the root the refs point to.)\n */\nexport function hoistDefsToRoot(schema: JsonSchema): JsonSchema {\n const collected: JsonSchema = {};\n const stripped = walkAndCollectDefs(schema, collected);\n if (Object.keys(collected).length > 0) {\n stripped.$defs = collected;\n }\n return stripped;\n}\n","/**\n * The ONE derivation function: `PipeInputContract` map → `RunField[]`.\n *\n * Everything heuristic stays module-private behind `buildRunFields`: the\n * native-concept taxonomy, `isDocumentObject`, the depth-based prose/label\n * rule, the `accept` strings, list splitting. Nothing here is exported except\n * the function itself - so the M1 milestone can swap the source of the\n * descriptor (server-derived) without touching consumers.\n */\n\nimport { inputMustBeFilled, type PipeInputContract } from './contracts';\nimport type { RunField, RunFieldCommon } from './descriptor';\nimport {\n FIELD_DOCUMENT_CONCEPTS,\n FIELD_TEXT_CONCEPTS,\n HTML_CONCEPTS,\n IMAGE_CONCEPTS,\n NUMBER_CONCEPTS,\n splitListConcept,\n TEXT_WRAPPER_CONCEPTS,\n YES_NO_CONCEPTS,\n} from './native-concepts';\nimport {\n collapseNullable,\n collectSchemaDefs,\n derefSchema,\n schemaTypeOf,\n type JsonSchema,\n} from './schema-utils';\n\n// Native concepts arrive as their pydantic wrapper schema (e.g. native.Text is\n// `TextContent {text}`, native.Document is `DocumentContent {url,…}`), NOT a bare\n// primitive - so we map them by concept_ref, before the generic schema-type\n// dispatch, or they'd all render as nested objects. The taxonomy lives in\n// `native-concepts.ts`, which also records where this mapper's view drifts from\n// the wire format's.\n\n/**\n * A url-bearing object renders as a document field. This is `Boolean(\n * schema.properties?.url)` and nothing more: the historical description check\n * (\"storage url\" / \"document url\") was followed by `|| 'url' in props`, which\n * made it unreachable. Stated honestly as the heuristic it is - M1 replaces it\n * with the server-derived descriptor; narrowing it to the description match is\n * a recorded M1 option, not a K1 change.\n */\nfunction isDocumentObject(schema: JsonSchema): boolean {\n const props = schema.properties as Record<string, JsonSchema> | undefined;\n return Boolean(props?.url);\n}\n\ninterface MapCtx {\n defs: Record<string, JsonSchema>;\n depth: number;\n}\n\n/**\n * The single property a pydantic scalar content model holds its value in -\n * `TextContent {text}`, `NumberContent {number}`, `YesNoContent {yes_no}`.\n *\n * A native scalar's value does NOT sit at the top of its declared schema, and\n * this is where that is discovered: from the CONTRACT, not from a hand-kept\n * list of which concepts wrap. Keeping such a list is what broke `native.Number`\n * - the render taxonomy knew the concept, the wrapper taxonomy did not, so a\n * number reached the gate bare and failed against `NumberContent`. Reading the\n * declared shape covers a concept nobody remembered to add.\n *\n * A wrapper is a schema declaring EXACTLY ONE property. A multi-property content\n * model (`DateContent {date, time}`, `HtmlContent {inner_html, css_class}`) is\n * not one and deliberately answers `undefined`; so does a contract that declares\n * no properties at all. The returned `schema` is the WRAPPED property's, which\n * is where its constraints live.\n */\nfunction scalarWrapper(\n schema: JsonSchema,\n ctx: MapCtx,\n): { key: string; schema: JsonSchema } | undefined {\n const props = schema.properties as Record<string, JsonSchema> | undefined;\n const entries = props ? Object.entries(props) : [];\n const only = entries.length === 1 ? entries[0] : undefined;\n if (!only) return undefined;\n const [key, propSchema] = only;\n return { key, schema: collapseNullable(derefSchema(propSchema ?? {}, ctx.defs)) };\n}\n\n/** Build the recursive RunField for a single resolved schema node. */\nfunction mapSchema(\n name: string,\n conceptRef: string | undefined,\n rawSchema: JsonSchema,\n required: boolean,\n ctx: MapCtx,\n): RunField {\n const schema = collapseNullable(derefSchema(rawSchema, ctx.defs));\n // The LABEL is always the stuff name (the variable key) - that's what\n // identifies the input in the method. We deliberately do NOT use\n // `schema.title`, which is the pydantic model name (TextContent, ImageContent,\n // DocumentContent…) and would mask the stuff name. The concept pill carries\n // the type instead. `title` stays undefined here so FieldShell falls back to\n // `name`; list items still pass `title: ''` to suppress the per-row label.\n const common: RunFieldCommon = {\n name,\n conceptRef,\n description: typeof schema.description === 'string' ? schema.description : undefined,\n required,\n };\n\n const { base, isList } = splitListConcept(conceptRef);\n\n // List concepts (native.Text[], demo.Invoice[]) and array schemas.\n if (isList || schemaTypeOf(schema) === 'array') {\n const itemsSchema = (schema.items as JsonSchema) ?? {};\n const item = mapSchema(name, base, itemsSchema, true, { ...ctx, depth: ctx.depth + 1 });\n return { ...common, kind: 'list', item };\n }\n\n // Enum (a custom concept may refine a native with a fixed value set).\n if (Array.isArray(schema.enum)) {\n return { ...common, kind: 'enum', options: schema.enum.map(String) };\n }\n\n // Native concepts: map by concept_ref regardless of the wrapper schema shape.\n if (base) {\n if (FIELD_DOCUMENT_CONCEPTS.has(base))\n return { ...common, kind: 'document', accept: 'PDF, DOCX, TXT' };\n if (IMAGE_CONCEPTS.has(base)) return { ...common, kind: 'image', accept: 'PNG, JPG, WEBP' };\n\n // The three native scalars render as a bare control but travel inside the\n // content model their concept declares. `contentKey` carries that property\n // name to the value bridge, which is how the control can hold `2` while the\n // wire carries `{number: 2}`.\n const wrapper = scalarWrapper(schema, ctx);\n\n if (FIELD_TEXT_CONCEPTS.has(base) || HTML_CONCEPTS.has(base)) {\n // `Date` declares two properties, so no wrapper is found for it and the\n // `{text}` fallback answers instead - the recorded drift, kept until the\n // derivation swap (see `native-concepts.ts`).\n const contentKey = wrapper?.key ?? (TEXT_WRAPPER_CONCEPTS.has(base) ? 'text' : undefined);\n return ctx.depth === 0\n ? { ...common, contentKey, kind: 'prose' }\n : { ...common, contentKey, kind: 'text' };\n }\n if (NUMBER_CONCEPTS.has(base))\n return {\n ...common,\n contentKey: wrapper?.key,\n kind: 'number',\n // `NumberContent.number` is `int | float`, an unresolvable union, so the\n // control stays a float input. Constraints are read off the WRAPPED\n // property - the wrapper object never carries them, which is why the\n // outer schema always answered `undefined`.\n integer: false,\n min: numOrUndef(wrapper?.schema.minimum ?? schema.minimum),\n max: numOrUndef(wrapper?.schema.maximum ?? schema.maximum),\n };\n if (YES_NO_CONCEPTS.has(base)) return { ...common, contentKey: wrapper?.key, kind: 'boolean' };\n }\n\n // A custom concept whose schema looks like DocumentContent (refines Document).\n if (isDocumentObject(schema)) {\n return { ...common, kind: 'document', accept: 'PDF, DOCX, TXT' };\n }\n\n const type = schemaTypeOf(schema);\n switch (type) {\n case 'string': {\n if (base && (FIELD_DOCUMENT_CONCEPTS.has(base) || base === 'native.Document'))\n return { ...common, kind: 'document', accept: 'PDF, DOCX, TXT' };\n // A `date` structure field compiles to a `format: date`/`date-time`\n // string. Render it as a real date picker so the user picks a day - no\n // hand-typed timestamps - and stores a value the API accepts.\n if (schema.format === 'date' || schema.format === 'date-time')\n return { ...common, kind: 'date', datetime: schema.format === 'date-time' };\n // A top-level Text input is usually the main prompt (roomy textarea); the\n // same concept nested in a concept/list is usually a short attribute\n // (name, label) and reads better as a single line.\n const long =\n base && FIELD_TEXT_CONCEPTS.has(base)\n ? ctx.depth === 0\n : typeof schema.maxLength === 'number'\n ? schema.maxLength > 120\n : false;\n return long\n ? { ...common, kind: 'prose' }\n : { ...common, kind: 'text', placeholder: undefined };\n }\n case 'integer':\n return {\n ...common,\n kind: 'number',\n integer: true,\n min: numOrUndef(schema.minimum),\n max: numOrUndef(schema.maximum),\n };\n case 'number':\n return {\n ...common,\n kind: 'number',\n integer: false,\n min: numOrUndef(schema.minimum),\n max: numOrUndef(schema.maximum),\n };\n case 'boolean':\n return { ...common, kind: 'boolean' };\n case 'object': {\n const props = (schema.properties as Record<string, JsonSchema>) ?? {};\n const req = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []);\n const fields = Object.entries(props).map(([fieldName, fieldSchema]) =>\n mapSchema(fieldName, undefined, fieldSchema, req.has(fieldName), {\n ...ctx,\n depth: ctx.depth + 1,\n }),\n );\n return { ...common, kind: 'object', fields };\n }\n default:\n // A bare `native.Text` concept may arrive as `{type:'string'}` (handled\n // above) but a custom concept with no resolvable shape lands here.\n if (base && FIELD_TEXT_CONCEPTS.has(base))\n return ctx.depth === 0 ? { ...common, kind: 'prose' } : { ...common, kind: 'text' };\n return { ...common, kind: 'unknown' };\n }\n}\n\nfunction numOrUndef(v: unknown): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * Convert the API's per-input contracts into the runner's field descriptors.\n * The map's insertion order is preserved (required-first is the caller's job).\n */\nexport function buildRunFields(inputs: Record<string, PipeInputContract>): RunField[] {\n return Object.entries(inputs).map(([name, input]) => {\n const defs: Record<string, JsonSchema> = {};\n collectSchemaDefs(input.json_schema, defs, { traverseArrays: true });\n // A top-level input is required unless the method declared it optional (`?`).\n const field = mapSchema(name, input.concept_ref, input.json_schema, input.optional !== true, {\n defs,\n depth: 0,\n });\n // Whether Run gates on it is a SEPARATE question, and it is answered by the\n // contract, not by the shape we mapped it to - see `mustBeFilled`.\n return { ...field, gating: inputMustBeFilled(input) };\n });\n}\n","/**\n * Value readiness - the helpers the runner uses to decide whether the Run\n * button may fire and which inputs are still missing.\n */\n\nimport type { RunField } from './descriptor';\n\n/** True when a value is meaningfully filled (not empty / blank / empty container). */\nexport function isFilled(value: unknown): boolean {\n if (value == null || value === '') return false;\n if (Array.isArray(value)) return value.length > 0 && value.some(isFilled);\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // A file value is { url } - filled when the url is set.\n if ('url' in obj) return isFilled(obj.url);\n return Object.values(obj).some(isFilled);\n }\n return true;\n}\n\n/** True when every required field has a value. */\nexport function fieldFilled(field: RunField, value: unknown): boolean {\n if (field.kind === 'object') {\n if (!value || typeof value !== 'object') return field.fields.every((f) => !f.required);\n const obj = value as Record<string, unknown>;\n return field.fields.every((f) => !f.required || fieldFilled(f, obj[f.name]));\n }\n return isFilled(value);\n}\n\nexport interface Readiness {\n total: number;\n ready: number;\n missing: string[];\n}\n\n/**\n * True when the user must put a value in this field before the run can start.\n *\n * Distinct from `required`, which also drives layout (a required field always\n * shows; an optional one may collapse). A **plural** field stays required - it\n * is a first-class input and keeps its place in the form - but it never gates:\n * a plural slot is never \"absent\" in MTHDS, its empty form IS the empty list,\n * and no method can declare \"at least one item\".\n *\n * **For a field this package built, the answer comes from `inputMustBeFilled`**\n * (`contracts.ts`) - the SAME predicate the method viewer's Run button, its ajv\n * `required` list and its missing-inputs toast all read. `buildRunFields`\n * stamps it onto `gating`. This used to be re-derived here as\n * `required && kind !== 'list'`: the same rule expressed against the MAPPED\n * field instead of the contract, and the two could disagree - `kind` is `'list'`\n * for a `conceptRef` ending in `[]` OR an array schema, while the contract's\n * plural test is the array schema alone, so a plural input carrying a non-array\n * schema gated on one surface and not the other.\n *\n * The shape heuristic survives only as the fallback for a **hand-authored**\n * `RunField` - story fixtures and unit tests, which have no contract to consult\n * and therefore nothing to disagree with. Every field a host renders comes from\n * `buildRunFields` and carries `gating`, so a host is on the contract's answer\n * alone.\n */\nexport function mustBeFilled(field: RunField): boolean {\n return field.gating ?? (field.required && field.kind !== 'list');\n}\n\n/** How many gating top-level inputs are satisfied by the current values. */\nexport function computeReadiness(fields: RunField[], values: Record<string, unknown>): Readiness {\n const gating = fields.filter(mustBeFilled);\n const missing = gating\n .filter((f) => !fieldFilled(f, values[f.name]))\n .map((f) => f.title ?? f.name);\n return { total: gating.length, ready: gating.length - missing.length, missing };\n}\n","/**\n * Pure conversions between a stored date value and what a native `<input\n * type=\"date\">` shows, plus the leniency rules our schema validation uses.\n * Kept React-free so both the runner's `DateField` and the RJSF `DateWidget`\n * share one source of truth (and it's trivially unit-tested).\n *\n * Two schema shapes reach us, and they are NOT interchangeable:\n * - an MTHDS `type = \"date\"` structure field compiles to `format: date-time`,\n * so its value round-trips as a full RFC 3339 timestamp;\n * - `native.Date`'s own `date` field is a python `datetime.date`, i.e.\n * `format: date` - a bare `YYYY-MM-DD`.\n *\n * ## Why these rules exist\n *\n * The runtime (pydantic) is LENIENT in both directions, and our client used to\n * be stricter than the contract it was enforcing: `ajv`'s stock `format: \"date\"`\n * accepts a bare `YYYY-MM-DD` and nothing else, so a hand-written\n * `\"2026-07-06T00:00:00Z\"` in an `inputs.json` was rejected here even though\n * pydantic accepts it happily and coerces it to `date(2026, 7, 6)`. The run\n * never even reached the runner. These predicates mirror pydantic exactly\n * (measured, not assumed):\n *\n * format: date \"2026-07-06\" -> date(2026, 7, 6)\n * \"2026-07-06T00:00:00Z\" -> date(2026, 7, 6)\n * \"2026-07-06T00:00:00+02:00\" -> date(2026, 7, 6) (literal date, no UTC shift)\n * \"2026-07-06T15:40:00Z\" -> REJECTED \"should have zero time\"\n * format: date-time \"2026-07-06\" -> datetime(2026, 7, 6, 0, 0)\n * \"2026-07-06T00:00:00Z\" -> datetime(2026, 7, 6, 0, 0, tz)\n *\n * A midnight-padded timestamp is unambiguously \"just a day\", so take it. A real\n * time is data - refusing it is the point (`DateContentError`: \"no silent\n * midnight\"), because silently dropping 15:40 corrupts the value. And an\n * ambiguous `06/07/2026` is never accepted by anyone: 6 July or June 7 depends\n * on who's reading, and guessing wrong fails silently.\n */\n\n/** `YYYY-MM-DD`, no time. */\nconst FULL_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/**\n * A datetime whose clock reads exactly zero - optional seconds, optional\n * all-zero fraction, optional `Z`/offset. `00:00:01` and `00:00:00.001` do NOT\n * match: they carry a real time.\n */\nconst ZERO_TIME_DATE_TIME_RE =\n /^(\\d{4}-\\d{2}-\\d{2})[T ]00:00(?::00(?:\\.0+)?)?(?:Z|z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** Any RFC 3339-ish datetime we can hand to the runtime as a date-time. */\nconst DATE_TIME_RE =\n /^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?(?:Z|z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** Guards against `2026-02-30` - a well-formed string that isn't a real day. */\nfunction isRealCalendarDate(value: string): boolean {\n const match = FULL_DATE_RE.exec(value);\n if (!match) return false;\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];\n if (month < 1 || month > 12) return false;\n const date = new Date(Date.UTC(year, month - 1, day));\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n );\n}\n\n/**\n * The calendar day a value denotes, or `null` when it doesn't denote one.\n * Accepts a bare date or a midnight-padded timestamp; the day is taken\n * LITERALLY from the string (never shifted through a timezone), matching\n * pydantic - `2026-07-06T00:00:00+02:00` is 2026-07-06, not the 5th.\n */\nexport function asCalendarDate(value: string): string | null {\n if (isRealCalendarDate(value)) return value;\n const zeroTime = ZERO_TIME_DATE_TIME_RE.exec(value);\n if (zeroTime && isRealCalendarDate(zeroTime[1]!)) return zeroTime[1]!;\n return null;\n}\n\n/**\n * The calendar day inside a value that carries a REAL time - precisely the case\n * `asCalendarDate` refuses. `null` when the value isn't a timestamp at all, or\n * when it IS already an acceptable day (nothing to report).\n *\n * This exists to EXPLAIN, never to coerce. `2026-07-06T14:30:00+02:00` is\n * rejected for a `format: date` field, and the rejection is right (DT3, \"no\n * silent midnight\" - dropping 14:30 corrupts the value). But telling the user\n * \"pick a valid date\" while the picker shows them a perfectly good 06/07/2026\n * reads as a lie: `toDateInputValue` renders the day, the stored value carries\n * the time, and only one of those is what gets validated. Naming both the value\n * we hold and the day it would have to become is what makes the error legible.\n */\nexport function dayWithinDateTime(value: string): string | null {\n if (asCalendarDate(value) !== null) return null;\n const match = DATE_TIME_RE.exec(value);\n if (!match || !isRealCalendarDate(match[1]!)) return null;\n return match[1]!;\n}\n\n/**\n * What `format: \"date\"` accepts: a bare `YYYY-MM-DD`, and nothing else.\n *\n * DO NOT relax this to take a midnight-padded timestamp. `DateContent` in\n * pipelex carries a `mode=\"before\"` field validator (`_reject_lax_temporal`)\n * that deliberately CLOSES pydantic's lax coercion for exactly this case:\n *\n * \"A Date's `date` field takes a calendar date alone; a string carrying a\n * time (e.g. '2026-07-07T00:00:00') would drop it - put the time and offset\n * in `time` instead.\"\n *\n * That rule (DT3, \"no silent midnight\") is the concept's whole point, so a\n * lenient client here does not help anyone: it just forwards the value and the\n * runner answers with a 500 instead of the field saying so up front.\n *\n * The leniency belongs in `asCalendarDate` - normalize the pasted timestamp to\n * the day it denotes, then this passes. Accept-and-fix, not accept-and-forward.\n */\nexport function isAcceptableDate(value: string): boolean {\n return isRealCalendarDate(value);\n}\n\n/** What `format: \"date-time\"` should accept - a bare day is midnight. */\nexport function isAcceptableDateTime(value: string): boolean {\n if (isRealCalendarDate(value)) return true;\n const match = DATE_TIME_RE.exec(value);\n if (!match || !isRealCalendarDate(match[1]!)) return false;\n const [hours, minutes, seconds] = [Number(match[2]), Number(match[3]), Number(match[4] ?? 0)];\n return hours <= 23 && minutes <= 59 && seconds <= 59;\n}\n\n/** The `YYYY-MM-DD` a native date input shows, from any stored date/date-time. */\nexport function toDateInputValue(value: string | undefined): string {\n if (typeof value !== 'string') return '';\n return asCalendarDate(value) ?? value.slice(0, 10);\n}\n\n/**\n * The value to store for a picked day. A `date-time` field becomes midnight-UTC\n * (`2026-07-06T00:00:00Z`); a plain `date` field keeps the bare `YYYY-MM-DD`.\n * An empty day clears the value.\n */\nexport function toStoredDateValue(day: string, datetime: boolean): string | undefined {\n if (!day) return undefined;\n return datetime ? `${day}T00:00:00Z` : day;\n}\n","/**\n * The run gate's OWN validator - ajv direct, no RJSF.\n *\n * Until the form-kernel extraction the gate validated through\n * `@rjsf/validator-ajv8` (`rjsf-validator.ts`), which is an RJSF `ValidatorType`\n * wrapper around exactly this: an ajv instance plus an error-shape transform.\n * The kernel must not depend on RJSF, so this module owns both halves directly,\n * configured to reproduce its output but for one deliberate divergence:\n *\n * - the ajv OPTIONS are `@rjsf/validator-ajv8`'s `AJV_CONFIG` plus the same\n * `coerceTypes: true` override this gate has always run with (pydantic runs in\n * lax mode - `\"20\"` is a number, `\"5\"` an int - and rejecting client-side what\n * the runner accepts blocks valid work; see `rjsf-validator.ts`);\n * - the `date` / `date-time` formats are the pydantic-parity predicates from\n * `date-format.ts`, same as before;\n * - `toRunInputError` reproduces RJSF's `transformRJSFValidationErrors` for the\n * no-uiSchema case the gate is: `property` is the dotted instance path (plus\n * the missing property name for `required` errors), and `stack` quotes the\n * parent schema's `title` when the error does not itself name a property.\n *\n * It diverges from RJSF in exactly one place, and deliberately: an error that\n * NAMES a property keeps the property's own name rather than swapping in that\n * property's schema `title`. RJSF substitutes because the title is the label its\n * forms render; this package labels a field by its identifier instead, so the\n * substitution named something the user could not find. See `toRunInputError`.\n */\nimport Ajv, { type ErrorObject } from 'ajv';\nimport addFormats from 'ajv-formats';\nimport { isAcceptableDate, isAcceptableDateTime } from './date-format';\n\n/**\n * One validation error, in the shape hosts read (`property`, `message`,\n * `name`, `stack`, `params.format`). Structurally a superset-compatible twin of\n * RJSF's `RJSFValidationError`, so a host surface still holding RJSF form errors\n * (an RJSF-based inputs panel) can hand them to the same message renderer.\n */\nexport interface RunInputError {\n /** The ajv keyword that failed (`required`, `format`, `type`, …). */\n name?: string;\n /** Dotted path into the form data (`.quote_date.date`); for a `required`\n * error the missing property name is appended (top-level: no leading dot). */\n property?: string;\n message?: string;\n params?: Record<string, unknown>;\n /** The human line: `property message`, or `'title' message` when the parent\n * schema titles the field. */\n stack: string;\n schemaPath?: string;\n}\n\n// The exact instance `@rjsf/validator-ajv8` builds (its AJV_CONFIG + the\n// standard ajv-formats + its two custom formats), plus our two overrides.\nconst ajv = new Ajv({\n allErrors: true,\n multipleOfPrecision: 8,\n strict: false,\n verbose: true,\n discriminator: false,\n coerceTypes: true,\n});\naddFormats(ajv);\najv.addFormat('data-url', /^data:([a-z]+\\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/);\najv.addFormat(\n 'color',\n /^(#?([0-9A-Fa-f]{3}){1,2}\\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\\(\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*\\))|(rgb\\(\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*\\)))$/,\n);\n// Pydantic-parity leniency, replacing ajv-formats' spec-strict versions: a\n// midnight-padded timestamp IS a date, a bare day IS a date-time. Measured\n// against pydantic in `date-format.ts` - keep in step with the runtime, not\n// with the JSON Schema spec.\najv.addFormat('date', isAcceptableDate);\najv.addFormat('date-time', isAcceptableDateTime);\n\n/**\n * Validate `data` against `schema`, returning mapped errors (empty = valid).\n * MUTATES `data` where ajv coerces (`\"20\"` → `20`) - deliberate and relied on:\n * the string the user typed is stored as a number going forward.\n */\nexport function validateRunInputsSchema(data: unknown, schema: object): RunInputError[] {\n let validate;\n try {\n validate = ajv.compile(schema);\n } catch (err) {\n // A malformed schema produces a verdict-less failure, same as RJSF's\n // `validationError` path: one bare-stack error, nothing to pin on a field.\n return [{ stack: err instanceof Error ? err.message : String(err) }];\n }\n validate(data);\n const errors = (validate.errors ?? []).map(toRunInputError);\n validate.errors = null;\n return errors;\n}\n\n/** RJSF's `transformRJSFValidationErrors`, minus the uiSchema lookups the gate\n * never had (it passes no uiSchema). */\nfunction toRunInputError(e: ErrorObject): RunInputError {\n const { instancePath, keyword, schemaPath, parentSchema } = e;\n const params = e.params as Record<string, unknown>;\n const message = e.message ?? '';\n let property = instancePath.replace(/\\//g, '.');\n let stack = `${property} ${message}`.trim();\n\n const namesAProperty = [\n ...(typeof params.deps === 'string' ? params.deps.split(', ') : []),\n params.missingProperty,\n params.property,\n ].some((item) => typeof item === 'string' && item.length > 0);\n\n if (namesAProperty) {\n // ajv already quotes the property NAME, and that is the name kept - the ONE\n // deliberate divergence from RJSF, which substitutes the parent schema's\n // `properties[name].title` here. That substitution is right in an RJSF form,\n // where the title IS the rendered label; it is wrong for this package, whose\n // controls label a field by its identifier on purpose (see `mapSchema`). A\n // pydantic contract titles `audience` as `Audience`, so the blocked run read\n // `must have required property 'Audience'` and sent the user hunting for a\n // field their bundle does not contain.\n stack = message;\n } else {\n const parentTitle = (parentSchema as { title?: unknown } | undefined)?.title;\n if (typeof parentTitle === 'string' && parentTitle) {\n stack = `'${parentTitle}' ${message}`.trim();\n }\n }\n\n if ('missingProperty' in params) {\n const missing = String(params.missingProperty);\n property = property ? `${property}.${missing}` : missing;\n }\n\n return { name: keyword, property, message, params, stack, schemaPath };\n}\n","/**\n * Converts between the simplified inputs.json format and the full RJSF form format.\n *\n * The inputs.json file uses a SIMPLIFIED format for users:\n * - Text: \"my text\" (instead of { text: \"my text\" })\n * - Document: \"file.pdf\" or { url: \"...\" } (instead of { url: \"...\", ... })\n * - Image: same as Document\n * - Text[]: [\"t1\", \"t2\"]\n * - Document[]: [\"f1.pdf\"] or [{ url: \"...\" }]\n * - Custom: { concept, content } (no simplification)\n *\n * The RJSF form uses the FULL concept structure from the json_schema.\n *\n * Two directions:\n * - deflate: form (full) → inputs.json (simplified) - for writing inputs.json / API calls\n * - inflate: inputs.json (simplified) → form (full) - for populating the form from inputs.json\n */\n\nimport { asCalendarDate } from './date-format';\nimport { isWireDocumentLikeConcept, isWireTextConcept, splitListConcept } from './native-concepts';\nimport { collectSchemaDefs, resolveSchemaIndirection, schemaTypeOf } from './schema-utils';\n\n/** The wire-format view of the native-concept taxonomy (which concept codes use\n * simplified formats) lives in `native-concepts.ts` - including the record of\n * where it drifts from the field mapper's view. */\nfunction isListConcept(conceptCode: string): { isList: boolean; baseConcept: string } {\n const { base, isList } = splitListConcept(conceptCode);\n return { isList, baseConcept: base ?? '' };\n}\n\nconst isTextConcept = isWireTextConcept;\nconst isDocumentLikeConcept = isWireDocumentLikeConcept;\n\n// ─── Deflate: form (full) → inputs.json (simplified) ──────────────────────\n\n/**\n * Convert a single form value to the simplified inputs.json format.\n * Used when writing inputs.json and when calling the run API.\n *\n * Rules:\n * - Text { text: \"hello\" } → \"hello\"\n * - Document { url: \"file.pdf\", ... } → \"file.pdf\" (if only url) or { url, ... }\n * - Image: same as Document\n * - Page: same as Document\n * - List types → array of deflated items\n * - Custom → { concept, content }\n */\nexport function deflateInput(value: unknown, conceptCode: string): unknown {\n const { isList, baseConcept } = isListConcept(conceptCode);\n\n if (isList) {\n const items = Array.isArray(value) ? value : [];\n // pipelex accepts Sequence[str] for list inputs, not list of dicts.\n // Always simplify list items to their scalar form (URL string for docs, plain string for text).\n return items.map((item) => deflateListItem(item, baseConcept));\n }\n\n return deflateSingleValue(value, baseConcept);\n}\n\n/** Deflate a single item within a list - always reduces to the simplest scalar form. */\nfunction deflateListItem(value: unknown, concept: string): unknown {\n if (isTextConcept(concept)) {\n if (value && typeof value === 'object' && 'text' in value) {\n return (value as { text: string }).text;\n }\n return typeof value === 'string' ? value : String(value ?? '');\n }\n\n if (isDocumentLikeConcept(concept)) {\n // Always extract just the URL for list items - pipelex resolves metadata at runtime\n if (value && typeof value === 'object' && 'url' in value) {\n return (value as { url: string }).url;\n }\n if (typeof value === 'string') return value;\n return '';\n }\n\n // Custom structured concept → { concept, content }.\n //\n // IDEMPOTENT ON PURPOSE - see `unwrapAllWrappers`. Wrapping unconditionally\n // corrupted persisted inputs: a host panel seeds the form with the RAW\n // stored value when the input schemas aren't loaded yet (no dry run yet),\n // so the form could hold an ALREADY-wrapped value; the next change deflated\n // it again and saved `{ concept, content: { concept, content: {...} } }`.\n // Wrapping exactly once, whatever we're handed, makes that unreachable.\n return { concept, content: unwrapAllWrappers(value) };\n}\n\nfunction deflateSingleValue(value: unknown, concept: string): unknown {\n if (isTextConcept(concept)) {\n // { text: \"hello\" } → \"hello\"\n if (value && typeof value === 'object' && 'text' in value) {\n return (value as { text: string }).text;\n }\n // Already a string (passthrough)\n return typeof value === 'string' ? value : String(value ?? '');\n }\n\n if (isDocumentLikeConcept(concept)) {\n // Always extract just the URL - pipelex resolves metadata at runtime.\n // A bare dict without a 'concept' key is rejected by StuffFactory.\n if (value && typeof value === 'object' && 'url' in value) {\n return (value as { url: string }).url;\n }\n // Already a string URL (passthrough)\n if (typeof value === 'string') return value;\n return '';\n }\n\n // Custom structured concept → { concept, content }.\n //\n // IDEMPOTENT ON PURPOSE - see `unwrapAllWrappers`. Wrapping unconditionally\n // corrupted persisted inputs: a host panel seeds the form with the RAW\n // stored value when the input schemas aren't loaded yet (no dry run yet),\n // so the form could hold an ALREADY-wrapped value; the next change deflated\n // it again and saved `{ concept, content: { concept, content: {...} } }`.\n // Wrapping exactly once, whatever we're handed, makes that unreachable.\n return { concept, content: unwrapAllWrappers(value) };\n}\n\n// ─── Inflate: inputs.json (simplified) → form (full) ──────────────────────\n\n/**\n * Convert a simplified inputs.json value to the full form structure.\n * Used when populating the RJSF form from inputs.json.\n *\n * Rules:\n * - \"hello\" → { text: \"hello\" } (for Text concepts)\n * - \"file.pdf\" → { url: \"file.pdf\" } (for Document/Image/Page concepts)\n * - { url: \"...\" } → passthrough (already full)\n * - [\"t1\", \"t2\"] → inflated array of items\n * - { concept, content } → content (for custom concepts)\n */\nexport function inflateInput(value: unknown, conceptCode: string): unknown {\n const { isList, baseConcept } = isListConcept(conceptCode);\n\n if (isList) {\n // The sandbox may write the wrapped form at the LIST level:\n // { concept: \"native.Document\", content: [item, item] } - pipelex accepts it.\n // Unwrap before the array check, otherwise the wrapper itself gets treated\n // as a single list item and inflates to one empty entry.\n const unwrapped = isWrappedForm(value) ? value.content : value;\n // Handle: array (correct), single object (legacy/form default), or null/undefined\n let items: unknown[];\n if (Array.isArray(unwrapped)) {\n items = unwrapped;\n } else if (unwrapped != null && typeof unwrapped === 'object') {\n // Single object instead of array (e.g., {\"url\": \"\"} from form default) - wrap it\n items = [unwrapped];\n } else {\n items = [];\n }\n return items.map((item) => inflateSingleValue(item, baseConcept));\n }\n\n return inflateSingleValue(value, baseConcept);\n}\n\n/** Known optional fields on DocumentContent (from pipelex Pydantic model). */\nconst DOCUMENT_FIELDS = new Set(['url', 'public_url', 'mime_type', 'filename', 'title', 'snippet']);\n\n/** Returns true if the object looks like a DocumentContent (has any known doc field). */\nfunction looksLikeDocument(obj: Record<string, unknown>): boolean {\n return Object.keys(obj).some((k) => DOCUMENT_FIELDS.has(k));\n}\n\n/**\n * Detect the fully-qualified wrapper form `{ concept: \"...\", content: ... }`.\n * pipelex accepts this for any concept (native or custom), and the mthds-inputs\n * agent skill writes it by default for disambiguation. We unwrap before applying\n * concept-specific inflation so the form populates correctly.\n */\nfunction isWrappedForm(value: unknown): value is { concept: string; content: unknown } {\n return (\n !!value &&\n typeof value === 'object' &&\n 'concept' in value &&\n 'content' in value &&\n typeof (value as { concept: unknown }).concept === 'string'\n );\n}\n\nfunction inflateSingleValue(value: unknown, concept: string): unknown {\n // Unwrap { concept, content } for native concepts - the content IS the value.\n // For custom concepts we unwrap below (historical behaviour) but after concept-specific checks.\n if (isWrappedForm(value) && (isTextConcept(concept) || isDocumentLikeConcept(concept))) {\n return inflateSingleValue(value.content, concept);\n }\n\n if (isTextConcept(concept)) {\n // \"hello\" → { text: \"hello\" }\n if (typeof value === 'string') {\n return { text: value };\n }\n // Already full structure { text: \"...\" }\n if (value && typeof value === 'object' && 'text' in value) {\n return value;\n }\n return { text: '' };\n }\n\n if (isDocumentLikeConcept(concept)) {\n // \"file.pdf\" → { url: \"file.pdf\" }\n if (typeof value === 'string') {\n return { url: value };\n }\n // Already full structure { url: \"...\" }\n if (value && typeof value === 'object' && 'url' in value) {\n return value;\n }\n // Object without url key but with other document fields (e.g. from RJSF defaults)\n // Ensure the required url field is present\n if (value && typeof value === 'object' && looksLikeDocument(value as Record<string, unknown>)) {\n return { ...(value as Record<string, unknown>), url: '' };\n }\n return { url: '' };\n }\n\n // Custom structured: unwrap { concept, content } → content.\n //\n // Unwrap REPEATEDLY. `deflateSingleValue` used to wrap unconditionally, so a\n // form change made while the input schemas weren't loaded yet re-wrapped an\n // already-wrapped value and persisted `{ concept, content: { concept,\n // content: {...} } }` to DynamoDB. Unwrapping a single level left the FORM\n // holding `{ concept, content }` - properties no schema declares, so RJSF\n // matched nothing and rendered every field empty, with the real values\n // sitting one level deeper. Deflate is idempotent now, but the corrupted\n // shape survives in persisted inputData, so this heals it on read.\n return unwrapAllWrappers(value);\n}\n\n/** Strip every `{ concept, content }` layer - one, or the double wrap a\n * non-idempotent deflate persisted. */\nfunction unwrapAllWrappers(value: unknown): unknown {\n let current = value;\n while (isWrappedForm(current)) {\n current = current.content;\n }\n // A `{ content }` with no `concept` is the historical half-wrapper.\n if (current && typeof current === 'object' && !Array.isArray(current) && 'content' in current) {\n return (current as { content: unknown }).content;\n }\n return current;\n}\n\n// ─── Schema helpers ─────────────────────────────────────────────────────\n\ninterface InputSchema {\n concept_ref: string;\n json_schema?: Record<string, unknown>;\n}\n\n/**\n * The validation API returns concept_ref WITHOUT the [] suffix for list inputs.\n * The array-ness is only encoded in json_schema.type === \"array\".\n * This helper resolves the correct concept ref by checking the schema.\n */\nexport function resolveConceptCode(schema: InputSchema): string {\n const code = schema.concept_ref;\n // Defensive: a malformed/partial contract entry (missing concept) must\n // degrade, never throw and blank the whole input panel.\n if (!code) return '';\n if (!code.endsWith('[]') && (schema.json_schema as Record<string, unknown>)?.type === 'array') {\n return code + '[]';\n }\n return code;\n}\n\n// ─── Batch helpers for full inputData objects ────────────────────────────\n\n/**\n * Deflate all inputs from form format to simplified inputs.json format.\n * Used by InputConfigPanel when preparing data for the run API.\n */\nexport function deflateAllInputs(\n formData: Record<string, unknown>,\n inputSchemas: Record<string, InputSchema>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [stuffName, schema] of Object.entries(inputSchemas)) {\n result[stuffName] = deflateInput(formData[stuffName], resolveConceptCode(schema));\n }\n return result;\n}\n\n/**\n * Heal values against their json_schema: the run-form bridge used to\n * double-wrap plain string properties as `{ text: \"...\" }` (fixed in\n * run-values.ts, but the corrupted shape survives in persisted inputData -\n * store and server copies). Wherever the schema expects a string but the\n * value is a lone `{ text: string }` wrapper, unwrap it. Walks nested\n * objects and arrays, resolving `#/$defs/...` refs against the root schema;\n * anything already valid passes through untouched.\n */\nexport function healStringWrappers(\n value: unknown,\n rawSchema: Record<string, unknown> | undefined,\n defs?: Record<string, Record<string, unknown>>,\n): unknown {\n if (!rawSchema || value == null) return value;\n\n // Resolve $ref / nullable-anyOf indirection (Pydantic emits `{$ref}` for\n // nested models and `anyOf: [T, {type:'null'}]` for optionals). The `$defs`\n // walk deliberately keeps its historical no-array-traversal mode - see\n // `CollectDefsOptions` in schema-utils.\n const allDefs = defs ?? collectSchemaDefs(rawSchema, {}, { traverseArrays: false });\n const schema = resolveSchemaIndirection(rawSchema, allDefs);\n const type = schemaTypeOf(schema);\n\n // A `format: date` field takes a calendar date ALONE. `DateContent` in pipelex\n // enforces that with a `mode=\"before\"` validator (`_reject_lax_temporal`) that\n // deliberately closes pydantic's lax coercion - a datetime string on `date`\n // would silently drop its time and offset (DT3, \"no silent midnight\"), so the\n // runner answers a 500, not a coercion.\n //\n // An agent-written or hand-written inputs.json says `\"2026-07-06T00:00:00Z\"`\n // anyway - that is how every system exports a date. So NORMALIZE it here to\n // the day it denotes rather than forwarding it to fail at the runner: the\n // padding is noise, and dropping noise is not the fidelity loss DT3 forbids.\n // A value carrying a REAL time (15:40) returns null and is left untouched -\n // it must fail, because silently discarding it is precisely the corruption\n // the rule exists to prevent.\n if (type === 'string' && schema.format === 'date' && typeof value === 'string') {\n return asCalendarDate(value) ?? value;\n }\n\n if (type === 'string') {\n if (\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length === 1 &&\n typeof (value as { text?: unknown }).text === 'string'\n ) {\n return (value as { text: string }).text;\n }\n return value;\n }\n if (type === 'object' && typeof value === 'object' && !Array.isArray(value)) {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return value;\n const out = { ...(value as Record<string, unknown>) };\n for (const [key, propSchema] of Object.entries(props)) {\n if (key in out) out[key] = healStringWrappers(out[key], propSchema, allDefs);\n }\n return out;\n }\n if (type === 'array' && Array.isArray(value)) {\n const items = schema.items as Record<string, unknown> | undefined;\n return value.map((item) => healStringWrappers(item, items, allDefs));\n }\n return value;\n}\n\n/** Nothing left worth sending, once this value has itself been pruned. */\nfunction isEmptyAfterPruning(value: unknown): boolean {\n if (value === '' || value === null || value === undefined) return true;\n // An object whose every property was itself pruned away carries nothing, and\n // that is what an untouched OPTIONAL STRUCTURED input looks like by the time\n // it reaches here - a shell of empty children, emptied out. Keeping the `{}`\n // handed it to ajv against the concept's full schema, which rejected the run\n // for a required child of an input the method said may be omitted. Dropping\n // it is the same judgement the wire payload already makes one step later\n // (`apiInputsFromSchemaData` omits it as unfilled); making the prune agree is\n // what stops the gate from failing a run it was about to omit anyway.\n //\n // An empty ARRAY is deliberately NOT empty: a plural slot is never absent in\n // MTHDS - its empty form IS the empty list - so dropping it would invent an\n // absence the method cannot express.\n return typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0;\n}\n\n/**\n * Drop optional properties the user never filled, so an untouched field cannot\n * fail validation or reach the API as an empty string.\n *\n * RJSF fills EVERY unset string property with `\"\"` on mount. That is harmless\n * for a plain string, but `prepareSchemaForRjsf` collapses pydantic's\n * `anyOf: [T, null]` by dropping the null branch, so an optional *constrained*\n * field - `DateContent.time`, declared `datetime.time | None` and rendered\n * `{ type: \"string\", format: \"time\" }` - is left demanding a well-formed time.\n * `\"\"` is not one, and the run was blocked on a field the user never opened.\n *\n * Pruning is the semantically correct repair, not a validation dodge: for\n * pipelex an absent optional field IS `None`, and `\"\"` would fail pydantic at\n * the runner just as it fails ajv here. Only properties absent from their\n * parent's `required` are dropped - an empty REQUIRED field must still fail, so\n * the user is told about it.\n *\n * What counts as empty is `isEmptyAfterPruning`, and it includes an optional\n * STRUCTURE the user never opened, on exactly the same grounds.\n */\nexport function pruneEmptyOptionals(\n value: unknown,\n rawSchema: Record<string, unknown> | undefined,\n defs?: Record<string, Record<string, unknown>>,\n): unknown {\n if (!rawSchema || value == null) return value;\n\n const allDefs = defs ?? collectSchemaDefs(rawSchema, {}, { traverseArrays: false });\n const schema = resolveSchemaIndirection(rawSchema, allDefs);\n const type = schemaTypeOf(schema);\n\n if (type === 'array' && Array.isArray(value)) {\n const items = schema.items as Record<string, unknown> | undefined;\n return value.map((item) => pruneEmptyOptionals(item, items, allDefs));\n }\n if (type !== 'object' || typeof value !== 'object' || Array.isArray(value)) return value;\n\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return value;\n const required = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []);\n const out: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {\n const propSchema = props[key];\n if (!propSchema) {\n out[key] = raw;\n continue;\n }\n const pruned = pruneEmptyOptionals(raw, propSchema, allDefs);\n if (isEmptyAfterPruning(pruned) && !required.has(key)) continue;\n out[key] = pruned;\n }\n return out;\n}\n\n/**\n * Inflate all inputs from simplified inputs.json format to form format.\n * Used by onInputUpdate when receiving inputs.json changes from the sandbox.\n */\nexport function inflateAllInputs(\n simplifiedData: Record<string, unknown>,\n inputSchemas: Record<string, InputSchema>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [stuffName, value] of Object.entries(simplifiedData)) {\n const schema = inputSchemas[stuffName];\n if (schema) {\n result[stuffName] = healStringWrappers(\n inflateInput(value, resolveConceptCode(schema)),\n schema.json_schema,\n );\n } else {\n // Unknown input - pass through unchanged\n result[stuffName] = value;\n }\n }\n return result;\n}\n","/**\n * Normalizes a JSON Schema for RJSF compatibility.\n *\n * Pydantic v2 generates `anyOf: [{type: \"string\"}, {type: \"null\"}]` for optional\n * fields (`str | None`). RJSF renders this as a dropdown selector asking the user\n * to pick a sub-schema, which is terrible UX. The normalizer flattens those\n * patterns on every node (see `flattenAnyOf` in `schema-utils.ts` for the exact\n * rules) and hoists nested `$defs` to the root so composed sub-schemas keep\n * their refs resolvable.\n *\n * The collapse and hoist engines live in `schema-utils.ts` - the\n * consolidated home for the kernel's JSON-Schema plumbing; this module owns the\n * recursive application over a whole schema tree.\n */\nimport { flattenAnyOf, hoistDefsToRoot } from './schema-utils';\n\nexport { hoistDefsToRoot };\n\n/**\n * Recursively normalize a JSON Schema for RJSF.\n * Walks the entire schema tree and flattens anyOf patterns on every node.\n */\nexport function normalizeSchemaForRjsf(schema: Record<string, unknown>): Record<string, unknown> {\n // Flatten anyOf at this level\n let normalized = flattenAnyOf(schema);\n\n // Recurse into properties\n if (normalized.properties && typeof normalized.properties === 'object') {\n const props = normalized.properties as Record<string, unknown>;\n const normalizedProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props)) {\n normalizedProps[key] =\n value && typeof value === 'object'\n ? normalizeSchemaForRjsf(value as Record<string, unknown>)\n : value;\n }\n normalized = { ...normalized, properties: normalizedProps };\n }\n\n // Recurse into items (array schemas)\n if (\n normalized.items &&\n typeof normalized.items === 'object' &&\n !Array.isArray(normalized.items)\n ) {\n normalized = {\n ...normalized,\n items: normalizeSchemaForRjsf(normalized.items as Record<string, unknown>),\n };\n }\n\n // Recurse into anyOf branches that weren't flattened (complex unions)\n if (Array.isArray(normalized.anyOf)) {\n normalized = {\n ...normalized,\n anyOf: (normalized.anyOf as Record<string, unknown>[]).map((branch) =>\n typeof branch === 'object' && branch !== null\n ? normalizeSchemaForRjsf(branch as Record<string, unknown>)\n : branch,\n ),\n };\n }\n\n // Recurse into $defs so nested definitions (e.g. ImageSize) also get anyOf normalized\n if (\n normalized.$defs &&\n typeof normalized.$defs === 'object' &&\n !Array.isArray(normalized.$defs)\n ) {\n const defs = normalized.$defs as Record<string, unknown>;\n const normalizedDefs: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(defs)) {\n normalizedDefs[key] =\n value && typeof value === 'object'\n ? normalizeSchemaForRjsf(value as Record<string, unknown>)\n : value;\n }\n normalized = { ...normalized, $defs: normalizedDefs };\n }\n\n return normalized;\n}\n\n/**\n * Prepare a schema for RJSF: hoist all nested `$defs` to the root, then normalize\n * anyOf patterns. Call this on any schema that composes multiple sub-schemas\n * (each of which may ship its own `$defs`).\n */\nexport function prepareSchemaForRjsf(schema: Record<string, unknown>): Record<string, unknown> {\n return normalizeSchemaForRjsf(hoistDefsToRoot(schema));\n}\n","/**\n * The gate every run passes through, whichever surface starts it.\n *\n * A host may offer more than one place to run a method - a schema-driven\n * inputs panel (an RJSF form) and a standalone run page (a bespoke field\n * renderer), say. **Only the rendering of inputs differs.** Everything between\n * \"the user pressed Run\" and \"the payload goes on the wire\" lives here, so\n * those surfaces cannot drift:\n *\n * 1. `buildRunInputsSchema` - the combined JSON Schema, whose `required` list\n * is `inputMustBeFilled` (optional `?` and plural `[]` never block).\n * 2. `prepareRunInputs` - heal legacy wrappers, then prune empty optionals.\n * 3. `validateRunInputs` - ajv, plus the missing-input scan that names the\n * VARIABLE at fault.\n * 4. `apiInputsFromSchemaData` - the `{concept, content}` payload, built from\n * the PREPARED data so the pruning reaches the wire too.\n *\n * This module is pure: no React, no toasts, no i18n. Each caller renders the\n * verdict in its own idiom.\n */\nimport { inputMustBeFilled, isPluralInput } from './contracts';\nimport { isFilled } from './readiness';\nimport { validateRunInputsSchema, type RunInputError } from './gate-validator';\nimport { healStringWrappers, pruneEmptyOptionals } from './wire-format';\nimport { prepareSchemaForRjsf } from './normalize-schema';\nimport type { PipeInputContract } from './contracts';\n\ntype Dict = Record<string, unknown>;\n\n/**\n * Combine the per-input schemas into one object schema.\n *\n * Each input variable becomes a property, titled with the variable name and\n * described with the concept code. Only the inputs the method actually demands\n * land in `required` - an optional (`?`) or plural (`[]`) input must not block\n * the form (see `inputMustBeFilled`).\n */\nexport function buildRunInputsSchema(inputs: Record<string, PipeInputContract>): Dict {\n const properties: Dict = {};\n const required: string[] = [];\n\n for (const [varName, input] of Object.entries(inputs)) {\n const inputSchema = { ...input.json_schema } as Dict;\n inputSchema.title = varName;\n if (input.concept_ref && input.concept_ref !== varName) {\n inputSchema.description = input.concept_ref;\n }\n properties[varName] = inputSchema;\n if (inputMustBeFilled(input)) required.push(varName);\n }\n\n return prepareSchemaForRjsf({ type: 'object', properties, required });\n}\n\n/**\n * Last-gate repair, in two passes against the exact schema ajv validates.\n *\n * 1. **HEAL** - persisted `inputData` may still carry the legacy double-wrapped\n * `{ text: { text } }` shape (or a form's state may lag a store fix).\n * 2. **PRUNE** - RJSF fills every unset string with `\"\"` on mount, which an\n * optional CONSTRAINED field rejects (`DateContent.time` is `format: \"time\"`)\n * - blocking a run on a field the user never opened. An absent optional field\n * is what pipelex means by `None` anyway, so dropping it is the semantically\n * correct repair, not a validation dodge.\n */\nexport function prepareRunInputs(data: Dict, schema: Dict): Dict {\n return pruneEmptyOptionals(healStringWrappers(data, schema), schema) as Dict;\n}\n\nexport interface RunInputsVerdict {\n isValid: boolean;\n /** Variable names the scan could pin a missing required field on. */\n missingInputs: string[];\n /** Raw ajv errors, for when the scan cannot name anything. */\n errors: RunInputError[];\n}\n\n/**\n * Validate PREPARED data against the combined schema.\n *\n * `missingInputs` is reported by VARIABLE NAME - the name on the node the user\n * clicks - never by `concept_ref`, which used to produce \"Missing required\n * fields in: native.Text\" and named neither the input at fault nor, when several\n * inputs share a concept, which of them. Inputs the method declared omittable\n * are skipped: an empty `?` input is not a missing one.\n *\n * The scan can come up empty even on an invalid form (a wrong value shape, a\n * nested mismatch); `errors` is what the caller falls back to then, so a failure\n * is never undiagnosable.\n */\nexport function validateRunInputs(\n preparedData: Dict,\n inputs: Record<string, PipeInputContract>,\n schema: Dict,\n): RunInputsVerdict {\n const errors = validateRunInputsSchema(preparedData, schema);\n if (errors.length === 0) return { isValid: true, missingInputs: [], errors: [] };\n\n const missingInputs: string[] = [];\n for (const [varName, input] of Object.entries(inputs)) {\n if (!inputMustBeFilled(input)) continue;\n const varData = preparedData[varName];\n const inputSchema = input.json_schema as Dict;\n const requiredFields = (inputSchema.required as string[]) || [];\n if (requiredFields.length === 0) continue;\n if (!varData || typeof varData !== 'object') {\n missingInputs.push(varName);\n continue;\n }\n const record = varData as Dict;\n if (requiredFields.some((f) => record[f] === undefined || record[f] === '')) {\n missingInputs.push(varName);\n }\n }\n\n return { isValid: false, missingInputs, errors };\n}\n\n/**\n * Build the `{ concept, content }` map a run expects, from PREPARED data.\n *\n * The two ways a method says \"this may be nothing\" land differently on the wire:\n * - an **optional (`?`)** input left blank is OMITTED, so the runtime records a\n * real absence the method can branch on - sending `{ text: \"\" }` would look\n * like the caller supplied an empty string;\n * - a **plural (`[]`)** input keeps its key, because a plural slot is never\n * absent - its empty form IS the empty list, and the runtime requires the key.\n * When that list is EMPTY it is sent BARE, without the envelope: the envelope\n * is the runtime's \"explicit form\", which bypasses the top-down shaper and\n * hands the value to the bottom-up factory, and that factory types a list from\n * its first item - so an empty list there raises \"Cannot create Stuff from\n * empty list in content\". The bare form keeps the shaper, which reads the\n * DECLARED concept and builds the empty list correctly. (pipelex/#1096 makes\n * the envelope agree; the bare form runs today and stays correct after.)\n */\nexport function apiInputsFromSchemaData(\n preparedData: Dict,\n inputs: Record<string, PipeInputContract>,\n): Dict {\n const out: Dict = {};\n for (const [varName, input] of Object.entries(inputs)) {\n const raw = preparedData[varName];\n if (input.optional === true && !isFilled(raw)) continue;\n if (isPluralInput(input) && !isFilled(raw)) {\n out[varName] = [];\n continue;\n }\n const content = isPluralInput(input) && !Array.isArray(raw) ? [] : raw;\n out[varName] = { concept: input.concept_ref, content };\n }\n return out;\n}\n","/**\n * Bridges the `MethodRunner`'s field values to the rest of the host.\n *\n * The method-store keeps inputs in the *simplified* format and runs send the\n * *full* RJSF form shape - both already handled by `inflate/deflateAllInputs`.\n * The only gap is that a few field controls use a friendlier value than RJSF: a\n * scalar is the bare scalar where the full shape is the content model its\n * concept declares (`{ text }`, `{ number }`, `{ yes_no }`), and a file is\n * `{ url, filename }`. `fromRjsf`/`toRjsf` translate just those, so store\n * reads/writes and run payloads stay byte-for-byte compatible with the proven\n * playground path.\n *\n * Which property a scalar wraps into is NOT decided here - it arrives on the\n * descriptor as `contentKey`, derived from the contract by `buildRunFields`.\n *\n * Pure module - no React, unit-tested.\n */\nimport type { RunField } from './descriptor';\nimport { buildRunFields } from './derive';\nimport { isFilled } from './readiness';\nimport { isPluralInput } from './contracts';\nimport { deflateAllInputs, inflateAllInputs } from './wire-format';\nimport type { PipeIOContract, PipeInputContract } from './contracts';\n\ntype Dict = Record<string, unknown>;\ntype InputSchemas = Record<string, PipeInputContract>;\n\n// ─── RJSF full shape ↔ RunField value ──────────────────────────────────────\n\n/**\n * Put a scalar back inside the content model its concept declares:\n * `\"hi\"` → `{ text: \"hi\" }`, `2` → `{ number: 2 }`, `false` → `{ yes_no: false }`.\n *\n * The property name comes from the DESCRIPTOR (`contentKey`, stamped by\n * `buildRunFields` - the only reader of JSON Schema). This module holds no\n * taxonomy of its own, which is the point: the version that did held a list of\n * concepts that wrap, `native.Number` was missing from it, and every run\n * carrying a number was rejected by the gate against `NumberContent`.\n *\n * A field with no `contentKey` keeps its value plain. That is not an oversight\n * either - a child property of a structured concept, or a custom concept whose\n * schema is a bare string, IS its value, and wrapping it double-nests it\n * (`{ text: { text } }`) into a payload no schema accepts.\n */\nfunction wrapContent(field: RunField, value: unknown): unknown {\n return field.contentKey === undefined ? value : { [field.contentKey]: value };\n}\n\n/**\n * The inverse. A value that is already bare passes through untouched: persisted\n * `inputData` predates the number and yes/no wrappers, and an inputs.json\n * written by hand or by an agent says `2`, not `{number: 2}`.\n */\nfunction unwrapContent(field: RunField, value: unknown): unknown {\n const key = field.contentKey;\n if (key === undefined || !value || typeof value !== 'object' || Array.isArray(value))\n return value;\n return (value as Record<string, unknown>)[key];\n}\n\n/** How deep a nested `{ text: … }` / `{ content: … }` chain we bother unwrapping. */\nconst MAX_UNWRAP_DEPTH = 8;\n\n/**\n * Pull a plain string out of whatever the store hands a text field.\n *\n * Persisted `inputData` carries historical corruptions - a double-wrapped\n * `{ text: { text } }`, a `{ concept, content }` envelope that was never\n * deflated - and the old fallback ran `String()` over them, which renders the\n * literal `\"[object Object]\"` into the textarea. That is worse than showing\n * nothing: it looks exactly like content the user typed, and one keystroke\n * later it is content the user typed. So unwrap the envelopes we know, and give\n * up with `undefined` (an empty field) rather than displaying garbage.\n *\n * Genuine primitives still stringify - a number or a boolean in a text slot is\n * a value, not a wrapper.\n */\nfunction textFromStored(value: unknown, depth = 0): string | undefined {\n if (value == null) return undefined;\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (typeof value !== 'object' || depth >= MAX_UNWRAP_DEPTH) return undefined;\n const envelope = value as { text?: unknown; content?: unknown };\n if ('text' in envelope) return textFromStored(envelope.text, depth + 1);\n if ('content' in envelope) return textFromStored(envelope.content, depth + 1);\n return undefined;\n}\n\n/** RJSF full form value → the runner's field value. */\nfunction fromRjsf(field: RunField, value: unknown): unknown {\n switch (field.kind) {\n case 'text':\n case 'prose':\n return textFromStored(value);\n case 'number': {\n // The control holds `number | undefined`. A numeric STRING is tolerated\n // because that is what a hand-written inputs.json tends to carry; anything\n // else empties the field rather than feeding NaN to a number input.\n const raw = unwrapContent(field, value);\n if (typeof raw === 'number') return Number.isFinite(raw) ? raw : undefined;\n if (typeof raw === 'string' && raw.trim() !== '') {\n const parsed = Number(raw);\n return Number.isFinite(parsed) ? parsed : undefined;\n }\n return undefined;\n }\n case 'boolean': {\n // Strictly a real boolean, deliberately: pipelex declares `YesNoContent.\n // yes_no` with `strict=True` precisely to refuse \"yes\"/1/\"true\", and\n // coercing here would smuggle back in what the runtime closed off.\n const raw = unwrapContent(field, value);\n return typeof raw === 'boolean' ? raw : undefined;\n }\n case 'unknown':\n // The escape hatch is a raw-JSON textarea, so a structured value belongs\n // there as JSON - `String(value)` would have shown \"[object Object]\" and\n // thrown the actual value away.\n if (typeof value === 'string') return value;\n if (value == null) return undefined;\n if (typeof value === 'object') {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return undefined;\n }\n }\n return String(value);\n case 'document':\n case 'image': {\n if (value && typeof value === 'object') {\n const o = value as { url?: unknown; filename?: unknown };\n return o.url\n ? { url: String(o.url), filename: o.filename as string | undefined }\n : undefined;\n }\n return typeof value === 'string' && value ? { url: value } : undefined;\n }\n case 'object': {\n const obj = (value && typeof value === 'object' ? value : {}) as Dict;\n const out: Dict = {};\n for (const child of field.fields) out[child.name] = fromRjsf(child, obj[child.name]);\n return out;\n }\n case 'list': {\n const arr = Array.isArray(value) ? value : [];\n return arr.map((item) => fromRjsf(field.item, item));\n }\n default:\n return value;\n }\n}\n\n/**\n * The runner's field value → RJSF full form value (what runs/store expect).\n *\n * `collapseEmpty` is what a SINGULAR slot does and a LIST ITEM must not: an\n * untouched structure in a singular slot is absent, but an item exists only\n * because the user added it, so adding IS the touch. Only the structure case\n * reads the flag.\n */\nfunction toRjsf(field: RunField, value: unknown, collapseEmpty = true): unknown {\n switch (field.kind) {\n case 'text':\n case 'prose':\n return wrapContent(field, typeof value === 'string' ? value : '');\n case 'number':\n // An untouched number stays ABSENT rather than becoming an empty wrapper.\n // The gate then does the right thing on both counts: it prunes an absent\n // optional input, and it reports a required one as missing by name -\n // where `{number: undefined}` would read as a malformed value instead.\n return typeof value === 'number' && Number.isFinite(value)\n ? wrapContent(field, value)\n : undefined;\n case 'boolean':\n // `false` is a value, not an absence - hence the type test rather than a\n // truthiness one.\n return typeof value === 'boolean' ? wrapContent(field, value) : undefined;\n case 'unknown':\n return typeof value === 'string' ? value : '';\n case 'document':\n case 'image': {\n const url = value && typeof value === 'object' ? (value as { url?: unknown }).url : value;\n const filename =\n value && typeof value === 'object' ? (value as { filename?: unknown }).filename : undefined;\n return { url: url ? String(url) : '', ...(filename ? { filename } : {}) };\n }\n case 'object': {\n const obj = (value && typeof value === 'object' ? value : {}) as Dict;\n const out: Dict = {};\n for (const child of field.fields) out[child.name] = toRjsf(child, obj[child.name]);\n // A structure nobody put anything into stays ABSENT, exactly as an\n // untouched number does above - it does NOT become a shell of empty\n // children. Materializing that shell made an OPTIONAL structured input\n // unrunnable whenever its concept declared a required child: readiness\n // ignored the input (correctly - the method said it may be omitted), Run\n // lit up, and the gate then judged an object the kernel had invented\n // against the concept's full schema and rejected the run for a child the\n // user was never asked to fill.\n //\n // Emptiness is `isFilled`, the SAME predicate readiness and the wire\n // payload use, so the three cannot disagree about whether this input is\n // there. Which also says what the touch is NOT: opening the optional\n // disclosure is local view state the value never sees, so a section\n // opened and left blank collapses exactly like one never opened. What\n // keeps a structure is a VALUE in it - and then the whole shell survives,\n // empty children and all, so a required child left blank still fails, and\n // loudly.\n return collapseEmpty && !isFilled(out) ? undefined : out;\n }\n case 'list': {\n const arr = Array.isArray(value) ? value : [];\n // An item is NEVER absent: it is in the array because the user added it,\n // and `ListField`'s \"Add\" seeds an object item with `{}`. Letting it\n // collapse the way an untouched singular slot does put `undefined` in the\n // array, which ajv rejects as `must be object` - blocking an empty item\n // the item schema allowed, and turning a required-child complaint into a\n // type error that names nothing the user can act on.\n return arr.map((item) => toRjsf(field.item, item, false));\n }\n default:\n return value;\n }\n}\n\n// ─── Store ↔ RunField values ──────────────────────────────────────────────\n\n/** Seed the runner's form values from the method-store's simplified inputData. */\nexport function runValuesFromStore(\n inputData: Dict | undefined,\n fields: RunField[],\n inputSchemas: InputSchemas,\n): Dict {\n const full = inflateAllInputs(inputData ?? {}, inputSchemas);\n const out: Dict = {};\n for (const field of fields) out[field.name] = fromRjsf(field, full[field.name]);\n return out;\n}\n\n/**\n * The runner's form values in **schema shape** - the same shape an RJSF panel\n * holds, and therefore the shape `gate.ts` validates against the per-input\n * JSON Schemas.\n *\n * Deliberately stops short of `deflateAllInputs`: deflation is the STORE's\n * compact form, and ajv validates the full one.\n */\nexport function rjsfDataFromRunValues(values: Dict, fields: RunField[]): Dict {\n const full: Dict = {};\n for (const field of fields) full[field.name] = toRjsf(field, values[field.name]);\n return full;\n}\n\n/** Convert the runner's form values back to the store's simplified inputData. */\nexport function storeInputDataFromRunValues(\n values: Dict,\n fields: RunField[],\n inputSchemas: InputSchemas,\n): Dict {\n return deflateAllInputs(rjsfDataFromRunValues(values, fields), inputSchemas);\n}\n\n/**\n * Build the `{ concept, content }` map a run expects from the form values.\n *\n * The two ways a method says \"this may be nothing\" land differently on the wire,\n * and both matter:\n * - an **optional (`?`)** input left blank is OMITTED, so the runtime records a\n * real absence the method can branch on - sending `{ text: \"\" }` would look\n * like the caller supplied an empty string;\n * - a **plural (`[]`)** input keeps its key, because a plural slot is never\n * absent - its empty form IS the empty list, and the runtime requires the key.\n * When that list is EMPTY it is sent BARE, without the envelope: the envelope\n * is the runtime's \"explicit form\", which bypasses the top-down shaper and\n * hands the value to the bottom-up factory, and that factory types a list from\n * its first item - so an empty list there raises \"Cannot create Stuff from\n * empty list in content\". The bare form keeps the shaper, which reads the\n * DECLARED concept and builds the empty list correctly. (pipelex/#1096 makes\n * the envelope agree; the bare form runs today and stays correct after.)\n */\nexport function apiInputsFromRunValues(\n values: Dict,\n fields: RunField[],\n inputSchemas: InputSchemas,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const field of fields) {\n const schema = inputSchemas[field.name];\n if (!schema) continue;\n if (schema.optional === true && !isFilled(values[field.name])) continue;\n if (isPluralInput(schema) && !isFilled(values[field.name])) {\n out[field.name] = [];\n continue;\n }\n out[field.name] = { concept: schema.concept_ref, content: toRjsf(field, values[field.name]) };\n }\n return out;\n}\n\n// ─── Pipe output → result entries ────────────────────────────────────────────\n\n/** One named output pulled out of a run's working memory, ready to render. */\nexport interface OutputEntry {\n /** The output variable key (mono). */\n key: string;\n conceptRef?: string;\n value: unknown;\n}\n\n/**\n * The slice of a serialized pipe output this module actually reads. Structural\n * on purpose: the SDK's `DictPipeOutput` is the host's wire type, and the kernel\n * must not depend on `@pipelex/sdk` - the guard below verifies the shape at\n * runtime anyway.\n */\ninterface PipeOutputWithWorkingMemory {\n working_memory: {\n root: Record<string, unknown>;\n aliases?: Record<string, string>;\n };\n}\n\nfunction hasWorkingMemoryRoot(value: unknown): value is PipeOutputWithWorkingMemory {\n return (\n !!value &&\n typeof value === 'object' &&\n 'working_memory' in value &&\n !!(value as { working_memory?: { root?: unknown } }).working_memory &&\n typeof (value as { working_memory: { root?: unknown } }).working_memory.root === 'object'\n );\n}\n\n/** The concept code of a working-memory entry (`{concept}` may be obj/str/absent). */\nfunction entryConceptRef(data: unknown): string | undefined {\n if (!data || typeof data !== 'object') return undefined;\n const raw = (data as { concept?: unknown; concept_code?: unknown }).concept;\n if (raw && typeof raw === 'object')\n return (\n ((raw as { concept_code?: string }).concept_code ?? (raw as { code?: string }).code) ||\n undefined\n );\n if (typeof raw === 'string') return raw;\n return (data as { concept_code?: string }).concept_code || undefined;\n}\n\n/**\n * Split a run's pipe output into the main result and any intermediate outputs,\n * excluding the inputs. The main output's identity comes from the working\n * memory's `main_stuff` alias (the authoritative pointer to the output variable)\n * - so its label is the REAL stuff name, not a positional guess. Falls back to\n * the last produced stuff only when the alias is absent.\n */\nexport function outputsFromPipeOutput(\n pipeOutput: unknown,\n inputKeys: string[],\n): { main: OutputEntry; intermediates: OutputEntry[] } | null {\n if (!hasWorkingMemoryRoot(pipeOutput)) return null;\n const wm = pipeOutput.working_memory as {\n root: Record<string, unknown>;\n aliases?: Record<string, string>;\n };\n const entries = Object.entries(wm.root).filter(([key]) => !inputKeys.includes(key));\n if (entries.length === 0) return null;\n\n const toEntry = ([key, data]: [string, unknown]): OutputEntry => ({\n key,\n conceptRef: entryConceptRef(data),\n value: (data as { content?: unknown })?.content ?? data,\n });\n\n // The real main-output name: `aliases.main_stuff` → its root key.\n const mainKey = wm.aliases?.['main_stuff'];\n const mainEntry: [string, unknown] =\n mainKey && Object.prototype.hasOwnProperty.call(wm.root, mainKey)\n ? [mainKey, wm.root[mainKey]]\n : entries[entries.length - 1]!;\n const intermediates = entries.filter(([key]) => key !== mainEntry[0]).map(toEntry);\n\n return { main: toEntry(mainEntry), intermediates };\n}\n\n/**\n * Recover the inputs a run was executed with from its working memory. The run's\n * `working_memory.root` holds every named stuff - inputs AND outputs - keyed by\n * variable name; we pull the entries whose keys are declared inputs and deflate\n * their `content` (the full form shape) back into the store's simplified\n * `inputData`. Lets the runner repopulate the form for a past/shared run - the\n * inputs that produced the result. Returns `null` when no inputs are present.\n */\nexport function inputDataFromWorkingMemory(\n workingMemory: unknown,\n inputSchemas: InputSchemas,\n): Dict | null {\n const root = (workingMemory as { root?: Record<string, unknown> } | null | undefined)?.root;\n if (!root || typeof root !== 'object') return null;\n const full: Dict = {};\n let found = false;\n for (const key of Object.keys(inputSchemas)) {\n const entry = root[key];\n if (entry && typeof entry === 'object' && 'content' in entry) {\n full[key] = (entry as { content: unknown }).content;\n found = true;\n }\n }\n if (!found) return null;\n return deflateAllInputs(full, inputSchemas);\n}\n\n/** Field descriptors for a method's main pipe. */\nexport function fieldsForContract(contract: PipeIOContract | undefined): RunField[] {\n return contract?.inputs ? buildRunFields(contract.inputs) : [];\n}\n\n/**\n * Immutably set a value at a dotted/indexed path (`a.0.b`). Used to write an\n * uploaded file's URL back to a field anywhere in the (possibly nested) tree.\n */\nexport function setValueAtPath(root: Dict, path: string[], value: unknown): Dict {\n const head = path[0];\n if (head === undefined) return root;\n const rest = path.slice(1);\n if (rest.length === 0) return { ...root, [head]: value };\n\n const nextSeg = rest[0] as string;\n const child = root[head];\n if (/^\\d+$/.test(nextSeg)) {\n const arr = Array.isArray(child) ? child.slice() : [];\n const idx = Number(nextSeg);\n arr[idx] =\n rest.length === 1 ? value : setValueAtPath((arr[idx] as Dict) ?? {}, rest.slice(1), value);\n return { ...root, [head]: arr };\n }\n return { ...root, [head]: setValueAtPath((child as Dict) ?? {}, rest, value) };\n}\n","/**\n * Turning one ajv/RJSF validation error into a line a human can act on.\n *\n * ## Why this isn't just `error.stack`\n *\n * A blocked run used to say \"Date: pick a valid date\" while the date picker\n * showed a perfectly good 06/07/2026. Both were telling the truth about\n * different values: the stored value was `2026-07-06T14:30:00+02:00` (a real\n * time - correctly rejected for a `format: date` field), but\n * `toDateInputValue` renders `.slice(0, 10)` of it, so the FIELD showed the day\n * while the VALIDATOR judged the timestamp. The user cannot reconcile that from\n * the message, because the message named neither value.\n *\n * So: every line here quotes what is ACTUALLY in the data. An error the user\n * can see the input of is one they can fix; an instruction to \"pick a valid\n * date\" for a date that looks valid is not.\n *\n * Kept React-free (the caller passes its `t`) so the wording is unit-testable\n * without mounting the panel.\n */\nimport { dayWithinDateTime } from './date-format';\nimport type { RunInputError } from './gate-validator';\n\n/**\n * A rejected value can be an entire base64 document, and this lands in a toast.\n * Past this many characters the tail is elided - a date never comes close, and\n * a megabyte of base64 in a toast helps nobody understand anything.\n */\nconst MAX_SHOWN_VALUE_CHARS = 120;\n\n/** The message keys this module renders, relative to the caller's namespace\n * (a host passes its own translator for that namespace). */\nexport type ValidationMessageKey =\n | 'inputPanel.aDateField'\n | 'inputPanel.pickValidDate'\n | 'inputPanel.pickValidDateEmpty'\n | 'inputPanel.dateCarriesTime'\n | 'inputPanel.invalidValue'\n | 'inputPanel.invalidValueWithData';\n\n/**\n * The translate function the caller injects. Typed on the EXACT keys this\n * module uses - not a loose `(key: string) => string` - for two reasons: a\n * typo'd key still fails the build here, and next-intl's translator (whose\n * `key` parameter is the namespace's real key union, a SUPERSET of these)\n * remains assignable by parameter contravariance. Kernel-owned: this module\n * must not import next-intl's types.\n */\nexport type Translate = (key: ValidationMessageKey, values?: Record<string, string>) => string;\n\n/**\n * The value the validator actually rejected, read back out of the submitted data.\n *\n * RJSF builds `property` from ajv's `instancePath` by swapping `/` for `.`\n * (`.quote_date.date`), so the segments index straight into the form data.\n * Array indices arrive as digit strings and index arrays natively.\n */\nexport function valueAtProperty(data: unknown, property: string | undefined): unknown {\n if (!property) return undefined;\n let current: unknown = data;\n for (const segment of property.split('.').filter(Boolean)) {\n if (typeof current !== 'object' || current === null) return undefined;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * The rejected value rendered for a toast, or `null` when there is nothing\n * worth showing (an absent or blank value - \"you left it empty\" is what the\n * message says on its own, and `“”` adds noise).\n */\nexport function displayValue(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value === 'string' && value.trim() === '') return null;\n const text = typeof value === 'string' ? value : JSON.stringify(value);\n if (text === undefined) return null;\n return text.length > MAX_SHOWN_VALUE_CHARS ? `${text.slice(0, MAX_SHOWN_VALUE_CHARS)}…` : text;\n}\n\n/** The field name ajv quoted in its stack, or a generic stand-in. */\nfunction labelOf(error: RunInputError, t: Translate): string {\n return error.stack?.match(/'([^']+)'/)?.[1] ?? t('inputPanel.aDateField');\n}\n\n/**\n * One validation error as a human line naming the offending value.\n *\n * The date branch is special-cased because ajv's own complaint (`'Date' must\n * match format \"date-time\"`) is opaque, and because the carries-a-time case has\n * a specific fix the user cannot guess: move the time into the sibling `time`\n * field, which is exactly what the runtime's own error says.\n */\nexport function describeValidationError(\n error: RunInputError,\n t: Translate,\n formData: unknown,\n): string {\n const format = (error.params as { format?: string } | undefined)?.format;\n const value = valueAtProperty(formData, error.property);\n const shown = displayValue(value);\n\n if (error.name === 'format' && (format === 'date' || format === 'date-time')) {\n const label = labelOf(error, t);\n if (shown === null) return t('inputPanel.pickValidDateEmpty', { label });\n // Only a `format: date` field rejects a real time; date-time takes it.\n const day = format === 'date' && typeof value === 'string' ? dayWithinDateTime(value) : null;\n if (day !== null) return t('inputPanel.dateCarriesTime', { label, value: shown, day });\n return t('inputPanel.pickValidDate', { label, value: shown });\n }\n\n const stack = error.stack ?? error.message ?? t('inputPanel.invalidValue');\n return shown === null ? stack : t('inputPanel.invalidValueWithData', { stack, value: shown });\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { R as RunField } from '../descriptor-X6MwFIWu.js';
2
- export { B as BooleanRunField, C as ConceptCategory, D as DateRunField, E as EnumRunField, F as FileRunField, L as ListRunField, N as NumberRunField, O as ObjectRunField, P as ProseRunField, a as RunFieldCommon, b as RunFieldKind, T as TextRunField, U as UnknownRunField, c as conceptCategory } from '../descriptor-X6MwFIWu.js';
1
+ import { R as RunField } from '../descriptor-DPrrfAjL.js';
2
+ export { B as BooleanRunField, C as ConceptCategory, D as DateRunField, E as EnumRunField, F as FileRunField, L as ListRunField, N as NumberRunField, O as ObjectRunField, P as ProseRunField, a as RunFieldCommon, b as RunFieldKind, T as TextRunField, U as UnknownRunField, c as conceptCategory } from '../descriptor-DPrrfAjL.js';
3
3
 
4
4
  /**
5
5
  * The typed `pipe_io_contracts` mirror and its gating predicates.
@@ -222,10 +222,15 @@ declare function apiInputsFromSchemaData(preparedData: Dict$1, inputs: Record<st
222
222
  *
223
223
  * The method-store keeps inputs in the *simplified* format and runs send the
224
224
  * *full* RJSF form shape - both already handled by `inflate/deflateAllInputs`.
225
- * The only gap is that a few field controls use a friendlier value than RJSF:
226
- * text is a plain string (RJSF wraps it `{ text }`) and a file is `{ url,
227
- * filename }`. `fromRjsf`/`toRjsf` translate just those, so store reads/writes
228
- * and run payloads stay byte-for-byte compatible with the proven playground path.
225
+ * The only gap is that a few field controls use a friendlier value than RJSF: a
226
+ * scalar is the bare scalar where the full shape is the content model its
227
+ * concept declares (`{ text }`, `{ number }`, `{ yes_no }`), and a file is
228
+ * `{ url, filename }`. `fromRjsf`/`toRjsf` translate just those, so store
229
+ * reads/writes and run payloads stay byte-for-byte compatible with the proven
230
+ * playground path.
231
+ *
232
+ * Which property a scalar wraps into is NOT decided here - it arrives on the
233
+ * descriptor as `contentKey`, derived from the contract by `buildRunFields`.
229
234
  *
230
235
  * Pure module - no React, unit-tested.
231
236
  */
@@ -235,9 +240,9 @@ type InputSchemas = Record<string, PipeInputContract>;
235
240
  /** Seed the runner's form values from the method-store's simplified inputData. */
236
241
  declare function runValuesFromStore(inputData: Dict | undefined, fields: RunField[], inputSchemas: InputSchemas): Dict;
237
242
  /**
238
- * The runner's form values in **schema shape** - the same shape the MethodViewer's
239
- * RJSF form holds, and therefore the shape `gate.ts` validates
240
- * against the per-input JSON Schemas.
243
+ * The runner's form values in **schema shape** - the same shape an RJSF panel
244
+ * holds, and therefore the shape `gate.ts` validates against the per-input
245
+ * JSON Schemas.
241
246
  *
242
247
  * Deliberately stops short of `deflateAllInputs`: deflation is the STORE's
243
248
  * compact form, and ajv validates the full one.
@@ -382,6 +387,9 @@ declare function healStringWrappers(value: unknown, rawSchema: Record<string, un
382
387
  * the runner just as it fails ajv here. Only properties absent from their
383
388
  * parent's `required` are dropped - an empty REQUIRED field must still fail, so
384
389
  * the user is told about it.
390
+ *
391
+ * What counts as empty is `isEmptyAfterPruning`, and it includes an optional
392
+ * STRUCTURE the user never opened, on exactly the same grounds.
385
393
  */
386
394
  declare function pruneEmptyOptionals(value: unknown, rawSchema: Record<string, unknown> | undefined, defs?: Record<string, Record<string, unknown>>): unknown;
387
395
  /**
@@ -1,3 +1,3 @@
1
- export { apiInputsFromRunValues, apiInputsFromSchemaData, asCalendarDate, buildPipeRef, buildRunFields, buildRunInputsSchema, collapseNullable, collectSchemaDefs, computeReadiness, conceptCategory, dayWithinDateTime, deflateAllInputs, deflateInput, derefSchema, describeValidationError, displayValue, fieldFilled, fieldsForContract, flattenAnyOf, getPipeIOContract, healStringWrappers, hoistDefsToRoot, inflateAllInputs, inflateInput, inputDataFromWorkingMemory, inputMustBeFilled, isAcceptableDate, isAcceptableDateTime, isFilled, isPluralInput, mustBeFilled, normalizeSchemaForRjsf, outputsFromPipeOutput, prepareRunInputs, prepareSchemaForRjsf, pruneEmptyOptionals, resolveConceptCode, resolveSchemaIndirection, rjsfDataFromRunValues, runValuesFromStore, schemaTypeOf, setValueAtPath, storeInputDataFromRunValues, toDateInputValue, toStoredDateValue, validateRunInputs, validateRunInputsSchema, valueAtProperty } from '../chunk-YWMUM7BC.js';
1
+ export { apiInputsFromRunValues, apiInputsFromSchemaData, asCalendarDate, buildPipeRef, buildRunFields, buildRunInputsSchema, collapseNullable, collectSchemaDefs, computeReadiness, conceptCategory, dayWithinDateTime, deflateAllInputs, deflateInput, derefSchema, describeValidationError, displayValue, fieldFilled, fieldsForContract, flattenAnyOf, getPipeIOContract, healStringWrappers, hoistDefsToRoot, inflateAllInputs, inflateInput, inputDataFromWorkingMemory, inputMustBeFilled, isAcceptableDate, isAcceptableDateTime, isFilled, isPluralInput, mustBeFilled, normalizeSchemaForRjsf, outputsFromPipeOutput, prepareRunInputs, prepareSchemaForRjsf, pruneEmptyOptionals, resolveConceptCode, resolveSchemaIndirection, rjsfDataFromRunValues, runValuesFromStore, schemaTypeOf, setValueAtPath, storeInputDataFromRunValues, toDateInputValue, toStoredDateValue, validateRunInputs, validateRunInputsSchema, valueAtProperty } from '../chunk-S6KOTTGD.js';
2
2
  //# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -30,6 +30,20 @@ interface RunFieldCommon {
30
30
  * they are gated through their parent's `fieldFilled`.
31
31
  */
32
32
  gating?: boolean;
33
+ /**
34
+ * The single property this field's value sits inside on the wire, when its
35
+ * concept declares a scalar content model: `native.Text` is `TextContent
36
+ * {text}`, `native.Number` is `NumberContent {number}`, `native.YesNo` is
37
+ * `YesNoContent {yes_no}`. The control still holds the plain scalar; the
38
+ * value bridge wraps into this property on the way out and unwraps on the way
39
+ * back in.
40
+ *
41
+ * A property NAME, never a schema - the descriptor stays the only currency
42
+ * and `buildRunFields` stays the only reader of JSON Schema. Absent whenever
43
+ * the value is already the whole content (a structured concept, a file, a
44
+ * child property of a structure): wrapping those would double-nest them.
45
+ */
46
+ contentKey?: string;
33
47
  }
34
48
  interface TextRunField extends RunFieldCommon {
35
49
  kind: 'text';
@@ -1,6 +1,6 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
- import { R as RunField, B as BooleanRunField, D as DateRunField, E as EnumRunField, F as FileRunField, L as ListRunField, N as NumberRunField, O as ObjectRunField, P as ProseRunField, T as TextRunField, U as UnknownRunField, C as ConceptCategory } from '../descriptor-X6MwFIWu.js';
3
+ import { R as RunField, B as BooleanRunField, D as DateRunField, E as EnumRunField, F as FileRunField, L as ListRunField, N as NumberRunField, O as ObjectRunField, P as ProseRunField, T as TextRunField, U as UnknownRunField, C as ConceptCategory } from '../descriptor-DPrrfAjL.js';
4
4
 
5
5
  /**
6
6
  * Ambient state that any field in the tree may need, threaded unchanged through
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { toStoredDateValue, toDateInputValue, isFilled } from '../chunk-YWMUM7BC.js';
2
+ import { toStoredDateValue, toDateInputValue, isFilled } from '../chunk-S6KOTTGD.js';
3
3
  import { clsx } from 'clsx';
4
4
  import { twMerge } from 'tailwind-merge';
5
5
  import { ChevronDown, ChevronUp, Check, List, Braces, ListChecks, ToggleLeft, Hash, Image, FileText, CalendarDays, Type, Loader2, Upload, Link2, ImageOff, EyeOff, Eye, X, Minus, Plus, Trash2 } from 'lucide-react';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pipelex/mthds-form",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Headless form kernel and control set for MTHDS method inputs",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/descriptor.ts","../src/core/contracts.ts","../src/core/native-concepts.ts","../src/core/schema-utils.ts","../src/core/derive.ts","../src/core/readiness.ts","../src/core/date-format.ts","../src/core/gate-validator.ts","../src/core/wire-format.ts","../src/core/normalize-schema.ts","../src/core/gate.ts","../src/core/values.ts","../src/core/validation-message.ts"],"names":[],"mappings":";;;;AAyHO,SAAS,gBAAgB,KAAA,EAAkC;AAChE,EAAA,QAAQ,MAAM,IAAA;AAAM,IAClB,KAAK,MAAA;AAAA,IACL,KAAK,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IAAA,EAAM,OAAO,CAAA,CAAE,4BAAA,EAA8B,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,GAAA,EAAK,CAAA;AACrF,IAAA,OAAO,EAAE,0BAAA,EAA4B,EAAE,KAAA,EAAO,KAAA,EAAO,OAAO,CAAA;AAAA,EAC9D;AAEA,EAAA,MAAM,QAAQ,KAAA,CAAM,KAAA,IAAS,KAAA,CAAM,OAAA,IAAW,EAAE,yBAAyB,CAAA;AACzE,EAAA,OAAO,KAAA,KAAU,OAAO,KAAA,GAAQ,CAAA,CAAE,mCAAmC,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,CAAA;AAC9F","file":"chunk-YWMUM7BC.js","sourcesContent":["/**\n * The `RunField` descriptor - the consumer-facing currency of the form kernel.\n *\n * A method's inputs arrive from the API as a map of variable name →\n * `PipeInputContract` ({ concept_ref, json_schema }). That JSON Schema is rich\n * (Pydantic-generated) and not pleasant to render directly. `buildRunFields`\n * (in `derive.ts`) normalizes it once into a flat, recursive `RunField[]`\n * descriptor that the presentational field components consume - so the\n * components never touch raw JSON Schema, and stories can describe any input\n * shape declaratively.\n *\n * Pure module: no React, no API calls. Trivially unit-testable.\n */\n\nexport type RunFieldKind =\n | 'text' // short single-line string\n | 'prose' // long free-text (textarea)\n | 'date' // a calendar date (schema `format: date` or `date-time`)\n | 'number' // integer or float\n | 'boolean' // true/false\n | 'enum' // pick one of a fixed set\n | 'document' // a file (PDF, docx…) by upload or URL\n | 'image' // a file rendered with a preview\n | 'object' // a structured concept with nested fields\n | 'list' // an array of one element type\n | 'unknown'; // anything we can't map → raw JSON escape hatch\n\nexport interface RunFieldCommon {\n /** The variable identifier as written in the method (rendered in mono). */\n name: string;\n /** Human label; falls back to `name` when absent. */\n title?: string;\n /** The concept this input carries, e.g. `native.Document`, `demo.Invoice`. */\n conceptRef?: string;\n /** One-line helper text shown under the label. */\n description?: string;\n /** Required inputs always show; optional ones can collapse. */\n required: boolean;\n /**\n * Whether Run waits for this input - set on TOP-LEVEL fields only, straight\n * from `inputMustBeFilled` (see `mustBeFilled` in `readiness.ts` for why this\n * is not the same question as `required`). Nested fields leave it undefined;\n * they are gated through their parent's `fieldFilled`.\n */\n gating?: boolean;\n}\n\nexport interface TextRunField extends RunFieldCommon {\n kind: 'text';\n placeholder?: string;\n}\n\nexport interface ProseRunField extends RunFieldCommon {\n kind: 'prose';\n placeholder?: string;\n}\n\nexport interface DateRunField extends RunFieldCommon {\n kind: 'date';\n /**\n * True when the backing schema is `format: date-time`: the stored value is a\n * full RFC 3339 timestamp (`2026-07-06T00:00:00Z`) so it passes the API's\n * `date-time` validation, even though the control only asks for a day. False\n * for a bare `format: date`, where the value stays `YYYY-MM-DD`.\n */\n datetime: boolean;\n}\n\nexport interface NumberRunField extends RunFieldCommon {\n kind: 'number';\n integer: boolean;\n min?: number;\n max?: number;\n}\n\nexport interface BooleanRunField extends RunFieldCommon {\n kind: 'boolean';\n}\n\nexport interface EnumRunField extends RunFieldCommon {\n kind: 'enum';\n options: string[];\n}\n\nexport interface FileRunField extends RunFieldCommon {\n kind: 'document' | 'image';\n /** Accept hint shown to the user, e.g. \"PDF, PNG, JPG\". */\n accept?: string;\n}\n\nexport interface ObjectRunField extends RunFieldCommon {\n kind: 'object';\n fields: RunField[];\n}\n\nexport interface ListRunField extends RunFieldCommon {\n kind: 'list';\n /** The element descriptor (its `name` is unused; the index labels items). */\n item: RunField;\n}\n\nexport interface UnknownRunField extends RunFieldCommon {\n kind: 'unknown';\n}\n\nexport type RunField =\n | TextRunField\n | ProseRunField\n | DateRunField\n | NumberRunField\n | BooleanRunField\n | EnumRunField\n | FileRunField\n | ObjectRunField\n | ListRunField\n | UnknownRunField;\n\n/** The short, friendly category label for a concept_ref (drives the pill dot). */\nexport type ConceptCategory =\n 'text' | 'date' | 'document' | 'image' | 'number' | 'boolean' | 'choice' | 'structured' | 'list';\n\nexport function conceptCategory(field: RunField): ConceptCategory {\n switch (field.kind) {\n case 'text':\n case 'prose':\n return 'text';\n case 'date':\n return 'date';\n case 'document':\n return 'document';\n case 'image':\n return 'image';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'enum':\n return 'choice';\n case 'list':\n return 'list';\n default:\n return 'structured';\n }\n}\n","/**\n * The typed `pipe_io_contracts` mirror and its gating predicates.\n *\n * Mirrors pipelex's `PipeIOContract` (pipelex/pipeline/pipe_io_contracts.py).\n * The SDK deliberately keeps `pipe_io_contracts` opaque, so the kernel is the\n * canonical TS home for this shape until the D-track specs it.\n *\n * The map itself is keyed by namespaced pipe ref (`<domain>.<pipe_code>`),\n * NOT bare pipe code - use `getPipeIOContract` to look entries up by the bare\n * codes the UI tracks.\n */\n\nexport interface PipeInputContract {\n concept_ref: string;\n json_schema: Record<string, unknown>;\n /**\n * `true` when the input is declared optional (`?`) - the caller may omit it\n * and the pipe handles the absence itself. Plain and force (`!`) inputs\n * report `false`. Absent on contracts persisted before the API carried the\n * flag, so read it as \"optional only when explicitly true\".\n */\n optional?: boolean;\n}\n\nexport interface PipeOutputContract {\n concept_ref: string;\n multiplicity: 'single' | 'variable';\n /** `true` when the output is declared optional (`?`) - the pipe may resolve\n * it as a recorded absence instead of a value. */\n optional?: boolean;\n}\n\nexport interface PipeIOContract {\n inputs: Record<string, PipeInputContract>;\n output: PipeOutputContract;\n}\n\n/** The `pipe_io_contracts` map: namespaced `pipe_ref` → IO contract. */\nexport type PipeIOContracts = Record<string, PipeIOContract>;\n\n/** Namespaced pipe ref (`<domain>.<pipe_code>`) - the identity convention the\n * validate artifacts key on. */\nexport function buildPipeRef(domain: string, pipeCode: string): string {\n return `${domain}.${pipeCode}`;\n}\n\n/**\n * Look up a pipe's IO contract by pipe code, tolerant of both key conventions.\n *\n * The map may be keyed by namespaced `pipe_ref` (`<domain>.<code>`, the\n * canonical convention) OR by bare pipe code - the current hosted `/validate`\n * keys `pipe_structures` by bare code, and methods persisted before the\n * pipe_ref re-keying also carry bare-code keys. Try the namespaced ref first\n * (when the caller supplies a domain), then fall back to the bare code.\n * Returns `undefined` (never crashes) when neither matches.\n */\nexport function getPipeIOContract(\n pipeIoContracts: PipeIOContracts | null | undefined,\n domain: string | null | undefined,\n pipeCode: string | null | undefined,\n): PipeIOContract | undefined {\n if (!pipeIoContracts || !pipeCode) return undefined;\n if (domain) {\n const byRef = pipeIoContracts[buildPipeRef(domain, pipeCode)];\n if (byRef) return byRef;\n }\n return pipeIoContracts[pipeCode];\n}\n\n/**\n * True when the input carries a plural concept (`Image[]`): its JSON Schema is\n * an array wrapper. A plural slot is never \"absent\" in MTHDS - its empty form\n * IS the empty list - so the UI must treat \"nothing entered\" as a real value.\n */\nexport function isPluralInput(input: PipeInputContract): boolean {\n return (input.json_schema as { type?: unknown } | undefined)?.type === 'array';\n}\n\n/**\n * True when the user MUST put a value in before a run can start.\n *\n * Two declarations relieve an input of that duty, for different reasons:\n * - **optional (`?`)** - the method itself states the caller may omit it;\n * - **plural (`[]`)** - the empty list is a legitimate value and no method can\n * declare \"at least one\", so gating on it would invent a constraint the\n * method never made.\n *\n * Everything else (plain and force `!`) still gates: that is the whole point of\n * the Run button telling you what is missing.\n */\nexport function inputMustBeFilled(input: PipeInputContract): boolean {\n return input.optional !== true && !isPluralInput(input);\n}\n","/**\n * The native-concept taxonomy, stated ONCE - with each call path's historical\n * view exported explicitly, because the three copies this consolidates had\n * DRIFTED and K1 preserves each path's observable behavior exactly (see\n * `concept-taxonomy-characterization.test.ts`).\n *\n * The drift, recorded for M1 (where the server-derived descriptor retires this\n * module entirely):\n *\n * | concept | field mapper (render) | wire format (deflate/inflate) | value bridge (`{text}` wrap) |\n * | ------- | ------------------------- | ----------------------------- | ---------------------------- |\n * | Text | text/prose | bare string | wraps |\n * | Date | text/prose (NOT a picker) | CUSTOM `{concept, content}` | wraps |\n * | HTML | text/prose | CUSTOM `{concept, content}` | wraps |\n * | Page | document | document-like (bare URL) | - |\n *\n * A `Date` input therefore ships as `{concept: \"native.Date\", content: {text}}`\n * today - consistent end-to-end, but not DateContent. Changing that is a\n * wire-visible fix and belongs to M1, not K1.\n */\n\n/** Both spellings a concept ref uses: bare (`Text`) and namespaced (`native.Text`). */\nfunction nativeSet(...names: string[]): ReadonlySet<string> {\n return new Set(names.flatMap((n) => [n, `native.${n}`]));\n}\n\nexport const TEXT_CONCEPTS = nativeSet('Text');\nexport const DATE_CONCEPTS = nativeSet('Date');\nexport const HTML_CONCEPTS = nativeSet('HTML');\nexport const DOCUMENT_CONCEPTS = nativeSet('Document');\nexport const PAGE_CONCEPTS = nativeSet('Page');\nexport const IMAGE_CONCEPTS = nativeSet('Image');\nexport const INTEGER_CONCEPTS = nativeSet('Integer');\nexport const NUMBER_CONCEPTS = nativeSet('Number', 'Float');\nexport const BOOLEAN_CONCEPTS = nativeSet('Boolean');\n\n// ─── The field mapper's view (field-model.ts) ───────────────────────────────\n\n/** Concepts the mapper renders as text/prose - `Date` deliberately included\n * (a `native.Date` input renders as prose today, not as a date picker). */\nexport const FIELD_TEXT_CONCEPTS: ReadonlySet<string> = new Set([\n ...TEXT_CONCEPTS,\n ...DATE_CONCEPTS,\n]);\n\n/** Concepts the mapper renders as a document upload - `Page` folded in. */\nexport const FIELD_DOCUMENT_CONCEPTS: ReadonlySet<string> = new Set([\n ...DOCUMENT_CONCEPTS,\n ...PAGE_CONCEPTS,\n]);\n\n// ─── The wire format's view (input-format.ts) ───────────────────────────────\n\n/** True when the simplified wire form is a bare string (`{text} ↔ \"...\"`).\n * `Date` and `HTML` are NOT here: they travel through the custom-concept\n * `{concept, content}` branch (the drift the header records). */\nexport function isWireTextConcept(concept: string): boolean {\n return TEXT_CONCEPTS.has(concept);\n}\n\n/** True when the simplified wire form is a bare URL string. */\nexport function isWireDocumentLikeConcept(concept: string): boolean {\n return (\n DOCUMENT_CONCEPTS.has(concept) || IMAGE_CONCEPTS.has(concept) || PAGE_CONCEPTS.has(concept)\n );\n}\n\n// ─── The value bridge's view (run-values.ts) ────────────────────────────────\n\n/**\n * Concepts whose full (RJSF) form value is the pydantic text wrapper `{ text }`.\n * Only a field that IS one of these concepts gets wrapped in `toRjsf`. A child\n * string property (`conceptRef` undefined) or a custom concept with a bare\n * string schema must stay a plain string - wrapping those double-nests the\n * value (`{ text: { text } }`), which fails schema validation and corrupts run\n * payloads.\n */\nexport const TEXT_WRAPPER_CONCEPTS: ReadonlySet<string> = new Set([\n ...TEXT_CONCEPTS,\n ...DATE_CONCEPTS,\n ...HTML_CONCEPTS,\n]);\n\n// ─── List refs ──────────────────────────────────────────────────────────────\n\n/** A concept ref like `native.Document[]` → base `native.Document`, isList true. */\nexport function splitListConcept(conceptRef: string | undefined): {\n base?: string;\n isList: boolean;\n} {\n if (!conceptRef) return { isList: false };\n if (conceptRef.endsWith('[]')) return { base: conceptRef.slice(0, -2), isList: true };\n return { base: conceptRef, isList: false };\n}\n","/**\n * The ONE place JSON-Schema plumbing lives for the run form kernel: nullable\n * `anyOf` collapsing, `$defs` collection/hoisting, `$ref` resolution, and type\n * extraction. Consolidated from three drifted private copies (`field-model.ts`,\n * `normalize-schema.ts`, `input-format.ts`) during the form-kernel extraction.\n *\n * Two collapse engines are exported ON PURPOSE - their semantics genuinely\n * differ, and each caller's observable behavior is characterized and preserved\n * (see `schema-utils-characterization.test.ts`):\n *\n * - `collapseNullable` (the field mapper's rule): collapse ONLY when exactly one\n * non-null branch remains, dropping the null. A multi-branch union stays an\n * `anyOf` and maps to the raw-JSON escape hatch.\n * - `flattenAnyOf` (the RJSF/ajv rule): a union of simple primitives becomes a\n * `type` ARRAY (null preserved as a type entry - ajv validates `type:\n * [\"number\",\"null\"]` natively); a 2-branch nullable non-primitive drops the\n * null branch.\n *\n * Whether these converge (and which semantics win) is an M1 question, decided\n * when the descriptor derivation moves server-side - not silently here.\n */\n\nexport type JsonSchema = Record<string, unknown>;\n\n// ─── anyOf collapsing ────────────────────────────────────────────────────────\n\n/** Pydantic emits `anyOf: [T, {type:'null'}]` for Optional[T]; collapse to T.\n * Collapses ONLY when exactly one non-null branch remains; the branch merges\n * OVER the outer schema (its constraints win). */\nexport function collapseNullable(schema: JsonSchema): JsonSchema {\n const anyOf = schema.anyOf;\n if (!Array.isArray(anyOf)) return schema;\n const branches = anyOf as JsonSchema[];\n const nonNull = branches.filter((b) => b?.type !== 'null');\n if (nonNull.length === 1) return { ...stripAnyOf(schema), ...nonNull[0] };\n return schema;\n}\n\nconst PRIMITIVE_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null']);\n\n/**\n * An `anyOf` entry that is a simple primitive with no constraints:\n * `{type: \"string\"}` is simple, `{type: \"string\", maxLength: 10}` is not.\n */\nfunction isSimplePrimitive(schema: JsonSchema): boolean {\n const type = schema.type;\n if (typeof type !== 'string' || !PRIMITIVE_TYPES.has(type)) return false;\n const allowedKeys = new Set(['type', 'default', 'description', 'title']);\n return Object.keys(schema).every((key) => allowedKeys.has(key));\n}\n\n/**\n * The RJSF/ajv collapse: a union of simple primitives flattens to a `type`\n * array (`anyOf: [{string},{null}]` → `type: [\"string\",\"null\"]`, which RJSF\n * renders as a plain input instead of a sub-schema picker); an exactly-two\n * `[T, {null}]` union of anything else drops the null branch and merges T over\n * the outer schema. Anything else passes through unchanged.\n */\nexport function flattenAnyOf(schema: JsonSchema): JsonSchema {\n const anyOf = schema.anyOf;\n if (!Array.isArray(anyOf)) return schema;\n\n const branches = anyOf as JsonSchema[];\n\n // Case 1: all branches are simple primitives → type array.\n if (\n branches.every(\n (branch) => typeof branch === 'object' && branch !== null && isSimplePrimitive(branch),\n )\n ) {\n const types: string[] = [];\n let mergedDefault: unknown = undefined;\n for (const branch of branches) {\n types.push(branch.type as string);\n if (branch.default !== undefined) mergedDefault = branch.default;\n }\n const { anyOf: _, ...rest } = schema;\n const result: JsonSchema = { ...rest, type: types };\n if (mergedDefault !== undefined && result.default === undefined) {\n result.default = mergedDefault;\n }\n return result;\n }\n\n // Case 2: exactly [T, {type: \"null\"}] - nullable non-primitive → drop null.\n if (branches.length === 2) {\n const nullBranch = branches.find(\n (b) => typeof b === 'object' && b !== null && b.type === 'null',\n );\n const otherBranch = branches.find((b) => b !== nullBranch);\n if (nullBranch && otherBranch && typeof otherBranch === 'object') {\n const { anyOf: _, ...rest } = schema;\n return { ...rest, ...otherBranch };\n }\n }\n\n return schema;\n}\n\nfunction stripAnyOf(schema: JsonSchema): JsonSchema {\n const { anyOf: _drop, ...rest } = schema;\n return rest;\n}\n\n// ─── Type & $ref helpers ─────────────────────────────────────────────────────\n\n/** The schema's non-null type: a bare `type` string, or the first non-null\n * entry of a `type` array (`[\"number\",\"null\"]` → `\"number\"`). */\nexport function schemaTypeOf(schema: JsonSchema): string | undefined {\n const t = schema.type;\n if (typeof t === 'string') return t;\n if (Array.isArray(t)) return t.find((x) => x !== 'null') as string | undefined;\n return undefined;\n}\n\n/** Resolve `{ $ref: \"#/$defs/Foo\" }` against a collected `$defs` map. Sibling\n * keys on the referencing schema override the definition's. */\nexport function derefSchema(schema: JsonSchema, defs: Record<string, JsonSchema>): JsonSchema {\n const ref = schema.$ref;\n if (typeof ref === 'string' && ref.startsWith('#/$defs/')) {\n const resolved = defs[ref.slice('#/$defs/'.length)];\n if (resolved) return { ...resolved, ...stripRef(schema) };\n }\n return schema;\n}\n\nfunction stripRef(schema: JsonSchema): JsonSchema {\n const { $ref: _drop, ...rest } = schema;\n return rest;\n}\n\n/**\n * Resolve the indirection layers pydantic puts in front of a value schema - a\n * `#/$defs/...` ref, a nullable `anyOf: [T, {null}]` wrapper, or a stack of\n * both - until a plain schema remains. This is the resolver `healStringWrappers`\n * and `pruneEmptyOptionals` apply before reading `type`. Unlike `derefSchema`\n * it REPLACES the schema with the definition (no sibling merge) - exactly what\n * the callers did inline.\n */\nexport function resolveSchemaIndirection(\n schema: JsonSchema,\n defs: Record<string, JsonSchema>,\n): JsonSchema {\n let current = schema;\n for (;;) {\n const ref = current.$ref;\n if (typeof ref === 'string' && ref.startsWith('#/$defs/')) {\n const resolved = defs[ref.slice('#/$defs/'.length)];\n if (resolved) {\n current = resolved;\n continue;\n }\n }\n if (Array.isArray(current.anyOf)) {\n const nonNull = (current.anyOf as JsonSchema[]).filter((b) => b?.type !== 'null');\n if (nonNull.length === 1) {\n current = nonNull[0]!;\n continue;\n }\n }\n return current;\n }\n}\n\n// ─── $defs collection ────────────────────────────────────────────────────────\n\nexport interface CollectDefsOptions {\n /**\n * Whether the walk descends into JSON arrays (`anyOf`/`allOf` branches,\n * tuple `items`). The field mapper always has (so a def declared inside an\n * `anyOf` branch resolves); the wire-format heal path historically has NOT -\n * both behaviors are characterized, and each caller states its mode\n * explicitly until M1 retires the difference.\n */\n traverseArrays: boolean;\n}\n\n/**\n * Collect every nested `$defs` entry into one flat map so `#/$defs/...` refs\n * resolve from anywhere. First definition of a name wins. The input schema is\n * NOT modified (see `hoistDefsToRoot` for the stripping variant).\n */\nexport function collectSchemaDefs(\n schema: JsonSchema,\n into: Record<string, JsonSchema>,\n options: CollectDefsOptions,\n): Record<string, JsonSchema> {\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$defs' && value && typeof value === 'object' && !Array.isArray(value)) {\n for (const [name, def] of Object.entries(value as Record<string, JsonSchema>)) {\n if (!(name in into) && def && typeof def === 'object') {\n into[name] = def;\n collectSchemaDefs(def, into, options);\n }\n }\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n collectSchemaDefs(value as JsonSchema, into, options);\n } else if (options.traverseArrays && Array.isArray(value)) {\n // Any object item recurses - including a nested array, whose indices then\n // walk as keys (matches the historical field-model walker exactly).\n for (const item of value) {\n if (item && typeof item === 'object') {\n collectSchemaDefs(item as JsonSchema, into, options);\n }\n }\n }\n }\n return into;\n}\n\n// ─── $defs hoisting (the RJSF wrapper-schema case) ──────────────────────────\n\n/**\n * Walk a schema, collect every `$defs` entry into `collected`, and return the\n * schema with those nested `$defs` STRIPPED. Cycle-safe: a def name is claimed\n * (placeholder) before its body is walked.\n */\nfunction walkAndCollectDefs(schema: JsonSchema, collected: JsonSchema): JsonSchema {\n const out: JsonSchema = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === '$defs' && value && typeof value === 'object' && !Array.isArray(value)) {\n for (const [defName, defValue] of Object.entries(value as JsonSchema)) {\n if (!(defName in collected) && defValue && typeof defValue === 'object') {\n collected[defName] = {};\n collected[defName] = walkAndCollectDefs(defValue as JsonSchema, collected);\n }\n }\n // Don't copy `$defs` into out - it's hoisted to the root.\n } else if (value && typeof value === 'object' && !Array.isArray(value)) {\n out[key] = walkAndCollectDefs(value as JsonSchema, collected);\n } else if (Array.isArray(value)) {\n out[key] = value.map((item) =>\n item && typeof item === 'object' && !Array.isArray(item)\n ? walkAndCollectDefs(item as JsonSchema, collected)\n : item,\n );\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Hoist every nested `$defs` to the schema root, so a wrapper schema composed\n * from several pydantic sub-schemas keeps its `#/$defs/...` refs resolvable.\n * (Pydantic emits one `$defs` per model; composing models as properties of a\n * wrapper object leaves those maps below the root the refs point to.)\n */\nexport function hoistDefsToRoot(schema: JsonSchema): JsonSchema {\n const collected: JsonSchema = {};\n const stripped = walkAndCollectDefs(schema, collected);\n if (Object.keys(collected).length > 0) {\n stripped.$defs = collected;\n }\n return stripped;\n}\n","/**\n * The ONE derivation function: `PipeInputContract` map → `RunField[]`.\n *\n * Everything heuristic stays module-private behind `buildRunFields`: the\n * native-concept taxonomy, `isDocumentObject`, the depth-based prose/label\n * rule, the `accept` strings, list splitting. Nothing here is exported except\n * the function itself - so the M1 milestone can swap the source of the\n * descriptor (server-derived) without touching consumers.\n */\n\nimport { inputMustBeFilled, type PipeInputContract } from './contracts';\nimport type { RunField, RunFieldCommon } from './descriptor';\nimport {\n BOOLEAN_CONCEPTS,\n FIELD_DOCUMENT_CONCEPTS,\n FIELD_TEXT_CONCEPTS,\n HTML_CONCEPTS,\n IMAGE_CONCEPTS,\n INTEGER_CONCEPTS,\n NUMBER_CONCEPTS,\n splitListConcept,\n} from './native-concepts';\nimport {\n collapseNullable,\n collectSchemaDefs,\n derefSchema,\n schemaTypeOf,\n type JsonSchema,\n} from './schema-utils';\n\n// Native concepts arrive as their pydantic wrapper schema (e.g. native.Text is\n// `TextContent {text}`, native.Document is `DocumentContent {url,…}`), NOT a bare\n// primitive - so we map them by concept_ref, before the generic schema-type\n// dispatch, or they'd all render as nested objects. The taxonomy lives in\n// `native-concepts.ts`, which also records where this mapper's view drifts from\n// the wire format's.\n\n/**\n * A url-bearing object renders as a document field. This is `Boolean(\n * schema.properties?.url)` and nothing more: the historical description check\n * (\"storage url\" / \"document url\") was followed by `|| 'url' in props`, which\n * made it unreachable. Stated honestly as the heuristic it is - M1 replaces it\n * with the server-derived descriptor; narrowing it to the description match is\n * a recorded M1 option, not a K1 change.\n */\nfunction isDocumentObject(schema: JsonSchema): boolean {\n const props = schema.properties as Record<string, JsonSchema> | undefined;\n return Boolean(props?.url);\n}\n\ninterface MapCtx {\n defs: Record<string, JsonSchema>;\n depth: number;\n}\n\n/** Build the recursive RunField for a single resolved schema node. */\nfunction mapSchema(\n name: string,\n conceptRef: string | undefined,\n rawSchema: JsonSchema,\n required: boolean,\n ctx: MapCtx,\n): RunField {\n const schema = collapseNullable(derefSchema(rawSchema, ctx.defs));\n // The LABEL is always the stuff name (the variable key) - that's what\n // identifies the input in the method. We deliberately do NOT use\n // `schema.title`, which is the pydantic model name (TextContent, ImageContent,\n // DocumentContent…) and would mask the stuff name. The concept pill carries\n // the type instead. `title` stays undefined here so FieldShell falls back to\n // `name`; list items still pass `title: ''` to suppress the per-row label.\n const common: RunFieldCommon = {\n name,\n conceptRef,\n description: typeof schema.description === 'string' ? schema.description : undefined,\n required,\n };\n\n const { base, isList } = splitListConcept(conceptRef);\n\n // List concepts (native.Text[], demo.Invoice[]) and array schemas.\n if (isList || schemaTypeOf(schema) === 'array') {\n const itemsSchema = (schema.items as JsonSchema) ?? {};\n const item = mapSchema(name, base, itemsSchema, true, { ...ctx, depth: ctx.depth + 1 });\n return { ...common, kind: 'list', item };\n }\n\n // Enum (a custom concept may refine a native with a fixed value set).\n if (Array.isArray(schema.enum)) {\n return { ...common, kind: 'enum', options: schema.enum.map(String) };\n }\n\n // Native concepts: map by concept_ref regardless of the wrapper schema shape.\n if (base) {\n if (FIELD_DOCUMENT_CONCEPTS.has(base))\n return { ...common, kind: 'document', accept: 'PDF, DOCX, TXT' };\n if (IMAGE_CONCEPTS.has(base)) return { ...common, kind: 'image', accept: 'PNG, JPG, WEBP' };\n if (FIELD_TEXT_CONCEPTS.has(base) || HTML_CONCEPTS.has(base))\n return ctx.depth === 0 ? { ...common, kind: 'prose' } : { ...common, kind: 'text' };\n if (INTEGER_CONCEPTS.has(base))\n return {\n ...common,\n kind: 'number',\n integer: true,\n min: numOrUndef(schema.minimum),\n max: numOrUndef(schema.maximum),\n };\n if (NUMBER_CONCEPTS.has(base))\n return {\n ...common,\n kind: 'number',\n integer: false,\n min: numOrUndef(schema.minimum),\n max: numOrUndef(schema.maximum),\n };\n if (BOOLEAN_CONCEPTS.has(base)) return { ...common, kind: 'boolean' };\n }\n\n // A custom concept whose schema looks like DocumentContent (refines Document).\n if (isDocumentObject(schema)) {\n return { ...common, kind: 'document', accept: 'PDF, DOCX, TXT' };\n }\n\n const type = schemaTypeOf(schema);\n switch (type) {\n case 'string': {\n if (base && (FIELD_DOCUMENT_CONCEPTS.has(base) || base === 'native.Document'))\n return { ...common, kind: 'document', accept: 'PDF, DOCX, TXT' };\n // A `date` structure field compiles to a `format: date`/`date-time`\n // string. Render it as a real date picker so the user picks a day - no\n // hand-typed timestamps - and stores a value the API accepts.\n if (schema.format === 'date' || schema.format === 'date-time')\n return { ...common, kind: 'date', datetime: schema.format === 'date-time' };\n // A top-level Text input is usually the main prompt (roomy textarea); the\n // same concept nested in a concept/list is usually a short attribute\n // (name, label) and reads better as a single line.\n const long =\n base && FIELD_TEXT_CONCEPTS.has(base)\n ? ctx.depth === 0\n : typeof schema.maxLength === 'number'\n ? schema.maxLength > 120\n : false;\n return long\n ? { ...common, kind: 'prose' }\n : { ...common, kind: 'text', placeholder: undefined };\n }\n case 'integer':\n return {\n ...common,\n kind: 'number',\n integer: true,\n min: numOrUndef(schema.minimum),\n max: numOrUndef(schema.maximum),\n };\n case 'number':\n return {\n ...common,\n kind: 'number',\n integer: false,\n min: numOrUndef(schema.minimum),\n max: numOrUndef(schema.maximum),\n };\n case 'boolean':\n return { ...common, kind: 'boolean' };\n case 'object': {\n const props = (schema.properties as Record<string, JsonSchema>) ?? {};\n const req = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []);\n const fields = Object.entries(props).map(([fieldName, fieldSchema]) =>\n mapSchema(fieldName, undefined, fieldSchema, req.has(fieldName), {\n ...ctx,\n depth: ctx.depth + 1,\n }),\n );\n return { ...common, kind: 'object', fields };\n }\n default:\n // A bare `native.Text` concept may arrive as `{type:'string'}` (handled\n // above) but a custom concept with no resolvable shape lands here.\n if (base && FIELD_TEXT_CONCEPTS.has(base))\n return ctx.depth === 0 ? { ...common, kind: 'prose' } : { ...common, kind: 'text' };\n return { ...common, kind: 'unknown' };\n }\n}\n\nfunction numOrUndef(v: unknown): number | undefined {\n return typeof v === 'number' ? v : undefined;\n}\n\n/**\n * Convert the API's per-input contracts into the runner's field descriptors.\n * The map's insertion order is preserved (required-first is the caller's job).\n */\nexport function buildRunFields(inputs: Record<string, PipeInputContract>): RunField[] {\n return Object.entries(inputs).map(([name, input]) => {\n const defs: Record<string, JsonSchema> = {};\n collectSchemaDefs(input.json_schema, defs, { traverseArrays: true });\n // A top-level input is required unless the method declared it optional (`?`).\n const field = mapSchema(name, input.concept_ref, input.json_schema, input.optional !== true, {\n defs,\n depth: 0,\n });\n // Whether Run gates on it is a SEPARATE question, and it is answered by the\n // contract, not by the shape we mapped it to - see `mustBeFilled`.\n return { ...field, gating: inputMustBeFilled(input) };\n });\n}\n","/**\n * Value readiness - the helpers the runner uses to decide whether the Run\n * button may fire and which inputs are still missing.\n */\n\nimport type { RunField } from './descriptor';\n\n/** True when a value is meaningfully filled (not empty / blank / empty container). */\nexport function isFilled(value: unknown): boolean {\n if (value == null || value === '') return false;\n if (Array.isArray(value)) return value.length > 0 && value.some(isFilled);\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n // A file value is { url } - filled when the url is set.\n if ('url' in obj) return isFilled(obj.url);\n return Object.values(obj).some(isFilled);\n }\n return true;\n}\n\n/** True when every required field has a value. */\nexport function fieldFilled(field: RunField, value: unknown): boolean {\n if (field.kind === 'object') {\n if (!value || typeof value !== 'object') return field.fields.every((f) => !f.required);\n const obj = value as Record<string, unknown>;\n return field.fields.every((f) => !f.required || fieldFilled(f, obj[f.name]));\n }\n return isFilled(value);\n}\n\nexport interface Readiness {\n total: number;\n ready: number;\n missing: string[];\n}\n\n/**\n * True when the user must put a value in this field before the run can start.\n *\n * Distinct from `required`, which also drives layout (a required field always\n * shows; an optional one may collapse). A **plural** field stays required - it\n * is a first-class input and keeps its place in the form - but it never gates:\n * a plural slot is never \"absent\" in MTHDS, its empty form IS the empty list,\n * and no method can declare \"at least one item\".\n *\n * **For a field this package built, the answer comes from `inputMustBeFilled`**\n * (`contracts.ts`) - the SAME predicate the method viewer's Run button, its ajv\n * `required` list and its missing-inputs toast all read. `buildRunFields`\n * stamps it onto `gating`. This used to be re-derived here as\n * `required && kind !== 'list'`: the same rule expressed against the MAPPED\n * field instead of the contract, and the two could disagree - `kind` is `'list'`\n * for a `conceptRef` ending in `[]` OR an array schema, while the contract's\n * plural test is the array schema alone, so a plural input carrying a non-array\n * schema gated on one surface and not the other.\n *\n * The shape heuristic survives only as the fallback for a **hand-authored**\n * `RunField` - story fixtures and unit tests, which have no contract to consult\n * and therefore nothing to disagree with. Every field a host renders comes from\n * `buildRunFields` and carries `gating`, so a host is on the contract's answer\n * alone.\n */\nexport function mustBeFilled(field: RunField): boolean {\n return field.gating ?? (field.required && field.kind !== 'list');\n}\n\n/** How many gating top-level inputs are satisfied by the current values. */\nexport function computeReadiness(fields: RunField[], values: Record<string, unknown>): Readiness {\n const gating = fields.filter(mustBeFilled);\n const missing = gating\n .filter((f) => !fieldFilled(f, values[f.name]))\n .map((f) => f.title ?? f.name);\n return { total: gating.length, ready: gating.length - missing.length, missing };\n}\n","/**\n * Pure conversions between a stored date value and what a native `<input\n * type=\"date\">` shows, plus the leniency rules our schema validation uses.\n * Kept React-free so both the runner's `DateField` and the RJSF `DateWidget`\n * share one source of truth (and it's trivially unit-tested).\n *\n * Two schema shapes reach us, and they are NOT interchangeable:\n * - an MTHDS `type = \"date\"` structure field compiles to `format: date-time`,\n * so its value round-trips as a full RFC 3339 timestamp;\n * - `native.Date`'s own `date` field is a python `datetime.date`, i.e.\n * `format: date` - a bare `YYYY-MM-DD`.\n *\n * ## Why these rules exist\n *\n * The runtime (pydantic) is LENIENT in both directions, and our client used to\n * be stricter than the contract it was enforcing: `ajv`'s stock `format: \"date\"`\n * accepts a bare `YYYY-MM-DD` and nothing else, so a hand-written\n * `\"2026-07-06T00:00:00Z\"` in an `inputs.json` was rejected here even though\n * pydantic accepts it happily and coerces it to `date(2026, 7, 6)`. The run\n * never even reached the runner. These predicates mirror pydantic exactly\n * (measured, not assumed):\n *\n * format: date \"2026-07-06\" -> date(2026, 7, 6)\n * \"2026-07-06T00:00:00Z\" -> date(2026, 7, 6)\n * \"2026-07-06T00:00:00+02:00\" -> date(2026, 7, 6) (literal date, no UTC shift)\n * \"2026-07-06T15:40:00Z\" -> REJECTED \"should have zero time\"\n * format: date-time \"2026-07-06\" -> datetime(2026, 7, 6, 0, 0)\n * \"2026-07-06T00:00:00Z\" -> datetime(2026, 7, 6, 0, 0, tz)\n *\n * A midnight-padded timestamp is unambiguously \"just a day\", so take it. A real\n * time is data - refusing it is the point (`DateContentError`: \"no silent\n * midnight\"), because silently dropping 15:40 corrupts the value. And an\n * ambiguous `06/07/2026` is never accepted by anyone: 6 July or June 7 depends\n * on who's reading, and guessing wrong fails silently.\n */\n\n/** `YYYY-MM-DD`, no time. */\nconst FULL_DATE_RE = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/**\n * A datetime whose clock reads exactly zero - optional seconds, optional\n * all-zero fraction, optional `Z`/offset. `00:00:01` and `00:00:00.001` do NOT\n * match: they carry a real time.\n */\nconst ZERO_TIME_DATE_TIME_RE =\n /^(\\d{4}-\\d{2}-\\d{2})[T ]00:00(?::00(?:\\.0+)?)?(?:Z|z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** Any RFC 3339-ish datetime we can hand to the runtime as a date-time. */\nconst DATE_TIME_RE =\n /^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?(?:Z|z|[+-]\\d{2}:?\\d{2})?$/;\n\n/** Guards against `2026-02-30` - a well-formed string that isn't a real day. */\nfunction isRealCalendarDate(value: string): boolean {\n const match = FULL_DATE_RE.exec(value);\n if (!match) return false;\n const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];\n if (month < 1 || month > 12) return false;\n const date = new Date(Date.UTC(year, month - 1, day));\n return (\n date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day\n );\n}\n\n/**\n * The calendar day a value denotes, or `null` when it doesn't denote one.\n * Accepts a bare date or a midnight-padded timestamp; the day is taken\n * LITERALLY from the string (never shifted through a timezone), matching\n * pydantic - `2026-07-06T00:00:00+02:00` is 2026-07-06, not the 5th.\n */\nexport function asCalendarDate(value: string): string | null {\n if (isRealCalendarDate(value)) return value;\n const zeroTime = ZERO_TIME_DATE_TIME_RE.exec(value);\n if (zeroTime && isRealCalendarDate(zeroTime[1]!)) return zeroTime[1]!;\n return null;\n}\n\n/**\n * The calendar day inside a value that carries a REAL time - precisely the case\n * `asCalendarDate` refuses. `null` when the value isn't a timestamp at all, or\n * when it IS already an acceptable day (nothing to report).\n *\n * This exists to EXPLAIN, never to coerce. `2026-07-06T14:30:00+02:00` is\n * rejected for a `format: date` field, and the rejection is right (DT3, \"no\n * silent midnight\" - dropping 14:30 corrupts the value). But telling the user\n * \"pick a valid date\" while the picker shows them a perfectly good 06/07/2026\n * reads as a lie: `toDateInputValue` renders the day, the stored value carries\n * the time, and only one of those is what gets validated. Naming both the value\n * we hold and the day it would have to become is what makes the error legible.\n */\nexport function dayWithinDateTime(value: string): string | null {\n if (asCalendarDate(value) !== null) return null;\n const match = DATE_TIME_RE.exec(value);\n if (!match || !isRealCalendarDate(match[1]!)) return null;\n return match[1]!;\n}\n\n/**\n * What `format: \"date\"` accepts: a bare `YYYY-MM-DD`, and nothing else.\n *\n * DO NOT relax this to take a midnight-padded timestamp. `DateContent` in\n * pipelex carries a `mode=\"before\"` field validator (`_reject_lax_temporal`)\n * that deliberately CLOSES pydantic's lax coercion for exactly this case:\n *\n * \"A Date's `date` field takes a calendar date alone; a string carrying a\n * time (e.g. '2026-07-07T00:00:00') would drop it - put the time and offset\n * in `time` instead.\"\n *\n * That rule (DT3, \"no silent midnight\") is the concept's whole point, so a\n * lenient client here does not help anyone: it just forwards the value and the\n * runner answers with a 500 instead of the field saying so up front.\n *\n * The leniency belongs in `asCalendarDate` - normalize the pasted timestamp to\n * the day it denotes, then this passes. Accept-and-fix, not accept-and-forward.\n */\nexport function isAcceptableDate(value: string): boolean {\n return isRealCalendarDate(value);\n}\n\n/** What `format: \"date-time\"` should accept - a bare day is midnight. */\nexport function isAcceptableDateTime(value: string): boolean {\n if (isRealCalendarDate(value)) return true;\n const match = DATE_TIME_RE.exec(value);\n if (!match || !isRealCalendarDate(match[1]!)) return false;\n const [hours, minutes, seconds] = [Number(match[2]), Number(match[3]), Number(match[4] ?? 0)];\n return hours <= 23 && minutes <= 59 && seconds <= 59;\n}\n\n/** The `YYYY-MM-DD` a native date input shows, from any stored date/date-time. */\nexport function toDateInputValue(value: string | undefined): string {\n if (typeof value !== 'string') return '';\n return asCalendarDate(value) ?? value.slice(0, 10);\n}\n\n/**\n * The value to store for a picked day. A `date-time` field becomes midnight-UTC\n * (`2026-07-06T00:00:00Z`); a plain `date` field keeps the bare `YYYY-MM-DD`.\n * An empty day clears the value.\n */\nexport function toStoredDateValue(day: string, datetime: boolean): string | undefined {\n if (!day) return undefined;\n return datetime ? `${day}T00:00:00Z` : day;\n}\n","/**\n * The run gate's OWN validator - ajv direct, no RJSF.\n *\n * Until the form-kernel extraction the gate validated through\n * `@rjsf/validator-ajv8` (`rjsf-validator.ts`), which is an RJSF `ValidatorType`\n * wrapper around exactly this: an ajv instance plus an error-shape transform.\n * The kernel must not depend on RJSF, so this module owns both halves directly,\n * configured for byte-identical output:\n *\n * - the ajv OPTIONS are `@rjsf/validator-ajv8`'s `AJV_CONFIG` plus the same\n * `coerceTypes: true` override this gate has always run with (pydantic runs in\n * lax mode - `\"20\"` is a number, `\"5\"` an int - and rejecting client-side what\n * the runner accepts blocks valid work; see `rjsf-validator.ts`);\n * - the `date` / `date-time` formats are the pydantic-parity predicates from\n * `date-format.ts`, same as before;\n * - `toRunInputError` reproduces RJSF's `transformRJSFValidationErrors` for the\n * no-uiSchema case the gate is: `property` is the dotted instance path (plus\n * the missing property name for `required` errors), `stack` quotes the parent\n * schema's `title` when one names the field.\n *\n * Parity is proven, not assumed: `validator-error-baseline.test.ts` records the\n * RJSF validator's output on the gate fixtures, and\n * `gate-validator-parity.test.ts` diffs this module against that recording.\n */\nimport Ajv, { type ErrorObject } from 'ajv';\nimport addFormats from 'ajv-formats';\nimport { isAcceptableDate, isAcceptableDateTime } from './date-format';\n\n/**\n * One validation error, in the shape hosts read (`property`, `message`,\n * `name`, `stack`, `params.format`). Structurally a superset-compatible twin of\n * RJSF's `RJSFValidationError`, so a host surface still holding RJSF form errors\n * (an RJSF-based inputs panel) can hand them to the same message renderer.\n */\nexport interface RunInputError {\n /** The ajv keyword that failed (`required`, `format`, `type`, …). */\n name?: string;\n /** Dotted path into the form data (`.quote_date.date`); for a `required`\n * error the missing property name is appended (top-level: no leading dot). */\n property?: string;\n message?: string;\n params?: Record<string, unknown>;\n /** The human line: `property message`, or `'title' message` when the parent\n * schema titles the field. */\n stack: string;\n schemaPath?: string;\n}\n\n// The exact instance `@rjsf/validator-ajv8` builds (its AJV_CONFIG + the\n// standard ajv-formats + its two custom formats), plus our two overrides.\nconst ajv = new Ajv({\n allErrors: true,\n multipleOfPrecision: 8,\n strict: false,\n verbose: true,\n discriminator: false,\n coerceTypes: true,\n});\naddFormats(ajv);\najv.addFormat('data-url', /^data:([a-z]+\\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/);\najv.addFormat(\n 'color',\n /^(#?([0-9A-Fa-f]{3}){1,2}\\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\\(\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*,\\s*\\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\b\\s*\\))|(rgb\\(\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*,\\s*(\\d?\\d%|100%)+\\s*\\)))$/,\n);\n// Pydantic-parity leniency, replacing ajv-formats' spec-strict versions: a\n// midnight-padded timestamp IS a date, a bare day IS a date-time. Measured\n// against pydantic in `date-format.ts` - keep in step with the runtime, not\n// with the JSON Schema spec.\najv.addFormat('date', isAcceptableDate);\najv.addFormat('date-time', isAcceptableDateTime);\n\n/**\n * Validate `data` against `schema`, returning mapped errors (empty = valid).\n * MUTATES `data` where ajv coerces (`\"20\"` → `20`) - deliberate and relied on:\n * the string the user typed is stored as a number going forward.\n */\nexport function validateRunInputsSchema(data: unknown, schema: object): RunInputError[] {\n let validate;\n try {\n validate = ajv.compile(schema);\n } catch (err) {\n // A malformed schema produces a verdict-less failure, same as RJSF's\n // `validationError` path: one bare-stack error, nothing to pin on a field.\n return [{ stack: err instanceof Error ? err.message : String(err) }];\n }\n validate(data);\n const errors = (validate.errors ?? []).map(toRunInputError);\n validate.errors = null;\n return errors;\n}\n\n/** RJSF's `transformRJSFValidationErrors`, minus the uiSchema lookups the gate\n * never had (it passes no uiSchema). */\nfunction toRunInputError(e: ErrorObject): RunInputError {\n const { instancePath, keyword, schemaPath, parentSchema } = e;\n const params = e.params as Record<string, unknown>;\n let message = e.message ?? '';\n let property = instancePath.replace(/\\//g, '.');\n let stack = `${property} ${message}`.trim();\n\n const rawPropertyNames = [\n ...(typeof params.deps === 'string' ? params.deps.split(', ') : []),\n params.missingProperty,\n params.property,\n ].filter((item): item is string => typeof item === 'string' && item.length > 0);\n\n if (rawPropertyNames.length > 0) {\n for (const currentProperty of rawPropertyNames) {\n const title = (\n parentSchema as { properties?: Record<string, { title?: unknown }> } | undefined\n )?.properties?.[currentProperty]?.title;\n if (typeof title === 'string' && title) {\n message = message.replace(`'${currentProperty}'`, `'${title}'`);\n }\n }\n stack = message;\n } else {\n const parentTitle = (parentSchema as { title?: unknown } | undefined)?.title;\n if (typeof parentTitle === 'string' && parentTitle) {\n stack = `'${parentTitle}' ${message}`.trim();\n }\n }\n\n if ('missingProperty' in params) {\n const missing = String(params.missingProperty);\n property = property ? `${property}.${missing}` : missing;\n }\n\n return { name: keyword, property, message, params, stack, schemaPath };\n}\n","/**\n * Converts between the simplified inputs.json format and the full RJSF form format.\n *\n * The inputs.json file uses a SIMPLIFIED format for users:\n * - Text: \"my text\" (instead of { text: \"my text\" })\n * - Document: \"file.pdf\" or { url: \"...\" } (instead of { url: \"...\", ... })\n * - Image: same as Document\n * - Text[]: [\"t1\", \"t2\"]\n * - Document[]: [\"f1.pdf\"] or [{ url: \"...\" }]\n * - Custom: { concept, content } (no simplification)\n *\n * The RJSF form uses the FULL concept structure from the json_schema.\n *\n * Two directions:\n * - deflate: form (full) → inputs.json (simplified) - for writing inputs.json / API calls\n * - inflate: inputs.json (simplified) → form (full) - for populating the form from inputs.json\n */\n\nimport { asCalendarDate } from './date-format';\nimport { isWireDocumentLikeConcept, isWireTextConcept, splitListConcept } from './native-concepts';\nimport { collectSchemaDefs, resolveSchemaIndirection, schemaTypeOf } from './schema-utils';\n\n/** The wire-format view of the native-concept taxonomy (which concept codes use\n * simplified formats) lives in `native-concepts.ts` - including the record of\n * where it drifts from the field mapper's view. */\nfunction isListConcept(conceptCode: string): { isList: boolean; baseConcept: string } {\n const { base, isList } = splitListConcept(conceptCode);\n return { isList, baseConcept: base ?? '' };\n}\n\nconst isTextConcept = isWireTextConcept;\nconst isDocumentLikeConcept = isWireDocumentLikeConcept;\n\n// ─── Deflate: form (full) → inputs.json (simplified) ──────────────────────\n\n/**\n * Convert a single form value to the simplified inputs.json format.\n * Used when writing inputs.json and when calling the run API.\n *\n * Rules:\n * - Text { text: \"hello\" } → \"hello\"\n * - Document { url: \"file.pdf\", ... } → \"file.pdf\" (if only url) or { url, ... }\n * - Image: same as Document\n * - Page: same as Document\n * - List types → array of deflated items\n * - Custom → { concept, content }\n */\nexport function deflateInput(value: unknown, conceptCode: string): unknown {\n const { isList, baseConcept } = isListConcept(conceptCode);\n\n if (isList) {\n const items = Array.isArray(value) ? value : [];\n // pipelex accepts Sequence[str] for list inputs, not list of dicts.\n // Always simplify list items to their scalar form (URL string for docs, plain string for text).\n return items.map((item) => deflateListItem(item, baseConcept));\n }\n\n return deflateSingleValue(value, baseConcept);\n}\n\n/** Deflate a single item within a list - always reduces to the simplest scalar form. */\nfunction deflateListItem(value: unknown, concept: string): unknown {\n if (isTextConcept(concept)) {\n if (value && typeof value === 'object' && 'text' in value) {\n return (value as { text: string }).text;\n }\n return typeof value === 'string' ? value : String(value ?? '');\n }\n\n if (isDocumentLikeConcept(concept)) {\n // Always extract just the URL for list items - pipelex resolves metadata at runtime\n if (value && typeof value === 'object' && 'url' in value) {\n return (value as { url: string }).url;\n }\n if (typeof value === 'string') return value;\n return '';\n }\n\n // Custom structured concept → { concept, content }.\n //\n // IDEMPOTENT ON PURPOSE - see `unwrapAllWrappers`. Wrapping unconditionally\n // corrupted persisted inputs: `input-config-panel` seeds the form with the\n // RAW stored value when the input schemas aren't loaded yet (no dry run yet),\n // so the form could hold an ALREADY-wrapped value; the next change deflated\n // it again and saved `{ concept, content: { concept, content: {...} } }`.\n // Wrapping exactly once, whatever we're handed, makes that unreachable.\n return { concept, content: unwrapAllWrappers(value) };\n}\n\nfunction deflateSingleValue(value: unknown, concept: string): unknown {\n if (isTextConcept(concept)) {\n // { text: \"hello\" } → \"hello\"\n if (value && typeof value === 'object' && 'text' in value) {\n return (value as { text: string }).text;\n }\n // Already a string (passthrough)\n return typeof value === 'string' ? value : String(value ?? '');\n }\n\n if (isDocumentLikeConcept(concept)) {\n // Always extract just the URL - pipelex resolves metadata at runtime.\n // A bare dict without a 'concept' key is rejected by StuffFactory.\n if (value && typeof value === 'object' && 'url' in value) {\n return (value as { url: string }).url;\n }\n // Already a string URL (passthrough)\n if (typeof value === 'string') return value;\n return '';\n }\n\n // Custom structured concept → { concept, content }.\n //\n // IDEMPOTENT ON PURPOSE - see `unwrapAllWrappers`. Wrapping unconditionally\n // corrupted persisted inputs: `input-config-panel` seeds the form with the\n // RAW stored value when the input schemas aren't loaded yet (no dry run yet),\n // so the form could hold an ALREADY-wrapped value; the next change deflated\n // it again and saved `{ concept, content: { concept, content: {...} } }`.\n // Wrapping exactly once, whatever we're handed, makes that unreachable.\n return { concept, content: unwrapAllWrappers(value) };\n}\n\n// ─── Inflate: inputs.json (simplified) → form (full) ──────────────────────\n\n/**\n * Convert a simplified inputs.json value to the full form structure.\n * Used when populating the RJSF form from inputs.json.\n *\n * Rules:\n * - \"hello\" → { text: \"hello\" } (for Text concepts)\n * - \"file.pdf\" → { url: \"file.pdf\" } (for Document/Image/Page concepts)\n * - { url: \"...\" } → passthrough (already full)\n * - [\"t1\", \"t2\"] → inflated array of items\n * - { concept, content } → content (for custom concepts)\n */\nexport function inflateInput(value: unknown, conceptCode: string): unknown {\n const { isList, baseConcept } = isListConcept(conceptCode);\n\n if (isList) {\n // The sandbox may write the wrapped form at the LIST level:\n // { concept: \"native.Document\", content: [item, item] } - pipelex accepts it.\n // Unwrap before the array check, otherwise the wrapper itself gets treated\n // as a single list item and inflates to one empty entry.\n const unwrapped = isWrappedForm(value) ? value.content : value;\n // Handle: array (correct), single object (legacy/form default), or null/undefined\n let items: unknown[];\n if (Array.isArray(unwrapped)) {\n items = unwrapped;\n } else if (unwrapped != null && typeof unwrapped === 'object') {\n // Single object instead of array (e.g., {\"url\": \"\"} from form default) - wrap it\n items = [unwrapped];\n } else {\n items = [];\n }\n return items.map((item) => inflateSingleValue(item, baseConcept));\n }\n\n return inflateSingleValue(value, baseConcept);\n}\n\n/** Known optional fields on DocumentContent (from pipelex Pydantic model). */\nconst DOCUMENT_FIELDS = new Set(['url', 'public_url', 'mime_type', 'filename', 'title', 'snippet']);\n\n/** Returns true if the object looks like a DocumentContent (has any known doc field). */\nfunction looksLikeDocument(obj: Record<string, unknown>): boolean {\n return Object.keys(obj).some((k) => DOCUMENT_FIELDS.has(k));\n}\n\n/**\n * Detect the fully-qualified wrapper form `{ concept: \"...\", content: ... }`.\n * pipelex accepts this for any concept (native or custom), and the mthds-inputs\n * agent skill writes it by default for disambiguation. We unwrap before applying\n * concept-specific inflation so the form populates correctly.\n */\nfunction isWrappedForm(value: unknown): value is { concept: string; content: unknown } {\n return (\n !!value &&\n typeof value === 'object' &&\n 'concept' in value &&\n 'content' in value &&\n typeof (value as { concept: unknown }).concept === 'string'\n );\n}\n\nfunction inflateSingleValue(value: unknown, concept: string): unknown {\n // Unwrap { concept, content } for native concepts - the content IS the value.\n // For custom concepts we unwrap below (historical behaviour) but after concept-specific checks.\n if (isWrappedForm(value) && (isTextConcept(concept) || isDocumentLikeConcept(concept))) {\n return inflateSingleValue(value.content, concept);\n }\n\n if (isTextConcept(concept)) {\n // \"hello\" → { text: \"hello\" }\n if (typeof value === 'string') {\n return { text: value };\n }\n // Already full structure { text: \"...\" }\n if (value && typeof value === 'object' && 'text' in value) {\n return value;\n }\n return { text: '' };\n }\n\n if (isDocumentLikeConcept(concept)) {\n // \"file.pdf\" → { url: \"file.pdf\" }\n if (typeof value === 'string') {\n return { url: value };\n }\n // Already full structure { url: \"...\" }\n if (value && typeof value === 'object' && 'url' in value) {\n return value;\n }\n // Object without url key but with other document fields (e.g. from RJSF defaults)\n // Ensure the required url field is present\n if (value && typeof value === 'object' && looksLikeDocument(value as Record<string, unknown>)) {\n return { ...(value as Record<string, unknown>), url: '' };\n }\n return { url: '' };\n }\n\n // Custom structured: unwrap { concept, content } → content.\n //\n // Unwrap REPEATEDLY. `deflateSingleValue` used to wrap unconditionally, so a\n // form change made while the input schemas weren't loaded yet re-wrapped an\n // already-wrapped value and persisted `{ concept, content: { concept,\n // content: {...} } }` to DynamoDB. Unwrapping a single level left the FORM\n // holding `{ concept, content }` - properties no schema declares, so RJSF\n // matched nothing and rendered every field empty, with the real values\n // sitting one level deeper. Deflate is idempotent now, but the corrupted\n // shape survives in persisted inputData, so this heals it on read.\n return unwrapAllWrappers(value);\n}\n\n/** Strip every `{ concept, content }` layer - one, or the double wrap a\n * non-idempotent deflate persisted. */\nfunction unwrapAllWrappers(value: unknown): unknown {\n let current = value;\n while (isWrappedForm(current)) {\n current = current.content;\n }\n // A `{ content }` with no `concept` is the historical half-wrapper.\n if (current && typeof current === 'object' && !Array.isArray(current) && 'content' in current) {\n return (current as { content: unknown }).content;\n }\n return current;\n}\n\n// ─── Schema helpers ─────────────────────────────────────────────────────\n\ninterface InputSchema {\n concept_ref: string;\n json_schema?: Record<string, unknown>;\n}\n\n/**\n * The validation API returns concept_ref WITHOUT the [] suffix for list inputs.\n * The array-ness is only encoded in json_schema.type === \"array\".\n * This helper resolves the correct concept ref by checking the schema.\n */\nexport function resolveConceptCode(schema: InputSchema): string {\n const code = schema.concept_ref;\n // Defensive: a malformed/partial contract entry (missing concept) must\n // degrade, never throw and blank the whole input panel.\n if (!code) return '';\n if (!code.endsWith('[]') && (schema.json_schema as Record<string, unknown>)?.type === 'array') {\n return code + '[]';\n }\n return code;\n}\n\n// ─── Batch helpers for full inputData objects ────────────────────────────\n\n/**\n * Deflate all inputs from form format to simplified inputs.json format.\n * Used by InputConfigPanel when preparing data for the run API.\n */\nexport function deflateAllInputs(\n formData: Record<string, unknown>,\n inputSchemas: Record<string, InputSchema>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [stuffName, schema] of Object.entries(inputSchemas)) {\n result[stuffName] = deflateInput(formData[stuffName], resolveConceptCode(schema));\n }\n return result;\n}\n\n/**\n * Heal values against their json_schema: the run-form bridge used to\n * double-wrap plain string properties as `{ text: \"...\" }` (fixed in\n * run-values.ts, but the corrupted shape survives in persisted inputData -\n * store and server copies). Wherever the schema expects a string but the\n * value is a lone `{ text: string }` wrapper, unwrap it. Walks nested\n * objects and arrays, resolving `#/$defs/...` refs against the root schema;\n * anything already valid passes through untouched.\n */\nexport function healStringWrappers(\n value: unknown,\n rawSchema: Record<string, unknown> | undefined,\n defs?: Record<string, Record<string, unknown>>,\n): unknown {\n if (!rawSchema || value == null) return value;\n\n // Resolve $ref / nullable-anyOf indirection (Pydantic emits `{$ref}` for\n // nested models and `anyOf: [T, {type:'null'}]` for optionals). The `$defs`\n // walk deliberately keeps its historical no-array-traversal mode - see\n // `CollectDefsOptions` in schema-utils.\n const allDefs = defs ?? collectSchemaDefs(rawSchema, {}, { traverseArrays: false });\n const schema = resolveSchemaIndirection(rawSchema, allDefs);\n const type = schemaTypeOf(schema);\n\n // A `format: date` field takes a calendar date ALONE. `DateContent` in pipelex\n // enforces that with a `mode=\"before\"` validator (`_reject_lax_temporal`) that\n // deliberately closes pydantic's lax coercion - a datetime string on `date`\n // would silently drop its time and offset (DT3, \"no silent midnight\"), so the\n // runner answers a 500, not a coercion.\n //\n // An agent-written or hand-written inputs.json says `\"2026-07-06T00:00:00Z\"`\n // anyway - that is how every system exports a date. So NORMALIZE it here to\n // the day it denotes rather than forwarding it to fail at the runner: the\n // padding is noise, and dropping noise is not the fidelity loss DT3 forbids.\n // A value carrying a REAL time (15:40) returns null and is left untouched -\n // it must fail, because silently discarding it is precisely the corruption\n // the rule exists to prevent.\n if (type === 'string' && schema.format === 'date' && typeof value === 'string') {\n return asCalendarDate(value) ?? value;\n }\n\n if (type === 'string') {\n if (\n typeof value === 'object' &&\n !Array.isArray(value) &&\n Object.keys(value).length === 1 &&\n typeof (value as { text?: unknown }).text === 'string'\n ) {\n return (value as { text: string }).text;\n }\n return value;\n }\n if (type === 'object' && typeof value === 'object' && !Array.isArray(value)) {\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return value;\n const out = { ...(value as Record<string, unknown>) };\n for (const [key, propSchema] of Object.entries(props)) {\n if (key in out) out[key] = healStringWrappers(out[key], propSchema, allDefs);\n }\n return out;\n }\n if (type === 'array' && Array.isArray(value)) {\n const items = schema.items as Record<string, unknown> | undefined;\n return value.map((item) => healStringWrappers(item, items, allDefs));\n }\n return value;\n}\n\n/**\n * Drop optional properties the user never filled, so an untouched field cannot\n * fail validation or reach the API as an empty string.\n *\n * RJSF fills EVERY unset string property with `\"\"` on mount. That is harmless\n * for a plain string, but `prepareSchemaForRjsf` collapses pydantic's\n * `anyOf: [T, null]` by dropping the null branch, so an optional *constrained*\n * field - `DateContent.time`, declared `datetime.time | None` and rendered\n * `{ type: \"string\", format: \"time\" }` - is left demanding a well-formed time.\n * `\"\"` is not one, and the run was blocked on a field the user never opened.\n *\n * Pruning is the semantically correct repair, not a validation dodge: for\n * pipelex an absent optional field IS `None`, and `\"\"` would fail pydantic at\n * the runner just as it fails ajv here. Only properties absent from their\n * parent's `required` are dropped - an empty REQUIRED field must still fail, so\n * the user is told about it.\n */\nexport function pruneEmptyOptionals(\n value: unknown,\n rawSchema: Record<string, unknown> | undefined,\n defs?: Record<string, Record<string, unknown>>,\n): unknown {\n if (!rawSchema || value == null) return value;\n\n const allDefs = defs ?? collectSchemaDefs(rawSchema, {}, { traverseArrays: false });\n const schema = resolveSchemaIndirection(rawSchema, allDefs);\n const type = schemaTypeOf(schema);\n\n if (type === 'array' && Array.isArray(value)) {\n const items = schema.items as Record<string, unknown> | undefined;\n return value.map((item) => pruneEmptyOptionals(item, items, allDefs));\n }\n if (type !== 'object' || typeof value !== 'object' || Array.isArray(value)) return value;\n\n const props = schema.properties as Record<string, Record<string, unknown>> | undefined;\n if (!props) return value;\n const required = new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []);\n const out: Record<string, unknown> = {};\n for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {\n const propSchema = props[key];\n if (!propSchema) {\n out[key] = raw;\n continue;\n }\n const pruned = pruneEmptyOptionals(raw, propSchema, allDefs);\n const isEmpty = pruned === '' || pruned === null || pruned === undefined;\n if (isEmpty && !required.has(key)) continue;\n out[key] = pruned;\n }\n return out;\n}\n\n/**\n * Inflate all inputs from simplified inputs.json format to form format.\n * Used by onInputUpdate when receiving inputs.json changes from the sandbox.\n */\nexport function inflateAllInputs(\n simplifiedData: Record<string, unknown>,\n inputSchemas: Record<string, InputSchema>,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [stuffName, value] of Object.entries(simplifiedData)) {\n const schema = inputSchemas[stuffName];\n if (schema) {\n result[stuffName] = healStringWrappers(\n inflateInput(value, resolveConceptCode(schema)),\n schema.json_schema,\n );\n } else {\n // Unknown input - pass through unchanged\n result[stuffName] = value;\n }\n }\n return result;\n}\n","/**\n * Normalizes a JSON Schema for RJSF compatibility.\n *\n * Pydantic v2 generates `anyOf: [{type: \"string\"}, {type: \"null\"}]` for optional\n * fields (`str | None`). RJSF renders this as a dropdown selector asking the user\n * to pick a sub-schema, which is terrible UX. The normalizer flattens those\n * patterns on every node (see `flattenAnyOf` in `schema-utils.ts` for the exact\n * rules) and hoists nested `$defs` to the root so composed sub-schemas keep\n * their refs resolvable.\n *\n * The collapse and hoist engines live in `schema-utils.ts` - the\n * consolidated home for the kernel's JSON-Schema plumbing; this module owns the\n * recursive application over a whole schema tree.\n */\nimport { flattenAnyOf, hoistDefsToRoot } from './schema-utils';\n\nexport { hoistDefsToRoot };\n\n/**\n * Recursively normalize a JSON Schema for RJSF.\n * Walks the entire schema tree and flattens anyOf patterns on every node.\n */\nexport function normalizeSchemaForRjsf(schema: Record<string, unknown>): Record<string, unknown> {\n // Flatten anyOf at this level\n let normalized = flattenAnyOf(schema);\n\n // Recurse into properties\n if (normalized.properties && typeof normalized.properties === 'object') {\n const props = normalized.properties as Record<string, unknown>;\n const normalizedProps: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(props)) {\n normalizedProps[key] =\n value && typeof value === 'object'\n ? normalizeSchemaForRjsf(value as Record<string, unknown>)\n : value;\n }\n normalized = { ...normalized, properties: normalizedProps };\n }\n\n // Recurse into items (array schemas)\n if (\n normalized.items &&\n typeof normalized.items === 'object' &&\n !Array.isArray(normalized.items)\n ) {\n normalized = {\n ...normalized,\n items: normalizeSchemaForRjsf(normalized.items as Record<string, unknown>),\n };\n }\n\n // Recurse into anyOf branches that weren't flattened (complex unions)\n if (Array.isArray(normalized.anyOf)) {\n normalized = {\n ...normalized,\n anyOf: (normalized.anyOf as Record<string, unknown>[]).map((branch) =>\n typeof branch === 'object' && branch !== null\n ? normalizeSchemaForRjsf(branch as Record<string, unknown>)\n : branch,\n ),\n };\n }\n\n // Recurse into $defs so nested definitions (e.g. ImageSize) also get anyOf normalized\n if (\n normalized.$defs &&\n typeof normalized.$defs === 'object' &&\n !Array.isArray(normalized.$defs)\n ) {\n const defs = normalized.$defs as Record<string, unknown>;\n const normalizedDefs: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(defs)) {\n normalizedDefs[key] =\n value && typeof value === 'object'\n ? normalizeSchemaForRjsf(value as Record<string, unknown>)\n : value;\n }\n normalized = { ...normalized, $defs: normalizedDefs };\n }\n\n return normalized;\n}\n\n/**\n * Prepare a schema for RJSF: hoist all nested `$defs` to the root, then normalize\n * anyOf patterns. Call this on any schema that composes multiple sub-schemas\n * (each of which may ship its own `$defs`).\n */\nexport function prepareSchemaForRjsf(schema: Record<string, unknown>): Record<string, unknown> {\n return normalizeSchemaForRjsf(hoistDefsToRoot(schema));\n}\n","/**\n * The gate every run passes through, whichever surface starts it.\n *\n * Two pages let a user run a method - the MethodViewer's Inputs panel\n * (`components/method/input-config-panel.tsx`, an RJSF form) and the standalone\n * run page (`components/method-run/*`, a bespoke field renderer). **Only the\n * rendering of inputs differs.** Everything between \"the user pressed Run\" and\n * \"the payload goes on the wire\" lives here, so the two cannot drift:\n *\n * 1. `buildRunInputsSchema` - the combined JSON Schema, whose `required` list\n * is `inputMustBeFilled` (optional `?` and plural `[]` never block).\n * 2. `prepareRunInputs` - heal legacy wrappers, then prune empty optionals.\n * 3. `validateRunInputs` - ajv, plus the missing-input scan that names the\n * VARIABLE at fault.\n * 4. `apiInputsFromSchemaData` - the `{concept, content}` payload, built from\n * the PREPARED data so the pruning reaches the wire too.\n *\n * This module is pure: no React, no toasts, no i18n. Each caller renders the\n * verdict in its own idiom.\n */\nimport { inputMustBeFilled, isPluralInput } from './contracts';\nimport { isFilled } from './readiness';\nimport { validateRunInputsSchema, type RunInputError } from './gate-validator';\nimport { healStringWrappers, pruneEmptyOptionals } from './wire-format';\nimport { prepareSchemaForRjsf } from './normalize-schema';\nimport type { PipeInputContract } from './contracts';\n\ntype Dict = Record<string, unknown>;\n\n/**\n * Combine the per-input schemas into one object schema.\n *\n * Each input variable becomes a property, titled with the variable name and\n * described with the concept code. Only the inputs the method actually demands\n * land in `required` - an optional (`?`) or plural (`[]`) input must not block\n * the form (see `inputMustBeFilled`).\n */\nexport function buildRunInputsSchema(inputs: Record<string, PipeInputContract>): Dict {\n const properties: Dict = {};\n const required: string[] = [];\n\n for (const [varName, input] of Object.entries(inputs)) {\n const inputSchema = { ...input.json_schema } as Dict;\n inputSchema.title = varName;\n if (input.concept_ref && input.concept_ref !== varName) {\n inputSchema.description = input.concept_ref;\n }\n properties[varName] = inputSchema;\n if (inputMustBeFilled(input)) required.push(varName);\n }\n\n return prepareSchemaForRjsf({ type: 'object', properties, required });\n}\n\n/**\n * Last-gate repair, in two passes against the exact schema ajv validates.\n *\n * 1. **HEAL** - persisted `inputData` may still carry the legacy double-wrapped\n * `{ text: { text } }` shape (or a form's state may lag a store fix).\n * 2. **PRUNE** - RJSF fills every unset string with `\"\"` on mount, which an\n * optional CONSTRAINED field rejects (`DateContent.time` is `format: \"time\"`)\n * - blocking a run on a field the user never opened. An absent optional field\n * is what pipelex means by `None` anyway, so dropping it is the semantically\n * correct repair, not a validation dodge.\n */\nexport function prepareRunInputs(data: Dict, schema: Dict): Dict {\n return pruneEmptyOptionals(healStringWrappers(data, schema), schema) as Dict;\n}\n\nexport interface RunInputsVerdict {\n isValid: boolean;\n /** Variable names the scan could pin a missing required field on. */\n missingInputs: string[];\n /** Raw ajv errors, for when the scan cannot name anything. */\n errors: RunInputError[];\n}\n\n/**\n * Validate PREPARED data against the combined schema.\n *\n * `missingInputs` is reported by VARIABLE NAME - the name on the node the user\n * clicks - never by `concept_ref`, which used to produce \"Missing required\n * fields in: native.Text\" and named neither the input at fault nor, when several\n * inputs share a concept, which of them. Inputs the method declared omittable\n * are skipped: an empty `?` input is not a missing one.\n *\n * The scan can come up empty even on an invalid form (a wrong value shape, a\n * nested mismatch); `errors` is what the caller falls back to then, so a failure\n * is never undiagnosable.\n */\nexport function validateRunInputs(\n preparedData: Dict,\n inputs: Record<string, PipeInputContract>,\n schema: Dict,\n): RunInputsVerdict {\n const errors = validateRunInputsSchema(preparedData, schema);\n if (errors.length === 0) return { isValid: true, missingInputs: [], errors: [] };\n\n const missingInputs: string[] = [];\n for (const [varName, input] of Object.entries(inputs)) {\n if (!inputMustBeFilled(input)) continue;\n const varData = preparedData[varName];\n const inputSchema = input.json_schema as Dict;\n const requiredFields = (inputSchema.required as string[]) || [];\n if (requiredFields.length === 0) continue;\n if (!varData || typeof varData !== 'object') {\n missingInputs.push(varName);\n continue;\n }\n const record = varData as Dict;\n if (requiredFields.some((f) => record[f] === undefined || record[f] === '')) {\n missingInputs.push(varName);\n }\n }\n\n return { isValid: false, missingInputs, errors };\n}\n\n/**\n * Build the `{ concept, content }` map a run expects, from PREPARED data.\n *\n * The two ways a method says \"this may be nothing\" land differently on the wire:\n * - an **optional (`?`)** input left blank is OMITTED, so the runtime records a\n * real absence the method can branch on - sending `{ text: \"\" }` would look\n * like the caller supplied an empty string;\n * - a **plural (`[]`)** input keeps its key, because a plural slot is never\n * absent - its empty form IS the empty list, and the runtime requires the key.\n * When that list is EMPTY it is sent BARE, without the envelope: the envelope\n * is the runtime's \"explicit form\", which bypasses the top-down shaper and\n * hands the value to the bottom-up factory, and that factory types a list from\n * its first item - so an empty list there raises \"Cannot create Stuff from\n * empty list in content\". The bare form keeps the shaper, which reads the\n * DECLARED concept and builds the empty list correctly. (pipelex/#1096 makes\n * the envelope agree; the bare form runs today and stays correct after.)\n */\nexport function apiInputsFromSchemaData(\n preparedData: Dict,\n inputs: Record<string, PipeInputContract>,\n): Dict {\n const out: Dict = {};\n for (const [varName, input] of Object.entries(inputs)) {\n const raw = preparedData[varName];\n if (input.optional === true && !isFilled(raw)) continue;\n if (isPluralInput(input) && !isFilled(raw)) {\n out[varName] = [];\n continue;\n }\n const content = isPluralInput(input) && !Array.isArray(raw) ? [] : raw;\n out[varName] = { concept: input.concept_ref, content };\n }\n return out;\n}\n","/**\n * Bridges the `MethodRunner`'s field values to the rest of the host.\n *\n * The method-store keeps inputs in the *simplified* format and runs send the\n * *full* RJSF form shape - both already handled by `inflate/deflateAllInputs`.\n * The only gap is that a few field controls use a friendlier value than RJSF:\n * text is a plain string (RJSF wraps it `{ text }`) and a file is `{ url,\n * filename }`. `fromRjsf`/`toRjsf` translate just those, so store reads/writes\n * and run payloads stay byte-for-byte compatible with the proven playground path.\n *\n * Pure module - no React, unit-tested.\n */\nimport type { RunField } from './descriptor';\nimport { buildRunFields } from './derive';\nimport { isFilled } from './readiness';\nimport { splitListConcept, TEXT_WRAPPER_CONCEPTS } from './native-concepts';\nimport { isPluralInput } from './contracts';\nimport { deflateAllInputs, inflateAllInputs } from './wire-format';\nimport type { PipeIOContract, PipeInputContract } from './contracts';\n\ntype Dict = Record<string, unknown>;\ntype InputSchemas = Record<string, PipeInputContract>;\n\n// ─── RJSF full shape ↔ RunField value ──────────────────────────────────────\n\n/** True when the field's concept wraps its full form value as `{ text }` -\n * the value-bridge view of the taxonomy (see `native-concepts.ts`). */\nfunction isTextWrapperConcept(conceptRef: string | undefined): boolean {\n const { base } = splitListConcept(conceptRef);\n return base !== undefined && TEXT_WRAPPER_CONCEPTS.has(base);\n}\n\n/** How deep a nested `{ text: … }` / `{ content: … }` chain we bother unwrapping. */\nconst MAX_UNWRAP_DEPTH = 8;\n\n/**\n * Pull a plain string out of whatever the store hands a text field.\n *\n * Persisted `inputData` carries historical corruptions - a double-wrapped\n * `{ text: { text } }`, a `{ concept, content }` envelope that was never\n * deflated - and the old fallback ran `String()` over them, which renders the\n * literal `\"[object Object]\"` into the textarea. That is worse than showing\n * nothing: it looks exactly like content the user typed, and one keystroke\n * later it is content the user typed. So unwrap the envelopes we know, and give\n * up with `undefined` (an empty field) rather than displaying garbage.\n *\n * Genuine primitives still stringify - a number or a boolean in a text slot is\n * a value, not a wrapper.\n */\nfunction textFromStored(value: unknown, depth = 0): string | undefined {\n if (value == null) return undefined;\n if (typeof value === 'string') return value;\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (typeof value !== 'object' || depth >= MAX_UNWRAP_DEPTH) return undefined;\n const envelope = value as { text?: unknown; content?: unknown };\n if ('text' in envelope) return textFromStored(envelope.text, depth + 1);\n if ('content' in envelope) return textFromStored(envelope.content, depth + 1);\n return undefined;\n}\n\n/** RJSF full form value → the runner's field value. */\nfunction fromRjsf(field: RunField, value: unknown): unknown {\n switch (field.kind) {\n case 'text':\n case 'prose':\n return textFromStored(value);\n case 'unknown':\n // The escape hatch is a raw-JSON textarea, so a structured value belongs\n // there as JSON - `String(value)` would have shown \"[object Object]\" and\n // thrown the actual value away.\n if (typeof value === 'string') return value;\n if (value == null) return undefined;\n if (typeof value === 'object') {\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return undefined;\n }\n }\n return String(value);\n case 'document':\n case 'image': {\n if (value && typeof value === 'object') {\n const o = value as { url?: unknown; filename?: unknown };\n return o.url\n ? { url: String(o.url), filename: o.filename as string | undefined }\n : undefined;\n }\n return typeof value === 'string' && value ? { url: value } : undefined;\n }\n case 'object': {\n const obj = (value && typeof value === 'object' ? value : {}) as Dict;\n const out: Dict = {};\n for (const child of field.fields) out[child.name] = fromRjsf(child, obj[child.name]);\n return out;\n }\n case 'list': {\n const arr = Array.isArray(value) ? value : [];\n return arr.map((item) => fromRjsf(field.item, item));\n }\n default:\n return value;\n }\n}\n\n/** The runner's field value → RJSF full form value (what runs/store expect). */\nfunction toRjsf(field: RunField, value: unknown): unknown {\n switch (field.kind) {\n case 'text':\n case 'prose': {\n const str = typeof value === 'string' ? value : '';\n return isTextWrapperConcept(field.conceptRef) ? { text: str } : str;\n }\n case 'unknown':\n return typeof value === 'string' ? value : '';\n case 'document':\n case 'image': {\n const url = value && typeof value === 'object' ? (value as { url?: unknown }).url : value;\n const filename =\n value && typeof value === 'object' ? (value as { filename?: unknown }).filename : undefined;\n return { url: url ? String(url) : '', ...(filename ? { filename } : {}) };\n }\n case 'object': {\n const obj = (value && typeof value === 'object' ? value : {}) as Dict;\n const out: Dict = {};\n for (const child of field.fields) out[child.name] = toRjsf(child, obj[child.name]);\n return out;\n }\n case 'list': {\n const arr = Array.isArray(value) ? value : [];\n return arr.map((item) => toRjsf(field.item, item));\n }\n default:\n return value;\n }\n}\n\n// ─── Store ↔ RunField values ──────────────────────────────────────────────\n\n/** Seed the runner's form values from the method-store's simplified inputData. */\nexport function runValuesFromStore(\n inputData: Dict | undefined,\n fields: RunField[],\n inputSchemas: InputSchemas,\n): Dict {\n const full = inflateAllInputs(inputData ?? {}, inputSchemas);\n const out: Dict = {};\n for (const field of fields) out[field.name] = fromRjsf(field, full[field.name]);\n return out;\n}\n\n/**\n * The runner's form values in **schema shape** - the same shape the MethodViewer's\n * RJSF form holds, and therefore the shape `gate.ts` validates\n * against the per-input JSON Schemas.\n *\n * Deliberately stops short of `deflateAllInputs`: deflation is the STORE's\n * compact form, and ajv validates the full one.\n */\nexport function rjsfDataFromRunValues(values: Dict, fields: RunField[]): Dict {\n const full: Dict = {};\n for (const field of fields) full[field.name] = toRjsf(field, values[field.name]);\n return full;\n}\n\n/** Convert the runner's form values back to the store's simplified inputData. */\nexport function storeInputDataFromRunValues(\n values: Dict,\n fields: RunField[],\n inputSchemas: InputSchemas,\n): Dict {\n return deflateAllInputs(rjsfDataFromRunValues(values, fields), inputSchemas);\n}\n\n/**\n * Build the `{ concept, content }` map a run expects from the form values.\n *\n * The two ways a method says \"this may be nothing\" land differently on the wire,\n * and both matter:\n * - an **optional (`?`)** input left blank is OMITTED, so the runtime records a\n * real absence the method can branch on - sending `{ text: \"\" }` would look\n * like the caller supplied an empty string;\n * - a **plural (`[]`)** input keeps its key, because a plural slot is never\n * absent - its empty form IS the empty list, and the runtime requires the key.\n * When that list is EMPTY it is sent BARE, without the envelope: the envelope\n * is the runtime's \"explicit form\", which bypasses the top-down shaper and\n * hands the value to the bottom-up factory, and that factory types a list from\n * its first item - so an empty list there raises \"Cannot create Stuff from\n * empty list in content\". The bare form keeps the shaper, which reads the\n * DECLARED concept and builds the empty list correctly. (pipelex/#1096 makes\n * the envelope agree; the bare form runs today and stays correct after.)\n */\nexport function apiInputsFromRunValues(\n values: Dict,\n fields: RunField[],\n inputSchemas: InputSchemas,\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const field of fields) {\n const schema = inputSchemas[field.name];\n if (!schema) continue;\n if (schema.optional === true && !isFilled(values[field.name])) continue;\n if (isPluralInput(schema) && !isFilled(values[field.name])) {\n out[field.name] = [];\n continue;\n }\n out[field.name] = { concept: schema.concept_ref, content: toRjsf(field, values[field.name]) };\n }\n return out;\n}\n\n// ─── Pipe output → result entries ────────────────────────────────────────────\n\n/** One named output pulled out of a run's working memory, ready to render. */\nexport interface OutputEntry {\n /** The output variable key (mono). */\n key: string;\n conceptRef?: string;\n value: unknown;\n}\n\n/**\n * The slice of a serialized pipe output this module actually reads. Structural\n * on purpose: the SDK's `DictPipeOutput` is the host's wire type, and the kernel\n * must not depend on `@pipelex/sdk` - the guard below verifies the shape at\n * runtime anyway.\n */\ninterface PipeOutputWithWorkingMemory {\n working_memory: {\n root: Record<string, unknown>;\n aliases?: Record<string, string>;\n };\n}\n\nfunction hasWorkingMemoryRoot(value: unknown): value is PipeOutputWithWorkingMemory {\n return (\n !!value &&\n typeof value === 'object' &&\n 'working_memory' in value &&\n !!(value as { working_memory?: { root?: unknown } }).working_memory &&\n typeof (value as { working_memory: { root?: unknown } }).working_memory.root === 'object'\n );\n}\n\n/** The concept code of a working-memory entry (`{concept}` may be obj/str/absent). */\nfunction entryConceptRef(data: unknown): string | undefined {\n if (!data || typeof data !== 'object') return undefined;\n const raw = (data as { concept?: unknown; concept_code?: unknown }).concept;\n if (raw && typeof raw === 'object')\n return (\n ((raw as { concept_code?: string }).concept_code ?? (raw as { code?: string }).code) ||\n undefined\n );\n if (typeof raw === 'string') return raw;\n return (data as { concept_code?: string }).concept_code || undefined;\n}\n\n/**\n * Split a run's pipe output into the main result and any intermediate outputs,\n * excluding the inputs. The main output's identity comes from the working\n * memory's `main_stuff` alias (the authoritative pointer to the output variable)\n * - so its label is the REAL stuff name, not a positional guess. Falls back to\n * the last produced stuff only when the alias is absent.\n */\nexport function outputsFromPipeOutput(\n pipeOutput: unknown,\n inputKeys: string[],\n): { main: OutputEntry; intermediates: OutputEntry[] } | null {\n if (!hasWorkingMemoryRoot(pipeOutput)) return null;\n const wm = pipeOutput.working_memory as {\n root: Record<string, unknown>;\n aliases?: Record<string, string>;\n };\n const entries = Object.entries(wm.root).filter(([key]) => !inputKeys.includes(key));\n if (entries.length === 0) return null;\n\n const toEntry = ([key, data]: [string, unknown]): OutputEntry => ({\n key,\n conceptRef: entryConceptRef(data),\n value: (data as { content?: unknown })?.content ?? data,\n });\n\n // The real main-output name: `aliases.main_stuff` → its root key.\n const mainKey = wm.aliases?.['main_stuff'];\n const mainEntry: [string, unknown] =\n mainKey && Object.prototype.hasOwnProperty.call(wm.root, mainKey)\n ? [mainKey, wm.root[mainKey]]\n : entries[entries.length - 1]!;\n const intermediates = entries.filter(([key]) => key !== mainEntry[0]).map(toEntry);\n\n return { main: toEntry(mainEntry), intermediates };\n}\n\n/**\n * Recover the inputs a run was executed with from its working memory. The run's\n * `working_memory.root` holds every named stuff - inputs AND outputs - keyed by\n * variable name; we pull the entries whose keys are declared inputs and deflate\n * their `content` (the full form shape) back into the store's simplified\n * `inputData`. Lets the runner repopulate the form for a past/shared run - the\n * inputs that produced the result. Returns `null` when no inputs are present.\n */\nexport function inputDataFromWorkingMemory(\n workingMemory: unknown,\n inputSchemas: InputSchemas,\n): Dict | null {\n const root = (workingMemory as { root?: Record<string, unknown> } | null | undefined)?.root;\n if (!root || typeof root !== 'object') return null;\n const full: Dict = {};\n let found = false;\n for (const key of Object.keys(inputSchemas)) {\n const entry = root[key];\n if (entry && typeof entry === 'object' && 'content' in entry) {\n full[key] = (entry as { content: unknown }).content;\n found = true;\n }\n }\n if (!found) return null;\n return deflateAllInputs(full, inputSchemas);\n}\n\n/** Field descriptors for a method's main pipe. */\nexport function fieldsForContract(contract: PipeIOContract | undefined): RunField[] {\n return contract?.inputs ? buildRunFields(contract.inputs) : [];\n}\n\n/**\n * Immutably set a value at a dotted/indexed path (`a.0.b`). Used to write an\n * uploaded file's URL back to a field anywhere in the (possibly nested) tree.\n */\nexport function setValueAtPath(root: Dict, path: string[], value: unknown): Dict {\n const head = path[0];\n if (head === undefined) return root;\n const rest = path.slice(1);\n if (rest.length === 0) return { ...root, [head]: value };\n\n const nextSeg = rest[0] as string;\n const child = root[head];\n if (/^\\d+$/.test(nextSeg)) {\n const arr = Array.isArray(child) ? child.slice() : [];\n const idx = Number(nextSeg);\n arr[idx] =\n rest.length === 1 ? value : setValueAtPath((arr[idx] as Dict) ?? {}, rest.slice(1), value);\n return { ...root, [head]: arr };\n }\n return { ...root, [head]: setValueAtPath((child as Dict) ?? {}, rest, value) };\n}\n","/**\n * Turning one ajv/RJSF validation error into a line a human can act on.\n *\n * ## Why this isn't just `error.stack`\n *\n * A blocked run used to say \"Date: pick a valid date\" while the date picker\n * showed a perfectly good 06/07/2026. Both were telling the truth about\n * different values: the stored value was `2026-07-06T14:30:00+02:00` (a real\n * time - correctly rejected for a `format: date` field), but\n * `toDateInputValue` renders `.slice(0, 10)` of it, so the FIELD showed the day\n * while the VALIDATOR judged the timestamp. The user cannot reconcile that from\n * the message, because the message named neither value.\n *\n * So: every line here quotes what is ACTUALLY in the data. An error the user\n * can see the input of is one they can fix; an instruction to \"pick a valid\n * date\" for a date that looks valid is not.\n *\n * Kept React-free (the caller passes its `t`) so the wording is unit-testable\n * without mounting the panel.\n */\nimport { dayWithinDateTime } from './date-format';\nimport type { RunInputError } from './gate-validator';\n\n/**\n * A rejected value can be an entire base64 document, and this lands in a toast.\n * Past this many characters the tail is elided - a date never comes close, and\n * a megabyte of base64 in a toast helps nobody understand anything.\n */\nconst MAX_SHOWN_VALUE_CHARS = 120;\n\n/** The message keys this module renders, relative to the caller's namespace\n * (a host passes its own translator for that namespace). */\nexport type ValidationMessageKey =\n | 'inputPanel.aDateField'\n | 'inputPanel.pickValidDate'\n | 'inputPanel.pickValidDateEmpty'\n | 'inputPanel.dateCarriesTime'\n | 'inputPanel.invalidValue'\n | 'inputPanel.invalidValueWithData';\n\n/**\n * The translate function the caller injects. Typed on the EXACT keys this\n * module uses - not a loose `(key: string) => string` - for two reasons: a\n * typo'd key still fails the build here, and next-intl's translator (whose\n * `key` parameter is the namespace's real key union, a SUPERSET of these)\n * remains assignable by parameter contravariance. Kernel-owned: this module\n * must not import next-intl's types.\n */\nexport type Translate = (key: ValidationMessageKey, values?: Record<string, string>) => string;\n\n/**\n * The value the validator actually rejected, read back out of the submitted data.\n *\n * RJSF builds `property` from ajv's `instancePath` by swapping `/` for `.`\n * (`.quote_date.date`), so the segments index straight into the form data.\n * Array indices arrive as digit strings and index arrays natively.\n */\nexport function valueAtProperty(data: unknown, property: string | undefined): unknown {\n if (!property) return undefined;\n let current: unknown = data;\n for (const segment of property.split('.').filter(Boolean)) {\n if (typeof current !== 'object' || current === null) return undefined;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\n/**\n * The rejected value rendered for a toast, or `null` when there is nothing\n * worth showing (an absent or blank value - \"you left it empty\" is what the\n * message says on its own, and `“”` adds noise).\n */\nexport function displayValue(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value === 'string' && value.trim() === '') return null;\n const text = typeof value === 'string' ? value : JSON.stringify(value);\n if (text === undefined) return null;\n return text.length > MAX_SHOWN_VALUE_CHARS ? `${text.slice(0, MAX_SHOWN_VALUE_CHARS)}…` : text;\n}\n\n/** The field name ajv quoted in its stack, or a generic stand-in. */\nfunction labelOf(error: RunInputError, t: Translate): string {\n return error.stack?.match(/'([^']+)'/)?.[1] ?? t('inputPanel.aDateField');\n}\n\n/**\n * One validation error as a human line naming the offending value.\n *\n * The date branch is special-cased because ajv's own complaint (`'Date' must\n * match format \"date-time\"`) is opaque, and because the carries-a-time case has\n * a specific fix the user cannot guess: move the time into the sibling `time`\n * field, which is exactly what the runtime's own error says.\n */\nexport function describeValidationError(\n error: RunInputError,\n t: Translate,\n formData: unknown,\n): string {\n const format = (error.params as { format?: string } | undefined)?.format;\n const value = valueAtProperty(formData, error.property);\n const shown = displayValue(value);\n\n if (error.name === 'format' && (format === 'date' || format === 'date-time')) {\n const label = labelOf(error, t);\n if (shown === null) return t('inputPanel.pickValidDateEmpty', { label });\n // Only a `format: date` field rejects a real time; date-time takes it.\n const day = format === 'date' && typeof value === 'string' ? dayWithinDateTime(value) : null;\n if (day !== null) return t('inputPanel.dateCarriesTime', { label, value: shown, day });\n return t('inputPanel.pickValidDate', { label, value: shown });\n }\n\n const stack = error.stack ?? error.message ?? t('inputPanel.invalidValue');\n return shown === null ? stack : t('inputPanel.invalidValueWithData', { stack, value: shown });\n}\n"]}