@agentprismform/agent-plugin 1.3.1 → 2.0.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.
@@ -5,17 +5,17 @@ var __commonJS = (cb, mod) => function __require() {
5
5
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
6
6
  };
7
7
 
8
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/types.js
8
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/types.js
9
9
  var require_types = __commonJS({
10
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/types.js"(exports2) {
10
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/types.js"(exports2) {
11
11
  "use strict";
12
12
  Object.defineProperty(exports2, "__esModule", { value: true });
13
13
  }
14
14
  });
15
15
 
16
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/expression/types.js
16
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/expression/types.js
17
17
  var require_types2 = __commonJS({
18
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/expression/types.js"(exports2) {
18
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/expression/types.js"(exports2) {
19
19
  "use strict";
20
20
  Object.defineProperty(exports2, "__esModule", { value: true });
21
21
  exports2.DEFAULT_MAX_DEPTH = exports2.DEFAULT_MAX_LENGTH = exports2.ExpressionError = void 0;
@@ -32,9 +32,9 @@ var require_types2 = __commonJS({
32
32
  }
33
33
  });
34
34
 
35
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/expression/safeV1.js
35
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/expression/safeV1.js
36
36
  var require_safeV1 = __commonJS({
37
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/expression/safeV1.js"(exports2) {
37
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/expression/safeV1.js"(exports2) {
38
38
  "use strict";
39
39
  Object.defineProperty(exports2, "__esModule", { value: true });
40
40
  exports2.tokenize = tokenize;
@@ -461,9 +461,9 @@ var require_safeV1 = __commonJS({
461
461
  }
462
462
  });
463
463
 
464
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/expression/index.js
464
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/expression/index.js
465
465
  var require_expression = __commonJS({
466
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/expression/index.js"(exports2) {
466
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/expression/index.js"(exports2) {
467
467
  "use strict";
468
468
  Object.defineProperty(exports2, "__esModule", { value: true });
469
469
  exports2.tokenize = exports2.parseSafeV1 = exports2.isSafeV1Expression = exports2.DEFAULT_MAX_LENGTH = exports2.DEFAULT_MAX_DEPTH = exports2.ExpressionError = void 0;
@@ -621,9 +621,9 @@ var require_expression = __commonJS({
621
621
  }
622
622
  });
623
623
 
624
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/utils.js
624
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/utils.js
625
625
  var require_utils = __commonJS({
626
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/utils.js"(exports2) {
626
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/utils.js"(exports2) {
627
627
  "use strict";
628
628
  Object.defineProperty(exports2, "__esModule", { value: true });
629
629
  exports2.evaluateExpression = void 0;
@@ -722,9 +722,9 @@ var require_utils = __commonJS({
722
722
  }
723
723
  });
724
724
 
725
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/validate.js
725
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/validate.js
726
726
  var require_validate = __commonJS({
727
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/validate.js"(exports2) {
727
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/validate.js"(exports2) {
728
728
  "use strict";
729
729
  Object.defineProperty(exports2, "__esModule", { value: true });
730
730
  exports2.isEmptyValue = isEmptyValue;
@@ -920,9 +920,9 @@ var require_validate = __commonJS({
920
920
  }
921
921
  });
922
922
 
923
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/relations.js
923
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/relations.js
924
924
  var require_relations = __commonJS({
925
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/relations.js"(exports2) {
925
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/relations.js"(exports2) {
926
926
  "use strict";
927
927
  Object.defineProperty(exports2, "__esModule", { value: true });
928
928
  exports2.resolveRelations = resolveRelations;
@@ -1021,9 +1021,9 @@ var require_relations = __commonJS({
1021
1021
  }
1022
1022
  });
1023
1023
 
1024
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/FormCore.js
1024
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/FormCore.js
1025
1025
  var require_FormCore = __commonJS({
1026
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/FormCore.js"(exports2) {
1026
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/FormCore.js"(exports2) {
1027
1027
  "use strict";
1028
1028
  Object.defineProperty(exports2, "__esModule", { value: true });
1029
1029
  exports2.FormCore = void 0;
@@ -2227,9 +2227,9 @@ var require_FormCore = __commonJS({
2227
2227
  }
2228
2228
  });
2229
2229
 
2230
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/questionnaire.js
2230
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/questionnaire.js
2231
2231
  var require_questionnaire = __commonJS({
2232
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/questionnaire.js"(exports2) {
2232
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/questionnaire.js"(exports2) {
2233
2233
  "use strict";
2234
2234
  Object.defineProperty(exports2, "__esModule", { value: true });
2235
2235
  exports2.schemaToQuestionnaire = schemaToQuestionnaire;
@@ -2284,9 +2284,9 @@ var require_questionnaire = __commonJS({
2284
2284
  }
2285
2285
  });
2286
2286
 
2287
- // output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/index.js
2287
+ // output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/index.js
2288
2288
  var require_dist = __commonJS({
2289
- "output/oss-release/agentprismform-1.0.0-stage/packages/core/dist/index.js"(exports2) {
2289
+ "output/oss-release/agentprismform-2.0.0-stage/packages/core/dist/index.js"(exports2) {
2290
2290
  "use strict";
2291
2291
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) {
2292
2292
  if (k2 === void 0) k2 = k;
@@ -4624,11 +4624,2400 @@ var require_dataHubStore = __commonJS({
4624
4624
  }
4625
4625
  });
4626
4626
 
4627
+ // packages/form-intent-fill/dist/slicer.js
4628
+ var require_slicer = __commonJS({
4629
+ "packages/form-intent-fill/dist/slicer.js"(exports2) {
4630
+ "use strict";
4631
+ Object.defineProperty(exports2, "__esModule", { value: true });
4632
+ exports2.isEmptyFieldValue = isEmptyFieldValue;
4633
+ exports2.extractStaticOptions = extractStaticOptions;
4634
+ exports2.classifyFieldPolicy = classifyFieldPolicy;
4635
+ exports2.classifyFieldRisk = classifyFieldRisk;
4636
+ exports2.collectSchemaItems = collectSchemaItems;
4637
+ exports2.buildActiveContextSlice = buildActiveContextSlice;
4638
+ exports2.compileIntentPrompt = compileIntentPrompt;
4639
+ exports2.buildSliceJsonSchema = buildSliceJsonSchema;
4640
+ var FORBIDDEN_TYPES = /* @__PURE__ */ new Set([
4641
+ "signature",
4642
+ "agreement",
4643
+ "imageUpload",
4644
+ "upload",
4645
+ "verifyCode",
4646
+ "task",
4647
+ "divider",
4648
+ "section",
4649
+ "html"
4650
+ ]);
4651
+ var MENTION_ONLY_TYPES = /* @__PURE__ */ new Set(["address", "search", "cascader"]);
4652
+ var CRITICAL_KEY_PATTERN = /(phone|mobile|tel|id_?card|identity|bank_?card|account_?no|email|salary|income|spouse_?id)/i;
4653
+ function isEmptyFieldValue(value) {
4654
+ if (value === null || value === void 0 || value === "")
4655
+ return true;
4656
+ if (Array.isArray(value))
4657
+ return value.length === 0;
4658
+ return false;
4659
+ }
4660
+ function extractStaticOptions(item) {
4661
+ const raw = item.initOptions || item.options || item.props?.options;
4662
+ if (!Array.isArray(raw) || raw.length === 0)
4663
+ return void 0;
4664
+ const out = [];
4665
+ for (const opt of raw) {
4666
+ if (!opt || typeof opt !== "object")
4667
+ continue;
4668
+ const code = String(opt.code ?? opt.value ?? "").trim();
4669
+ const name = String(opt.name ?? opt.label ?? code).trim();
4670
+ if (code)
4671
+ out.push({ code, name });
4672
+ }
4673
+ return out.length > 0 ? out : void 0;
4674
+ }
4675
+ function classifyFieldPolicy(item, dictionaryFields = /* @__PURE__ */ new Set()) {
4676
+ if (item.extractable === false)
4677
+ return "forbidden";
4678
+ if (FORBIDDEN_TYPES.has(item.type))
4679
+ return "forbidden";
4680
+ if (dictionaryFields.has(item.key))
4681
+ return "mention_only";
4682
+ if (MENTION_ONLY_TYPES.has(item.type))
4683
+ return "mention_only";
4684
+ if ((item.type === "select" || item.type === "radioGroup" || item.type === "checkboxGroup") && !extractStaticOptions(item)) {
4685
+ return "mention_only";
4686
+ }
4687
+ if (item.type === "list")
4688
+ return "forbidden";
4689
+ return "extractable";
4690
+ }
4691
+ function classifyFieldRisk(item, criticalFields = /* @__PURE__ */ new Set()) {
4692
+ if (item.risk === "CRITICAL" || criticalFields.has(item.key))
4693
+ return "CRITICAL";
4694
+ if (item.type === "phone")
4695
+ return "CRITICAL";
4696
+ if (CRITICAL_KEY_PATTERN.test(item.key))
4697
+ return "CRITICAL";
4698
+ return "NORMAL";
4699
+ }
4700
+ function collectSchemaItems(schema) {
4701
+ const out = [];
4702
+ for (const g of schema.groups || []) {
4703
+ for (const item of g.items || []) {
4704
+ out.push(item);
4705
+ }
4706
+ }
4707
+ return out;
4708
+ }
4709
+ function buildActiveContextSlice(schema, runtimeFields, options = {}) {
4710
+ const locale = options.locale === "en-US" ? "en-US" : "zh-CN";
4711
+ const dictSet = new Set(options.dictionaryFields || []);
4712
+ const critSet = new Set(options.criticalFields || []);
4713
+ const items = collectSchemaItems(schema);
4714
+ const visibleTriggerHints = /* @__PURE__ */ new Map();
4715
+ for (const item of items) {
4716
+ const f = runtimeFields[item.key];
4717
+ const isVis = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
4718
+ const isDis = Boolean(f?.disabled ?? item.disabled);
4719
+ if (!isVis || isDis)
4720
+ continue;
4721
+ for (const rel of item.relations || []) {
4722
+ if (rel && rel.target && rel.effect === "visible") {
4723
+ visibleTriggerHints.set(String(rel.target), `${item.label || item.key}(${item.key}): ${String(rel.logic || "")}`);
4724
+ }
4725
+ }
4726
+ }
4727
+ const extractableFields = [];
4728
+ const conditionalFields = [];
4729
+ const mentionFields = [];
4730
+ const forbiddenFields = [];
4731
+ for (const item of items) {
4732
+ const f = runtimeFields[item.key];
4733
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
4734
+ const disabled = Boolean(f?.disabled ?? item.disabled);
4735
+ const readonly = Boolean(item.readonly || item.readOnly);
4736
+ const policy = classifyFieldPolicy(item, dictSet);
4737
+ const risk = classifyFieldRisk(item, critSet);
4738
+ const currentValue = f !== void 0 ? f.value : item.defaultValue;
4739
+ const required = Boolean(f?.required ?? item.required);
4740
+ if (policy === "forbidden") {
4741
+ if (visible) {
4742
+ forbiddenFields.push({
4743
+ key: item.key,
4744
+ label: item.label || item.key,
4745
+ type: item.type,
4746
+ required,
4747
+ visible
4748
+ });
4749
+ }
4750
+ continue;
4751
+ }
4752
+ if (disabled || readonly)
4753
+ continue;
4754
+ const conditionallyReachable = !visible && visibleTriggerHints.has(item.key);
4755
+ if (!visible && !conditionallyReachable)
4756
+ continue;
4757
+ const sliceItem = {
4758
+ key: item.key,
4759
+ label: item.label || item.key,
4760
+ type: item.type,
4761
+ required,
4762
+ visible,
4763
+ conditionallyReachable,
4764
+ policy,
4765
+ risk,
4766
+ currentValue,
4767
+ hasValue: !isEmptyFieldValue(currentValue),
4768
+ placeholder: item.placeholder,
4769
+ help: item.help || item.description,
4770
+ options: extractStaticOptions(item),
4771
+ min: typeof item.props?.min === "number" ? item.props.min : void 0,
4772
+ max: typeof item.props?.max === "number" ? item.props.max : void 0,
4773
+ triggerHint: conditionallyReachable ? visibleTriggerHints.get(item.key) : void 0
4774
+ };
4775
+ if (policy === "mention_only") {
4776
+ if (visible)
4777
+ mentionFields.push(sliceItem);
4778
+ } else if (visible) {
4779
+ extractableFields.push(sliceItem);
4780
+ } else {
4781
+ conditionalFields.push(sliceItem);
4782
+ }
4783
+ }
4784
+ return {
4785
+ schemaTitle: schema.title || (locale === "en-US" ? "Form" : "\u8868\u5355"),
4786
+ storageKey: schema.storageKey || "",
4787
+ locale,
4788
+ extractableFields,
4789
+ conditionalFields,
4790
+ mentionFields,
4791
+ forbiddenFields
4792
+ };
4793
+ }
4794
+ function formatFieldLine(f, locale) {
4795
+ const isEn = locale === "en-US";
4796
+ const valType = f.type === "number" || f.type === "stepper" || f.type === "slider" ? isEn ? "number" : "\u6570\u5B57" : f.type === "switch" ? isEn ? "boolean" : "\u5E03\u5C14" : f.type === "checkboxGroup" ? isEn ? "string[]" : "\u5B57\u7B26\u4E32\u6570\u7EC4" : isEn ? "string" : "\u5B57\u7B26\u4E32";
4797
+ const optsStr = f.options ? (isEn ? " Options: " : " \u53EF\u9009\u4EE3\u7801\uFF1A") + f.options.map((o) => `${JSON.stringify(o.code)}=${o.name}`).join(isEn ? ", " : "\u3001") : "";
4798
+ const rangeStr = f.min !== void 0 || f.max !== void 0 ? isEn ? ` Range:[${f.min ?? ""},${f.max ?? ""}]` : ` \u8303\u56F4:[${f.min ?? ""},${f.max ?? ""}]` : "";
4799
+ const hintStr = f.help ? isEn ? ` Note: ${f.help}` : ` \u8BF4\u660E\uFF1A${f.help}` : "";
4800
+ const condStr = f.triggerHint ? isEn ? ` (Only if ${f.triggerHint})` : `\uFF08\u4EC5\u5F53 ${f.triggerHint} \u6EE1\u8DB3\u65F6\u8F93\u51FA\uFF09` : "";
4801
+ return `- ${f.key} (${f.label}, ${valType}${f.required ? isEn ? ", required" : ", \u5FC5\u586B" : ""})${optsStr}${rangeStr}${hintStr}${condStr}`;
4802
+ }
4803
+ function compileIntentPrompt(slice) {
4804
+ const isEn = slice.locale === "en-US";
4805
+ const lines = [
4806
+ ...slice.extractableFields.map((f) => formatFieldLine(f, slice.locale)),
4807
+ ...slice.conditionalFields.map((f) => formatFieldLine(f, slice.locale))
4808
+ ];
4809
+ const mentionLines = slice.mentionFields.map((f) => isEn ? `- ${f.key}_raw (${f.label}, verbatim string only; NEVER invent codes)` : `- ${f.key}_raw\uFF08${f.label}\uFF0C\u4EC5\u4FDD\u7559\u7528\u6237\u539F\u8BDD\u6587\u672C\uFF0C\u7981\u6B62\u7F16\u9020\u4EE3\u7801\uFF09`);
4810
+ const forbiddenKeys = slice.forbiddenFields.map((f) => f.key);
4811
+ if (isEn) {
4812
+ return [
4813
+ `Convert the user's utterance for "${slice.schemaTitle}" into a SPARSE JSON patch object (not the full form).`,
4814
+ "Only include keys explicitly stated by the user. Omit unmentioned keys completely. Never output null or empty strings.",
4815
+ "Available fields:",
4816
+ ...lines.length ? lines : ["- (none)"],
4817
+ ...mentionLines.length ? ["Verbatim mention fields (use <key>_raw only, never guess option/area codes):", ...mentionLines] : [],
4818
+ ...forbiddenKeys.length ? [`Forbidden keys (NEVER output): ${forbiddenKeys.join(", ")}`] : [],
4819
+ "Rules:",
4820
+ '- For option fields, output ONLY the exact option code string listed above (e.g., "team" not "Team").',
4821
+ '- For numeric/stepper/slider fields, output a JSON number (convert spoken words like "three" -> 3).',
4822
+ "- For boolean switch fields, output true or false.",
4823
+ "- Return ONE compact JSON object with no markdown or explanation. Return {} if nothing can be extracted."
4824
+ ].join("\n");
4825
+ }
4826
+ return [
4827
+ `\u628A\u672C\u8F6E\u7528\u6237\u9488\u5BF9\u300C${slice.schemaTitle}\u300D\u7684\u8F93\u5165\u8F6C\u6362\u4E3A\u7A00\u758F JSON \u5B57\u6BB5\u8865\u4E01\uFF0C\u4E0D\u662F\u5B8C\u6574\u8868\u5355\u3002`,
4828
+ "\u4EC5\u8FD4\u56DE\u7528\u6237\u660E\u786E\u63D0\u5230\u7684\u5B57\u6BB5\uFF1B\u6CA1\u8BF4\u7684 key \u7EDD\u5BF9\u4E0D\u8981\u51FA\u73B0\uFF0C\u7981\u6B62\u7528 null\u3001\u7A7A\u5B57\u7B26\u4E32\u6216\u731C\u6D4B\u503C\u8865\u9F50\u3002",
4829
+ "\u5F53\u524D\u53EF\u63D0\u53D6\u5B57\u6BB5\u4E0E\u53D6\u503C\uFF1A",
4830
+ ...lines.length ? lines : ["- \uFF08\u6682\u65E0\u53EF\u63D0\u53D6\u5B57\u6BB5\uFF09"],
4831
+ ...mentionLines.length ? ["\u539F\u8BDD\u6682\u5B58\u5B57\u6BB5\uFF08\u4EC5\u8F93\u51FA <key>_raw \u4FDD\u7559\u539F\u8BDD\uFF0C\u4E25\u7981\u7F16\u9020\u884C\u653F\u533A\u7801\u6216\u5B57\u5178\u4EE3\u7801\uFF09\uFF1A", ...mentionLines] : [],
4832
+ ...forbiddenKeys.length ? [`\u4E25\u7981\u8F93\u51FA\u7684\u9AD8\u5371\u5B57\u6BB5\uFF08\u5FC5\u987B\u7528\u6237\u672C\u4EBA\u64CD\u4F5C\uFF09\uFF1A${forbiddenKeys.join("\u3001")}`] : [],
4833
+ "\u6267\u884C\u89C4\u5219\uFF1A",
4834
+ '- \u9009\u9879\u5B57\u6BB5\u53EA\u8F93\u51FA\u4E0A\u65B9\u5217\u51FA\u7684\u7CBE\u786E\u4EE3\u7801\u5B57\u7B26\u4E32\uFF08\u4F8B\u5982\u8F93\u51FA "team" \u800C\u975E "\u7EC4\u961F\u53C2\u8D5B"\uFF09\u3002',
4835
+ "- \u6570\u5B57 / \u6B65\u8FDB\u5668 / \u6ED1\u5757\u5B57\u6BB5\u8F93\u51FA JSON \u6570\u5B57\uFF08\u5C06\u4E2D\u6587\u53E3\u8BED\u6570\u5B57\u8F6C\u4E3A\u963F\u62C9\u4F2F\u6570\u5B57\uFF0C\u5982\u201C\u4E09\u201D\u21923\u3001\u201C\u516B\u5343\u201D\u21928000\u3001\u201C\u4E8C\u5341\u56DB\u4E07\u201D\u2192240000\uFF09\u3002",
4836
+ "- \u5F00\u5173\uFF08switch\uFF09\u5B57\u6BB5\u8F93\u51FA\u5E03\u5C14\u503C true \u6216 false\u3002",
4837
+ "- \u9010\u9879\u63D0\u53D6\u53E5\u4E2D\u6240\u6709\u660E\u786E\u63D0\u5230\u7684\u5B57\u6BB5\uFF08\u542B\u540C\u53E5\u89E6\u53D1\u7684\u6761\u4EF6\u5B57\u6BB5\uFF09\uFF0C\u4E0D\u9057\u6F0F\u53E5\u5C3E\u4FE1\u606F\u3002",
4838
+ "- \u53EA\u8FD4\u56DE\u4E00\u4E2A\u7D27\u51D1 JSON \u5BF9\u8C61\uFF0C\u4E0D\u89E3\u91CA\u3001\u4E0D\u8FFD\u95EE\u3001\u4E0D\u8F93\u51FA Markdown \u4EE3\u7801\u5757\uFF1B\u65E0\u53EF\u586B\u4FE1\u606F\u8FD4\u56DE {}\u3002"
4839
+ ].join("\n");
4840
+ }
4841
+ function buildSliceJsonSchema(slice) {
4842
+ const properties = {};
4843
+ const addExtractable = (f) => {
4844
+ if (f.type === "number" || f.type === "stepper" || f.type === "slider") {
4845
+ properties[f.key] = {
4846
+ type: "number",
4847
+ ...f.min !== void 0 ? { minimum: f.min } : {},
4848
+ ...f.max !== void 0 ? { maximum: f.max } : {}
4849
+ };
4850
+ return;
4851
+ }
4852
+ if (f.type === "switch") {
4853
+ properties[f.key] = { type: "boolean" };
4854
+ return;
4855
+ }
4856
+ if (f.type === "checkboxGroup") {
4857
+ properties[f.key] = {
4858
+ type: "array",
4859
+ items: f.options && f.options.length ? { type: "string", enum: f.options.map((o) => o.code) } : { type: "string" }
4860
+ };
4861
+ return;
4862
+ }
4863
+ if (f.options && f.options.length) {
4864
+ properties[f.key] = {
4865
+ type: "string",
4866
+ enum: f.options.map((o) => o.code)
4867
+ };
4868
+ return;
4869
+ }
4870
+ properties[f.key] = { type: "string" };
4871
+ };
4872
+ for (const f of slice.extractableFields)
4873
+ addExtractable(f);
4874
+ for (const f of slice.conditionalFields)
4875
+ addExtractable(f);
4876
+ for (const m of slice.mentionFields) {
4877
+ properties[`${m.key}_raw`] = { type: "string" };
4878
+ }
4879
+ return {
4880
+ type: "object",
4881
+ additionalProperties: false,
4882
+ properties
4883
+ };
4884
+ }
4885
+ }
4886
+ });
4887
+
4888
+ // packages/form-intent-fill/dist/adapters.js
4889
+ var require_adapters = __commonJS({
4890
+ "packages/form-intent-fill/dist/adapters.js"(exports2) {
4891
+ "use strict";
4892
+ Object.defineProperty(exports2, "__esModule", { value: true });
4893
+ exports2.normalizeBase64Image = normalizeBase64Image;
4894
+ exports2.parseJsonFromModelText = parseJsonFromModelText;
4895
+ exports2.sanitizeRawExtraction = sanitizeRawExtraction;
4896
+ exports2.createOllamaIntentAdapter = createOllamaIntentAdapter;
4897
+ exports2.createOpenAICompatibleIntentAdapter = createOpenAICompatibleIntentAdapter;
4898
+ exports2.createHttpIntentAdapter = createHttpIntentAdapter;
4899
+ exports2.createOnDeviceBridgeAdapter = createOnDeviceBridgeAdapter;
4900
+ var slicer_1 = require_slicer();
4901
+ function normalizeBase64Image(input, fallbackMime = "image/png") {
4902
+ const raw = String(input || "").trim();
4903
+ if (!raw) {
4904
+ throw new Error("\u56FE\u7247\u5185\u5BB9\u4E3A\u7A7A\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u56FE\u7247\u3002");
4905
+ }
4906
+ const m = raw.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]+)$/i);
4907
+ if (m) {
4908
+ const clean2 = m[2].replace(/\s+/g, "");
4909
+ if (!clean2)
4910
+ throw new Error("\u56FE\u7247\u6570\u636E\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u56FE\u7247\u3002");
4911
+ return { mimeType: m[1].toLowerCase(), base64: clean2 };
4912
+ }
4913
+ const clean = raw.replace(/\s+/g, "");
4914
+ return { mimeType: fallbackMime, base64: clean };
4915
+ }
4916
+ function buildVisionUserInstruction(locale, hintText) {
4917
+ const base = locale === "en-US" ? "Extract ONLY fields explicitly visible in this image following the system schema rules. Never guess, invent, or output fields that do not appear in the image." : "\u8BF7\u4E25\u683C\u6309\u89C4\u5219\u53EA\u63D0\u53D6\u8FD9\u5F20\u56FE\u7247\u4E2D\u660E\u786E\u51FA\u73B0\u7684\u5B57\u6BB5\uFF1B\u56FE\u7247\u672A\u51FA\u73B0\u7684\u4FE1\u606F\u7EDD\u4E0D\u8981\u731C\u6D4B\u3001\u7F16\u9020\u6216\u8F93\u51FA\u3002";
4918
+ const extra = String(hintText || "").trim();
4919
+ if (!extra)
4920
+ return base;
4921
+ return locale === "en-US" ? `${base}
4922
+ Additional user note: ${extra}` : `${base}
4923
+ \u7528\u6237\u8865\u5145\u8BF4\u660E\uFF1A${extra}`;
4924
+ }
4925
+ function getGlobalFetch(custom) {
4926
+ const fn = custom || globalThis.fetch;
4927
+ if (typeof fn !== "function") {
4928
+ throw new Error("\u5F53\u524D\u8FD0\u884C\u65F6\u7F3A\u5C11 fetch \u5B9E\u73B0\uFF0C\u8BF7\u901A\u8FC7 fetchImpl \u6CE8\u5165\u3002");
4929
+ }
4930
+ return fn;
4931
+ }
4932
+ function parseJsonFromModelText(raw) {
4933
+ const text = String(raw || "").trim();
4934
+ if (!text)
4935
+ return {};
4936
+ const stripped = text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
4937
+ let parsed;
4938
+ try {
4939
+ parsed = JSON.parse(stripped);
4940
+ } catch {
4941
+ const start = stripped.indexOf("{");
4942
+ const end = stripped.lastIndexOf("}");
4943
+ if (start >= 0 && end > start) {
4944
+ parsed = JSON.parse(stripped.slice(start, end + 1));
4945
+ } else {
4946
+ throw new Error("\u6A21\u578B\u672A\u8FD4\u56DE\u6709\u6548 JSON \u5BF9\u8C61\uFF0C\u8BF7\u91CD\u8BD5\u3002");
4947
+ }
4948
+ }
4949
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
4950
+ throw new Error("\u6A21\u578B\u8FD4\u56DE\u7ED3\u679C\u4E0D\u662F JSON \u5BF9\u8C61\uFF0C\u8BF7\u91CD\u8BD5\u3002");
4951
+ }
4952
+ return parsed;
4953
+ }
4954
+ function sanitizeRawExtraction(rawObj, slice) {
4955
+ const mentionMap = /* @__PURE__ */ new Map();
4956
+ for (const m of slice.mentionFields) {
4957
+ mentionMap.set(`${m.key}_raw`, m.key);
4958
+ }
4959
+ const patch = {};
4960
+ const mentions = {};
4961
+ const omittedEmptyFields = [];
4962
+ for (const [key, value] of Object.entries(rawObj)) {
4963
+ if (value === null || value === void 0 || typeof value === "string" && !value.trim()) {
4964
+ omittedEmptyFields.push(key);
4965
+ continue;
4966
+ }
4967
+ if (mentionMap.has(key)) {
4968
+ mentions[mentionMap.get(key)] = String(value).trim();
4969
+ continue;
4970
+ }
4971
+ patch[key] = value;
4972
+ }
4973
+ return { patch, mentions, omittedEmptyFields };
4974
+ }
4975
+ function createOllamaIntentAdapter(options = {}) {
4976
+ const baseUrl = String(options.baseUrl || "http://127.0.0.1:11434").replace(/\/+$/, "");
4977
+ const model = options.model || "qwen3.5:4b-q4_K_M";
4978
+ const visionModel = options.visionModel || model;
4979
+ const think = options.think ?? false;
4980
+ const structuredOutput = options.structuredOutput ?? false;
4981
+ const temperature = options.temperature ?? 0;
4982
+ const numCtx = options.numCtx ?? 4096;
4983
+ const numPredict = options.numPredict ?? 384;
4984
+ const keepAlive = options.keepAlive ?? "5m";
4985
+ const fetchImpl = options.fetchImpl;
4986
+ async function runChat(targetModel, messages, slice, signal) {
4987
+ const started = Date.now();
4988
+ const format = structuredOutput ? (0, slicer_1.buildSliceJsonSchema)(slice) : "json";
4989
+ const res = await getGlobalFetch(fetchImpl)(`${baseUrl}/api/chat`, {
4990
+ method: "POST",
4991
+ headers: { "content-type": "application/json" },
4992
+ body: JSON.stringify({
4993
+ model: targetModel,
4994
+ stream: false,
4995
+ think,
4996
+ keep_alive: keepAlive,
4997
+ format,
4998
+ options: {
4999
+ temperature,
5000
+ num_ctx: numCtx,
5001
+ num_predict: numPredict
5002
+ },
5003
+ messages
5004
+ }),
5005
+ signal
5006
+ });
5007
+ if (!res.ok) {
5008
+ throw new Error(`\u672C\u5730 Ollama \u8C03\u7528\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
5009
+ }
5010
+ const data = await res.json();
5011
+ if (data?.done === false || data?.done_reason === "length" || typeof data?.message?.content !== "string") {
5012
+ throw new Error("\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6574\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002");
5013
+ }
5014
+ const rawObj = parseJsonFromModelText(data.message.content);
5015
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
5016
+ return {
5017
+ patch,
5018
+ mentions,
5019
+ rawText: data.message.content,
5020
+ model: targetModel,
5021
+ elapsedMs: Date.now() - started,
5022
+ omittedEmptyFields
5023
+ };
5024
+ }
5025
+ return {
5026
+ name: `ollama:${model}`,
5027
+ async health() {
5028
+ try {
5029
+ const res = await getGlobalFetch(fetchImpl)(`${baseUrl}/api/tags`);
5030
+ if (!res.ok)
5031
+ return { ready: false, model, message: `Ollama HTTP ${res.status}` };
5032
+ const data = await res.json();
5033
+ const names = Array.isArray(data?.models) ? data.models.map((m) => String(m.name || "")) : [];
5034
+ const ready = names.includes(model);
5035
+ return {
5036
+ ready,
5037
+ model,
5038
+ message: ready ? `Ollama ready (${model})` : `Model ${model} not found in local Ollama`
5039
+ };
5040
+ } catch (err) {
5041
+ return { ready: false, model, message: err?.message || "Ollama unavailable" };
5042
+ }
5043
+ },
5044
+ async extract(text, slice, opts) {
5045
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
5046
+ return runChat(model, [
5047
+ { role: "system", content: systemPrompt },
5048
+ { role: "user", content: text }
5049
+ ], slice, opts?.signal);
5050
+ },
5051
+ async extractFromImage(imageBase64, slice, opts) {
5052
+ const { base64 } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
5053
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
5054
+ const userPrompt = buildVisionUserInstruction(opts?.locale || slice.locale, opts?.hintText);
5055
+ return runChat(visionModel, [
5056
+ { role: "system", content: systemPrompt },
5057
+ { role: "user", content: userPrompt, images: [base64] }
5058
+ ], slice, opts?.signal);
5059
+ }
5060
+ };
5061
+ }
5062
+ function createOpenAICompatibleIntentAdapter(options) {
5063
+ const baseUrl = String(options.baseUrl || "").replace(/\/+$/, "");
5064
+ const model = options.model;
5065
+ const visionModel = options.visionModel || model;
5066
+ const fetchImpl = options.fetchImpl;
5067
+ async function runOpenAiChat(targetModel, messages, slice, signal) {
5068
+ const started = Date.now();
5069
+ const headers = { "content-type": "application/json" };
5070
+ if (options.apiKey)
5071
+ headers.authorization = `Bearer ${options.apiKey}`;
5072
+ const res = await getGlobalFetch(fetchImpl)(`${baseUrl}/v1/chat/completions`, {
5073
+ method: "POST",
5074
+ headers,
5075
+ body: JSON.stringify({
5076
+ model: targetModel,
5077
+ temperature: options.temperature ?? 0,
5078
+ max_tokens: options.maxTokens ?? 384,
5079
+ response_format: { type: "json_object" },
5080
+ messages
5081
+ }),
5082
+ signal
5083
+ });
5084
+ if (!res.ok) {
5085
+ throw new Error(`\u6A21\u578B\u63A5\u53E3\u8C03\u7528\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
5086
+ }
5087
+ const data = await res.json();
5088
+ const content = data?.choices?.[0]?.message?.content;
5089
+ if (typeof content !== "string") {
5090
+ throw new Error("\u6A21\u578B\u54CD\u5E94\u7F3A\u5C11\u6709\u6548\u6587\u672C\u5185\u5BB9\u3002");
5091
+ }
5092
+ const rawObj = parseJsonFromModelText(content);
5093
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
5094
+ return {
5095
+ patch,
5096
+ mentions,
5097
+ rawText: content,
5098
+ model: targetModel,
5099
+ elapsedMs: Date.now() - started,
5100
+ omittedEmptyFields
5101
+ };
5102
+ }
5103
+ return {
5104
+ name: `openai-compat:${model}`,
5105
+ async extract(text, slice, opts) {
5106
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
5107
+ return runOpenAiChat(model, [
5108
+ { role: "system", content: systemPrompt },
5109
+ { role: "user", content: text }
5110
+ ], slice, opts?.signal);
5111
+ },
5112
+ async extractFromImage(imageBase64, slice, opts) {
5113
+ const { base64, mimeType } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
5114
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
5115
+ const userPrompt = buildVisionUserInstruction(opts?.locale || slice.locale, opts?.hintText);
5116
+ return runOpenAiChat(visionModel, [
5117
+ { role: "system", content: systemPrompt },
5118
+ {
5119
+ role: "user",
5120
+ content: [
5121
+ { type: "text", text: userPrompt },
5122
+ { type: "image_url", image_url: { url: `data:${mimeType};base64,${base64}` } }
5123
+ ]
5124
+ }
5125
+ ], slice, opts?.signal);
5126
+ }
5127
+ };
5128
+ }
5129
+ function createHttpIntentAdapter(options) {
5130
+ const endpoint = options.endpoint;
5131
+ const imageEndpoint = options.imageEndpoint || endpoint;
5132
+ const fetchImpl = options.fetchImpl;
5133
+ return {
5134
+ name: `http:${endpoint}`,
5135
+ async extract(text, slice, opts) {
5136
+ const started = Date.now();
5137
+ const res = await getGlobalFetch(fetchImpl)(endpoint, {
5138
+ method: "POST",
5139
+ headers: { "content-type": "application/json" },
5140
+ body: JSON.stringify({ text, slice }),
5141
+ signal: opts?.signal
5142
+ });
5143
+ if (!res.ok) {
5144
+ throw new Error(`\u667A\u586B\u4EE3\u7406\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
5145
+ }
5146
+ const data = await res.json();
5147
+ return {
5148
+ patch: data?.patch || {},
5149
+ mentions: data?.mentions || {},
5150
+ rawText: data?.rawText,
5151
+ model: data?.model,
5152
+ elapsedMs: typeof data?.elapsedMs === "number" ? data.elapsedMs : Date.now() - started,
5153
+ omittedEmptyFields: Array.isArray(data?.omittedEmptyFields) ? data.omittedEmptyFields : []
5154
+ };
5155
+ },
5156
+ async extractFromImage(imageBase64, slice, opts) {
5157
+ const started = Date.now();
5158
+ const { base64, mimeType } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
5159
+ const res = await getGlobalFetch(fetchImpl)(imageEndpoint, {
5160
+ method: "POST",
5161
+ headers: { "content-type": "application/json" },
5162
+ body: JSON.stringify({ imageBase64: base64, mimeType, hintText: opts?.hintText, slice }),
5163
+ signal: opts?.signal
5164
+ });
5165
+ if (!res.ok) {
5166
+ throw new Error(`\u56FE\u7247\u8BC6\u522B\u4EE3\u7406\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
5167
+ }
5168
+ const data = await res.json();
5169
+ return {
5170
+ patch: data?.patch || {},
5171
+ mentions: data?.mentions || {},
5172
+ rawText: data?.rawText,
5173
+ model: data?.model,
5174
+ elapsedMs: typeof data?.elapsedMs === "number" ? data.elapsedMs : Date.now() - started,
5175
+ omittedEmptyFields: Array.isArray(data?.omittedEmptyFields) ? data.omittedEmptyFields : []
5176
+ };
5177
+ }
5178
+ };
5179
+ }
5180
+ function createOnDeviceBridgeAdapter(options) {
5181
+ const engineName = options.engineName || "on-device-slm";
5182
+ const modelName = options.modelName || engineName;
5183
+ const maxTokens = options.maxTokens ?? 256;
5184
+ const temperature = options.temperature ?? 0;
5185
+ return {
5186
+ name: `${engineName}:${modelName}`,
5187
+ async health() {
5188
+ try {
5189
+ const ready = options.isReady ? await options.isReady() : true;
5190
+ return {
5191
+ ready: Boolean(ready),
5192
+ model: modelName,
5193
+ message: ready ? `On-device SLM ready (${modelName})` : `On-device SLM not loaded (${modelName})`
5194
+ };
5195
+ } catch (err) {
5196
+ return { ready: false, model: modelName, message: err?.message || "On-device SLM unavailable" };
5197
+ }
5198
+ },
5199
+ async extract(text, slice, opts) {
5200
+ const started = Date.now();
5201
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
5202
+ const jsonSchema = (0, slicer_1.buildSliceJsonSchema)(slice);
5203
+ const out = await options.invoke({
5204
+ systemPrompt,
5205
+ userText: text,
5206
+ jsonSchema,
5207
+ maxTokens,
5208
+ temperature,
5209
+ signal: opts?.signal
5210
+ });
5211
+ const rawText = typeof out === "string" ? out : JSON.stringify(out);
5212
+ const rawObj = typeof out === "string" ? parseJsonFromModelText(out) : out;
5213
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
5214
+ return {
5215
+ patch,
5216
+ mentions,
5217
+ rawText,
5218
+ model: modelName,
5219
+ elapsedMs: Date.now() - started,
5220
+ omittedEmptyFields
5221
+ };
5222
+ },
5223
+ ...options.invokeVision ? {
5224
+ async extractFromImage(imageBase64, slice, opts) {
5225
+ const started = Date.now();
5226
+ const { base64, mimeType } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
5227
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
5228
+ const jsonSchema = (0, slicer_1.buildSliceJsonSchema)(slice);
5229
+ const userText = buildVisionUserInstruction(opts?.locale || slice.locale, opts?.hintText);
5230
+ const out = await options.invokeVision({
5231
+ systemPrompt,
5232
+ userText,
5233
+ imageBase64: base64,
5234
+ mimeType,
5235
+ jsonSchema,
5236
+ maxTokens,
5237
+ temperature,
5238
+ signal: opts?.signal
5239
+ });
5240
+ const rawText = typeof out === "string" ? out : JSON.stringify(out);
5241
+ const rawObj = typeof out === "string" ? parseJsonFromModelText(out) : out;
5242
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
5243
+ return {
5244
+ patch,
5245
+ mentions,
5246
+ rawText,
5247
+ model: modelName,
5248
+ elapsedMs: Date.now() - started,
5249
+ omittedEmptyFields
5250
+ };
5251
+ }
5252
+ } : {}
5253
+ };
5254
+ }
5255
+ }
5256
+ });
5257
+
5258
+ // packages/form-intent-fill/dist/dictionaries.js
5259
+ var require_dictionaries = __commonJS({
5260
+ "packages/form-intent-fill/dist/dictionaries.js"(exports2) {
5261
+ "use strict";
5262
+ Object.defineProperty(exports2, "__esModule", { value: true });
5263
+ exports2.DictionaryMatcher = void 0;
5264
+ function createEpochId() {
5265
+ const gCrypto = globalThis.crypto;
5266
+ if (gCrypto && typeof gCrypto.randomUUID === "function") {
5267
+ return gCrypto.randomUUID();
5268
+ }
5269
+ return `ep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
5270
+ }
5271
+ var normalizeText = (value) => value.normalize("NFKC").replace(/\s+/g, "").toLowerCase();
5272
+ function flattenOptions(nodes, parentPath = []) {
5273
+ const out = [];
5274
+ const seen = /* @__PURE__ */ new Set();
5275
+ for (const node of nodes) {
5276
+ if (!node || typeof node.code !== "string" || !node.code.trim() || typeof node.name !== "string" || !node.name.trim()) {
5277
+ throw new Error("\u5B57\u5178\u8282\u70B9\u7F3A\u5C11\u6709\u6548\u7684 code \u6216 name\u3002");
5278
+ }
5279
+ if (seen.has(node.code)) {
5280
+ throw new Error(`\u5B57\u5178\u540C\u7EA7\u8282\u70B9\u4EE3\u7801\u91CD\u590D\uFF1A${node.code}`);
5281
+ }
5282
+ seen.add(node.code);
5283
+ const nextPath = [...parentPath, { code: node.code, name: node.name }];
5284
+ if (nextPath.length > 4) {
5285
+ throw new Error("\u5B57\u5178\u5C42\u7EA7\u4E0D\u5F97\u8D85\u8FC7 4 \u7EA7\u3002");
5286
+ }
5287
+ if (Array.isArray(node.children) && node.children.length > 0) {
5288
+ out.push(...flattenOptions(node.children, nextPath));
5289
+ } else {
5290
+ const names = [node.name, ...Array.isArray(node.aliases) ? node.aliases : []];
5291
+ out.push({
5292
+ id: JSON.stringify(nextPath.map((n) => n.code)),
5293
+ code: node.code,
5294
+ label: nextPath.map((n) => n.name).join(" / "),
5295
+ path: nextPath,
5296
+ names
5297
+ });
5298
+ }
5299
+ }
5300
+ return out;
5301
+ }
5302
+ var DictionaryMatcher = class {
5303
+ constructor(fields = []) {
5304
+ this.definitions = {};
5305
+ this.records = {};
5306
+ this.sequence = 0;
5307
+ this.epoch = createEpochId();
5308
+ this.fields = [...new Set(fields)];
5309
+ }
5310
+ ensureField(key) {
5311
+ if (!this.fields.includes(key))
5312
+ this.fields.push(key);
5313
+ }
5314
+ load(bundle) {
5315
+ if (!bundle || bundle.version !== 1 || !bundle.source || !bundle.dictionaries) {
5316
+ throw new Error("\u5B57\u5178\u5305\u683C\u5F0F\u65E0\u6548\uFF08\u9700\u8981 version: 1\u3001source \u4E0E dictionaries\uFF09\u3002");
5317
+ }
5318
+ for (const [key, def] of Object.entries(bundle.dictionaries)) {
5319
+ this.ensureField(key);
5320
+ if (!def || !def.version || !Array.isArray(def.options) || def.options.length === 0) {
5321
+ throw new Error(`\u5B57\u5178\u5B57\u6BB5 ${key} \u7F3A\u5C11\u6709\u6548 version \u6216 options\u3002`);
5322
+ }
5323
+ const flat = flattenOptions(def.options);
5324
+ this.definitions[key] = {
5325
+ source: bundle.source,
5326
+ version: def.version,
5327
+ options: flat
5328
+ };
5329
+ if (this.records[key]) {
5330
+ this.records[key] = { raw: this.records[key].raw };
5331
+ }
5332
+ }
5333
+ this.sequence++;
5334
+ }
5335
+ capture(key, raw) {
5336
+ const clean = String(raw || "").trim();
5337
+ if (!clean || clean.length > 200) {
5338
+ throw new Error(`\u5B57\u6BB5 ${key} \u7684\u539F\u8BDD\u6587\u672C\u5FC5\u987B\u4E3A 1\u2013200 \u5B57\u3002`);
5339
+ }
5340
+ this.ensureField(key);
5341
+ if (this.records[key]?.raw !== clean) {
5342
+ this.records[key] = { raw: clean };
5343
+ this.sequence++;
5344
+ }
5345
+ return this.state(key);
5346
+ }
5347
+ clear(key) {
5348
+ delete this.records[key];
5349
+ this.sequence++;
5350
+ }
5351
+ clearAll() {
5352
+ this.records = {};
5353
+ this.sequence++;
5354
+ }
5355
+ state(key) {
5356
+ if (!this.fields.includes(key))
5357
+ return null;
5358
+ const record = this.records[key];
5359
+ const raw = record?.raw || "";
5360
+ const def = this.definitions[key];
5361
+ const options = def?.options || [];
5362
+ const norm = raw ? normalizeText(raw) : "";
5363
+ const candidates = norm ? options.filter((opt) => opt.names.some((n) => normalizeText(n) === norm)) : [];
5364
+ const selected = (record?.choice ? options.find((o) => o.id === record.choice) : null) || (candidates.length === 1 ? candidates[0] : null);
5365
+ const status = !raw ? "missing" : !def ? "awaiting_dictionary" : selected ? "resolved" : candidates.length > 1 ? "awaiting_confirmation" : "unmatched";
5366
+ return {
5367
+ key,
5368
+ raw,
5369
+ status,
5370
+ token: `${this.epoch}:${this.sequence}`,
5371
+ code: selected?.code ?? null,
5372
+ label: selected?.label ?? null,
5373
+ value: selected ? selected.path.length > 1 ? selected.path : selected.code : null,
5374
+ source: def?.source ?? null,
5375
+ version: def?.version ?? null,
5376
+ candidates: candidates.map((c) => ({ id: c.id, code: c.code, label: c.label, path: c.path }))
5377
+ };
5378
+ }
5379
+ choose(key, candidateId, token) {
5380
+ if (token !== `${this.epoch}:${this.sequence}`) {
5381
+ throw new Error("\u5B57\u5178\u5019\u9009\u4EE4\u724C\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u57FA\u4E8E\u6700\u65B0\u5019\u9009\u91CD\u65B0\u786E\u8BA4\u3002");
5382
+ }
5383
+ const def = this.definitions[key];
5384
+ const rec = this.records[key];
5385
+ if (!def || !rec?.raw) {
5386
+ throw new Error(`\u5B57\u6BB5 ${key} \u5C1A\u672A\u52A0\u8F7D\u5B57\u5178\u6216\u7F3A\u5C11\u539F\u8BDD\u3002`);
5387
+ }
5388
+ const hit = def.options.find((o) => o.id === candidateId);
5389
+ if (!hit) {
5390
+ throw new Error(`\u65E0\u6548\u7684\u5B57\u5178\u5019\u9009\u9879\uFF1A${candidateId}`);
5391
+ }
5392
+ this.records[key] = { raw: rec.raw, choice: hit.id };
5393
+ this.sequence++;
5394
+ return this.state(key);
5395
+ }
5396
+ allStates() {
5397
+ return this.fields.map((k) => this.state(k)).filter(Boolean);
5398
+ }
5399
+ };
5400
+ exports2.DictionaryMatcher = DictionaryMatcher;
5401
+ }
5402
+ });
5403
+
5404
+ // packages/form-intent-fill/dist/fastPath.js
5405
+ var require_fastPath = __commonJS({
5406
+ "packages/form-intent-fill/dist/fastPath.js"(exports2) {
5407
+ "use strict";
5408
+ Object.defineProperty(exports2, "__esModule", { value: true });
5409
+ exports2.parseSimpleNumber = parseSimpleNumber;
5410
+ exports2.tryFastPathExtract = tryFastPathExtract;
5411
+ var MULTI_CLAUSE_RE = /[,,。;;、\n]|(?:改一下|换成|并且|而且|还有|以及|同时|我叫|我是)/;
5412
+ var YES_RE = /^(是|是的|对|需要|要|开的|开|开启|打开|有|yes|y|true)$/i;
5413
+ var NO_RE = /^(否|不是|不需要|不要|不用|不开|关闭|无|没有|no|n|false)$/i;
5414
+ var MOBILE_RE = /^1[3-9]\d{9}$/;
5415
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
5416
+ var CN_DIGITS = {
5417
+ \u96F6: 0,
5418
+ "\u3007": 0,
5419
+ \u4E00: 1,
5420
+ \u4E8C: 2,
5421
+ \u4E24: 2,
5422
+ \u4FE9: 2,
5423
+ \u4E09: 3,
5424
+ \u56DB: 4,
5425
+ \u4E94: 5,
5426
+ \u516D: 6,
5427
+ \u4E03: 7,
5428
+ \u516B: 8,
5429
+ \u4E5D: 9
5430
+ };
5431
+ function parseSimpleNumber(raw) {
5432
+ const clean = raw.trim().replace(/[人位张份个元块岁年天次]+$/g, "").replace(/^(一共|总共|共|约)/, "").trim();
5433
+ if (!clean)
5434
+ return null;
5435
+ if (/^\d+(?:\.\d+)?$/.test(clean))
5436
+ return Number(clean);
5437
+ const wanMatch = /^(\d+(?:\.\d+)?)万$/.exec(clean);
5438
+ if (wanMatch)
5439
+ return Number(wanMatch[1]) * 1e4;
5440
+ const qianMatch = /^(\d+(?:\.\d+)?)千$/.exec(clean);
5441
+ if (qianMatch)
5442
+ return Number(qianMatch[1]) * 1e3;
5443
+ if (clean.length === 1 && CN_DIGITS[clean] !== void 0)
5444
+ return CN_DIGITS[clean];
5445
+ if (/^[零〇一二两俩三四五六七八九十百千万]+$/.test(clean)) {
5446
+ let total = 0;
5447
+ let section = 0;
5448
+ let num = 0;
5449
+ for (const ch of clean) {
5450
+ if (CN_DIGITS[ch] !== void 0) {
5451
+ num = CN_DIGITS[ch];
5452
+ } else if (ch === "\u5341") {
5453
+ section += (num || 1) * 10;
5454
+ num = 0;
5455
+ } else if (ch === "\u767E") {
5456
+ section += (num || 1) * 100;
5457
+ num = 0;
5458
+ } else if (ch === "\u5343") {
5459
+ section += (num || 1) * 1e3;
5460
+ num = 0;
5461
+ } else if (ch === "\u4E07") {
5462
+ section = (section + num) * 1e4;
5463
+ total += section;
5464
+ section = 0;
5465
+ num = 0;
5466
+ }
5467
+ }
5468
+ return total + section + num;
5469
+ }
5470
+ return null;
5471
+ }
5472
+ function tryFastPathExtract(text, activeBeat, slice) {
5473
+ const clean = String(text || "").trim().replace(/[。!!??]+$/, "").trim();
5474
+ if (!clean || clean.length > 24 || MULTI_CLAUSE_RE.test(clean)) {
5475
+ return { matched: false, patch: {}, mentions: {} };
5476
+ }
5477
+ const allExtractable = slice.extractableFields;
5478
+ const beatKeys = new Set(activeBeat?.fieldKeys || []);
5479
+ const beatFields = beatKeys.size ? allExtractable.filter((f) => beatKeys.has(f.key)) : allExtractable;
5480
+ const missingInBeat = beatFields.filter((f) => !f.hasValue || activeBeat?.missingKeys.includes(f.key));
5481
+ if (MOBILE_RE.test(clean)) {
5482
+ const phoneFields = allExtractable.filter((f) => f.type === "phone" || /(phone|mobile)/i.test(f.key));
5483
+ if (phoneFields.length === 1) {
5484
+ return { matched: true, patch: { [phoneFields[0].key]: clean }, mentions: {}, matchedRule: "exact_mobile" };
5485
+ }
5486
+ }
5487
+ if (EMAIL_RE.test(clean)) {
5488
+ const emailFields = allExtractable.filter((f) => /email/i.test(f.key));
5489
+ if (emailFields.length === 1) {
5490
+ return { matched: true, patch: { [emailFields[0].key]: clean }, mentions: {}, matchedRule: "exact_email" };
5491
+ }
5492
+ }
5493
+ const norm = clean.toLowerCase();
5494
+ const matchOptionsIn = (fields) => {
5495
+ const cands = [];
5496
+ for (const field of fields) {
5497
+ if (!field.options || !field.options.length)
5498
+ continue;
5499
+ for (const opt of field.options) {
5500
+ const codeL = opt.code.toLowerCase();
5501
+ const nameL = opt.name.toLowerCase();
5502
+ if (norm === codeL || norm === nameL) {
5503
+ cands.push({ key: field.key, code: opt.code, score: 2 });
5504
+ } else if (norm.length >= 2 && (nameL.includes(norm) || norm.length <= 6 && norm.includes(nameL))) {
5505
+ cands.push({ key: field.key, code: opt.code, score: 1 });
5506
+ }
5507
+ }
5508
+ }
5509
+ const best = cands.reduce((m, c) => Math.max(m, c.score), 0);
5510
+ const tops = cands.filter((c) => c.score === best);
5511
+ return tops.length === 1 ? { hit: tops[0], score: best } : null;
5512
+ };
5513
+ const optMatch = matchOptionsIn(beatFields) || matchOptionsIn(allExtractable);
5514
+ if (optMatch) {
5515
+ return {
5516
+ matched: true,
5517
+ patch: { [optMatch.hit.key]: optMatch.hit.code },
5518
+ mentions: {},
5519
+ matchedRule: optMatch.score === 2 ? "exact_option" : "unique_option_alias"
5520
+ };
5521
+ }
5522
+ const beatSwitches = beatFields.filter((f) => f.type === "switch");
5523
+ const switchFields = beatSwitches.length ? beatSwitches : allExtractable.filter((f) => f.type === "switch");
5524
+ if (switchFields.length === 1) {
5525
+ if (YES_RE.test(clean)) {
5526
+ return { matched: true, patch: { [switchFields[0].key]: true }, mentions: {}, matchedRule: "switch_yes" };
5527
+ }
5528
+ if (NO_RE.test(clean)) {
5529
+ return { matched: true, patch: { [switchFields[0].key]: false }, mentions: {}, matchedRule: "switch_no" };
5530
+ }
5531
+ }
5532
+ const isNumField = (f) => f.type === "number" || f.type === "stepper" || f.type === "slider";
5533
+ const beatNums = (missingInBeat.length ? missingInBeat : beatFields).filter(isNumField);
5534
+ const numCandidates = beatNums.length ? beatNums : allExtractable.filter(isNumField);
5535
+ if (numCandidates.length === 1) {
5536
+ const parsed = parseSimpleNumber(clean);
5537
+ if (parsed !== null) {
5538
+ const target = numCandidates[0];
5539
+ const min = target.min ?? -Infinity;
5540
+ const max = target.max ?? Infinity;
5541
+ if (parsed >= min && parsed <= max) {
5542
+ return {
5543
+ matched: true,
5544
+ patch: { [target.key]: parsed },
5545
+ mentions: {},
5546
+ matchedRule: "single_numeric"
5547
+ };
5548
+ }
5549
+ }
5550
+ }
5551
+ return { matched: false, patch: {}, mentions: {} };
5552
+ }
5553
+ }
5554
+ });
5555
+
5556
+ // packages/form-intent-fill/dist/planner.js
5557
+ var require_planner = __commonJS({
5558
+ "packages/form-intent-fill/dist/planner.js"(exports2) {
5559
+ "use strict";
5560
+ Object.defineProperty(exports2, "__esModule", { value: true });
5561
+ exports2.maskSensitiveValue = maskSensitiveValue;
5562
+ exports2.buildFillPlan = buildFillPlan;
5563
+ var slicer_1 = require_slicer();
5564
+ function maskSensitiveValue(item, display) {
5565
+ const key = item.key || "";
5566
+ const raw = String(display || "");
5567
+ if (item.type === "phone" || /(phone|mobile|tel)/i.test(key)) {
5568
+ const digits = raw.replace(/\s+/g, "");
5569
+ const masked = digits.length >= 7 ? `${digits.slice(0, 3)}****${digits.slice(-4)}` : raw.replace(/.(?=.{2})/g, "*");
5570
+ return { isPii: true, masked };
5571
+ }
5572
+ if (/(id_?card|identity|bank_?card|account_?no)/i.test(key)) {
5573
+ const masked = raw.length >= 8 ? `${raw.slice(0, 4)}********${raw.slice(-4)}` : "****";
5574
+ return { isPii: true, masked };
5575
+ }
5576
+ if (/email/i.test(key) && raw.includes("@")) {
5577
+ const [u, domain] = raw.split("@");
5578
+ const masked = `${u.slice(0, Math.min(2, u.length))}***@${domain}`;
5579
+ return { isPii: true, masked };
5580
+ }
5581
+ return { isPii: false, masked: raw };
5582
+ }
5583
+ function formatItemDisplay(item, value, locale) {
5584
+ if ((0, slicer_1.isEmptyFieldValue)(value))
5585
+ return locale === "en-US" ? "Empty" : "\u672A\u586B\u5199";
5586
+ if (item.type === "agreement") {
5587
+ const yes = value === true || value === 1 || value === "1";
5588
+ return yes ? locale === "en-US" ? "Agreed \u2713" : "\u5DF2\u52FE\u9009\u540C\u610F \u2713" : locale === "en-US" ? "Not agreed" : "\u672A\u540C\u610F";
5589
+ }
5590
+ if (item.type === "signature") {
5591
+ return value ? locale === "en-US" ? "Signed \u2713" : "\u5DF2\u672C\u4EBA\u7B7E\u540D \u2713" : locale === "en-US" ? "Unsigned" : "\u5F85\u7B7E\u540D";
5592
+ }
5593
+ if (typeof value === "boolean") {
5594
+ return value ? locale === "en-US" ? "Yes" : "\u662F" : locale === "en-US" ? "No" : "\u5426";
5595
+ }
5596
+ const opts = (0, slicer_1.extractStaticOptions)(item);
5597
+ if (opts) {
5598
+ if (Array.isArray(value)) {
5599
+ return value.map((v) => opts.find((o) => o.code === String(v))?.name || String(v)).join("\u3001");
5600
+ }
5601
+ const hit = opts.find((o) => o.code === String(value));
5602
+ if (hit)
5603
+ return hit.name;
5604
+ }
5605
+ const suffix = item.props?.suffix ? ` ${String(item.props.suffix)}` : "";
5606
+ return `${Array.isArray(value) ? value.join(", ") : String(value)}${suffix}`.trim();
5607
+ }
5608
+ function isItemFilled(item, value) {
5609
+ if (item.type === "agreement")
5610
+ return value === true || value === 1 || value === "1";
5611
+ return !(0, slicer_1.isEmptyFieldValue)(value);
5612
+ }
5613
+ function buildQuickChipsForItems(items, runtimeFields, locale) {
5614
+ const isEn = locale === "en-US";
5615
+ const groups = [];
5616
+ for (const item of items) {
5617
+ const f = runtimeFields[item.key];
5618
+ const curVal = f !== void 0 ? f.value : item.defaultValue;
5619
+ const opts = (0, slicer_1.extractStaticOptions)(item);
5620
+ if ((item.type === "radioGroup" || item.type === "select") && opts && opts.length > 0 && opts.length <= 6) {
5621
+ groups.push({
5622
+ key: item.key,
5623
+ label: item.label || item.key,
5624
+ type: item.type,
5625
+ required: Boolean(f?.required ?? item.required),
5626
+ options: opts.map((o) => ({
5627
+ value: o.code,
5628
+ label: o.name,
5629
+ selected: String(curVal ?? "") === o.code
5630
+ }))
5631
+ });
5632
+ continue;
5633
+ }
5634
+ if (item.type === "switch") {
5635
+ groups.push({
5636
+ key: item.key,
5637
+ label: item.label || item.key,
5638
+ type: "switch",
5639
+ required: Boolean(f?.required ?? item.required),
5640
+ options: [
5641
+ { value: true, label: isEn ? "Yes" : "\u9700\u8981 / \u662F", selected: curVal === true },
5642
+ { value: false, label: isEn ? "No" : "\u4E0D\u9700\u8981 / \u5426", selected: curVal === false }
5643
+ ]
5644
+ });
5645
+ continue;
5646
+ }
5647
+ if (item.type === "stepper") {
5648
+ const min = typeof item.props?.min === "number" ? item.props.min : 1;
5649
+ const max = typeof item.props?.max === "number" ? item.props.max : min + 4;
5650
+ const suffix = String(item.props?.suffix || "");
5651
+ if (max >= min && max - min <= 5) {
5652
+ const nums = [];
5653
+ for (let n = min; n <= max; n++) {
5654
+ nums.push({
5655
+ value: n,
5656
+ label: suffix ? `${n}${suffix}` : String(n),
5657
+ selected: Number(curVal) === n
5658
+ });
5659
+ }
5660
+ groups.push({
5661
+ key: item.key,
5662
+ label: item.label || item.key,
5663
+ type: "stepper",
5664
+ required: Boolean(f?.required ?? item.required),
5665
+ options: nums
5666
+ });
5667
+ }
5668
+ }
5669
+ }
5670
+ return groups;
5671
+ }
5672
+ function synthesizeSpokenExample(items, locale) {
5673
+ const isEn = locale === "en-US";
5674
+ const fragments = [];
5675
+ for (const item of items.slice(0, 4)) {
5676
+ const label = item.label || item.key;
5677
+ const opts = (0, slicer_1.extractStaticOptions)(item);
5678
+ if (opts && opts.length > 0) {
5679
+ const pick = opts.length > 1 ? opts[opts.length - 1] : opts[0];
5680
+ fragments.push(isEn ? `${label} is ${pick.name}` : `${label}\u9009${pick.name}`);
5681
+ continue;
5682
+ }
5683
+ if (item.type === "phone" || /(phone|mobile)/i.test(item.key)) {
5684
+ fragments.push(isEn ? "phone 13800138000" : "\u624B\u673A13800138000");
5685
+ continue;
5686
+ }
5687
+ if (/email/i.test(item.key)) {
5688
+ fragments.push(isEn ? "email demo@example.com" : "\u90AE\u7BB1demo@example.test");
5689
+ continue;
5690
+ }
5691
+ if (item.type === "switch") {
5692
+ fragments.push(isEn ? `${label}: yes` : `\u9700\u8981${label.replace(/^是否(需要)?/, "")}`);
5693
+ continue;
5694
+ }
5695
+ if (item.type === "stepper" || item.type === "number") {
5696
+ const min = typeof item.props?.min === "number" ? item.props.min : 2;
5697
+ const val = Math.max(min, 3);
5698
+ const suffix = String(item.props?.suffix || "");
5699
+ fragments.push(isEn ? `${label} ${val}` : `${label}${val}${suffix}`);
5700
+ continue;
5701
+ }
5702
+ if (/name/i.test(item.key) && !/company/i.test(item.key)) {
5703
+ fragments.push(isEn ? "my name is Alex Lin" : "\u6211\u53EB\u6797\u5C0F\u79BE");
5704
+ continue;
5705
+ }
5706
+ if (/(company|org|invoice_title)/i.test(item.key)) {
5707
+ fragments.push(isEn ? `${label} Acme Cloud Tech` : `${label}\u9752\u79BE\u79D1\u6280\u6709\u9650\u516C\u53F8`);
5708
+ continue;
5709
+ }
5710
+ fragments.push(isEn ? `${label}: ...` : `${label}\u793A\u4F8B\u5185\u5BB9`);
5711
+ }
5712
+ return fragments.join(isEn ? ", " : "\uFF0C");
5713
+ }
5714
+ function buildBeatGuidance(beatTitle, kind, missingItems, pendingForBeat, locale) {
5715
+ const isEn = locale === "en-US";
5716
+ if (kind === "signoff") {
5717
+ if (missingItems.length > 0) {
5718
+ const names = missingItems.map((i) => i.label || i.key).join(isEn ? ", " : "\u3001");
5719
+ return isEn ? `Almost done! Review your summary below and complete: ${names}.` : `\u4FE1\u606F\u5DF2\u5168\u90E8\u91C7\u96C6\u5B8C\u6210\uFF01\u8BF7\u6838\u5BF9\u4E0B\u65B9\u786E\u8BA4\u5355\uFF0C\u5E76\u7531\u672C\u4EBA\u5B8C\u6210\uFF1A${names}\u3002`;
5720
+ }
5721
+ return isEn ? "Everything looks great! Review your summary and submit." : "\u6240\u6709\u4FE1\u606F\u5DF2\u6838\u5BF9\u5C31\u7EEA\uFF0C\u786E\u8BA4\u65E0\u8BEF\u5373\u53EF\u4E00\u952E\u63D0\u4EA4\u3002";
5722
+ }
5723
+ if (pendingForBeat.length > 0 && missingItems.length === 0) {
5724
+ const names = pendingForBeat.map((p) => p.label).join(isEn ? ", " : "\u3001");
5725
+ return isEn ? `Please confirm ${names} below to continue.` : `\u8BF7\u5148\u8F7B\u70B9\u786E\u8BA4\u4E0B\u65B9\u7684\u300C${names}\u300D\uFF0C\u786E\u8BA4\u540E\u81EA\u52A8\u8FDB\u5165\u4E0B\u4E00\u6B65\u3002`;
5726
+ }
5727
+ const focus = missingItems.slice(0, 3);
5728
+ if (focus.length === 0) {
5729
+ return isEn ? `${beatTitle} is complete.` : `\u300C${beatTitle}\u300D\u5DF2\u5B8C\u6210\u3002`;
5730
+ }
5731
+ const listStr = focus.map((i) => i.label || i.key).join(isEn ? ", " : "\u3001");
5732
+ const tail = missingItems.length > 3 ? isEn ? ", etc." : "\u7B49" : "";
5733
+ return isEn ? `Tell me your ${listStr}${tail} in one sentence, or tap a quick chip below.` : `\u544A\u8BC9\u6211\u60A8\u7684${listStr}${tail}\u2014\u2014\u53EF\u4EE5\u76F4\u63A5\u8BF4\u4E00\u53E5\u8BDD\uFF0C\u6216\u8F7B\u70B9\u4E0B\u65B9\u5FEB\u6377\u9009\u9879\u3002`;
5734
+ }
5735
+ function buildFillPlan(schema, runtimeFields, options = {}) {
5736
+ const locale = options.locale === "en-US" ? "en-US" : "zh-CN";
5737
+ const isEn = locale === "en-US";
5738
+ const dictSet = new Set(options.dictionaryFields || []);
5739
+ const critSet = new Set(options.criticalFields || []);
5740
+ const pendingList = options.pendingProposals || [];
5741
+ const pendingKeySet = new Set(pendingList.map((p) => p.key));
5742
+ const touched = options.touchedKeys || /* @__PURE__ */ new Set();
5743
+ const recent = options.recentlyUpdatedKeys || /* @__PURE__ */ new Set();
5744
+ const allItems = (0, slicer_1.collectSchemaItems)(schema);
5745
+ const triggerTargets = /* @__PURE__ */ new Map();
5746
+ const triggeredBy = /* @__PURE__ */ new Map();
5747
+ for (const item of allItems) {
5748
+ for (const rel of item.relations || []) {
5749
+ if (rel && rel.target && rel.effect === "visible") {
5750
+ const tgt = String(rel.target);
5751
+ const list = triggerTargets.get(item.key) || [];
5752
+ if (!list.includes(tgt))
5753
+ list.push(tgt);
5754
+ triggerTargets.set(item.key, list);
5755
+ const rev = triggeredBy.get(tgt) || [];
5756
+ if (!rev.includes(item.key))
5757
+ rev.push(item.key);
5758
+ triggeredBy.set(tgt, rev);
5759
+ }
5760
+ }
5761
+ }
5762
+ const prunedFieldKeys = [];
5763
+ for (const [tgtKey] of triggeredBy.entries()) {
5764
+ const f = runtimeFields[tgtKey];
5765
+ const visible = typeof f?.visible === "boolean" ? f.visible : false;
5766
+ if (!visible)
5767
+ prunedFieldKeys.push(tgtKey);
5768
+ }
5769
+ const beats = [];
5770
+ const signoffItems = [];
5771
+ let totalVisibleExtractable = 0;
5772
+ for (let gi = 0; gi < (schema.groups || []).length; gi++) {
5773
+ const grp = schema.groups[gi];
5774
+ const visibleCollectable = [];
5775
+ for (const item of grp.items || []) {
5776
+ const f = runtimeFields[item.key];
5777
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
5778
+ const disabled = Boolean(f?.disabled ?? item.disabled);
5779
+ if (!visible || disabled)
5780
+ continue;
5781
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, dictSet);
5782
+ if (policy === "forbidden") {
5783
+ signoffItems.push(item);
5784
+ } else {
5785
+ visibleCollectable.push(item);
5786
+ totalVisibleExtractable++;
5787
+ }
5788
+ }
5789
+ if (visibleCollectable.length === 0)
5790
+ continue;
5791
+ const ordered = [...visibleCollectable].sort((a, b) => {
5792
+ const aGate = triggerTargets.has(a.key) ? 0 : 1;
5793
+ const bGate = triggerTargets.has(b.key) ? 0 : 1;
5794
+ const aChild = triggeredBy.has(a.key) ? 1 : 0;
5795
+ const bChild = triggeredBy.has(b.key) ? 1 : 0;
5796
+ return aChild - bChild || aGate - bGate;
5797
+ });
5798
+ const chunkSize = ordered.length <= 5 ? ordered.length : 4;
5799
+ for (let offset = 0; offset < ordered.length; offset += chunkSize) {
5800
+ const chunk = ordered.slice(offset, offset + chunkSize);
5801
+ const chunkIdx = Math.floor(offset / chunkSize);
5802
+ const baseTitle = grp.title || (isEn ? `Step ${gi + 1}` : `\u7B2C ${gi + 1} \u90E8\u5206`);
5803
+ const isBranchOnly = chunk.every((i) => triggeredBy.has(i.key));
5804
+ const title = isBranchOnly && chunk.length <= 2 ? chunk.map((i) => i.label || i.key).join(" / ") : chunkIdx === 0 ? baseTitle : `${baseTitle} (${chunkIdx + 1})`;
5805
+ const missingItems = chunk.filter((item) => {
5806
+ const f = runtimeFields[item.key];
5807
+ const req = Boolean(f?.required ?? item.required);
5808
+ const val = f?.value;
5809
+ const isUntouchedDefault = !touched.has(item.key) && triggerTargets.has(item.key) && item.defaultValue !== void 0 && JSON.stringify(val) === JSON.stringify(item.defaultValue);
5810
+ if (isUntouchedDefault)
5811
+ return true;
5812
+ return req && !isItemFilled(item, val) || Boolean(f?.errMsg);
5813
+ });
5814
+ const pendingForBeat = pendingList.filter((p) => chunk.some((i) => i.key === p.key));
5815
+ const beatDone = missingItems.length === 0 && pendingForBeat.length === 0;
5816
+ const chipCandidates = chunk.filter((item) => missingItems.some((m) => m.key === item.key) || triggerTargets.has(item.key));
5817
+ beats.push({
5818
+ id: `beat_${grp.key || gi}_${chunkIdx}`,
5819
+ title,
5820
+ kind: isBranchOnly ? "branch" : "collect",
5821
+ status: beatDone ? "done" : "upcoming",
5822
+ fieldKeys: chunk.map((i) => i.key),
5823
+ missingKeys: missingItems.map((i) => i.key),
5824
+ guidance: buildBeatGuidance(title, isBranchOnly ? "branch" : "collect", missingItems, pendingForBeat, locale),
5825
+ spokenExample: synthesizeSpokenExample(missingItems.length ? missingItems : chunk, locale),
5826
+ quickChips: buildQuickChipsForItems(chipCandidates.length ? chipCandidates : chunk, runtimeFields, locale),
5827
+ isBranchGate: chunk.some((i) => triggerTargets.has(i.key))
5828
+ });
5829
+ }
5830
+ }
5831
+ const signoffMissing = signoffItems.filter((item) => {
5832
+ const f = runtimeFields[item.key];
5833
+ return Boolean(f?.required ?? item.required) && !isItemFilled(item, f?.value);
5834
+ });
5835
+ const signoffTitle = isEn ? "Review & Sign-Off" : "\u6838\u5BF9\u4E0E\u672C\u4EBA\u786E\u8BA4";
5836
+ beats.push({
5837
+ id: "beat_signoff",
5838
+ title: signoffTitle,
5839
+ kind: "signoff",
5840
+ status: signoffMissing.length === 0 && beats.every((b) => b.status === "done") ? "active" : "upcoming",
5841
+ fieldKeys: signoffItems.map((i) => i.key),
5842
+ missingKeys: signoffMissing.map((i) => i.key),
5843
+ guidance: buildBeatGuidance(signoffTitle, "signoff", signoffMissing, [], locale),
5844
+ spokenExample: "",
5845
+ quickChips: []
5846
+ });
5847
+ let activeIndex = beats.findIndex((b) => b.kind !== "signoff" && b.status !== "done");
5848
+ if (activeIndex < 0)
5849
+ activeIndex = beats.length - 1;
5850
+ for (let i = 0; i < beats.length; i++) {
5851
+ if (i === activeIndex) {
5852
+ beats[i].status = "active";
5853
+ } else if (beats[i].status !== "done") {
5854
+ beats[i].status = "upcoming";
5855
+ }
5856
+ }
5857
+ const crystallizedFields = [];
5858
+ for (const item of allItems) {
5859
+ const f = runtimeFields[item.key];
5860
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
5861
+ if (!visible)
5862
+ continue;
5863
+ const val = f?.value;
5864
+ if (!isItemFilled(item, val))
5865
+ continue;
5866
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, dictSet);
5867
+ const rawDisplay = formatItemDisplay(item, val, locale);
5868
+ const dictLabel = options.dictionaryLabelMap?.get(item.key);
5869
+ const displayValue = dictLabel || rawDisplay;
5870
+ const { isPii, masked } = maskSensitiveValue(item, displayValue);
5871
+ crystallizedFields.push({
5872
+ key: item.key,
5873
+ label: item.label || item.key,
5874
+ type: item.type,
5875
+ value: val,
5876
+ displayValue,
5877
+ maskedDisplayValue: masked,
5878
+ isPii,
5879
+ risk: (0, slicer_1.classifyFieldRisk)(item, critSet),
5880
+ required: Boolean(f?.required ?? item.required),
5881
+ editable: policy !== "forbidden" && !f?.disabled && !item.readonly,
5882
+ justUpdated: recent.has(item.key)
5883
+ });
5884
+ }
5885
+ const archetype = triggerTargets.size > 0 ? "branching" : totalVisibleExtractable <= 4 ? "micro" : "multi-beat";
5886
+ const remainingMissingCount = beats.reduce((sum, b) => sum + b.missingKeys.length, 0) + pendingList.length;
5887
+ const estimatedSecondsLeft = remainingMissingCount === 0 ? 0 : Math.max(5, remainingMissingCount * 6);
5888
+ return {
5889
+ archetype,
5890
+ beats,
5891
+ activeBeatId: beats[activeIndex].id,
5892
+ activeBeat: beats[activeIndex],
5893
+ activeBeatIndex: activeIndex,
5894
+ prunedFieldKeys,
5895
+ prunedFieldCount: prunedFieldKeys.length,
5896
+ estimatedSecondsLeft,
5897
+ crystallizedFields
5898
+ };
5899
+ }
5900
+ }
5901
+ });
5902
+
5903
+ // packages/form-intent-fill/dist/session.js
5904
+ var require_session = __commonJS({
5905
+ "packages/form-intent-fill/dist/session.js"(exports2) {
5906
+ "use strict";
5907
+ Object.defineProperty(exports2, "__esModule", { value: true });
5908
+ exports2.IntentFillSession = void 0;
5909
+ var dictionaries_1 = require_dictionaries();
5910
+ var fastPath_1 = require_fastPath();
5911
+ var planner_1 = require_planner();
5912
+ var slicer_1 = require_slicer();
5913
+ function formatDisplayValue(item, value, locale) {
5914
+ if ((0, slicer_1.isEmptyFieldValue)(value))
5915
+ return locale === "en-US" ? "Empty" : "\u672A\u586B\u5199";
5916
+ if (typeof value === "boolean") {
5917
+ return value ? locale === "en-US" ? "Yes" : "\u662F" : locale === "en-US" ? "No" : "\u5426";
5918
+ }
5919
+ const opts = (0, slicer_1.extractStaticOptions)(item);
5920
+ if (opts) {
5921
+ if (Array.isArray(value)) {
5922
+ return value.map((v) => opts.find((o) => o.code === String(v))?.name || String(v)).join("\u3001");
5923
+ }
5924
+ const hit = opts.find((o) => o.code === String(value));
5925
+ if (hit)
5926
+ return hit.name;
5927
+ }
5928
+ return Array.isArray(value) ? value.join(", ") : String(value);
5929
+ }
5930
+ function coerceAndValidateValue(item, rawValue) {
5931
+ const opts = (0, slicer_1.extractStaticOptions)(item);
5932
+ if (item.type === "number" || item.type === "stepper" || item.type === "slider") {
5933
+ const num = typeof rawValue === "number" ? rawValue : typeof rawValue === "string" ? Number(rawValue.trim()) : NaN;
5934
+ if (!Number.isFinite(num)) {
5935
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u6709\u6548\u6570\u5B57\u3002` };
5936
+ }
5937
+ const min = typeof item.props?.min === "number" ? item.props.min : -Infinity;
5938
+ const max = typeof item.props?.max === "number" ? item.props.max : Infinity;
5939
+ if (num < min || num > max) {
5940
+ return {
5941
+ ok: false,
5942
+ code: "VALIDATION_FAILED",
5943
+ message: `${item.label || item.key} \u9700\u5728 [${min}, ${max}] \u8303\u56F4\u5185\u3002`
5944
+ };
5945
+ }
5946
+ return { ok: true, value: num };
5947
+ }
5948
+ if (item.type === "switch") {
5949
+ if (typeof rawValue === "boolean")
5950
+ return { ok: true, value: rawValue };
5951
+ if (rawValue === "true" || rawValue === "Y" || rawValue === 1)
5952
+ return { ok: true, value: true };
5953
+ if (rawValue === "false" || rawValue === "N" || rawValue === 0)
5954
+ return { ok: true, value: false };
5955
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u5E03\u5C14\u503C\u3002` };
5956
+ }
5957
+ if (item.type === "checkboxGroup") {
5958
+ const arr = Array.isArray(rawValue) ? rawValue.map(String) : typeof rawValue === "string" ? [rawValue] : null;
5959
+ if (!arr || arr.length === 0) {
5960
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u9009\u9879\u6570\u7EC4\u3002` };
5961
+ }
5962
+ if (opts) {
5963
+ const mapped = arr.map((v) => opts.find((o) => o.code === v || o.name === v)?.code || "");
5964
+ if (mapped.some((m) => !m)) {
5965
+ return { ok: false, code: "INVALID_OPTION", message: `${item.label || item.key} \u5305\u542B\u65E0\u6548\u9009\u9879\u4EE3\u7801\u3002` };
5966
+ }
5967
+ return { ok: true, value: [...new Set(mapped)] };
5968
+ }
5969
+ return { ok: true, value: arr };
5970
+ }
5971
+ if (item.type === "select" || item.type === "radioGroup") {
5972
+ const str2 = String(rawValue ?? "").trim();
5973
+ if (!str2)
5974
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u4E0D\u80FD\u4E3A\u7A7A\u3002` };
5975
+ if (opts) {
5976
+ const hit = opts.find((o) => o.code === str2) || opts.find((o) => o.name === str2);
5977
+ if (!hit) {
5978
+ return { ok: false, code: "INVALID_OPTION", message: `${item.label || item.key} \u9009\u9879\u300C${str2}\u300D\u4E0D\u5728\u5408\u6CD5\u679A\u4E3E\u5185\u3002` };
5979
+ }
5980
+ return { ok: true, value: hit.code };
5981
+ }
5982
+ return { ok: true, value: str2 };
5983
+ }
5984
+ const str = typeof rawValue === "string" ? rawValue.trim() : typeof rawValue === "number" ? String(rawValue) : "";
5985
+ if (!str) {
5986
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u6709\u6548\u6587\u672C\u3002` };
5987
+ }
5988
+ const maxLen = typeof item.props?.maxlength === "number" ? item.props.maxlength : 500;
5989
+ if (str.length > maxLen) {
5990
+ return { ok: false, code: "VALIDATION_FAILED", message: `${item.label || item.key} \u8D85\u51FA\u6700\u5927\u957F\u5EA6 ${maxLen}\u3002` };
5991
+ }
5992
+ for (const rule of item.rules || []) {
5993
+ if (rule && rule.type === "regex" && rule.regex) {
5994
+ try {
5995
+ if (!new RegExp(rule.regex).test(str)) {
5996
+ return { ok: false, code: "VALIDATION_FAILED", message: rule.message || `${item.label || item.key} \u683C\u5F0F\u4E0D\u7B26\u5408\u8981\u6C42\u3002` };
5997
+ }
5998
+ } catch {
5999
+ }
6000
+ }
6001
+ }
6002
+ return { ok: true, value: str };
6003
+ }
6004
+ var IntentFillSession = class {
6005
+ constructor(options) {
6006
+ this.itemsByKey = /* @__PURE__ */ new Map();
6007
+ this.revision = 0;
6008
+ this.sequence = 0;
6009
+ this.activeTicket = null;
6010
+ this.pendingMap = /* @__PURE__ */ new Map();
6011
+ this.touchedKeys = /* @__PURE__ */ new Set();
6012
+ this.recentlyUpdatedKeys = /* @__PURE__ */ new Set();
6013
+ this.schema = options.schema;
6014
+ this.core = options.core;
6015
+ this.adapter = options.adapter;
6016
+ this.mode = options.mode || "smart";
6017
+ this.locale = options.locale === "en-US" ? "en-US" : "zh-CN";
6018
+ this.dictionaryFieldSet = new Set(options.dictionaryFields || []);
6019
+ this.criticalFieldSet = new Set(options.criticalFields || []);
6020
+ this.reviewCritical = options.reviewCritical !== false;
6021
+ this.protectOverwrite = options.protectOverwrite !== false;
6022
+ this.enableFastPath = options.enableFastPath !== false;
6023
+ const items = (0, slicer_1.collectSchemaItems)(this.schema);
6024
+ const mentionKeys = [...this.dictionaryFieldSet];
6025
+ for (const item of items) {
6026
+ this.itemsByKey.set(item.key, item);
6027
+ if ((0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet) === "mention_only") {
6028
+ mentionKeys.push(item.key);
6029
+ }
6030
+ }
6031
+ this.dictionaries = new dictionaries_1.DictionaryMatcher(mentionKeys);
6032
+ }
6033
+ setMode(mode) {
6034
+ if (this.mode !== mode) {
6035
+ this.invalidate();
6036
+ this.mode = mode;
6037
+ }
6038
+ }
6039
+ setLocale(locale) {
6040
+ this.locale = locale === "en-US" ? "en-US" : "zh-CN";
6041
+ }
6042
+ invalidate() {
6043
+ this.sequence++;
6044
+ this.activeTicket = null;
6045
+ }
6046
+ /**
6047
+ * 用户手动编辑某字段时调用:递增版本号,立刻作废所有在途的异步模型抽取结果。
6048
+ */
6049
+ manualEdit(key, value) {
6050
+ this.invalidate();
6051
+ this.pendingMap.delete(key);
6052
+ this.touchedKeys.add(key);
6053
+ this.recentlyUpdatedKeys = /* @__PURE__ */ new Set([key]);
6054
+ this.revision++;
6055
+ this.core.setControlData(key, value);
6056
+ }
6057
+ /**
6058
+ * 焦点卡快捷芯片直达(1ms):视为用户主动点选,直接写入 FormCore 并刷新 BFS 联动与 FillPlan。
6059
+ */
6060
+ applyQuickChip(key, value) {
6061
+ const started = Date.now();
6062
+ const item = this.itemsByKey.get(key);
6063
+ if (!item) {
6064
+ throw new Error(`\u672A\u77E5\u5B57\u6BB5\uFF1A${key}`);
6065
+ }
6066
+ this.invalidate();
6067
+ const ticket = Object.freeze({
6068
+ id: this.sequence,
6069
+ revision: this.revision,
6070
+ text: `[chip:${key}=${String(value)}]`
6071
+ });
6072
+ const f = this.core.fields[key];
6073
+ const prev = f?.value;
6074
+ const visibleBefore = this.snapshotVisibleKeys();
6075
+ this.pendingMap.delete(key);
6076
+ this.core.setControlData(key, value);
6077
+ this.touchedKeys.add(key);
6078
+ this.recentlyUpdatedKeys = /* @__PURE__ */ new Set([key]);
6079
+ this.revision++;
6080
+ const visibleAfter = this.snapshotVisibleKeys();
6081
+ const revealed = [...visibleAfter].filter((k) => !visibleBefore.has(k));
6082
+ const applied = [
6083
+ {
6084
+ key,
6085
+ label: item.label || key,
6086
+ value,
6087
+ displayValue: formatDisplayValue(item, value, this.locale),
6088
+ previousValue: prev,
6089
+ ...revealed.length ? { triggeredReveal: revealed } : {}
6090
+ }
6091
+ ];
6092
+ return {
6093
+ status: "applied",
6094
+ route: "quick-chip",
6095
+ ticket,
6096
+ mode: this.mode,
6097
+ applied,
6098
+ pendingConfirm: this.getPendingProposals(),
6099
+ mentions: [],
6100
+ rejected: [],
6101
+ readiness: this.inspectReadiness(),
6102
+ plan: this.getFillPlan(),
6103
+ metadata: {
6104
+ model: "deterministic-chip",
6105
+ elapsedMs: Date.now() - started,
6106
+ omittedEmptyFields: [],
6107
+ matchedRule: "quick_chip"
6108
+ }
6109
+ };
6110
+ }
6111
+ getFillPlan() {
6112
+ const dictionaryLabelMap = /* @__PURE__ */ new Map();
6113
+ for (const st of this.dictionaries.allStates()) {
6114
+ if (st.status === "resolved" && st.label)
6115
+ dictionaryLabelMap.set(st.key, st.label);
6116
+ }
6117
+ return (0, planner_1.buildFillPlan)(this.schema, this.core.fields, {
6118
+ locale: this.locale,
6119
+ dictionaryFields: [...this.dictionaryFieldSet],
6120
+ criticalFields: [...this.criticalFieldSet],
6121
+ pendingProposals: this.getPendingProposals(),
6122
+ touchedKeys: this.touchedKeys,
6123
+ recentlyUpdatedKeys: this.recentlyUpdatedKeys,
6124
+ dictionaryLabelMap
6125
+ });
6126
+ }
6127
+ loadDictionaries(bundle) {
6128
+ this.invalidate();
6129
+ this.dictionaries.load(bundle);
6130
+ this.revision++;
6131
+ const resolved = [];
6132
+ for (const st of this.dictionaries.allStates()) {
6133
+ if (st.status === "resolved" && st.code) {
6134
+ const f = this.core.fields[st.key];
6135
+ if (f && f.visible !== false && !f.disabled) {
6136
+ this.core.setControlData(st.key, st.value ?? st.code);
6137
+ }
6138
+ resolved.push(st);
6139
+ }
6140
+ }
6141
+ return resolved;
6142
+ }
6143
+ chooseDictionaryCandidate(key, candidateId, token) {
6144
+ this.invalidate();
6145
+ const st = this.dictionaries.choose(key, candidateId, token);
6146
+ this.revision++;
6147
+ if (st.status === "resolved" && st.code) {
6148
+ const f = this.core.fields[key];
6149
+ if (f && f.visible !== false && !f.disabled) {
6150
+ this.core.setControlData(key, st.value ?? st.code);
6151
+ }
6152
+ }
6153
+ return st;
6154
+ }
6155
+ getActiveSlice() {
6156
+ return (0, slicer_1.buildActiveContextSlice)(this.schema, this.core.fields, {
6157
+ locale: this.locale,
6158
+ dictionaryFields: [...this.dictionaryFieldSet],
6159
+ criticalFields: [...this.criticalFieldSet]
6160
+ });
6161
+ }
6162
+ getPendingProposals() {
6163
+ return [...this.pendingMap.values()];
6164
+ }
6165
+ confirmPending(keys) {
6166
+ const targetKeys = keys && keys.length ? keys : [...this.pendingMap.keys()];
6167
+ const applied = [];
6168
+ this.invalidate();
6169
+ const remaining = new Set(targetKeys.filter((k) => this.pendingMap.has(k)));
6170
+ for (let pass = 0; pass < 2 && remaining.size > 0; pass++) {
6171
+ let progressed = false;
6172
+ for (const key of [...remaining]) {
6173
+ const prop = this.pendingMap.get(key);
6174
+ const item = this.itemsByKey.get(key);
6175
+ const f = this.core.fields[key];
6176
+ if (!prop || !item || !f) {
6177
+ remaining.delete(key);
6178
+ this.pendingMap.delete(key);
6179
+ continue;
6180
+ }
6181
+ const isWritable = f.visible !== false && !f.disabled && !item.readonly;
6182
+ if (!isWritable)
6183
+ continue;
6184
+ const visibleBefore = this.snapshotVisibleKeys();
6185
+ const prev = f.value;
6186
+ this.core.setControlData(key, prop.value);
6187
+ this.touchedKeys.add(key);
6188
+ const visibleAfter = this.snapshotVisibleKeys();
6189
+ const revealed = [...visibleAfter].filter((k) => !visibleBefore.has(k));
6190
+ applied.push({
6191
+ key,
6192
+ label: prop.label,
6193
+ value: prop.value,
6194
+ displayValue: prop.displayValue,
6195
+ previousValue: prev,
6196
+ ...revealed.length ? { triggeredReveal: revealed } : {}
6197
+ });
6198
+ this.pendingMap.delete(key);
6199
+ remaining.delete(key);
6200
+ progressed = true;
6201
+ }
6202
+ if (!progressed)
6203
+ break;
6204
+ }
6205
+ if (applied.length > 0) {
6206
+ this.recentlyUpdatedKeys = new Set(applied.map((a) => a.key));
6207
+ this.revision++;
6208
+ }
6209
+ return applied;
6210
+ }
6211
+ rejectPending(keys) {
6212
+ const targetKeys = keys && keys.length ? keys : [...this.pendingMap.keys()];
6213
+ for (const k of targetKeys)
6214
+ this.pendingMap.delete(k);
6215
+ }
6216
+ async extractFromText(text, options) {
6217
+ const clean = String(text || "").trim();
6218
+ if (!clean || clean.length > 2e3) {
6219
+ throw new Error(this.locale === "en-US" ? "Please enter 1\u20132000 characters." : "\u8BF7\u8F93\u5165 1\u20132000 \u5B57\u7684\u586B\u5199\u5185\u5BB9\u3002");
6220
+ }
6221
+ this.invalidate();
6222
+ const ticket = Object.freeze({
6223
+ id: this.sequence,
6224
+ revision: this.revision,
6225
+ text: clean
6226
+ });
6227
+ this.activeTicket = ticket;
6228
+ const slice = this.getActiveSlice();
6229
+ const planBefore = this.getFillPlan();
6230
+ let route = "slm";
6231
+ let matchedRule;
6232
+ let rawResult;
6233
+ const fastStarted = Date.now();
6234
+ const fast = this.enableFastPath ? (0, fastPath_1.tryFastPathExtract)(clean, planBefore.activeBeat, slice) : { matched: false, patch: {}, mentions: {} };
6235
+ if (fast.matched) {
6236
+ route = "fast-path";
6237
+ matchedRule = fast.matchedRule;
6238
+ rawResult = {
6239
+ patch: fast.patch,
6240
+ mentions: fast.mentions,
6241
+ model: "deterministic-fast-path",
6242
+ elapsedMs: Date.now() - fastStarted,
6243
+ omittedEmptyFields: []
6244
+ };
6245
+ } else {
6246
+ rawResult = await this.adapter.extract(clean, slice, {
6247
+ signal: options?.signal,
6248
+ locale: this.locale
6249
+ });
6250
+ }
6251
+ return this.applyRawExtractionResult(rawResult, ticket, route, matchedRule);
6252
+ }
6253
+ /**
6254
+ * 多模态图片直出成卡:支持拍名片、聊天截图、证件/工牌照片直接走本地视觉模型抽槽,
6255
+ * 复用完全相同的 Revision-Ticket、两趟 BFS 联动、主权红线拦截与风险确认矩阵。
6256
+ */
6257
+ async extractFromImage(imageBase64, options) {
6258
+ if (typeof this.adapter.extractFromImage !== "function") {
6259
+ throw new Error(this.locale === "en-US" ? `Current model adapter (${this.adapter.name}) does not support image extraction.` : `\u5F53\u524D\u6A21\u578B\u9002\u914D\u5668\uFF08${this.adapter.name}\uFF09\u4E0D\u652F\u6301\u56FE\u7247\u8BC6\u522B\u62BD\u69FD\u3002`);
6260
+ }
6261
+ const cleanImg = String(imageBase64 || "").trim();
6262
+ if (!cleanImg) {
6263
+ throw new Error(this.locale === "en-US" ? "Image payload is empty." : "\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u56FE\u7247\u5185\u5BB9\u3002");
6264
+ }
6265
+ this.invalidate();
6266
+ const ticket = Object.freeze({
6267
+ id: this.sequence,
6268
+ revision: this.revision,
6269
+ text: options?.hintText ? `[image:${options.hintText.slice(0, 60)}]` : "[image]"
6270
+ });
6271
+ this.activeTicket = ticket;
6272
+ const slice = this.getActiveSlice();
6273
+ const rawResult = await this.adapter.extractFromImage(cleanImg, slice, {
6274
+ ...options,
6275
+ locale: options?.locale || this.locale
6276
+ });
6277
+ return this.applyRawExtractionResult(rawResult, ticket, "vision", "multimodal_vision");
6278
+ }
6279
+ applyRawExtractionResult(rawResult, ticket, route, matchedRule) {
6280
+ if (this.activeTicket !== ticket || ticket.revision !== this.revision) {
6281
+ return {
6282
+ status: "stale",
6283
+ route,
6284
+ ticket,
6285
+ mode: this.mode,
6286
+ applied: [],
6287
+ pendingConfirm: this.getPendingProposals(),
6288
+ mentions: [],
6289
+ rejected: [],
6290
+ readiness: this.inspectReadiness(),
6291
+ plan: this.getFillPlan(),
6292
+ metadata: {
6293
+ model: rawResult.model,
6294
+ elapsedMs: rawResult.elapsedMs,
6295
+ omittedEmptyFields: rawResult.omittedEmptyFields || [],
6296
+ matchedRule
6297
+ }
6298
+ };
6299
+ }
6300
+ const applied = [];
6301
+ const newPending = [];
6302
+ const rejected = [];
6303
+ const capturedMentions = [];
6304
+ for (const [mKey, mRaw] of Object.entries(rawResult.mentions || {})) {
6305
+ const item = this.itemsByKey.get(mKey);
6306
+ if (!item || (0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet) !== "mention_only") {
6307
+ rejected.push({
6308
+ key: `${mKey}_raw`,
6309
+ value: mRaw,
6310
+ code: "UNKNOWN_FIELD",
6311
+ message: `\u672A\u77E5\u539F\u8BDD\u5B57\u6BB5\uFF1A${mKey}_raw`
6312
+ });
6313
+ continue;
6314
+ }
6315
+ const st = this.dictionaries.capture(mKey, mRaw);
6316
+ capturedMentions.push(st);
6317
+ if (st.status === "resolved" && st.code && this.mode === "smart") {
6318
+ const f = this.core.fields[mKey];
6319
+ if (f && f.visible !== false && !f.disabled) {
6320
+ this.core.setControlData(mKey, st.value ?? st.code);
6321
+ }
6322
+ }
6323
+ }
6324
+ const deferred = [];
6325
+ const entries = Object.entries(rawResult.patch || {});
6326
+ const processEntry = (key, rawVal, allowDefer) => {
6327
+ const item = this.itemsByKey.get(key);
6328
+ if (!item) {
6329
+ rejected.push({
6330
+ key,
6331
+ value: rawVal,
6332
+ code: "UNKNOWN_FIELD",
6333
+ message: `\u6A21\u578B\u8FD4\u56DE\u4E86\u672A\u77E5\u5B57\u6BB5\uFF1A${key}`
6334
+ });
6335
+ return;
6336
+ }
6337
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet);
6338
+ if (policy === "forbidden") {
6339
+ rejected.push({
6340
+ key,
6341
+ value: rawVal,
6342
+ code: "FORBIDDEN_FIELD",
6343
+ message: `${item.label || key} \u5C5E\u4E8E\u9AD8\u5371\u6216\u672C\u4EBA\u64CD\u4F5C\u5B57\u6BB5\uFF0C\u7981\u6B62\u7531\u6A21\u578B\u81EA\u52A8\u586B\u5199\u3002`
6344
+ });
6345
+ return;
6346
+ }
6347
+ if (policy === "mention_only") {
6348
+ const st = this.dictionaries.capture(key, String(rawVal));
6349
+ capturedMentions.push(st);
6350
+ if (st.status === "resolved" && st.code && this.mode === "smart") {
6351
+ const f2 = this.core.fields[key];
6352
+ if (f2 && f2.visible !== false && !f2.disabled) {
6353
+ this.core.setControlData(key, st.value ?? st.code);
6354
+ }
6355
+ }
6356
+ return;
6357
+ }
6358
+ const f = this.core.fields[key];
6359
+ const isVisible = f ? f.visible !== false : item.visible !== false;
6360
+ const isDisabled = Boolean(f?.disabled ?? item.disabled);
6361
+ const isReadonly = Boolean(item.readonly || item.readOnly);
6362
+ if (!isVisible) {
6363
+ if (allowDefer) {
6364
+ deferred.push([key, rawVal]);
6365
+ } else {
6366
+ rejected.push({
6367
+ key,
6368
+ value: rawVal,
6369
+ code: "FIELD_NOT_WRITABLE",
6370
+ message: `${item.label || key} \u5F53\u524D\u5904\u4E8E\u9690\u85CF\u72B6\u6001\uFF0C\u4E0D\u80FD\u7531\u6A21\u578B\u586B\u5199\u3002`
6371
+ });
6372
+ }
6373
+ return;
6374
+ }
6375
+ if (isDisabled || isReadonly) {
6376
+ rejected.push({
6377
+ key,
6378
+ value: rawVal,
6379
+ code: "FIELD_NOT_WRITABLE",
6380
+ message: `${item.label || key} \u4E3A\u7981\u7528\u6216\u53EA\u8BFB\u5B57\u6BB5\uFF0C\u4E0D\u80FD\u5199\u5165\u3002`
6381
+ });
6382
+ return;
6383
+ }
6384
+ const checked = coerceAndValidateValue(item, rawVal);
6385
+ if (!checked.ok) {
6386
+ rejected.push({ key, value: rawVal, code: checked.code, message: checked.message });
6387
+ return;
6388
+ }
6389
+ const prevValue = f?.value;
6390
+ const sameAsPrev = JSON.stringify(prevValue) === JSON.stringify(checked.value);
6391
+ if (sameAsPrev)
6392
+ return;
6393
+ const risk = (0, slicer_1.classifyFieldRisk)(item, this.criticalFieldSet);
6394
+ const isUntouchedDefault = !this.touchedKeys.has(key) && item.defaultValue !== void 0 && JSON.stringify(prevValue) === JSON.stringify(item.defaultValue);
6395
+ const isOverwrite = !(0, slicer_1.isEmptyFieldValue)(prevValue) && !sameAsPrev && !isUntouchedDefault;
6396
+ let confirmReason = null;
6397
+ if (this.mode === "preview")
6398
+ confirmReason = "PREVIEW_MODE";
6399
+ else if (this.protectOverwrite && isOverwrite)
6400
+ confirmReason = "OVERWRITE_EXISTING";
6401
+ else if (this.reviewCritical && risk === "CRITICAL")
6402
+ confirmReason = "CRITICAL_FIELD";
6403
+ const displayValue = formatDisplayValue(item, checked.value, this.locale);
6404
+ if (confirmReason) {
6405
+ const proposal = {
6406
+ key,
6407
+ label: item.label || key,
6408
+ value: checked.value,
6409
+ displayValue,
6410
+ previousValue: prevValue,
6411
+ risk,
6412
+ reason: confirmReason
6413
+ };
6414
+ this.pendingMap.set(key, proposal);
6415
+ newPending.push(proposal);
6416
+ return;
6417
+ }
6418
+ const visibleBefore = this.snapshotVisibleKeys();
6419
+ this.core.setControlData(key, checked.value);
6420
+ this.touchedKeys.add(key);
6421
+ const visibleAfter = this.snapshotVisibleKeys();
6422
+ const revealed = [...visibleAfter].filter((k) => !visibleBefore.has(k));
6423
+ applied.push({
6424
+ key,
6425
+ label: item.label || key,
6426
+ value: checked.value,
6427
+ displayValue,
6428
+ previousValue: prevValue,
6429
+ ...revealed.length ? { triggeredReveal: revealed } : {}
6430
+ });
6431
+ };
6432
+ for (const [k, v] of entries)
6433
+ processEntry(k, v, true);
6434
+ for (const [k, v] of deferred) {
6435
+ const f = this.core.fields[k];
6436
+ if (this.mode === "preview" && f && f.visible === false && newPending.length > 0) {
6437
+ const item = this.itemsByKey.get(k);
6438
+ if (item) {
6439
+ const checked = coerceAndValidateValue(item, v);
6440
+ if (checked.ok) {
6441
+ const proposal = {
6442
+ key: k,
6443
+ label: item.label || k,
6444
+ value: checked.value,
6445
+ displayValue: formatDisplayValue(item, checked.value, this.locale),
6446
+ previousValue: f.value,
6447
+ risk: (0, slicer_1.classifyFieldRisk)(item, this.criticalFieldSet),
6448
+ reason: "PREVIEW_MODE"
6449
+ };
6450
+ this.pendingMap.set(k, proposal);
6451
+ newPending.push(proposal);
6452
+ continue;
6453
+ }
6454
+ }
6455
+ }
6456
+ processEntry(k, v, false);
6457
+ }
6458
+ if (applied.length > 0 || capturedMentions.length > 0) {
6459
+ this.recentlyUpdatedKeys = new Set(applied.map((a) => a.key));
6460
+ this.revision++;
6461
+ }
6462
+ this.activeTicket = null;
6463
+ const status = applied.length > 0 ? "applied" : newPending.length > 0 || capturedMentions.length > 0 ? "preview" : "empty";
6464
+ return {
6465
+ status,
6466
+ route,
6467
+ ticket,
6468
+ mode: this.mode,
6469
+ applied,
6470
+ pendingConfirm: this.getPendingProposals(),
6471
+ mentions: capturedMentions,
6472
+ rejected,
6473
+ readiness: this.inspectReadiness(),
6474
+ plan: this.getFillPlan(),
6475
+ metadata: {
6476
+ model: rawResult.model,
6477
+ elapsedMs: rawResult.elapsedMs,
6478
+ omittedEmptyFields: rawResult.omittedEmptyFields || [],
6479
+ matchedRule
6480
+ }
6481
+ };
6482
+ }
6483
+ inspectReadiness() {
6484
+ const missingRequired = [];
6485
+ const invalidFields = [];
6486
+ const manualOnlyPending = [];
6487
+ let totalRequiredCount = 0;
6488
+ let filledRequiredCount = 0;
6489
+ for (const item of this.itemsByKey.values()) {
6490
+ const f = this.core.fields[item.key];
6491
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
6492
+ if (!visible)
6493
+ continue;
6494
+ const required = Boolean(f?.required ?? item.required);
6495
+ const value = f?.value;
6496
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet);
6497
+ const isFilled = item.type === "agreement" ? value === true || value === 1 || value === "1" : !(0, slicer_1.isEmptyFieldValue)(value);
6498
+ if (required) {
6499
+ totalRequiredCount++;
6500
+ if (isFilled)
6501
+ filledRequiredCount++;
6502
+ }
6503
+ if (f?.errMsg) {
6504
+ invalidFields.push({ key: item.key, label: item.label || item.key, reason: String(f.errMsg) });
6505
+ }
6506
+ if (required && !isFilled) {
6507
+ if (policy === "forbidden") {
6508
+ manualOnlyPending.push({ key: item.key, label: item.label || item.key, type: item.type });
6509
+ } else {
6510
+ missingRequired.push({ key: item.key, label: item.label || item.key, type: item.type });
6511
+ }
6512
+ }
6513
+ }
6514
+ const pendingConfirmations = this.getPendingProposals();
6515
+ const pendingMentions = this.dictionaries.allStates().filter((s) => s.raw && s.status !== "resolved");
6516
+ const progressPercent = totalRequiredCount === 0 ? 100 : Math.round(filledRequiredCount / totalRequiredCount * 100);
6517
+ const complete = missingRequired.length === 0 && invalidFields.length === 0 && pendingConfirmations.length === 0 && manualOnlyPending.length === 0;
6518
+ const nextPrompt = this.buildNextPrompt({
6519
+ missingRequired,
6520
+ invalidFields,
6521
+ pendingConfirmations,
6522
+ pendingMentions,
6523
+ manualOnlyPending
6524
+ });
6525
+ return {
6526
+ complete,
6527
+ filledRequiredCount,
6528
+ totalRequiredCount,
6529
+ progressPercent,
6530
+ missingRequired,
6531
+ invalidFields,
6532
+ pendingConfirmations,
6533
+ pendingMentions,
6534
+ manualOnlyPending,
6535
+ nextPrompt
6536
+ };
6537
+ }
6538
+ buildNextPrompt(parts) {
6539
+ const isEn = this.locale === "en-US";
6540
+ if (parts.pendingConfirmations.length > 0) {
6541
+ const names = parts.pendingConfirmations.map((p) => p.label).join(isEn ? ", " : "\u3001");
6542
+ return isEn ? `Please review and confirm ${parts.pendingConfirmations.length} extracted field(s): ${names}.` : `\u8BF7\u5148\u6838\u5BF9\u5E76\u786E\u8BA4 ${parts.pendingConfirmations.length} \u9879\u5F85\u786E\u8BA4\u4FE1\u606F\uFF1A${names}\u3002`;
6543
+ }
6544
+ if (parts.invalidFields.length > 0) {
6545
+ const first = parts.invalidFields[0];
6546
+ return isEn ? `Please fix "${first.label}": ${first.reason}` : `\u8BF7\u4FEE\u6B63\u300C${first.label}\u300D\uFF1A${first.reason}`;
6547
+ }
6548
+ if (parts.missingRequired.length > 0) {
6549
+ const top = parts.missingRequired.slice(0, 3).map((m) => m.label).join(isEn ? ", " : "\u3001");
6550
+ const more = parts.missingRequired.length > 3 ? isEn ? "\u2026" : "\u7B49" : "";
6551
+ return isEn ? `Still needed (${parts.missingRequired.length}): ${top}${more}. You can speak or type them in one sentence.` : `\u8FD8\u5DEE ${parts.missingRequired.length} \u9879\u5FC5\u586B\u4FE1\u606F\uFF1A${top}${more}\uFF0C\u53EF\u4EE5\u76F4\u63A5\u7528\u4E00\u53E5\u8BDD\u544A\u8BC9\u6211\u3002`;
6552
+ }
6553
+ if (parts.manualOnlyPending.length > 0) {
6554
+ const names = parts.manualOnlyPending.map((m) => m.label).join(isEn ? ", " : "\u3001");
6555
+ return isEn ? `All extractable fields are ready! Please complete manually: ${names}.` : `\u53EF\u81EA\u52A8\u63D0\u53D6\u7684\u4FE1\u606F\u5DF2\u5168\u90E8\u5C31\u7EEA\uFF01\u8BF7\u672C\u4EBA\u624B\u52A8\u5B8C\u6210\uFF1A${names}\u3002`;
6556
+ }
6557
+ if (parts.pendingMentions.length > 0) {
6558
+ const names = parts.pendingMentions.map((m) => `${m.key}(${m.raw})`).join(isEn ? ", " : "\u3001");
6559
+ return isEn ? `Verbatim text captured awaiting dictionary match: ${names}.` : `\u5DF2\u6682\u5B58\u539F\u8BDD\u5F85\u5B57\u5178\u5339\u914D\uFF1A${names}\u3002`;
6560
+ }
6561
+ return isEn ? "All required information is ready to submit \u2713" : "\u6240\u6709\u5FC5\u586B\u4FE1\u606F\u5DF2\u5C31\u7EEA\uFF0C\u53EF\u76F4\u63A5\u6838\u5BF9\u63D0\u4EA4 \u2713";
6562
+ }
6563
+ snapshotVisibleKeys() {
6564
+ const set = /* @__PURE__ */ new Set();
6565
+ for (const [k, f] of Object.entries(this.core.fields)) {
6566
+ if (f && f.visible !== false)
6567
+ set.add(k);
6568
+ }
6569
+ return set;
6570
+ }
6571
+ };
6572
+ exports2.IntentFillSession = IntentFillSession;
6573
+ }
6574
+ });
6575
+
6576
+ // packages/form-intent-fill/dist/intakeManager.js
6577
+ var require_intakeManager = __commonJS({
6578
+ "packages/form-intent-fill/dist/intakeManager.js"(exports2) {
6579
+ "use strict";
6580
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
6581
+ return mod && mod.__esModule ? mod : { "default": mod };
6582
+ };
6583
+ Object.defineProperty(exports2, "__esModule", { value: true });
6584
+ exports2.intakeStart = intakeStart;
6585
+ exports2.intakeSubmitTurn = intakeSubmitTurn;
6586
+ exports2.intakeConfirm = intakeConfirm;
6587
+ exports2.intakeStatus = intakeStatus;
6588
+ exports2.intakeFinalize = intakeFinalize;
6589
+ exports2.loadIntakeRecordRaw = loadIntakeRecordRaw;
6590
+ exports2.saveIntakeRecordRaw = saveIntakeRecordRaw;
6591
+ var node_crypto_1 = __importDefault(require("node:crypto"));
6592
+ var node_fs_1 = __importDefault(require("node:fs"));
6593
+ var node_os_1 = __importDefault(require("node:os"));
6594
+ var node_path_1 = __importDefault(require("node:path"));
6595
+ var adapters_1 = require_adapters();
6596
+ var session_1 = require_session();
6597
+ var slicer_1 = require_slicer();
6598
+ function resolveFormCoreCtor() {
6599
+ try {
6600
+ const mod2 = require_dist();
6601
+ if (mod2 && mod2.FormCore)
6602
+ return mod2.FormCore;
6603
+ } catch {
6604
+ }
6605
+ const mod = require(node_path_1.default.resolve(__dirname, "../../../dist/index.js"));
6606
+ return mod.FormCore;
6607
+ }
6608
+ function resolveSessionsDir(dataDir) {
6609
+ const base = node_path_1.default.resolve(dataDir || process.env.FORM_SCHEMA_AGENT_DATA_DIR || node_path_1.default.join(node_os_1.default.homedir(), ".form-schema-agent"));
6610
+ const dir = node_path_1.default.join(base, "intake-sessions");
6611
+ node_fs_1.default.mkdirSync(dir, { recursive: true });
6612
+ return dir;
6613
+ }
6614
+ function sessionFilePath(sessionId, dataDir) {
6615
+ const safeId = String(sessionId || "").replace(/[^a-zA-Z0-9_-]/g, "");
6616
+ if (!safeId)
6617
+ throw Object.assign(new Error("\u65E0\u6548\u7684 intake sessionId"), { code: "INVALID_ARGUMENT" });
6618
+ return node_path_1.default.join(resolveSessionsDir(dataDir), `${safeId}.json`);
6619
+ }
6620
+ function writeJsonAtomic(filePath, payload) {
6621
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
6622
+ node_fs_1.default.writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n", "utf8");
6623
+ node_fs_1.default.renameSync(tmp, filePath);
6624
+ }
6625
+ function loadSchemaInput(input) {
6626
+ if (input.schema && typeof input.schema === "object" && Array.isArray(input.schema.groups)) {
6627
+ return JSON.parse(JSON.stringify(input.schema));
6628
+ }
6629
+ if (input.schemaPath) {
6630
+ const abs = node_path_1.default.resolve(input.schemaPath);
6631
+ if (!node_fs_1.default.existsSync(abs)) {
6632
+ throw Object.assign(new Error(`FormSchema \u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${abs}`), { code: "NOT_FOUND" });
6633
+ }
6634
+ const raw = JSON.parse(node_fs_1.default.readFileSync(abs, "utf8"));
6635
+ const unwrapped = raw && raw.schema && Array.isArray(raw.schema.groups) ? raw.schema : raw;
6636
+ if (!unwrapped || !Array.isArray(unwrapped.groups)) {
6637
+ throw Object.assign(new Error("\u6587\u4EF6\u4E0D\u662F\u5408\u6CD5\u7684 FormSchema\uFF08\u7F3A\u5C11 groups \u6570\u7EC4\uFF09"), { code: "INVALID_ARGUMENT" });
6638
+ }
6639
+ return unwrapped;
6640
+ }
6641
+ throw Object.assign(new Error("\u5FC5\u987B\u63D0\u4F9B schema \u6216 schemaPath"), { code: "INVALID_ARGUMENT" });
6642
+ }
6643
+ async function hydrateRuntime(record, adapter) {
6644
+ const FormCoreCtor = resolveFormCoreCtor();
6645
+ const mem = /* @__PURE__ */ new Map();
6646
+ const core = new FormCoreCtor(JSON.parse(JSON.stringify(record.schema)), {
6647
+ get: (k) => mem.get(k),
6648
+ set: (k, v) => mem.set(k, v),
6649
+ remove: (k) => mem.delete(k)
6650
+ });
6651
+ await core.init({});
6652
+ const entries = Object.entries(record.values || {});
6653
+ for (let pass = 0; pass < 2; pass++) {
6654
+ for (const [k, v] of entries) {
6655
+ if (core.fields[k] && (pass === 0 || core.fields[k].visible !== false)) {
6656
+ try {
6657
+ core.setControlData(k, v);
6658
+ } catch {
6659
+ }
6660
+ }
6661
+ }
6662
+ }
6663
+ const session = new session_1.IntentFillSession({
6664
+ schema: record.schema,
6665
+ core,
6666
+ adapter,
6667
+ mode: record.mode,
6668
+ locale: record.locale,
6669
+ reviewCritical: record.reviewCritical,
6670
+ protectOverwrite: record.protectOverwrite
6671
+ });
6672
+ session.revision = record.revision;
6673
+ for (const k of record.touchedKeys || []) {
6674
+ ;
6675
+ session.touchedKeys.add(k);
6676
+ }
6677
+ for (const prop of record.pendingProposals || []) {
6678
+ ;
6679
+ session.pendingMap.set(prop.key, prop);
6680
+ }
6681
+ if (record.dictionaryBundle) {
6682
+ session.dictionaries.load(record.dictionaryBundle);
6683
+ }
6684
+ for (const [k, raw] of Object.entries(record.dictionaryRawMentions || {})) {
6685
+ if (raw) {
6686
+ const st = session.dictionaries.capture(k, raw);
6687
+ const choice = record.dictionaryChoices?.[k];
6688
+ if (choice) {
6689
+ try {
6690
+ session.dictionaries.choose(k, choice, st.token);
6691
+ } catch {
6692
+ }
6693
+ }
6694
+ }
6695
+ }
6696
+ return { core, session };
6697
+ }
6698
+ function buildAgentQuestion(plan, readiness, locale) {
6699
+ const isEn = locale === "en-US";
6700
+ if (readiness.pendingConfirmations.length > 0) {
6701
+ const list = readiness.pendingConfirmations.map((p) => `${p.label}\uFF08${p.displayValue}\uFF09`).join(isEn ? ", " : "\u3001");
6702
+ return isEn ? `Please confirm these extracted details with the user: ${list}.` : `\u8BF7\u5411\u7528\u6237\u786E\u8BA4\u4EE5\u4E0B\u4FE1\u606F\u65E0\u8BEF\uFF1A${list}\u3002`;
6703
+ }
6704
+ if (readiness.invalidFields.length > 0) {
6705
+ const f = readiness.invalidFields[0];
6706
+ return isEn ? `Ask the user to correct "${f.label}": ${f.reason}` : `\u8BF7\u5411\u7528\u6237\u6838\u5BF9\u300C${f.label}\u300D\uFF1A${f.reason}`;
6707
+ }
6708
+ if (readiness.missingRequired.length === 0 && readiness.manualOnlyPending.length > 0) {
6709
+ const names = readiness.manualOnlyPending.map((m) => m.label).join(isEn ? ", " : "\u3001");
6710
+ return isEn ? `All conversational fields are complete. Hand off to user for sovereign sign-off: ${names}.` : `\u6240\u6709\u5BF9\u8BDD\u5B57\u6BB5\u5DF2\u6536\u9F50\uFF01\u8BF7\u5C06\u786E\u8BA4\u5361\u7247\u4EA4\u7ED9\u7528\u6237\u672C\u4EBA\u5B8C\u6210\uFF1A${names}\u3002`;
6711
+ }
6712
+ if (readiness.complete) {
6713
+ return isEn ? "All required information is complete and validated. Ready to call intake_finalize." : "\u6240\u6709\u5FC5\u586B\u4FE1\u606F\u5DF2\u6536\u96C6\u5E76\u6821\u9A8C\u901A\u8FC7\uFF0C\u53EF\u8C03\u7528 intake_finalize \u751F\u6210\u6700\u7EC8\u63D0\u4EA4\u8F7D\u8377\u3002";
6714
+ }
6715
+ return plan.activeBeat.guidance;
6716
+ }
6717
+ function snapshotRecordFromRuntime(prev, core, session, extra) {
6718
+ const values = {};
6719
+ for (const item of (0, slicer_1.collectSchemaItems)(prev.schema)) {
6720
+ const f = core.fields[item.key];
6721
+ if (f && !(0, slicer_1.isEmptyFieldValue)(f.value)) {
6722
+ values[item.key] = f.value;
6723
+ }
6724
+ }
6725
+ const dictMentions = {};
6726
+ const dictChoices = {};
6727
+ for (const st of session.dictionaries.allStates()) {
6728
+ if (st.raw)
6729
+ dictMentions[st.key] = st.raw;
6730
+ if (st.status === "resolved" && st.candidates.length > 1 && st.code) {
6731
+ const hit = st.candidates.find((c) => c.code === st.code);
6732
+ if (hit)
6733
+ dictChoices[st.key] = hit.id;
6734
+ }
6735
+ }
6736
+ const readiness = session.inspectReadiness();
6737
+ const nextStatus = extra?.status || (prev.status === "finalized" ? "finalized" : readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.invalidFields.length === 0 ? "ready_for_signoff" : "collecting");
6738
+ return {
6739
+ ...prev,
6740
+ ...extra,
6741
+ status: nextStatus,
6742
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6743
+ revision: session.revision,
6744
+ values,
6745
+ touchedKeys: [...session.touchedKeys],
6746
+ pendingProposals: session.getPendingProposals(),
6747
+ dictionaryRawMentions: dictMentions,
6748
+ dictionaryChoices: dictChoices
6749
+ };
6750
+ }
6751
+ var NOOP_ADAPTER = {
6752
+ name: "agent-direct",
6753
+ async extract() {
6754
+ return { patch: {}, mentions: {}, elapsedMs: 0, model: "agent-direct" };
6755
+ }
6756
+ };
6757
+ function loadPersistedRecord(sessionId, dataDir) {
6758
+ const fp = sessionFilePath(sessionId, dataDir);
6759
+ if (!node_fs_1.default.existsSync(fp)) {
6760
+ throw Object.assign(new Error(`\u672A\u627E\u5230 Intake \u4F1A\u8BDD\uFF1A${sessionId}`), { code: "NOT_FOUND" });
6761
+ }
6762
+ return JSON.parse(node_fs_1.default.readFileSync(fp, "utf8"));
6763
+ }
6764
+ async function intakeStart(input) {
6765
+ const schema = loadSchemaInput(input);
6766
+ const locale = input.locale === "en-US" ? "en-US" : "zh-CN";
6767
+ const mode = input.mode || "smart";
6768
+ const sessionId = input.sessionId ? String(input.sessionId).replace(/[^a-zA-Z0-9_-]/g, "") : `intk_${Date.now().toString(36)}_${node_crypto_1.default.randomBytes(3).toString("hex")}`;
6769
+ const initialRecord = {
6770
+ version: 1,
6771
+ sessionId,
6772
+ status: "collecting",
6773
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
6774
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6775
+ locale,
6776
+ mode,
6777
+ reviewCritical: input.reviewCritical !== false,
6778
+ protectOverwrite: input.protectOverwrite !== false,
6779
+ schema,
6780
+ values: {},
6781
+ touchedKeys: [],
6782
+ pendingProposals: [],
6783
+ dictionaryBundle: input.dictionaryBundle || null,
6784
+ dictionaryRawMentions: {},
6785
+ dictionaryChoices: {},
6786
+ revision: 0,
6787
+ finalSubmission: null
6788
+ };
6789
+ const { core, session } = await hydrateRuntime(initialRecord, NOOP_ADAPTER);
6790
+ const saved = snapshotRecordFromRuntime(initialRecord, core, session);
6791
+ writeJsonAtomic(sessionFilePath(sessionId, input.dataDir), saved);
6792
+ const plan = session.getFillPlan();
6793
+ const readiness = session.inspectReadiness();
6794
+ const slice = session.getActiveSlice();
6795
+ return {
6796
+ status: "started",
6797
+ sessionId,
6798
+ sessionStatus: saved.status,
6799
+ schemaTitle: schema.title || "",
6800
+ locale,
6801
+ archetype: plan.archetype,
6802
+ revision: saved.revision,
6803
+ activeContextSlice: slice,
6804
+ plan,
6805
+ readiness,
6806
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, locale),
6807
+ handoffRecommended: readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.manualOnlyPending.length > 0
6808
+ };
6809
+ }
6810
+ async function intakeSubmitTurn(input) {
6811
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
6812
+ if (record.status === "finalized") {
6813
+ throw Object.assign(new Error("\u8BE5 Intake \u4F1A\u8BDD\u5DF2\u5B8C\u6210\u6700\u7EC8\u63D0\u4EA4\uFF0C\u4E0D\u53EF\u7EE7\u7EED\u4FEE\u6539\u3002"), { code: "INVALID_STATE" });
6814
+ }
6815
+ const hasDirectPatch = Boolean(input.patch && Object.keys(input.patch).length > 0 || input.mentions && Object.keys(input.mentions).length > 0);
6816
+ const hasText = typeof input.text === "string" && input.text.trim().length > 0;
6817
+ let resolvedImageBase64 = typeof input.imageBase64 === "string" ? input.imageBase64.trim() : "";
6818
+ let resolvedMimeType = input.imageMimeType;
6819
+ if (!resolvedImageBase64 && input.imagePath) {
6820
+ const absImg = node_path_1.default.resolve(input.imagePath);
6821
+ if (!node_fs_1.default.existsSync(absImg)) {
6822
+ throw Object.assign(new Error(`\u56FE\u7247\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${absImg}`), { code: "NOT_FOUND" });
6823
+ }
6824
+ resolvedImageBase64 = node_fs_1.default.readFileSync(absImg).toString("base64");
6825
+ if (!resolvedMimeType) {
6826
+ const ext = node_path_1.default.extname(absImg).toLowerCase();
6827
+ resolvedMimeType = ext === ".jpg" || ext === ".jpeg" ? "image/jpeg" : ext === ".webp" ? "image/webp" : "image/png";
6828
+ }
6829
+ }
6830
+ const hasImage = Boolean(resolvedImageBase64);
6831
+ if (!hasDirectPatch && !hasText && !hasImage) {
6832
+ throw Object.assign(new Error("\u8BF7\u63D0\u4F9B patch/mentions\uFF08Agent \u7ED3\u6784\u5316\u586B\u69FD\uFF09\u3001text\uFF08\u7528\u6237\u539F\u8BDD\uFF09\u6216 imageBase64/imagePath\uFF08\u540D\u7247\u6216\u622A\u56FE\uFF09\u4E4B\u4E00\u3002"), {
6833
+ code: "INVALID_ARGUMENT"
6834
+ });
6835
+ }
6836
+ let adapter = input.adapter || NOOP_ADAPTER;
6837
+ let turnText = hasText ? String(input.text).trim() : "[agent-patch]";
6838
+ let enableFastPath = true;
6839
+ if (hasDirectPatch) {
6840
+ enableFastPath = false;
6841
+ adapter = {
6842
+ name: "agent-direct-patch",
6843
+ async extract() {
6844
+ return {
6845
+ patch: input.patch || {},
6846
+ mentions: input.mentions || {},
6847
+ elapsedMs: 0,
6848
+ model: "agent-direct-patch"
6849
+ };
6850
+ }
6851
+ };
6852
+ } else if (input.useLocalSlm !== false && !input.adapter) {
6853
+ adapter = (0, adapters_1.createOllamaIntentAdapter)({
6854
+ baseUrl: input.ollamaUrl || process.env.OLLAMA_URL || "http://127.0.0.1:11434",
6855
+ model: input.model || process.env.INTENT_FILL_MODEL || "qwen3.5:4b-q4_K_M",
6856
+ visionModel: input.visionModel || process.env.INTENT_FILL_VISION_MODEL || input.model || process.env.INTENT_FILL_MODEL || "qwen3.5:4b-q4_K_M",
6857
+ think: false
6858
+ });
6859
+ }
6860
+ const { core, session } = await hydrateRuntime(record, adapter);
6861
+ session.enableFastPath = enableFastPath;
6862
+ const turn = !hasDirectPatch && hasImage ? await session.extractFromImage(resolvedImageBase64, {
6863
+ mimeType: resolvedMimeType,
6864
+ hintText: hasText ? String(input.text).trim() : void 0
6865
+ }) : await session.extractFromText(turnText);
6866
+ const saved = snapshotRecordFromRuntime(record, core, session);
6867
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), saved);
6868
+ const plan = turn.plan;
6869
+ const readiness = turn.readiness;
6870
+ const handoffRecommended = readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.invalidFields.length === 0 && readiness.manualOnlyPending.length > 0;
6871
+ return {
6872
+ status: turn.status,
6873
+ sessionId: record.sessionId,
6874
+ sessionStatus: saved.status,
6875
+ revision: saved.revision,
6876
+ route: hasDirectPatch ? "agent-patch" : turn.route,
6877
+ applied: turn.applied,
6878
+ pendingConfirm: turn.pendingConfirm,
6879
+ mentions: turn.mentions,
6880
+ rejected: turn.rejected,
6881
+ readiness,
6882
+ plan,
6883
+ activeContextSlice: session.getActiveSlice(),
6884
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, record.locale),
6885
+ handoffRecommended,
6886
+ metadata: turn.metadata
6887
+ };
6888
+ }
6889
+ async function intakeConfirm(input) {
6890
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
6891
+ if (record.status === "finalized") {
6892
+ throw Object.assign(new Error("\u8BE5 Intake \u4F1A\u8BDD\u5DF2\u5B8C\u6210\u6700\u7EC8\u63D0\u4EA4\u3002"), { code: "INVALID_STATE" });
6893
+ }
6894
+ const { core, session } = await hydrateRuntime(record, NOOP_ADAPTER);
6895
+ let nextDictBundle = record.dictionaryBundle;
6896
+ let resolvedDictionaries = [];
6897
+ if (input.dictionaryBundle) {
6898
+ nextDictBundle = input.dictionaryBundle;
6899
+ resolvedDictionaries = session.loadDictionaries(input.dictionaryBundle);
6900
+ }
6901
+ if (input.chooseCandidate) {
6902
+ const chosen = session.chooseDictionaryCandidate(input.chooseCandidate.key, input.chooseCandidate.candidateId, input.chooseCandidate.token);
6903
+ resolvedDictionaries.push(chosen);
6904
+ }
6905
+ if (Array.isArray(input.rejectKeys) && input.rejectKeys.length > 0) {
6906
+ session.rejectPending(input.rejectKeys);
6907
+ }
6908
+ const confirmed = input.confirmKeys === void 0 || input.confirmKeys.length > 0 ? session.confirmPending(input.confirmKeys) : [];
6909
+ const saved = snapshotRecordFromRuntime(record, core, session, { dictionaryBundle: nextDictBundle });
6910
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), saved);
6911
+ const plan = session.getFillPlan();
6912
+ const readiness = session.inspectReadiness();
6913
+ const handoffRecommended = readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.invalidFields.length === 0 && readiness.manualOnlyPending.length > 0;
6914
+ return {
6915
+ status: "confirmed",
6916
+ sessionId: record.sessionId,
6917
+ sessionStatus: saved.status,
6918
+ revision: saved.revision,
6919
+ confirmed,
6920
+ resolvedDictionaries,
6921
+ pendingConfirm: session.getPendingProposals(),
6922
+ readiness,
6923
+ plan,
6924
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, record.locale),
6925
+ handoffRecommended
6926
+ };
6927
+ }
6928
+ async function intakeStatus(input) {
6929
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
6930
+ const { session } = await hydrateRuntime(record, NOOP_ADAPTER);
6931
+ const plan = session.getFillPlan();
6932
+ const readiness = session.inspectReadiness();
6933
+ const mask = input.maskPii !== false;
6934
+ const collectedSummary = plan.crystallizedFields.map((f) => ({
6935
+ key: f.key,
6936
+ label: f.label,
6937
+ value: mask && f.isPii ? f.maskedDisplayValue : f.displayValue,
6938
+ isPii: f.isPii
6939
+ }));
6940
+ return {
6941
+ status: record.status,
6942
+ sessionId: record.sessionId,
6943
+ schemaTitle: record.schema.title || "",
6944
+ revision: record.revision,
6945
+ collectedSummary,
6946
+ pendingConfirm: session.getPendingProposals(),
6947
+ dictionaries: session.dictionaries.allStates(),
6948
+ readiness,
6949
+ plan,
6950
+ activeContextSlice: (0, slicer_1.buildActiveContextSlice)(record.schema, session.core.fields, { locale: record.locale }),
6951
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, record.locale),
6952
+ finalSubmission: record.finalSubmission || null
6953
+ };
6954
+ }
6955
+ async function intakeFinalize(input) {
6956
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
6957
+ const { core, session } = await hydrateRuntime(record, NOOP_ADAPTER);
6958
+ if (input.manualValues && typeof input.manualValues === "object") {
6959
+ for (const [k, v] of Object.entries(input.manualValues)) {
6960
+ if (core.fields[k]) {
6961
+ session.manualEdit(k, v);
6962
+ }
6963
+ }
6964
+ }
6965
+ const readiness = session.inspectReadiness();
6966
+ const coreOk = core.validateAll();
6967
+ if (!readiness.complete || !coreOk) {
6968
+ const savedPartial = snapshotRecordFromRuntime(record, core, session);
6969
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), savedPartial);
6970
+ return {
6971
+ status: "blocked",
6972
+ sessionId: record.sessionId,
6973
+ sessionStatus: savedPartial.status,
6974
+ reason: readiness.nextPrompt,
6975
+ readiness,
6976
+ nextQuestionForUser: buildAgentQuestion(session.getFillPlan(), readiness, record.locale)
6977
+ };
6978
+ }
6979
+ const data = core.collectFormData({ skipVerify: true });
6980
+ const submissionId = `sub_${Date.now().toString(36)}_${node_crypto_1.default.randomBytes(3).toString("hex")}`;
6981
+ const finalSubmission = {
6982
+ submissionId,
6983
+ submittedAt: (/* @__PURE__ */ new Date()).toISOString(),
6984
+ storageKey: record.schema.storageKey || "",
6985
+ schemaVersion: record.schema.version || "1.0.0",
6986
+ data
6987
+ };
6988
+ const saved = snapshotRecordFromRuntime(record, core, session, {
6989
+ status: "finalized",
6990
+ finalSubmission
6991
+ });
6992
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), saved);
6993
+ const plan = session.getFillPlan();
6994
+ return {
6995
+ status: "finalized",
6996
+ sessionId: record.sessionId,
6997
+ sessionStatus: "finalized",
6998
+ submission: finalSubmission,
6999
+ readableSummary: plan.crystallizedFields.map((f) => ({
7000
+ key: f.key,
7001
+ label: f.label,
7002
+ displayValue: f.isPii ? f.maskedDisplayValue : f.displayValue
7003
+ }))
7004
+ };
7005
+ }
7006
+ function loadIntakeRecordRaw(sessionId, dataDir) {
7007
+ return loadPersistedRecord(sessionId, dataDir);
7008
+ }
7009
+ function saveIntakeRecordRaw(record, dataDir) {
7010
+ writeJsonAtomic(sessionFilePath(record.sessionId, dataDir), record);
7011
+ }
7012
+ }
7013
+ });
7014
+
4627
7015
  // packages/form-agent/src/v2Core.cjs
4628
7016
  var require_v2Core = __commonJS({
4629
7017
  "packages/form-agent/src/v2Core.cjs"(exports2, module2) {
4630
7018
  "use strict";
4631
7019
  var fs = require("node:fs");
7020
+ var os2 = require("node:os");
4632
7021
  var path2 = require("node:path");
4633
7022
  var crypto = require("node:crypto");
4634
7023
  var { FormCore } = require_dist();
@@ -4648,6 +7037,7 @@ var require_v2Core = __commonJS({
4648
7037
  buildSubmissionEnvelope
4649
7038
  } = require_dataContract();
4650
7039
  var dataHub = require_dataHubStore();
7040
+ var intake = require_intakeManager();
4651
7041
  var VALID_SKINS = ["fin-minimal", "clean-outline", "bank-card", "tdesign"];
4652
7042
  var VALID_MODES = ["flat", "collapsible", "step"];
4653
7043
  var VALID_DENSITIES = ["comfortable", "compact"];
@@ -5025,7 +7415,18 @@ var require_v2Core = __commonJS({
5025
7415
  function escapeInlineScript(text) {
5026
7416
  return String(text).replace(/<\/(script)/gi, "<\\/$1");
5027
7417
  }
5028
- function renderStandaloneHtml({ schema, themeConfig, mode, locale, assetsDir }) {
7418
+ function normalizeSubmitUrl(raw) {
7419
+ if (raw === void 0 || raw === null) return "";
7420
+ const trimmed = String(raw).trim();
7421
+ if (!trimmed) return "";
7422
+ if (!/^https?:\/\//i.test(trimmed)) {
7423
+ throw Object.assign(new Error(`\u65E0\u6548\u7684 submitUrl\uFF1A${trimmed}\uFF08\u4EC5\u652F\u6301 http:// \u6216 https:// \u5730\u5740\uFF09`), {
7424
+ code: "INVALID_ARGUMENT"
7425
+ });
7426
+ }
7427
+ return trimmed;
7428
+ }
7429
+ function renderStandaloneHtml({ schema, themeConfig, mode, locale, submitUrl, assetsDir }) {
5029
7430
  const normalizedTheme = themeConfig ? { ...themeConfig } : { version: "1.0.0", skin: "fin-minimal", override: {}, formMode: "flat", showProgressBar: true };
5030
7431
  const effectiveMode = mode === "final" || normalizedTheme.mode === "final" ? "final" : "preview";
5031
7432
  if (effectiveMode === "final") {
@@ -5035,6 +7436,7 @@ var require_v2Core = __commonJS({
5035
7436
  if (locale !== void 0 || normalizedTheme.locale) {
5036
7437
  normalizedTheme.locale = effectiveLocale;
5037
7438
  }
7439
+ const effectiveSubmitUrl = normalizeSubmitUrl(submitUrl);
5038
7440
  const jsPath = path2.join(assetsDir, "modern-preview.iife.js");
5039
7441
  const cssPath = path2.join(assetsDir, "modern-preview.css");
5040
7442
  if (!fs.existsSync(jsPath) || !fs.existsSync(cssPath)) {
@@ -5046,6 +7448,8 @@ var require_v2Core = __commonJS({
5046
7448
  const cssCode = fs.readFileSync(cssPath, "utf8");
5047
7449
  const safeTitle = String(schema.title || (effectiveLocale === "en-US" ? "FormSchema Live Preview" : "FormSchema \u5B9E\u65F6\u9884\u89C8")).replace(/[<>&"]/g, "");
5048
7450
  const pageTitle = effectiveMode === "final" ? safeTitle : `${safeTitle} \xB7 FormSchema Preview`;
7451
+ const submitUrlScriptLine = effectiveSubmitUrl ? `
7452
+ window.__AGENT_SUBMIT_URL__ = ${escapeInlineScript(JSON.stringify(effectiveSubmitUrl))};` : "";
5049
7453
  const html = `<!DOCTYPE html>
5050
7454
  <html lang="${effectiveLocale}">
5051
7455
  <head>
@@ -5057,7 +7461,7 @@ var require_v2Core = __commonJS({
5057
7461
  <body>
5058
7462
  <div id="app"></div>
5059
7463
  <script>
5060
- window.__AGENT_PREVIEW_MODE__ = ${JSON.stringify(effectiveMode)};
7464
+ window.__AGENT_PREVIEW_MODE__ = ${JSON.stringify(effectiveMode)};${submitUrlScriptLine}
5061
7465
  window.__AGENT_FORM_SCHEMA__ = ${escapeInlineScript(JSON.stringify(schema))};
5062
7466
  window.__AGENT_THEME_CONFIG__ = ${escapeInlineScript(JSON.stringify(normalizedTheme))};
5063
7467
  </script>
@@ -5065,16 +7469,22 @@ var require_v2Core = __commonJS({
5065
7469
  </body>
5066
7470
  </html>
5067
7471
  `;
5068
- return { html, mode: effectiveMode, locale: effectiveLocale };
7472
+ return { html, mode: effectiveMode, locale: effectiveLocale, submitUrl: effectiveSubmitUrl || null };
5069
7473
  }
5070
- function previewExportHtml({ schemaPath, themePath, out, mode, locale, assetsDir }) {
7474
+ function previewExportHtml({ schemaPath, themePath, out, mode, locale, submitUrl, assetsDir }) {
5071
7475
  const schema = normalizeSchemaEnvelope(readJsonFile(schemaPath, "FormSchema \u6587\u4EF6"));
5072
7476
  const themeConfig = themePath ? readJsonFile(themePath, "ThemeConfigJson \u6587\u4EF6") : { version: "1.0.0", skin: "fin-minimal", override: {}, formMode: "flat", showProgressBar: true };
5073
- const { html, mode: effectiveMode, locale: effectiveLocale } = renderStandaloneHtml({
7477
+ const {
7478
+ html,
7479
+ mode: effectiveMode,
7480
+ locale: effectiveLocale,
7481
+ submitUrl: effectiveSubmitUrl
7482
+ } = renderStandaloneHtml({
5074
7483
  schema,
5075
7484
  themeConfig,
5076
7485
  mode,
5077
7486
  locale,
7487
+ submitUrl,
5078
7488
  assetsDir
5079
7489
  });
5080
7490
  const absOut = path2.resolve(out);
@@ -5085,6 +7495,7 @@ var require_v2Core = __commonJS({
5085
7495
  status: "exported",
5086
7496
  mode: effectiveMode,
5087
7497
  locale: effectiveLocale,
7498
+ submitUrl: effectiveSubmitUrl,
5088
7499
  path: absOut,
5089
7500
  sizeKb,
5090
7501
  fileUrl: `file://${absOut}`
@@ -5150,8 +7561,10 @@ module.exports = ${JSON.stringify(payload, null, 2)}
5150
7561
  outDir,
5151
7562
  keyStyle = "snake_case",
5152
7563
  includeHtml = true,
7564
+ submitUrl,
5153
7565
  assetsDir
5154
7566
  }) {
7567
+ const effectiveSubmitUrl = normalizeSubmitUrl(submitUrl);
5155
7568
  const schema = normalizeSchemaEnvelope(readJsonFile(schemaPath, "FormSchema \u6587\u4EF6"));
5156
7569
  const governance = validateFormSchemaGovernance(schema);
5157
7570
  if (!governance.valid) {
@@ -5189,7 +7602,7 @@ module.exports = ${JSON.stringify(payload, null, 2)}
5189
7602
  let finalHtmlOut = null;
5190
7603
  let finalHtmlSizeKb = null;
5191
7604
  if (includeHtml !== false && assetsDir) {
5192
- const { html } = renderStandaloneHtml({ schema, themeConfig, mode: "final", assetsDir });
7605
+ const { html } = renderStandaloneHtml({ schema, themeConfig, mode: "final", submitUrl: effectiveSubmitUrl, assetsDir });
5193
7606
  finalHtmlOut = path2.join(absDir, "final.html");
5194
7607
  fs.writeFileSync(finalHtmlOut, html, "utf8");
5195
7608
  finalHtmlSizeKb = Math.round(fs.statSync(finalHtmlOut).size / 1024);
@@ -5206,6 +7619,7 @@ module.exports = ${JSON.stringify(payload, null, 2)}
5206
7619
  piiFields: contract.piiSummary.map((p) => p.key),
5207
7620
  governanceValid: governance.valid,
5208
7621
  presetAuditCount: auditFieldPresetCoverage(schema).length,
7622
+ ...effectiveSubmitUrl ? { submitUrl: effectiveSubmitUrl } : {},
5209
7623
  artifacts: {
5210
7624
  schema: { file: "form.schema.json", sha256: sha256(schemaOut) },
5211
7625
  theme: { file: "theme.config.json", sha256: sha256(themeOut) },
@@ -5277,22 +7691,148 @@ module.exports = ${JSON.stringify(payload, null, 2)}
5277
7691
  if (!name.endsWith("Form")) name += "Form";
5278
7692
  return name;
5279
7693
  }
7694
+ function tryReadJsonSafe(filePath) {
7695
+ try {
7696
+ if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) return null;
7697
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
7698
+ } catch (_) {
7699
+ return null;
7700
+ }
7701
+ }
7702
+ function findNearestExistingDir(targetPath) {
7703
+ let cur = path2.resolve(targetPath || process.cwd());
7704
+ for (let i = 0; i < 12; i++) {
7705
+ try {
7706
+ if (fs.existsSync(cur)) {
7707
+ return fs.statSync(cur).isDirectory() ? cur : path2.dirname(cur);
7708
+ }
7709
+ } catch (_) {
7710
+ }
7711
+ const parent = path2.dirname(cur);
7712
+ if (parent === cur) break;
7713
+ cur = parent;
7714
+ }
7715
+ return process.cwd();
7716
+ }
7717
+ function detectHostEnvironment({ projectDir, outDir } = {}) {
7718
+ const startDir = findNearestExistingDir(projectDir || outDir || process.cwd());
7719
+ const homeDir = path2.resolve(os2.homedir());
7720
+ const tmpDirs = /* @__PURE__ */ new Set([path2.resolve(os2.tmpdir())]);
7721
+ try {
7722
+ tmpDirs.add(fs.realpathSync(os2.tmpdir()));
7723
+ } catch (_) {
7724
+ }
7725
+ let cur = startDir;
7726
+ for (let depth = 0; depth < 6; depth++) {
7727
+ if (depth > 0 && (cur === homeDir || tmpDirs.has(cur))) break;
7728
+ const wxProj = tryReadJsonSafe(path2.join(cur, "project.config.json"));
7729
+ if (wxProj && (wxProj.appid !== void 0 || wxProj.miniprogramRoot !== void 0 || wxProj.compileType === "miniprogram")) {
7730
+ return {
7731
+ resolvedPlatform: "miniapp",
7732
+ confidence: "high",
7733
+ projectRoot: cur,
7734
+ signals: ["project.config.json"],
7735
+ summary: "Detected WeChat Miniapp project via project.config.json"
7736
+ };
7737
+ }
7738
+ const wxApp = tryReadJsonSafe(path2.join(cur, "app.json"));
7739
+ if (wxApp && Array.isArray(wxApp.pages)) {
7740
+ return {
7741
+ resolvedPlatform: "miniapp",
7742
+ confidence: "high",
7743
+ projectRoot: cur,
7744
+ signals: ["app.json(pages)"],
7745
+ summary: "Detected WeChat Miniapp project via app.json"
7746
+ };
7747
+ }
7748
+ const pkg = tryReadJsonSafe(path2.join(cur, "package.json"));
7749
+ if (pkg && typeof pkg === "object") {
7750
+ const deps = { ...pkg.dependencies || {}, ...pkg.devDependencies || {} };
7751
+ const hasVue = Boolean(deps.vue || deps.nuxt || deps["@vitejs/plugin-vue"]);
7752
+ const hasReact = Boolean(deps.react || deps["react-dom"] || deps.next || deps["@vitejs/plugin-react"]);
7753
+ if (hasVue && !hasReact) {
7754
+ const signals = ["package.json", deps.nuxt ? "dep:nuxt" : "dep:vue"];
7755
+ return {
7756
+ resolvedPlatform: "vue3",
7757
+ confidence: "high",
7758
+ projectRoot: cur,
7759
+ signals,
7760
+ summary: `Detected Vue 3 host project (${signals.join(", ")})`
7761
+ };
7762
+ }
7763
+ if (hasReact && !hasVue) {
7764
+ const signals = ["package.json", deps.next ? "dep:next" : "dep:react"];
7765
+ return {
7766
+ resolvedPlatform: "react18",
7767
+ confidence: "high",
7768
+ projectRoot: cur,
7769
+ signals,
7770
+ summary: `Detected React 18 host project (${signals.join(", ")})`
7771
+ };
7772
+ }
7773
+ if (hasVue && hasReact) {
7774
+ if (fs.existsSync(path2.join(cur, "src/App.vue"))) {
7775
+ return {
7776
+ resolvedPlatform: "vue3",
7777
+ confidence: "high",
7778
+ projectRoot: cur,
7779
+ signals: ["package.json", "src/App.vue"],
7780
+ summary: "Detected Vue 3 host project via src/App.vue"
7781
+ };
7782
+ }
7783
+ if (fs.existsSync(path2.join(cur, "src/App.tsx")) || fs.existsSync(path2.join(cur, "src/App.jsx"))) {
7784
+ return {
7785
+ resolvedPlatform: "react18",
7786
+ confidence: "high",
7787
+ projectRoot: cur,
7788
+ signals: ["package.json", "src/App.tsx"],
7789
+ summary: "Detected React 18 host project via src/App.tsx"
7790
+ };
7791
+ }
7792
+ }
7793
+ }
7794
+ const parent = path2.dirname(cur);
7795
+ if (parent === cur) break;
7796
+ cur = parent;
7797
+ }
7798
+ return {
7799
+ resolvedPlatform: "standalone",
7800
+ confidence: "fallback",
7801
+ projectRoot: startDir,
7802
+ signals: ["no-frontend-framework-detected"],
7803
+ summary: "No Vue/React/Miniapp host detected \u2014 delivering zero-dependency standalone HTML bundle"
7804
+ };
7805
+ }
5280
7806
  function scaffoldHost({
5281
7807
  schemaPath,
5282
7808
  themePath,
5283
- platform,
7809
+ platform = "auto",
5284
7810
  outDir,
7811
+ projectDir,
5285
7812
  componentName,
5286
7813
  keyStyle = "snake_case",
5287
- packageScope = "@agentprismform"
7814
+ packageScope = "@agentprismform",
7815
+ submitUrl,
7816
+ assetsDir
5288
7817
  }) {
5289
- const VALID_PLATFORMS = ["vue3", "react18", "miniapp", "headless"];
5290
- if (!VALID_PLATFORMS.includes(platform)) {
7818
+ const VALID_PLATFORMS = ["auto", "vue3", "react18", "miniapp", "standalone", "headless"];
7819
+ const requestedPlatform = platform || "auto";
7820
+ if (!VALID_PLATFORMS.includes(requestedPlatform)) {
5291
7821
  throw Object.assign(
5292
- new Error(`\u4E0D\u652F\u6301\u7684\u76EE\u6807\u5E73\u53F0\uFF1A${platform}\uFF08\u53EF\u9009\uFF1A${VALID_PLATFORMS.join(", ")}\uFF09`),
7822
+ new Error(`\u4E0D\u652F\u6301\u7684\u76EE\u6807\u5E73\u53F0\uFF1A${requestedPlatform}\uFF08\u53EF\u9009\uFF1A${VALID_PLATFORMS.join(", ")}\uFF09`),
5293
7823
  { code: "INVALID_ARGUMENT" }
5294
7824
  );
5295
7825
  }
7826
+ const effectiveSubmitUrl = normalizeSubmitUrl(submitUrl);
7827
+ const detection = requestedPlatform === "auto" ? { requestedPlatform: "auto", ...detectHostEnvironment({ projectDir, outDir }) } : {
7828
+ requestedPlatform,
7829
+ resolvedPlatform: requestedPlatform,
7830
+ confidence: "explicit",
7831
+ projectRoot: findNearestExistingDir(projectDir || outDir || process.cwd()),
7832
+ signals: ["explicit-platform"],
7833
+ summary: `Explicit platform requested: ${requestedPlatform}`
7834
+ };
7835
+ const resolvedPlatform = detection.resolvedPlatform;
5296
7836
  const schema = normalizeSchemaEnvelope(readJsonFile(schemaPath, "FormSchema \u6587\u4EF6"));
5297
7837
  const rawTheme = themePath ? readJsonFile(themePath, "ThemeConfigJson \u6587\u4EF6") : { version: "1.0.0", skin: "fin-minimal", override: {}, formMode: "flat", showProgressBar: true };
5298
7838
  const themeConfig = { ...rawTheme, mode: "final" };
@@ -5306,7 +7846,8 @@ module.exports = ${JSON.stringify(payload, null, 2)}
5306
7846
  format: "agentprismform-mobile-bundle/v1",
5307
7847
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
5308
7848
  schema,
5309
- themeConfig
7849
+ themeConfig,
7850
+ ...effectiveSubmitUrl ? { submitUrl: effectiveSubmitUrl } : {}
5310
7851
  };
5311
7852
  const bundleOut = writeJsonAtomic(path2.join(absDir, "form.bundle.json"), bundle, { overwrite: true });
5312
7853
  const typesOut = path2.join(absDir, "types.d.ts");
@@ -5315,7 +7856,7 @@ module.exports = ${JSON.stringify(payload, null, 2)}
5315
7856
  let packages = [];
5316
7857
  let entryFile = "";
5317
7858
  let mountSnippet = "";
5318
- if (platform === "vue3") {
7859
+ if (resolvedPlatform === "vue3") {
5319
7860
  packages = [`${scope}/render-vue`];
5320
7861
  entryFile = path2.join(absDir, `${compName}.vue`);
5321
7862
  const vueCode = `<script setup lang="ts">
@@ -5360,7 +7901,7 @@ const emit = defineEmits<{
5360
7901
  fs.writeFileSync(entryFile, vueCode, "utf8");
5361
7902
  files.component = entryFile;
5362
7903
  mountSnippet = `<${compName} :host-handlers="hostHandlers" :custom-controls="{}" @submit="handleSubmit" />`;
5363
- } else if (platform === "react18") {
7904
+ } else if (resolvedPlatform === "react18") {
5364
7905
  packages = [`${scope}/render-web`];
5365
7906
  entryFile = path2.join(absDir, `${compName}.tsx`);
5366
7907
  const reactCode = `import React from 'react'
@@ -5406,7 +7947,7 @@ export function ${compName}({
5406
7947
  fs.writeFileSync(entryFile, reactCode, "utf8");
5407
7948
  files.component = entryFile;
5408
7949
  mountSnippet = `<${compName} hostHandlers={hostHandlers} customControls={{}} onSubmit={handleSubmit} />`;
5409
- } else if (platform === "headless") {
7950
+ } else if (resolvedPlatform === "headless") {
5410
7951
  packages = [`${scope}/core`, `${scope}/render`];
5411
7952
  entryFile = path2.join(absDir, `${compName}.tsx`);
5412
7953
  const headlessCode = `import React, { useEffect, useRef, useState } from 'react'
@@ -5492,8 +8033,23 @@ export function ${compName}({ onSubmit }: ${compName}Props) {
5492
8033
  fs.writeFileSync(entryFile, headlessCode, "utf8");
5493
8034
  files.component = entryFile;
5494
8035
  mountSnippet = `<${compName} onSubmit={handleSubmit} />`;
8036
+ } else if (resolvedPlatform === "standalone") {
8037
+ packages = [];
8038
+ const resolvedAssetsDir = assetsDir || path2.resolve(__dirname, "../preview");
8039
+ const { html } = renderStandaloneHtml({
8040
+ schema,
8041
+ themeConfig,
8042
+ mode: "final",
8043
+ submitUrl: effectiveSubmitUrl,
8044
+ assetsDir: resolvedAssetsDir
8045
+ });
8046
+ entryFile = path2.join(absDir, "index.html");
8047
+ fs.writeFileSync(entryFile, html, "utf8");
8048
+ files.html = entryFile;
8049
+ mountSnippet = effectiveSubmitUrl ? `# Deploy index.html to any static host (Cloudflare Pages / Vercel / Nginx / OSS)
8050
+ # Submissions POST JSON with Idempotency-Key -> ${effectiveSubmitUrl}` : `# Open index.html directly in any browser, or deploy to Cloudflare Pages / Vercel / Nginx / OSS (zero backend required)`;
5495
8051
  } else {
5496
- packages = [`${scope}/core`, `${scope}/render`, `${scope}/render-miniapp`];
8052
+ packages = [`${scope}/render-miniapp`];
5497
8053
  const dataFile = path2.join(absDir, "preview-data.js");
5498
8054
  const jsonFile = path2.join(absDir, "index.json");
5499
8055
  const wxmlFile = path2.join(absDir, "index.wxml");
@@ -5523,6 +8079,7 @@ export function ${compName}({ onSubmit }: ${compName}Props) {
5523
8079
  `,
5524
8080
  "utf8"
5525
8081
  );
8082
+ const defaultMiniappUrl = effectiveSubmitUrl || "https://api.example.com/forms/submit";
5526
8083
  fs.writeFileSync(
5527
8084
  jsFile,
5528
8085
  `const bundle = require('./preview-data.js')
@@ -5535,7 +8092,7 @@ Page({
5535
8092
  onFormSubmit(ev) {
5536
8093
  this.setData({ submitting: true })
5537
8094
  wx.request({
5538
- url: (this.data.schema && this.data.schema.submitApi) || 'https://api.example.com/forms/submit',
8095
+ url: bundle.submitUrl || (this.data.schema && this.data.schema.submitApi) || ${JSON.stringify(defaultMiniappUrl)},
5539
8096
  method: 'POST',
5540
8097
  header: { 'Idempotency-Key': 'wx_' + Date.now() },
5541
8098
  data: ev.detail,
@@ -5553,14 +8110,19 @@ Page({
5553
8110
  files.pageJs = jsFile;
5554
8111
  mountSnippet = `// Register "${path2.basename(absDir)}/index" inside WeChat Miniapp app.json -> "pages"`;
5555
8112
  }
5556
- const localInstallCmd = "npm install --install-links " + packages.map((p) => `<path-to-AgentPrismForm>/packages/${p.split("/")[1]}`).join(" ");
5557
- const npmInstallCmd = `npm install ${packages.join(" ")}`;
5558
- const integrationDoc = path2.join(absDir, "INTEGRATION.md");
5559
- fs.writeFileSync(
5560
- integrationDoc,
5561
- `# ${compName} Integration Guide / \u63A5\u5165\u6307\u5357
8113
+ const localInstallCmd = packages.length ? "npm install --install-links " + packages.map((p) => `<path-to-AgentPrismForm>/packages/${p.split("/")[1]}`).join(" ") : "";
8114
+ const npmInstallCmd = packages.length ? `npm install ${packages.join(" ")}` : "";
8115
+ const submitNote = effectiveSubmitUrl ? `
8116
+ ## Submit Endpoint / \u63D0\u4EA4\u63A5\u53E3\u51FA\u53E3
8117
+
8118
+ Configured \`submitUrl\`: \`${effectiveSubmitUrl}\`
5562
8119
 
5563
- ## 1. Install Required Packages / \u5B89\u88C5\u4F9D\u8D56\u5305
8120
+ Payload envelope sent via \`POST\` (with \`Idempotency-Key\` header):
8121
+ \`\`\`json
8122
+ { "submissionId": "sub_...", "schemaVersion": "1.0.0", "storageKey": "${schema.storageKey || ""}", "submittedAt": "...", "channel": "web-mobile", "data": { ... } }
8123
+ \`\`\`
8124
+ ` : "";
8125
+ const installSection = packages.length ? `## 1. Install Required Packages / \u5B89\u88C5\u4F9D\u8D56\u5305
5564
8126
 
5565
8127
  **Option A \u2014 From npm registry / \u4ECE npm \u5B98\u65B9\u6E90\u76F4\u63A5\u5B89\u88C5\uFF08\u63A8\u8350\uFF09:**
5566
8128
  \`\`\`bash
@@ -5571,24 +8133,37 @@ ${npmInstallCmd}
5571
8133
  \`\`\`bash
5572
8134
  ${localInstallCmd}
5573
8135
  \`\`\`
8136
+ ` : `## 1. Zero-Dependency Standalone Delivery / \u96F6\u4F9D\u8D56\u72EC\u7ACB\u4EA4\u4ED8
8137
+
8138
+ No npm packages or build step required. \`index.html\` is a self-contained zero-chrome deliverable ready for any static host (Cloudflare Pages, Vercel, GitHub Pages, Nginx, or OSS).
8139
+ `;
8140
+ const integrationDoc = path2.join(absDir, "INTEGRATION.md");
8141
+ fs.writeFileSync(
8142
+ integrationDoc,
8143
+ `# ${compName} Integration Guide / \u63A5\u5165\u6307\u5357
8144
+
8145
+ > **Resolved Delivery Target**: \`${resolvedPlatform}\` (${detection.summary})
5574
8146
 
5575
- ## 2. Mount in Your App / \u5728\u4E1A\u52A1\u9875\u9762\u6302\u8F7D
8147
+ ${installSection}
8148
+ ## 2. Mount or Deploy / \u6302\u8F7D\u6216\u90E8\u7F72
5576
8149
 
5577
8150
  \`\`\`tsx
5578
8151
  ${mountSnippet}
5579
8152
  \`\`\`
5580
-
8153
+ ${submitNote}
5581
8154
  ## 3. Files Generated / \u751F\u6210\u6587\u4EF6\u6E05\u5355
5582
8155
  - \`form.bundle.json\` \u2014 Finalized FormSchema + locked ThemeConfig
5583
8156
  - \`types.d.ts\` \u2014 TypeScript DTO derived from FormSchema
5584
- - \`${path2.basename(entryFile)}\` \u2014 Ready-to-run ${platform} page/component (supports \`hostHandlers\` & \`customControls\`)
8157
+ - \`${path2.basename(entryFile)}\` \u2014 Ready-to-run ${resolvedPlatform} deliverable
5585
8158
  `,
5586
8159
  "utf8"
5587
8160
  );
5588
8161
  files.integrationGuide = integrationDoc;
5589
8162
  return {
5590
8163
  status: "scaffolded",
5591
- platform,
8164
+ platform: resolvedPlatform,
8165
+ detection,
8166
+ submitUrl: effectiveSubmitUrl || null,
5592
8167
  componentName: compName,
5593
8168
  outDir: absDir,
5594
8169
  packages,
@@ -5599,6 +8174,7 @@ ${mountSnippet}
5599
8174
  }
5600
8175
  module2.exports = {
5601
8176
  listSnippetsAndPresets,
8177
+ detectHostEnvironment,
5602
8178
  schemaInit,
5603
8179
  schemaSet,
5604
8180
  schemaPatch,
@@ -5619,7 +8195,12 @@ ${mountSnippet}
5619
8195
  hubIngest: dataHub.ingestSubmission,
5620
8196
  hubQuery: dataHub.querySubmissions,
5621
8197
  hubExportCsv: dataHub.exportInboxCsv,
5622
- hubWebhook: dataHub.deliverWebhook
8198
+ hubWebhook: dataHub.deliverWebhook,
8199
+ intakeStart: intake.intakeStart,
8200
+ intakeTurn: intake.intakeSubmitTurn,
8201
+ intakeConfirm: intake.intakeConfirm,
8202
+ intakeStatus: intake.intakeStatus,
8203
+ intakeFinalize: intake.intakeFinalize
5623
8204
  };
5624
8205
  }
5625
8206
  });
@@ -5951,7 +8532,7 @@ data: ${JSON.stringify({
5951
8532
  }
5952
8533
  });
5953
8534
 
5954
- // output/oss-release/agentprismform-1.0.0-stage/packages/agent-plugin/.oss-cli-entry.cjs
8535
+ // output/oss-release/agentprismform-2.0.0-stage/packages/agent-plugin/.oss-cli-entry.cjs
5955
8536
  var path = require("node:path");
5956
8537
  var os = require("node:os");
5957
8538
  var { spawnSync } = require("node:child_process");
@@ -5977,7 +8558,7 @@ var commands = {
5977
8558
  "preview-miniapp": ["--schema", "--miniapp-project"],
5978
8559
  "schema-export": ["--schema", "--out"],
5979
8560
  "release-export": ["--schema", "--out-dir"],
5980
- "scaffold-host": ["--schema", "--platform", "--out-dir"],
8561
+ "scaffold-host": ["--schema", "--out-dir"],
5981
8562
  "schema-contract": ["--schema"],
5982
8563
  "contract-verify": ["--schema", "--target"],
5983
8564
  "payload-map": ["--schema", "--data"],
@@ -5985,6 +8566,11 @@ var commands = {
5985
8566
  "hub-query": [],
5986
8567
  "hub-export-csv": ["--form-key", "--out"],
5987
8568
  "hub-webhook": ["--schema", "--data", "--url"],
8569
+ "intake-start": ["--schema"],
8570
+ "intake-turn": ["--session"],
8571
+ "intake-confirm": ["--session"],
8572
+ "intake-status": ["--session"],
8573
+ "intake-finalize": ["--session"],
5988
8574
  serve: []
5989
8575
  };
5990
8576
  function parse(argv) {
@@ -6005,7 +8591,7 @@ async function run() {
6005
8591
  const assetsDir = path.resolve(flags["--assets-dir"] || path.join(__dirname, "../preview"));
6006
8592
  let result;
6007
8593
  if (command === "describe") {
6008
- result = { name: "@agentprismform/agent-plugin", version: "1.3.1", protocolVersion, v2Supported: true, v2Loop: Object.keys(commands) };
8594
+ result = { name: "@agentprismform/agent-plugin", version: "2.0.0", protocolVersion, v2Supported: true, v2Loop: Object.keys(commands) };
6009
8595
  } else if (command === "snippets") {
6010
8596
  result = v2.listSnippetsAndPresets();
6011
8597
  } else if (command === "schema-init") {
@@ -6039,7 +8625,7 @@ async function run() {
6039
8625
  } else if (command === "preview-register") {
6040
8626
  result = v2.registerV2Preview({ schemaPath: flags["--schema"], themePath: flags["--theme"], dataDir });
6041
8627
  } else if (command === "preview-html") {
6042
- result = v2.previewExportHtml({ schemaPath: flags["--schema"], themePath: flags["--theme"], out: flags["--out"], mode: flags["--mode"], locale: flags["--locale"], assetsDir });
8628
+ result = v2.previewExportHtml({ schemaPath: flags["--schema"], themePath: flags["--theme"], out: flags["--out"], mode: flags["--mode"], locale: flags["--locale"], submitUrl: flags["--submit-url"], assetsDir });
6043
8629
  } else if (command === "preview-miniapp") {
6044
8630
  result = v2.previewSyncMiniapp({ schemaPath: flags["--schema"], themePath: flags["--theme"], miniappProject: flags["--miniapp-project"] });
6045
8631
  } else if (command === "schema-export") {
@@ -6052,17 +8638,21 @@ async function run() {
6052
8638
  outDir: flags["--out-dir"],
6053
8639
  keyStyle: flags["--key-style"] || "snake_case",
6054
8640
  includeHtml: flags["--include-html"] === void 0 ? true : flags["--include-html"] !== "false",
8641
+ submitUrl: flags["--submit-url"],
6055
8642
  assetsDir
6056
8643
  });
6057
8644
  } else if (command === "scaffold-host") {
6058
8645
  result = v2.scaffoldHost({
6059
8646
  schemaPath: flags["--schema"],
6060
8647
  themePath: flags["--theme"],
6061
- platform: flags["--platform"],
8648
+ platform: flags["--platform"] || "auto",
6062
8649
  outDir: flags["--out-dir"],
8650
+ projectDir: flags["--project-dir"],
6063
8651
  componentName: flags["--component-name"],
6064
8652
  keyStyle: flags["--key-style"] || "snake_case",
6065
- packageScope: flags["--scope"] || "@agentprismform"
8653
+ packageScope: flags["--scope"] || "@agentprismform",
8654
+ submitUrl: flags["--submit-url"],
8655
+ assetsDir
6066
8656
  });
6067
8657
  } else if (command === "schema-contract") {
6068
8658
  result = v2.schemaContract({ schemaPath: flags["--schema"], keyStyle: flags["--key-style"], out: flags["--out"] });
@@ -6125,6 +8715,50 @@ async function run() {
6125
8715
  dryRun: flags["--dry-run"] === void 0 ? true : flags["--dry-run"] !== "false",
6126
8716
  retries: flags["--retries"] !== void 0 ? Number(flags["--retries"]) : 2
6127
8717
  });
8718
+ } else if (command === "intake-start") {
8719
+ result = await v2.intakeStart({
8720
+ schemaPath: flags["--schema"],
8721
+ locale: flags["--locale"],
8722
+ mode: flags["--mode"],
8723
+ reviewCritical: flags["--review-critical"] === void 0 ? true : flags["--review-critical"] !== "false",
8724
+ protectOverwrite: flags["--protect-overwrite"] === void 0 ? true : flags["--protect-overwrite"] !== "false",
8725
+ sessionId: flags["--session-id"],
8726
+ dataDir
8727
+ });
8728
+ } else if (command === "intake-turn") {
8729
+ result = await v2.intakeTurn({
8730
+ sessionId: flags["--session"],
8731
+ text: flags["--text"],
8732
+ patch: flags["--patch"] ? JSON.parse(flags["--patch"]) : void 0,
8733
+ mentions: flags["--mentions"] ? JSON.parse(flags["--mentions"]) : void 0,
8734
+ imagePath: flags["--image"],
8735
+ useLocalSlm: flags["--use-local-slm"] === void 0 ? true : flags["--use-local-slm"] !== "false",
8736
+ model: flags["--model"],
8737
+ visionModel: flags["--vision-model"],
8738
+ ollamaUrl: flags["--ollama-url"],
8739
+ dataDir
8740
+ });
8741
+ } else if (command === "intake-confirm") {
8742
+ const fs = require("node:fs");
8743
+ result = await v2.intakeConfirm({
8744
+ sessionId: flags["--session"],
8745
+ confirmKeys: flags["--keys"] ? String(flags["--keys"]).split(",").map((s) => s.trim()).filter(Boolean) : void 0,
8746
+ rejectKeys: flags["--reject-keys"] ? String(flags["--reject-keys"]).split(",").map((s) => s.trim()).filter(Boolean) : void 0,
8747
+ dictionaryBundle: flags["--dictionary"] ? JSON.parse(fs.readFileSync(path.resolve(flags["--dictionary"]), "utf8")) : void 0,
8748
+ dataDir
8749
+ });
8750
+ } else if (command === "intake-status") {
8751
+ result = await v2.intakeStatus({
8752
+ sessionId: flags["--session"],
8753
+ maskPii: flags["--mask-pii"] === void 0 ? true : flags["--mask-pii"] !== "false",
8754
+ dataDir
8755
+ });
8756
+ } else if (command === "intake-finalize") {
8757
+ result = await v2.intakeFinalize({
8758
+ sessionId: flags["--session"],
8759
+ manualValues: flags["--manual"] ? JSON.parse(flags["--manual"]) : void 0,
8760
+ dataDir
8761
+ });
6128
8762
  } else if (command === "serve") {
6129
8763
  result = await startServer({ dataDir, port: Number(flags["--port"] || 0), assetsDir });
6130
8764
  }