@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.
@@ -16276,11 +16276,2400 @@ var require_dataHubStore = __commonJS({
16276
16276
  }
16277
16277
  });
16278
16278
 
16279
+ // packages/form-intent-fill/dist/slicer.js
16280
+ var require_slicer = __commonJS({
16281
+ "packages/form-intent-fill/dist/slicer.js"(exports2) {
16282
+ "use strict";
16283
+ Object.defineProperty(exports2, "__esModule", { value: true });
16284
+ exports2.isEmptyFieldValue = isEmptyFieldValue;
16285
+ exports2.extractStaticOptions = extractStaticOptions;
16286
+ exports2.classifyFieldPolicy = classifyFieldPolicy;
16287
+ exports2.classifyFieldRisk = classifyFieldRisk;
16288
+ exports2.collectSchemaItems = collectSchemaItems;
16289
+ exports2.buildActiveContextSlice = buildActiveContextSlice;
16290
+ exports2.compileIntentPrompt = compileIntentPrompt;
16291
+ exports2.buildSliceJsonSchema = buildSliceJsonSchema;
16292
+ var FORBIDDEN_TYPES = /* @__PURE__ */ new Set([
16293
+ "signature",
16294
+ "agreement",
16295
+ "imageUpload",
16296
+ "upload",
16297
+ "verifyCode",
16298
+ "task",
16299
+ "divider",
16300
+ "section",
16301
+ "html"
16302
+ ]);
16303
+ var MENTION_ONLY_TYPES = /* @__PURE__ */ new Set(["address", "search", "cascader"]);
16304
+ var CRITICAL_KEY_PATTERN = /(phone|mobile|tel|id_?card|identity|bank_?card|account_?no|email|salary|income|spouse_?id)/i;
16305
+ function isEmptyFieldValue(value) {
16306
+ if (value === null || value === void 0 || value === "")
16307
+ return true;
16308
+ if (Array.isArray(value))
16309
+ return value.length === 0;
16310
+ return false;
16311
+ }
16312
+ function extractStaticOptions(item) {
16313
+ const raw = item.initOptions || item.options || item.props?.options;
16314
+ if (!Array.isArray(raw) || raw.length === 0)
16315
+ return void 0;
16316
+ const out = [];
16317
+ for (const opt of raw) {
16318
+ if (!opt || typeof opt !== "object")
16319
+ continue;
16320
+ const code = String(opt.code ?? opt.value ?? "").trim();
16321
+ const name = String(opt.name ?? opt.label ?? code).trim();
16322
+ if (code)
16323
+ out.push({ code, name });
16324
+ }
16325
+ return out.length > 0 ? out : void 0;
16326
+ }
16327
+ function classifyFieldPolicy(item, dictionaryFields = /* @__PURE__ */ new Set()) {
16328
+ if (item.extractable === false)
16329
+ return "forbidden";
16330
+ if (FORBIDDEN_TYPES.has(item.type))
16331
+ return "forbidden";
16332
+ if (dictionaryFields.has(item.key))
16333
+ return "mention_only";
16334
+ if (MENTION_ONLY_TYPES.has(item.type))
16335
+ return "mention_only";
16336
+ if ((item.type === "select" || item.type === "radioGroup" || item.type === "checkboxGroup") && !extractStaticOptions(item)) {
16337
+ return "mention_only";
16338
+ }
16339
+ if (item.type === "list")
16340
+ return "forbidden";
16341
+ return "extractable";
16342
+ }
16343
+ function classifyFieldRisk(item, criticalFields = /* @__PURE__ */ new Set()) {
16344
+ if (item.risk === "CRITICAL" || criticalFields.has(item.key))
16345
+ return "CRITICAL";
16346
+ if (item.type === "phone")
16347
+ return "CRITICAL";
16348
+ if (CRITICAL_KEY_PATTERN.test(item.key))
16349
+ return "CRITICAL";
16350
+ return "NORMAL";
16351
+ }
16352
+ function collectSchemaItems(schema) {
16353
+ const out = [];
16354
+ for (const g of schema.groups || []) {
16355
+ for (const item of g.items || []) {
16356
+ out.push(item);
16357
+ }
16358
+ }
16359
+ return out;
16360
+ }
16361
+ function buildActiveContextSlice(schema, runtimeFields, options = {}) {
16362
+ const locale = options.locale === "en-US" ? "en-US" : "zh-CN";
16363
+ const dictSet = new Set(options.dictionaryFields || []);
16364
+ const critSet = new Set(options.criticalFields || []);
16365
+ const items = collectSchemaItems(schema);
16366
+ const visibleTriggerHints = /* @__PURE__ */ new Map();
16367
+ for (const item of items) {
16368
+ const f = runtimeFields[item.key];
16369
+ const isVis = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
16370
+ const isDis = Boolean(f?.disabled ?? item.disabled);
16371
+ if (!isVis || isDis)
16372
+ continue;
16373
+ for (const rel of item.relations || []) {
16374
+ if (rel && rel.target && rel.effect === "visible") {
16375
+ visibleTriggerHints.set(String(rel.target), `${item.label || item.key}(${item.key}): ${String(rel.logic || "")}`);
16376
+ }
16377
+ }
16378
+ }
16379
+ const extractableFields = [];
16380
+ const conditionalFields = [];
16381
+ const mentionFields = [];
16382
+ const forbiddenFields = [];
16383
+ for (const item of items) {
16384
+ const f = runtimeFields[item.key];
16385
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
16386
+ const disabled = Boolean(f?.disabled ?? item.disabled);
16387
+ const readonly = Boolean(item.readonly || item.readOnly);
16388
+ const policy = classifyFieldPolicy(item, dictSet);
16389
+ const risk = classifyFieldRisk(item, critSet);
16390
+ const currentValue = f !== void 0 ? f.value : item.defaultValue;
16391
+ const required = Boolean(f?.required ?? item.required);
16392
+ if (policy === "forbidden") {
16393
+ if (visible) {
16394
+ forbiddenFields.push({
16395
+ key: item.key,
16396
+ label: item.label || item.key,
16397
+ type: item.type,
16398
+ required,
16399
+ visible
16400
+ });
16401
+ }
16402
+ continue;
16403
+ }
16404
+ if (disabled || readonly)
16405
+ continue;
16406
+ const conditionallyReachable = !visible && visibleTriggerHints.has(item.key);
16407
+ if (!visible && !conditionallyReachable)
16408
+ continue;
16409
+ const sliceItem = {
16410
+ key: item.key,
16411
+ label: item.label || item.key,
16412
+ type: item.type,
16413
+ required,
16414
+ visible,
16415
+ conditionallyReachable,
16416
+ policy,
16417
+ risk,
16418
+ currentValue,
16419
+ hasValue: !isEmptyFieldValue(currentValue),
16420
+ placeholder: item.placeholder,
16421
+ help: item.help || item.description,
16422
+ options: extractStaticOptions(item),
16423
+ min: typeof item.props?.min === "number" ? item.props.min : void 0,
16424
+ max: typeof item.props?.max === "number" ? item.props.max : void 0,
16425
+ triggerHint: conditionallyReachable ? visibleTriggerHints.get(item.key) : void 0
16426
+ };
16427
+ if (policy === "mention_only") {
16428
+ if (visible)
16429
+ mentionFields.push(sliceItem);
16430
+ } else if (visible) {
16431
+ extractableFields.push(sliceItem);
16432
+ } else {
16433
+ conditionalFields.push(sliceItem);
16434
+ }
16435
+ }
16436
+ return {
16437
+ schemaTitle: schema.title || (locale === "en-US" ? "Form" : "\u8868\u5355"),
16438
+ storageKey: schema.storageKey || "",
16439
+ locale,
16440
+ extractableFields,
16441
+ conditionalFields,
16442
+ mentionFields,
16443
+ forbiddenFields
16444
+ };
16445
+ }
16446
+ function formatFieldLine(f, locale) {
16447
+ const isEn = locale === "en-US";
16448
+ 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";
16449
+ const optsStr = f.options ? (isEn ? " Options: " : " \u53EF\u9009\u4EE3\u7801\uFF1A") + f.options.map((o) => `${JSON.stringify(o.code)}=${o.name}`).join(isEn ? ", " : "\u3001") : "";
16450
+ const rangeStr = f.min !== void 0 || f.max !== void 0 ? isEn ? ` Range:[${f.min ?? ""},${f.max ?? ""}]` : ` \u8303\u56F4:[${f.min ?? ""},${f.max ?? ""}]` : "";
16451
+ const hintStr = f.help ? isEn ? ` Note: ${f.help}` : ` \u8BF4\u660E\uFF1A${f.help}` : "";
16452
+ const condStr = f.triggerHint ? isEn ? ` (Only if ${f.triggerHint})` : `\uFF08\u4EC5\u5F53 ${f.triggerHint} \u6EE1\u8DB3\u65F6\u8F93\u51FA\uFF09` : "";
16453
+ return `- ${f.key} (${f.label}, ${valType}${f.required ? isEn ? ", required" : ", \u5FC5\u586B" : ""})${optsStr}${rangeStr}${hintStr}${condStr}`;
16454
+ }
16455
+ function compileIntentPrompt(slice) {
16456
+ const isEn = slice.locale === "en-US";
16457
+ const lines = [
16458
+ ...slice.extractableFields.map((f) => formatFieldLine(f, slice.locale)),
16459
+ ...slice.conditionalFields.map((f) => formatFieldLine(f, slice.locale))
16460
+ ];
16461
+ 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`);
16462
+ const forbiddenKeys = slice.forbiddenFields.map((f) => f.key);
16463
+ if (isEn) {
16464
+ return [
16465
+ `Convert the user's utterance for "${slice.schemaTitle}" into a SPARSE JSON patch object (not the full form).`,
16466
+ "Only include keys explicitly stated by the user. Omit unmentioned keys completely. Never output null or empty strings.",
16467
+ "Available fields:",
16468
+ ...lines.length ? lines : ["- (none)"],
16469
+ ...mentionLines.length ? ["Verbatim mention fields (use <key>_raw only, never guess option/area codes):", ...mentionLines] : [],
16470
+ ...forbiddenKeys.length ? [`Forbidden keys (NEVER output): ${forbiddenKeys.join(", ")}`] : [],
16471
+ "Rules:",
16472
+ '- For option fields, output ONLY the exact option code string listed above (e.g., "team" not "Team").',
16473
+ '- For numeric/stepper/slider fields, output a JSON number (convert spoken words like "three" -> 3).',
16474
+ "- For boolean switch fields, output true or false.",
16475
+ "- Return ONE compact JSON object with no markdown or explanation. Return {} if nothing can be extracted."
16476
+ ].join("\n");
16477
+ }
16478
+ return [
16479
+ `\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`,
16480
+ "\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",
16481
+ "\u5F53\u524D\u53EF\u63D0\u53D6\u5B57\u6BB5\u4E0E\u53D6\u503C\uFF1A",
16482
+ ...lines.length ? lines : ["- \uFF08\u6682\u65E0\u53EF\u63D0\u53D6\u5B57\u6BB5\uFF09"],
16483
+ ...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] : [],
16484
+ ...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")}`] : [],
16485
+ "\u6267\u884C\u89C4\u5219\uFF1A",
16486
+ '- \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',
16487
+ "- \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",
16488
+ "- \u5F00\u5173\uFF08switch\uFF09\u5B57\u6BB5\u8F93\u51FA\u5E03\u5C14\u503C true \u6216 false\u3002",
16489
+ "- \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",
16490
+ "- \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"
16491
+ ].join("\n");
16492
+ }
16493
+ function buildSliceJsonSchema(slice) {
16494
+ const properties = {};
16495
+ const addExtractable = (f) => {
16496
+ if (f.type === "number" || f.type === "stepper" || f.type === "slider") {
16497
+ properties[f.key] = {
16498
+ type: "number",
16499
+ ...f.min !== void 0 ? { minimum: f.min } : {},
16500
+ ...f.max !== void 0 ? { maximum: f.max } : {}
16501
+ };
16502
+ return;
16503
+ }
16504
+ if (f.type === "switch") {
16505
+ properties[f.key] = { type: "boolean" };
16506
+ return;
16507
+ }
16508
+ if (f.type === "checkboxGroup") {
16509
+ properties[f.key] = {
16510
+ type: "array",
16511
+ items: f.options && f.options.length ? { type: "string", enum: f.options.map((o) => o.code) } : { type: "string" }
16512
+ };
16513
+ return;
16514
+ }
16515
+ if (f.options && f.options.length) {
16516
+ properties[f.key] = {
16517
+ type: "string",
16518
+ enum: f.options.map((o) => o.code)
16519
+ };
16520
+ return;
16521
+ }
16522
+ properties[f.key] = { type: "string" };
16523
+ };
16524
+ for (const f of slice.extractableFields)
16525
+ addExtractable(f);
16526
+ for (const f of slice.conditionalFields)
16527
+ addExtractable(f);
16528
+ for (const m of slice.mentionFields) {
16529
+ properties[`${m.key}_raw`] = { type: "string" };
16530
+ }
16531
+ return {
16532
+ type: "object",
16533
+ additionalProperties: false,
16534
+ properties
16535
+ };
16536
+ }
16537
+ }
16538
+ });
16539
+
16540
+ // packages/form-intent-fill/dist/adapters.js
16541
+ var require_adapters2 = __commonJS({
16542
+ "packages/form-intent-fill/dist/adapters.js"(exports2) {
16543
+ "use strict";
16544
+ Object.defineProperty(exports2, "__esModule", { value: true });
16545
+ exports2.normalizeBase64Image = normalizeBase64Image;
16546
+ exports2.parseJsonFromModelText = parseJsonFromModelText;
16547
+ exports2.sanitizeRawExtraction = sanitizeRawExtraction;
16548
+ exports2.createOllamaIntentAdapter = createOllamaIntentAdapter;
16549
+ exports2.createOpenAICompatibleIntentAdapter = createOpenAICompatibleIntentAdapter;
16550
+ exports2.createHttpIntentAdapter = createHttpIntentAdapter;
16551
+ exports2.createOnDeviceBridgeAdapter = createOnDeviceBridgeAdapter;
16552
+ var slicer_1 = require_slicer();
16553
+ function normalizeBase64Image(input, fallbackMime = "image/png") {
16554
+ const raw = String(input || "").trim();
16555
+ if (!raw) {
16556
+ throw new Error("\u56FE\u7247\u5185\u5BB9\u4E3A\u7A7A\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u56FE\u7247\u3002");
16557
+ }
16558
+ const m = raw.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]+)$/i);
16559
+ if (m) {
16560
+ const clean2 = m[2].replace(/\s+/g, "");
16561
+ if (!clean2)
16562
+ throw new Error("\u56FE\u7247\u6570\u636E\u65E0\u6548\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u56FE\u7247\u3002");
16563
+ return { mimeType: m[1].toLowerCase(), base64: clean2 };
16564
+ }
16565
+ const clean = raw.replace(/\s+/g, "");
16566
+ return { mimeType: fallbackMime, base64: clean };
16567
+ }
16568
+ function buildVisionUserInstruction(locale, hintText) {
16569
+ 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";
16570
+ const extra = String(hintText || "").trim();
16571
+ if (!extra)
16572
+ return base;
16573
+ return locale === "en-US" ? `${base}
16574
+ Additional user note: ${extra}` : `${base}
16575
+ \u7528\u6237\u8865\u5145\u8BF4\u660E\uFF1A${extra}`;
16576
+ }
16577
+ function getGlobalFetch(custom) {
16578
+ const fn = custom || globalThis.fetch;
16579
+ if (typeof fn !== "function") {
16580
+ throw new Error("\u5F53\u524D\u8FD0\u884C\u65F6\u7F3A\u5C11 fetch \u5B9E\u73B0\uFF0C\u8BF7\u901A\u8FC7 fetchImpl \u6CE8\u5165\u3002");
16581
+ }
16582
+ return fn;
16583
+ }
16584
+ function parseJsonFromModelText(raw) {
16585
+ const text = String(raw || "").trim();
16586
+ if (!text)
16587
+ return {};
16588
+ const stripped = text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "").trim();
16589
+ let parsed;
16590
+ try {
16591
+ parsed = JSON.parse(stripped);
16592
+ } catch {
16593
+ const start = stripped.indexOf("{");
16594
+ const end = stripped.lastIndexOf("}");
16595
+ if (start >= 0 && end > start) {
16596
+ parsed = JSON.parse(stripped.slice(start, end + 1));
16597
+ } else {
16598
+ throw new Error("\u6A21\u578B\u672A\u8FD4\u56DE\u6709\u6548 JSON \u5BF9\u8C61\uFF0C\u8BF7\u91CD\u8BD5\u3002");
16599
+ }
16600
+ }
16601
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
16602
+ throw new Error("\u6A21\u578B\u8FD4\u56DE\u7ED3\u679C\u4E0D\u662F JSON \u5BF9\u8C61\uFF0C\u8BF7\u91CD\u8BD5\u3002");
16603
+ }
16604
+ return parsed;
16605
+ }
16606
+ function sanitizeRawExtraction(rawObj, slice) {
16607
+ const mentionMap = /* @__PURE__ */ new Map();
16608
+ for (const m of slice.mentionFields) {
16609
+ mentionMap.set(`${m.key}_raw`, m.key);
16610
+ }
16611
+ const patch = {};
16612
+ const mentions = {};
16613
+ const omittedEmptyFields = [];
16614
+ for (const [key, value] of Object.entries(rawObj)) {
16615
+ if (value === null || value === void 0 || typeof value === "string" && !value.trim()) {
16616
+ omittedEmptyFields.push(key);
16617
+ continue;
16618
+ }
16619
+ if (mentionMap.has(key)) {
16620
+ mentions[mentionMap.get(key)] = String(value).trim();
16621
+ continue;
16622
+ }
16623
+ patch[key] = value;
16624
+ }
16625
+ return { patch, mentions, omittedEmptyFields };
16626
+ }
16627
+ function createOllamaIntentAdapter(options = {}) {
16628
+ const baseUrl = String(options.baseUrl || "http://127.0.0.1:11434").replace(/\/+$/, "");
16629
+ const model = options.model || "qwen3.5:4b-q4_K_M";
16630
+ const visionModel = options.visionModel || model;
16631
+ const think = options.think ?? false;
16632
+ const structuredOutput = options.structuredOutput ?? false;
16633
+ const temperature = options.temperature ?? 0;
16634
+ const numCtx = options.numCtx ?? 4096;
16635
+ const numPredict = options.numPredict ?? 384;
16636
+ const keepAlive = options.keepAlive ?? "5m";
16637
+ const fetchImpl = options.fetchImpl;
16638
+ async function runChat(targetModel, messages, slice, signal) {
16639
+ const started = Date.now();
16640
+ const format = structuredOutput ? (0, slicer_1.buildSliceJsonSchema)(slice) : "json";
16641
+ const res = await getGlobalFetch(fetchImpl)(`${baseUrl}/api/chat`, {
16642
+ method: "POST",
16643
+ headers: { "content-type": "application/json" },
16644
+ body: JSON.stringify({
16645
+ model: targetModel,
16646
+ stream: false,
16647
+ think,
16648
+ keep_alive: keepAlive,
16649
+ format,
16650
+ options: {
16651
+ temperature,
16652
+ num_ctx: numCtx,
16653
+ num_predict: numPredict
16654
+ },
16655
+ messages
16656
+ }),
16657
+ signal
16658
+ });
16659
+ if (!res.ok) {
16660
+ throw new Error(`\u672C\u5730 Ollama \u8C03\u7528\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
16661
+ }
16662
+ const data = await res.json();
16663
+ if (data?.done === false || data?.done_reason === "length" || typeof data?.message?.content !== "string") {
16664
+ throw new Error("\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6574\u7ED3\u675F\uFF0C\u8BF7\u91CD\u8BD5\u3002");
16665
+ }
16666
+ const rawObj = parseJsonFromModelText(data.message.content);
16667
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
16668
+ return {
16669
+ patch,
16670
+ mentions,
16671
+ rawText: data.message.content,
16672
+ model: targetModel,
16673
+ elapsedMs: Date.now() - started,
16674
+ omittedEmptyFields
16675
+ };
16676
+ }
16677
+ return {
16678
+ name: `ollama:${model}`,
16679
+ async health() {
16680
+ try {
16681
+ const res = await getGlobalFetch(fetchImpl)(`${baseUrl}/api/tags`);
16682
+ if (!res.ok)
16683
+ return { ready: false, model, message: `Ollama HTTP ${res.status}` };
16684
+ const data = await res.json();
16685
+ const names = Array.isArray(data?.models) ? data.models.map((m) => String(m.name || "")) : [];
16686
+ const ready = names.includes(model);
16687
+ return {
16688
+ ready,
16689
+ model,
16690
+ message: ready ? `Ollama ready (${model})` : `Model ${model} not found in local Ollama`
16691
+ };
16692
+ } catch (err) {
16693
+ return { ready: false, model, message: err?.message || "Ollama unavailable" };
16694
+ }
16695
+ },
16696
+ async extract(text, slice, opts) {
16697
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
16698
+ return runChat(model, [
16699
+ { role: "system", content: systemPrompt },
16700
+ { role: "user", content: text }
16701
+ ], slice, opts?.signal);
16702
+ },
16703
+ async extractFromImage(imageBase64, slice, opts) {
16704
+ const { base64 } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
16705
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
16706
+ const userPrompt = buildVisionUserInstruction(opts?.locale || slice.locale, opts?.hintText);
16707
+ return runChat(visionModel, [
16708
+ { role: "system", content: systemPrompt },
16709
+ { role: "user", content: userPrompt, images: [base64] }
16710
+ ], slice, opts?.signal);
16711
+ }
16712
+ };
16713
+ }
16714
+ function createOpenAICompatibleIntentAdapter(options) {
16715
+ const baseUrl = String(options.baseUrl || "").replace(/\/+$/, "");
16716
+ const model = options.model;
16717
+ const visionModel = options.visionModel || model;
16718
+ const fetchImpl = options.fetchImpl;
16719
+ async function runOpenAiChat(targetModel, messages, slice, signal) {
16720
+ const started = Date.now();
16721
+ const headers = { "content-type": "application/json" };
16722
+ if (options.apiKey)
16723
+ headers.authorization = `Bearer ${options.apiKey}`;
16724
+ const res = await getGlobalFetch(fetchImpl)(`${baseUrl}/v1/chat/completions`, {
16725
+ method: "POST",
16726
+ headers,
16727
+ body: JSON.stringify({
16728
+ model: targetModel,
16729
+ temperature: options.temperature ?? 0,
16730
+ max_tokens: options.maxTokens ?? 384,
16731
+ response_format: { type: "json_object" },
16732
+ messages
16733
+ }),
16734
+ signal
16735
+ });
16736
+ if (!res.ok) {
16737
+ throw new Error(`\u6A21\u578B\u63A5\u53E3\u8C03\u7528\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
16738
+ }
16739
+ const data = await res.json();
16740
+ const content = data?.choices?.[0]?.message?.content;
16741
+ if (typeof content !== "string") {
16742
+ throw new Error("\u6A21\u578B\u54CD\u5E94\u7F3A\u5C11\u6709\u6548\u6587\u672C\u5185\u5BB9\u3002");
16743
+ }
16744
+ const rawObj = parseJsonFromModelText(content);
16745
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
16746
+ return {
16747
+ patch,
16748
+ mentions,
16749
+ rawText: content,
16750
+ model: targetModel,
16751
+ elapsedMs: Date.now() - started,
16752
+ omittedEmptyFields
16753
+ };
16754
+ }
16755
+ return {
16756
+ name: `openai-compat:${model}`,
16757
+ async extract(text, slice, opts) {
16758
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
16759
+ return runOpenAiChat(model, [
16760
+ { role: "system", content: systemPrompt },
16761
+ { role: "user", content: text }
16762
+ ], slice, opts?.signal);
16763
+ },
16764
+ async extractFromImage(imageBase64, slice, opts) {
16765
+ const { base64, mimeType } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
16766
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
16767
+ const userPrompt = buildVisionUserInstruction(opts?.locale || slice.locale, opts?.hintText);
16768
+ return runOpenAiChat(visionModel, [
16769
+ { role: "system", content: systemPrompt },
16770
+ {
16771
+ role: "user",
16772
+ content: [
16773
+ { type: "text", text: userPrompt },
16774
+ { type: "image_url", image_url: { url: `data:${mimeType};base64,${base64}` } }
16775
+ ]
16776
+ }
16777
+ ], slice, opts?.signal);
16778
+ }
16779
+ };
16780
+ }
16781
+ function createHttpIntentAdapter(options) {
16782
+ const endpoint = options.endpoint;
16783
+ const imageEndpoint = options.imageEndpoint || endpoint;
16784
+ const fetchImpl = options.fetchImpl;
16785
+ return {
16786
+ name: `http:${endpoint}`,
16787
+ async extract(text, slice, opts) {
16788
+ const started = Date.now();
16789
+ const res = await getGlobalFetch(fetchImpl)(endpoint, {
16790
+ method: "POST",
16791
+ headers: { "content-type": "application/json" },
16792
+ body: JSON.stringify({ text, slice }),
16793
+ signal: opts?.signal
16794
+ });
16795
+ if (!res.ok) {
16796
+ throw new Error(`\u667A\u586B\u4EE3\u7406\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
16797
+ }
16798
+ const data = await res.json();
16799
+ return {
16800
+ patch: data?.patch || {},
16801
+ mentions: data?.mentions || {},
16802
+ rawText: data?.rawText,
16803
+ model: data?.model,
16804
+ elapsedMs: typeof data?.elapsedMs === "number" ? data.elapsedMs : Date.now() - started,
16805
+ omittedEmptyFields: Array.isArray(data?.omittedEmptyFields) ? data.omittedEmptyFields : []
16806
+ };
16807
+ },
16808
+ async extractFromImage(imageBase64, slice, opts) {
16809
+ const started = Date.now();
16810
+ const { base64, mimeType } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
16811
+ const res = await getGlobalFetch(fetchImpl)(imageEndpoint, {
16812
+ method: "POST",
16813
+ headers: { "content-type": "application/json" },
16814
+ body: JSON.stringify({ imageBase64: base64, mimeType, hintText: opts?.hintText, slice }),
16815
+ signal: opts?.signal
16816
+ });
16817
+ if (!res.ok) {
16818
+ throw new Error(`\u56FE\u7247\u8BC6\u522B\u4EE3\u7406\u8BF7\u6C42\u5931\u8D25\uFF08HTTP ${res.status}\uFF09`);
16819
+ }
16820
+ const data = await res.json();
16821
+ return {
16822
+ patch: data?.patch || {},
16823
+ mentions: data?.mentions || {},
16824
+ rawText: data?.rawText,
16825
+ model: data?.model,
16826
+ elapsedMs: typeof data?.elapsedMs === "number" ? data.elapsedMs : Date.now() - started,
16827
+ omittedEmptyFields: Array.isArray(data?.omittedEmptyFields) ? data.omittedEmptyFields : []
16828
+ };
16829
+ }
16830
+ };
16831
+ }
16832
+ function createOnDeviceBridgeAdapter(options) {
16833
+ const engineName = options.engineName || "on-device-slm";
16834
+ const modelName = options.modelName || engineName;
16835
+ const maxTokens = options.maxTokens ?? 256;
16836
+ const temperature = options.temperature ?? 0;
16837
+ return {
16838
+ name: `${engineName}:${modelName}`,
16839
+ async health() {
16840
+ try {
16841
+ const ready = options.isReady ? await options.isReady() : true;
16842
+ return {
16843
+ ready: Boolean(ready),
16844
+ model: modelName,
16845
+ message: ready ? `On-device SLM ready (${modelName})` : `On-device SLM not loaded (${modelName})`
16846
+ };
16847
+ } catch (err) {
16848
+ return { ready: false, model: modelName, message: err?.message || "On-device SLM unavailable" };
16849
+ }
16850
+ },
16851
+ async extract(text, slice, opts) {
16852
+ const started = Date.now();
16853
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
16854
+ const jsonSchema = (0, slicer_1.buildSliceJsonSchema)(slice);
16855
+ const out = await options.invoke({
16856
+ systemPrompt,
16857
+ userText: text,
16858
+ jsonSchema,
16859
+ maxTokens,
16860
+ temperature,
16861
+ signal: opts?.signal
16862
+ });
16863
+ const rawText = typeof out === "string" ? out : JSON.stringify(out);
16864
+ const rawObj = typeof out === "string" ? parseJsonFromModelText(out) : out;
16865
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
16866
+ return {
16867
+ patch,
16868
+ mentions,
16869
+ rawText,
16870
+ model: modelName,
16871
+ elapsedMs: Date.now() - started,
16872
+ omittedEmptyFields
16873
+ };
16874
+ },
16875
+ ...options.invokeVision ? {
16876
+ async extractFromImage(imageBase64, slice, opts) {
16877
+ const started = Date.now();
16878
+ const { base64, mimeType } = normalizeBase64Image(imageBase64, opts?.mimeType || "image/png");
16879
+ const systemPrompt = (0, slicer_1.compileIntentPrompt)(slice);
16880
+ const jsonSchema = (0, slicer_1.buildSliceJsonSchema)(slice);
16881
+ const userText = buildVisionUserInstruction(opts?.locale || slice.locale, opts?.hintText);
16882
+ const out = await options.invokeVision({
16883
+ systemPrompt,
16884
+ userText,
16885
+ imageBase64: base64,
16886
+ mimeType,
16887
+ jsonSchema,
16888
+ maxTokens,
16889
+ temperature,
16890
+ signal: opts?.signal
16891
+ });
16892
+ const rawText = typeof out === "string" ? out : JSON.stringify(out);
16893
+ const rawObj = typeof out === "string" ? parseJsonFromModelText(out) : out;
16894
+ const { patch, mentions, omittedEmptyFields } = sanitizeRawExtraction(rawObj, slice);
16895
+ return {
16896
+ patch,
16897
+ mentions,
16898
+ rawText,
16899
+ model: modelName,
16900
+ elapsedMs: Date.now() - started,
16901
+ omittedEmptyFields
16902
+ };
16903
+ }
16904
+ } : {}
16905
+ };
16906
+ }
16907
+ }
16908
+ });
16909
+
16910
+ // packages/form-intent-fill/dist/dictionaries.js
16911
+ var require_dictionaries = __commonJS({
16912
+ "packages/form-intent-fill/dist/dictionaries.js"(exports2) {
16913
+ "use strict";
16914
+ Object.defineProperty(exports2, "__esModule", { value: true });
16915
+ exports2.DictionaryMatcher = void 0;
16916
+ function createEpochId() {
16917
+ const gCrypto = globalThis.crypto;
16918
+ if (gCrypto && typeof gCrypto.randomUUID === "function") {
16919
+ return gCrypto.randomUUID();
16920
+ }
16921
+ return `ep_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
16922
+ }
16923
+ var normalizeText = (value) => value.normalize("NFKC").replace(/\s+/g, "").toLowerCase();
16924
+ function flattenOptions(nodes, parentPath = []) {
16925
+ const out = [];
16926
+ const seen = /* @__PURE__ */ new Set();
16927
+ for (const node of nodes) {
16928
+ if (!node || typeof node.code !== "string" || !node.code.trim() || typeof node.name !== "string" || !node.name.trim()) {
16929
+ throw new Error("\u5B57\u5178\u8282\u70B9\u7F3A\u5C11\u6709\u6548\u7684 code \u6216 name\u3002");
16930
+ }
16931
+ if (seen.has(node.code)) {
16932
+ throw new Error(`\u5B57\u5178\u540C\u7EA7\u8282\u70B9\u4EE3\u7801\u91CD\u590D\uFF1A${node.code}`);
16933
+ }
16934
+ seen.add(node.code);
16935
+ const nextPath = [...parentPath, { code: node.code, name: node.name }];
16936
+ if (nextPath.length > 4) {
16937
+ throw new Error("\u5B57\u5178\u5C42\u7EA7\u4E0D\u5F97\u8D85\u8FC7 4 \u7EA7\u3002");
16938
+ }
16939
+ if (Array.isArray(node.children) && node.children.length > 0) {
16940
+ out.push(...flattenOptions(node.children, nextPath));
16941
+ } else {
16942
+ const names = [node.name, ...Array.isArray(node.aliases) ? node.aliases : []];
16943
+ out.push({
16944
+ id: JSON.stringify(nextPath.map((n) => n.code)),
16945
+ code: node.code,
16946
+ label: nextPath.map((n) => n.name).join(" / "),
16947
+ path: nextPath,
16948
+ names
16949
+ });
16950
+ }
16951
+ }
16952
+ return out;
16953
+ }
16954
+ var DictionaryMatcher = class {
16955
+ constructor(fields = []) {
16956
+ this.definitions = {};
16957
+ this.records = {};
16958
+ this.sequence = 0;
16959
+ this.epoch = createEpochId();
16960
+ this.fields = [...new Set(fields)];
16961
+ }
16962
+ ensureField(key) {
16963
+ if (!this.fields.includes(key))
16964
+ this.fields.push(key);
16965
+ }
16966
+ load(bundle) {
16967
+ if (!bundle || bundle.version !== 1 || !bundle.source || !bundle.dictionaries) {
16968
+ throw new Error("\u5B57\u5178\u5305\u683C\u5F0F\u65E0\u6548\uFF08\u9700\u8981 version: 1\u3001source \u4E0E dictionaries\uFF09\u3002");
16969
+ }
16970
+ for (const [key, def] of Object.entries(bundle.dictionaries)) {
16971
+ this.ensureField(key);
16972
+ if (!def || !def.version || !Array.isArray(def.options) || def.options.length === 0) {
16973
+ throw new Error(`\u5B57\u5178\u5B57\u6BB5 ${key} \u7F3A\u5C11\u6709\u6548 version \u6216 options\u3002`);
16974
+ }
16975
+ const flat = flattenOptions(def.options);
16976
+ this.definitions[key] = {
16977
+ source: bundle.source,
16978
+ version: def.version,
16979
+ options: flat
16980
+ };
16981
+ if (this.records[key]) {
16982
+ this.records[key] = { raw: this.records[key].raw };
16983
+ }
16984
+ }
16985
+ this.sequence++;
16986
+ }
16987
+ capture(key, raw) {
16988
+ const clean = String(raw || "").trim();
16989
+ if (!clean || clean.length > 200) {
16990
+ throw new Error(`\u5B57\u6BB5 ${key} \u7684\u539F\u8BDD\u6587\u672C\u5FC5\u987B\u4E3A 1\u2013200 \u5B57\u3002`);
16991
+ }
16992
+ this.ensureField(key);
16993
+ if (this.records[key]?.raw !== clean) {
16994
+ this.records[key] = { raw: clean };
16995
+ this.sequence++;
16996
+ }
16997
+ return this.state(key);
16998
+ }
16999
+ clear(key) {
17000
+ delete this.records[key];
17001
+ this.sequence++;
17002
+ }
17003
+ clearAll() {
17004
+ this.records = {};
17005
+ this.sequence++;
17006
+ }
17007
+ state(key) {
17008
+ if (!this.fields.includes(key))
17009
+ return null;
17010
+ const record = this.records[key];
17011
+ const raw = record?.raw || "";
17012
+ const def = this.definitions[key];
17013
+ const options = def?.options || [];
17014
+ const norm = raw ? normalizeText(raw) : "";
17015
+ const candidates = norm ? options.filter((opt) => opt.names.some((n) => normalizeText(n) === norm)) : [];
17016
+ const selected = (record?.choice ? options.find((o) => o.id === record.choice) : null) || (candidates.length === 1 ? candidates[0] : null);
17017
+ const status = !raw ? "missing" : !def ? "awaiting_dictionary" : selected ? "resolved" : candidates.length > 1 ? "awaiting_confirmation" : "unmatched";
17018
+ return {
17019
+ key,
17020
+ raw,
17021
+ status,
17022
+ token: `${this.epoch}:${this.sequence}`,
17023
+ code: selected?.code ?? null,
17024
+ label: selected?.label ?? null,
17025
+ value: selected ? selected.path.length > 1 ? selected.path : selected.code : null,
17026
+ source: def?.source ?? null,
17027
+ version: def?.version ?? null,
17028
+ candidates: candidates.map((c) => ({ id: c.id, code: c.code, label: c.label, path: c.path }))
17029
+ };
17030
+ }
17031
+ choose(key, candidateId, token) {
17032
+ if (token !== `${this.epoch}:${this.sequence}`) {
17033
+ 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");
17034
+ }
17035
+ const def = this.definitions[key];
17036
+ const rec = this.records[key];
17037
+ if (!def || !rec?.raw) {
17038
+ throw new Error(`\u5B57\u6BB5 ${key} \u5C1A\u672A\u52A0\u8F7D\u5B57\u5178\u6216\u7F3A\u5C11\u539F\u8BDD\u3002`);
17039
+ }
17040
+ const hit = def.options.find((o) => o.id === candidateId);
17041
+ if (!hit) {
17042
+ throw new Error(`\u65E0\u6548\u7684\u5B57\u5178\u5019\u9009\u9879\uFF1A${candidateId}`);
17043
+ }
17044
+ this.records[key] = { raw: rec.raw, choice: hit.id };
17045
+ this.sequence++;
17046
+ return this.state(key);
17047
+ }
17048
+ allStates() {
17049
+ return this.fields.map((k) => this.state(k)).filter(Boolean);
17050
+ }
17051
+ };
17052
+ exports2.DictionaryMatcher = DictionaryMatcher;
17053
+ }
17054
+ });
17055
+
17056
+ // packages/form-intent-fill/dist/fastPath.js
17057
+ var require_fastPath = __commonJS({
17058
+ "packages/form-intent-fill/dist/fastPath.js"(exports2) {
17059
+ "use strict";
17060
+ Object.defineProperty(exports2, "__esModule", { value: true });
17061
+ exports2.parseSimpleNumber = parseSimpleNumber;
17062
+ exports2.tryFastPathExtract = tryFastPathExtract;
17063
+ var MULTI_CLAUSE_RE = /[,,。;;、\n]|(?:改一下|换成|并且|而且|还有|以及|同时|我叫|我是)/;
17064
+ var YES_RE = /^(是|是的|对|需要|要|开的|开|开启|打开|有|yes|y|true)$/i;
17065
+ var NO_RE = /^(否|不是|不需要|不要|不用|不开|关闭|无|没有|no|n|false)$/i;
17066
+ var MOBILE_RE = /^1[3-9]\d{9}$/;
17067
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
17068
+ var CN_DIGITS = {
17069
+ \u96F6: 0,
17070
+ "\u3007": 0,
17071
+ \u4E00: 1,
17072
+ \u4E8C: 2,
17073
+ \u4E24: 2,
17074
+ \u4FE9: 2,
17075
+ \u4E09: 3,
17076
+ \u56DB: 4,
17077
+ \u4E94: 5,
17078
+ \u516D: 6,
17079
+ \u4E03: 7,
17080
+ \u516B: 8,
17081
+ \u4E5D: 9
17082
+ };
17083
+ function parseSimpleNumber(raw) {
17084
+ const clean = raw.trim().replace(/[人位张份个元块岁年天次]+$/g, "").replace(/^(一共|总共|共|约)/, "").trim();
17085
+ if (!clean)
17086
+ return null;
17087
+ if (/^\d+(?:\.\d+)?$/.test(clean))
17088
+ return Number(clean);
17089
+ const wanMatch = /^(\d+(?:\.\d+)?)万$/.exec(clean);
17090
+ if (wanMatch)
17091
+ return Number(wanMatch[1]) * 1e4;
17092
+ const qianMatch = /^(\d+(?:\.\d+)?)千$/.exec(clean);
17093
+ if (qianMatch)
17094
+ return Number(qianMatch[1]) * 1e3;
17095
+ if (clean.length === 1 && CN_DIGITS[clean] !== void 0)
17096
+ return CN_DIGITS[clean];
17097
+ if (/^[零〇一二两俩三四五六七八九十百千万]+$/.test(clean)) {
17098
+ let total = 0;
17099
+ let section = 0;
17100
+ let num = 0;
17101
+ for (const ch of clean) {
17102
+ if (CN_DIGITS[ch] !== void 0) {
17103
+ num = CN_DIGITS[ch];
17104
+ } else if (ch === "\u5341") {
17105
+ section += (num || 1) * 10;
17106
+ num = 0;
17107
+ } else if (ch === "\u767E") {
17108
+ section += (num || 1) * 100;
17109
+ num = 0;
17110
+ } else if (ch === "\u5343") {
17111
+ section += (num || 1) * 1e3;
17112
+ num = 0;
17113
+ } else if (ch === "\u4E07") {
17114
+ section = (section + num) * 1e4;
17115
+ total += section;
17116
+ section = 0;
17117
+ num = 0;
17118
+ }
17119
+ }
17120
+ return total + section + num;
17121
+ }
17122
+ return null;
17123
+ }
17124
+ function tryFastPathExtract(text, activeBeat, slice) {
17125
+ const clean = String(text || "").trim().replace(/[。!!??]+$/, "").trim();
17126
+ if (!clean || clean.length > 24 || MULTI_CLAUSE_RE.test(clean)) {
17127
+ return { matched: false, patch: {}, mentions: {} };
17128
+ }
17129
+ const allExtractable = slice.extractableFields;
17130
+ const beatKeys = new Set(activeBeat?.fieldKeys || []);
17131
+ const beatFields = beatKeys.size ? allExtractable.filter((f) => beatKeys.has(f.key)) : allExtractable;
17132
+ const missingInBeat = beatFields.filter((f) => !f.hasValue || activeBeat?.missingKeys.includes(f.key));
17133
+ if (MOBILE_RE.test(clean)) {
17134
+ const phoneFields = allExtractable.filter((f) => f.type === "phone" || /(phone|mobile)/i.test(f.key));
17135
+ if (phoneFields.length === 1) {
17136
+ return { matched: true, patch: { [phoneFields[0].key]: clean }, mentions: {}, matchedRule: "exact_mobile" };
17137
+ }
17138
+ }
17139
+ if (EMAIL_RE.test(clean)) {
17140
+ const emailFields = allExtractable.filter((f) => /email/i.test(f.key));
17141
+ if (emailFields.length === 1) {
17142
+ return { matched: true, patch: { [emailFields[0].key]: clean }, mentions: {}, matchedRule: "exact_email" };
17143
+ }
17144
+ }
17145
+ const norm = clean.toLowerCase();
17146
+ const matchOptionsIn = (fields) => {
17147
+ const cands = [];
17148
+ for (const field of fields) {
17149
+ if (!field.options || !field.options.length)
17150
+ continue;
17151
+ for (const opt of field.options) {
17152
+ const codeL = opt.code.toLowerCase();
17153
+ const nameL = opt.name.toLowerCase();
17154
+ if (norm === codeL || norm === nameL) {
17155
+ cands.push({ key: field.key, code: opt.code, score: 2 });
17156
+ } else if (norm.length >= 2 && (nameL.includes(norm) || norm.length <= 6 && norm.includes(nameL))) {
17157
+ cands.push({ key: field.key, code: opt.code, score: 1 });
17158
+ }
17159
+ }
17160
+ }
17161
+ const best = cands.reduce((m, c) => Math.max(m, c.score), 0);
17162
+ const tops = cands.filter((c) => c.score === best);
17163
+ return tops.length === 1 ? { hit: tops[0], score: best } : null;
17164
+ };
17165
+ const optMatch = matchOptionsIn(beatFields) || matchOptionsIn(allExtractable);
17166
+ if (optMatch) {
17167
+ return {
17168
+ matched: true,
17169
+ patch: { [optMatch.hit.key]: optMatch.hit.code },
17170
+ mentions: {},
17171
+ matchedRule: optMatch.score === 2 ? "exact_option" : "unique_option_alias"
17172
+ };
17173
+ }
17174
+ const beatSwitches = beatFields.filter((f) => f.type === "switch");
17175
+ const switchFields = beatSwitches.length ? beatSwitches : allExtractable.filter((f) => f.type === "switch");
17176
+ if (switchFields.length === 1) {
17177
+ if (YES_RE.test(clean)) {
17178
+ return { matched: true, patch: { [switchFields[0].key]: true }, mentions: {}, matchedRule: "switch_yes" };
17179
+ }
17180
+ if (NO_RE.test(clean)) {
17181
+ return { matched: true, patch: { [switchFields[0].key]: false }, mentions: {}, matchedRule: "switch_no" };
17182
+ }
17183
+ }
17184
+ const isNumField = (f) => f.type === "number" || f.type === "stepper" || f.type === "slider";
17185
+ const beatNums = (missingInBeat.length ? missingInBeat : beatFields).filter(isNumField);
17186
+ const numCandidates = beatNums.length ? beatNums : allExtractable.filter(isNumField);
17187
+ if (numCandidates.length === 1) {
17188
+ const parsed = parseSimpleNumber(clean);
17189
+ if (parsed !== null) {
17190
+ const target = numCandidates[0];
17191
+ const min = target.min ?? -Infinity;
17192
+ const max = target.max ?? Infinity;
17193
+ if (parsed >= min && parsed <= max) {
17194
+ return {
17195
+ matched: true,
17196
+ patch: { [target.key]: parsed },
17197
+ mentions: {},
17198
+ matchedRule: "single_numeric"
17199
+ };
17200
+ }
17201
+ }
17202
+ }
17203
+ return { matched: false, patch: {}, mentions: {} };
17204
+ }
17205
+ }
17206
+ });
17207
+
17208
+ // packages/form-intent-fill/dist/planner.js
17209
+ var require_planner = __commonJS({
17210
+ "packages/form-intent-fill/dist/planner.js"(exports2) {
17211
+ "use strict";
17212
+ Object.defineProperty(exports2, "__esModule", { value: true });
17213
+ exports2.maskSensitiveValue = maskSensitiveValue;
17214
+ exports2.buildFillPlan = buildFillPlan;
17215
+ var slicer_1 = require_slicer();
17216
+ function maskSensitiveValue(item, display) {
17217
+ const key = item.key || "";
17218
+ const raw = String(display || "");
17219
+ if (item.type === "phone" || /(phone|mobile|tel)/i.test(key)) {
17220
+ const digits = raw.replace(/\s+/g, "");
17221
+ const masked = digits.length >= 7 ? `${digits.slice(0, 3)}****${digits.slice(-4)}` : raw.replace(/.(?=.{2})/g, "*");
17222
+ return { isPii: true, masked };
17223
+ }
17224
+ if (/(id_?card|identity|bank_?card|account_?no)/i.test(key)) {
17225
+ const masked = raw.length >= 8 ? `${raw.slice(0, 4)}********${raw.slice(-4)}` : "****";
17226
+ return { isPii: true, masked };
17227
+ }
17228
+ if (/email/i.test(key) && raw.includes("@")) {
17229
+ const [u, domain] = raw.split("@");
17230
+ const masked = `${u.slice(0, Math.min(2, u.length))}***@${domain}`;
17231
+ return { isPii: true, masked };
17232
+ }
17233
+ return { isPii: false, masked: raw };
17234
+ }
17235
+ function formatItemDisplay(item, value, locale) {
17236
+ if ((0, slicer_1.isEmptyFieldValue)(value))
17237
+ return locale === "en-US" ? "Empty" : "\u672A\u586B\u5199";
17238
+ if (item.type === "agreement") {
17239
+ const yes = value === true || value === 1 || value === "1";
17240
+ return yes ? locale === "en-US" ? "Agreed \u2713" : "\u5DF2\u52FE\u9009\u540C\u610F \u2713" : locale === "en-US" ? "Not agreed" : "\u672A\u540C\u610F";
17241
+ }
17242
+ if (item.type === "signature") {
17243
+ return value ? locale === "en-US" ? "Signed \u2713" : "\u5DF2\u672C\u4EBA\u7B7E\u540D \u2713" : locale === "en-US" ? "Unsigned" : "\u5F85\u7B7E\u540D";
17244
+ }
17245
+ if (typeof value === "boolean") {
17246
+ return value ? locale === "en-US" ? "Yes" : "\u662F" : locale === "en-US" ? "No" : "\u5426";
17247
+ }
17248
+ const opts = (0, slicer_1.extractStaticOptions)(item);
17249
+ if (opts) {
17250
+ if (Array.isArray(value)) {
17251
+ return value.map((v) => opts.find((o) => o.code === String(v))?.name || String(v)).join("\u3001");
17252
+ }
17253
+ const hit = opts.find((o) => o.code === String(value));
17254
+ if (hit)
17255
+ return hit.name;
17256
+ }
17257
+ const suffix = item.props?.suffix ? ` ${String(item.props.suffix)}` : "";
17258
+ return `${Array.isArray(value) ? value.join(", ") : String(value)}${suffix}`.trim();
17259
+ }
17260
+ function isItemFilled(item, value) {
17261
+ if (item.type === "agreement")
17262
+ return value === true || value === 1 || value === "1";
17263
+ return !(0, slicer_1.isEmptyFieldValue)(value);
17264
+ }
17265
+ function buildQuickChipsForItems(items, runtimeFields, locale) {
17266
+ const isEn = locale === "en-US";
17267
+ const groups = [];
17268
+ for (const item of items) {
17269
+ const f = runtimeFields[item.key];
17270
+ const curVal = f !== void 0 ? f.value : item.defaultValue;
17271
+ const opts = (0, slicer_1.extractStaticOptions)(item);
17272
+ if ((item.type === "radioGroup" || item.type === "select") && opts && opts.length > 0 && opts.length <= 6) {
17273
+ groups.push({
17274
+ key: item.key,
17275
+ label: item.label || item.key,
17276
+ type: item.type,
17277
+ required: Boolean(f?.required ?? item.required),
17278
+ options: opts.map((o) => ({
17279
+ value: o.code,
17280
+ label: o.name,
17281
+ selected: String(curVal ?? "") === o.code
17282
+ }))
17283
+ });
17284
+ continue;
17285
+ }
17286
+ if (item.type === "switch") {
17287
+ groups.push({
17288
+ key: item.key,
17289
+ label: item.label || item.key,
17290
+ type: "switch",
17291
+ required: Boolean(f?.required ?? item.required),
17292
+ options: [
17293
+ { value: true, label: isEn ? "Yes" : "\u9700\u8981 / \u662F", selected: curVal === true },
17294
+ { value: false, label: isEn ? "No" : "\u4E0D\u9700\u8981 / \u5426", selected: curVal === false }
17295
+ ]
17296
+ });
17297
+ continue;
17298
+ }
17299
+ if (item.type === "stepper") {
17300
+ const min = typeof item.props?.min === "number" ? item.props.min : 1;
17301
+ const max = typeof item.props?.max === "number" ? item.props.max : min + 4;
17302
+ const suffix = String(item.props?.suffix || "");
17303
+ if (max >= min && max - min <= 5) {
17304
+ const nums = [];
17305
+ for (let n = min; n <= max; n++) {
17306
+ nums.push({
17307
+ value: n,
17308
+ label: suffix ? `${n}${suffix}` : String(n),
17309
+ selected: Number(curVal) === n
17310
+ });
17311
+ }
17312
+ groups.push({
17313
+ key: item.key,
17314
+ label: item.label || item.key,
17315
+ type: "stepper",
17316
+ required: Boolean(f?.required ?? item.required),
17317
+ options: nums
17318
+ });
17319
+ }
17320
+ }
17321
+ }
17322
+ return groups;
17323
+ }
17324
+ function synthesizeSpokenExample(items, locale) {
17325
+ const isEn = locale === "en-US";
17326
+ const fragments = [];
17327
+ for (const item of items.slice(0, 4)) {
17328
+ const label = item.label || item.key;
17329
+ const opts = (0, slicer_1.extractStaticOptions)(item);
17330
+ if (opts && opts.length > 0) {
17331
+ const pick = opts.length > 1 ? opts[opts.length - 1] : opts[0];
17332
+ fragments.push(isEn ? `${label} is ${pick.name}` : `${label}\u9009${pick.name}`);
17333
+ continue;
17334
+ }
17335
+ if (item.type === "phone" || /(phone|mobile)/i.test(item.key)) {
17336
+ fragments.push(isEn ? "phone 13800138000" : "\u624B\u673A13800138000");
17337
+ continue;
17338
+ }
17339
+ if (/email/i.test(item.key)) {
17340
+ fragments.push(isEn ? "email demo@example.com" : "\u90AE\u7BB1demo@example.test");
17341
+ continue;
17342
+ }
17343
+ if (item.type === "switch") {
17344
+ fragments.push(isEn ? `${label}: yes` : `\u9700\u8981${label.replace(/^是否(需要)?/, "")}`);
17345
+ continue;
17346
+ }
17347
+ if (item.type === "stepper" || item.type === "number") {
17348
+ const min = typeof item.props?.min === "number" ? item.props.min : 2;
17349
+ const val = Math.max(min, 3);
17350
+ const suffix = String(item.props?.suffix || "");
17351
+ fragments.push(isEn ? `${label} ${val}` : `${label}${val}${suffix}`);
17352
+ continue;
17353
+ }
17354
+ if (/name/i.test(item.key) && !/company/i.test(item.key)) {
17355
+ fragments.push(isEn ? "my name is Alex Lin" : "\u6211\u53EB\u6797\u5C0F\u79BE");
17356
+ continue;
17357
+ }
17358
+ if (/(company|org|invoice_title)/i.test(item.key)) {
17359
+ fragments.push(isEn ? `${label} Acme Cloud Tech` : `${label}\u9752\u79BE\u79D1\u6280\u6709\u9650\u516C\u53F8`);
17360
+ continue;
17361
+ }
17362
+ fragments.push(isEn ? `${label}: ...` : `${label}\u793A\u4F8B\u5185\u5BB9`);
17363
+ }
17364
+ return fragments.join(isEn ? ", " : "\uFF0C");
17365
+ }
17366
+ function buildBeatGuidance(beatTitle, kind, missingItems, pendingForBeat, locale) {
17367
+ const isEn = locale === "en-US";
17368
+ if (kind === "signoff") {
17369
+ if (missingItems.length > 0) {
17370
+ const names = missingItems.map((i) => i.label || i.key).join(isEn ? ", " : "\u3001");
17371
+ 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`;
17372
+ }
17373
+ 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";
17374
+ }
17375
+ if (pendingForBeat.length > 0 && missingItems.length === 0) {
17376
+ const names = pendingForBeat.map((p) => p.label).join(isEn ? ", " : "\u3001");
17377
+ 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`;
17378
+ }
17379
+ const focus = missingItems.slice(0, 3);
17380
+ if (focus.length === 0) {
17381
+ return isEn ? `${beatTitle} is complete.` : `\u300C${beatTitle}\u300D\u5DF2\u5B8C\u6210\u3002`;
17382
+ }
17383
+ const listStr = focus.map((i) => i.label || i.key).join(isEn ? ", " : "\u3001");
17384
+ const tail = missingItems.length > 3 ? isEn ? ", etc." : "\u7B49" : "";
17385
+ 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`;
17386
+ }
17387
+ function buildFillPlan(schema, runtimeFields, options = {}) {
17388
+ const locale = options.locale === "en-US" ? "en-US" : "zh-CN";
17389
+ const isEn = locale === "en-US";
17390
+ const dictSet = new Set(options.dictionaryFields || []);
17391
+ const critSet = new Set(options.criticalFields || []);
17392
+ const pendingList = options.pendingProposals || [];
17393
+ const pendingKeySet = new Set(pendingList.map((p) => p.key));
17394
+ const touched = options.touchedKeys || /* @__PURE__ */ new Set();
17395
+ const recent = options.recentlyUpdatedKeys || /* @__PURE__ */ new Set();
17396
+ const allItems = (0, slicer_1.collectSchemaItems)(schema);
17397
+ const triggerTargets = /* @__PURE__ */ new Map();
17398
+ const triggeredBy = /* @__PURE__ */ new Map();
17399
+ for (const item of allItems) {
17400
+ for (const rel of item.relations || []) {
17401
+ if (rel && rel.target && rel.effect === "visible") {
17402
+ const tgt = String(rel.target);
17403
+ const list = triggerTargets.get(item.key) || [];
17404
+ if (!list.includes(tgt))
17405
+ list.push(tgt);
17406
+ triggerTargets.set(item.key, list);
17407
+ const rev = triggeredBy.get(tgt) || [];
17408
+ if (!rev.includes(item.key))
17409
+ rev.push(item.key);
17410
+ triggeredBy.set(tgt, rev);
17411
+ }
17412
+ }
17413
+ }
17414
+ const prunedFieldKeys = [];
17415
+ for (const [tgtKey] of triggeredBy.entries()) {
17416
+ const f = runtimeFields[tgtKey];
17417
+ const visible = typeof f?.visible === "boolean" ? f.visible : false;
17418
+ if (!visible)
17419
+ prunedFieldKeys.push(tgtKey);
17420
+ }
17421
+ const beats = [];
17422
+ const signoffItems = [];
17423
+ let totalVisibleExtractable = 0;
17424
+ for (let gi = 0; gi < (schema.groups || []).length; gi++) {
17425
+ const grp = schema.groups[gi];
17426
+ const visibleCollectable = [];
17427
+ for (const item of grp.items || []) {
17428
+ const f = runtimeFields[item.key];
17429
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
17430
+ const disabled = Boolean(f?.disabled ?? item.disabled);
17431
+ if (!visible || disabled)
17432
+ continue;
17433
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, dictSet);
17434
+ if (policy === "forbidden") {
17435
+ signoffItems.push(item);
17436
+ } else {
17437
+ visibleCollectable.push(item);
17438
+ totalVisibleExtractable++;
17439
+ }
17440
+ }
17441
+ if (visibleCollectable.length === 0)
17442
+ continue;
17443
+ const ordered = [...visibleCollectable].sort((a, b) => {
17444
+ const aGate = triggerTargets.has(a.key) ? 0 : 1;
17445
+ const bGate = triggerTargets.has(b.key) ? 0 : 1;
17446
+ const aChild = triggeredBy.has(a.key) ? 1 : 0;
17447
+ const bChild = triggeredBy.has(b.key) ? 1 : 0;
17448
+ return aChild - bChild || aGate - bGate;
17449
+ });
17450
+ const chunkSize = ordered.length <= 5 ? ordered.length : 4;
17451
+ for (let offset = 0; offset < ordered.length; offset += chunkSize) {
17452
+ const chunk = ordered.slice(offset, offset + chunkSize);
17453
+ const chunkIdx = Math.floor(offset / chunkSize);
17454
+ const baseTitle = grp.title || (isEn ? `Step ${gi + 1}` : `\u7B2C ${gi + 1} \u90E8\u5206`);
17455
+ const isBranchOnly = chunk.every((i) => triggeredBy.has(i.key));
17456
+ const title = isBranchOnly && chunk.length <= 2 ? chunk.map((i) => i.label || i.key).join(" / ") : chunkIdx === 0 ? baseTitle : `${baseTitle} (${chunkIdx + 1})`;
17457
+ const missingItems = chunk.filter((item) => {
17458
+ const f = runtimeFields[item.key];
17459
+ const req = Boolean(f?.required ?? item.required);
17460
+ const val = f?.value;
17461
+ const isUntouchedDefault = !touched.has(item.key) && triggerTargets.has(item.key) && item.defaultValue !== void 0 && JSON.stringify(val) === JSON.stringify(item.defaultValue);
17462
+ if (isUntouchedDefault)
17463
+ return true;
17464
+ return req && !isItemFilled(item, val) || Boolean(f?.errMsg);
17465
+ });
17466
+ const pendingForBeat = pendingList.filter((p) => chunk.some((i) => i.key === p.key));
17467
+ const beatDone = missingItems.length === 0 && pendingForBeat.length === 0;
17468
+ const chipCandidates = chunk.filter((item) => missingItems.some((m) => m.key === item.key) || triggerTargets.has(item.key));
17469
+ beats.push({
17470
+ id: `beat_${grp.key || gi}_${chunkIdx}`,
17471
+ title,
17472
+ kind: isBranchOnly ? "branch" : "collect",
17473
+ status: beatDone ? "done" : "upcoming",
17474
+ fieldKeys: chunk.map((i) => i.key),
17475
+ missingKeys: missingItems.map((i) => i.key),
17476
+ guidance: buildBeatGuidance(title, isBranchOnly ? "branch" : "collect", missingItems, pendingForBeat, locale),
17477
+ spokenExample: synthesizeSpokenExample(missingItems.length ? missingItems : chunk, locale),
17478
+ quickChips: buildQuickChipsForItems(chipCandidates.length ? chipCandidates : chunk, runtimeFields, locale),
17479
+ isBranchGate: chunk.some((i) => triggerTargets.has(i.key))
17480
+ });
17481
+ }
17482
+ }
17483
+ const signoffMissing = signoffItems.filter((item) => {
17484
+ const f = runtimeFields[item.key];
17485
+ return Boolean(f?.required ?? item.required) && !isItemFilled(item, f?.value);
17486
+ });
17487
+ const signoffTitle = isEn ? "Review & Sign-Off" : "\u6838\u5BF9\u4E0E\u672C\u4EBA\u786E\u8BA4";
17488
+ beats.push({
17489
+ id: "beat_signoff",
17490
+ title: signoffTitle,
17491
+ kind: "signoff",
17492
+ status: signoffMissing.length === 0 && beats.every((b) => b.status === "done") ? "active" : "upcoming",
17493
+ fieldKeys: signoffItems.map((i) => i.key),
17494
+ missingKeys: signoffMissing.map((i) => i.key),
17495
+ guidance: buildBeatGuidance(signoffTitle, "signoff", signoffMissing, [], locale),
17496
+ spokenExample: "",
17497
+ quickChips: []
17498
+ });
17499
+ let activeIndex = beats.findIndex((b) => b.kind !== "signoff" && b.status !== "done");
17500
+ if (activeIndex < 0)
17501
+ activeIndex = beats.length - 1;
17502
+ for (let i = 0; i < beats.length; i++) {
17503
+ if (i === activeIndex) {
17504
+ beats[i].status = "active";
17505
+ } else if (beats[i].status !== "done") {
17506
+ beats[i].status = "upcoming";
17507
+ }
17508
+ }
17509
+ const crystallizedFields = [];
17510
+ for (const item of allItems) {
17511
+ const f = runtimeFields[item.key];
17512
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
17513
+ if (!visible)
17514
+ continue;
17515
+ const val = f?.value;
17516
+ if (!isItemFilled(item, val))
17517
+ continue;
17518
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, dictSet);
17519
+ const rawDisplay = formatItemDisplay(item, val, locale);
17520
+ const dictLabel = options.dictionaryLabelMap?.get(item.key);
17521
+ const displayValue = dictLabel || rawDisplay;
17522
+ const { isPii, masked } = maskSensitiveValue(item, displayValue);
17523
+ crystallizedFields.push({
17524
+ key: item.key,
17525
+ label: item.label || item.key,
17526
+ type: item.type,
17527
+ value: val,
17528
+ displayValue,
17529
+ maskedDisplayValue: masked,
17530
+ isPii,
17531
+ risk: (0, slicer_1.classifyFieldRisk)(item, critSet),
17532
+ required: Boolean(f?.required ?? item.required),
17533
+ editable: policy !== "forbidden" && !f?.disabled && !item.readonly,
17534
+ justUpdated: recent.has(item.key)
17535
+ });
17536
+ }
17537
+ const archetype = triggerTargets.size > 0 ? "branching" : totalVisibleExtractable <= 4 ? "micro" : "multi-beat";
17538
+ const remainingMissingCount = beats.reduce((sum, b) => sum + b.missingKeys.length, 0) + pendingList.length;
17539
+ const estimatedSecondsLeft = remainingMissingCount === 0 ? 0 : Math.max(5, remainingMissingCount * 6);
17540
+ return {
17541
+ archetype,
17542
+ beats,
17543
+ activeBeatId: beats[activeIndex].id,
17544
+ activeBeat: beats[activeIndex],
17545
+ activeBeatIndex: activeIndex,
17546
+ prunedFieldKeys,
17547
+ prunedFieldCount: prunedFieldKeys.length,
17548
+ estimatedSecondsLeft,
17549
+ crystallizedFields
17550
+ };
17551
+ }
17552
+ }
17553
+ });
17554
+
17555
+ // packages/form-intent-fill/dist/session.js
17556
+ var require_session = __commonJS({
17557
+ "packages/form-intent-fill/dist/session.js"(exports2) {
17558
+ "use strict";
17559
+ Object.defineProperty(exports2, "__esModule", { value: true });
17560
+ exports2.IntentFillSession = void 0;
17561
+ var dictionaries_1 = require_dictionaries();
17562
+ var fastPath_1 = require_fastPath();
17563
+ var planner_1 = require_planner();
17564
+ var slicer_1 = require_slicer();
17565
+ function formatDisplayValue(item, value, locale) {
17566
+ if ((0, slicer_1.isEmptyFieldValue)(value))
17567
+ return locale === "en-US" ? "Empty" : "\u672A\u586B\u5199";
17568
+ if (typeof value === "boolean") {
17569
+ return value ? locale === "en-US" ? "Yes" : "\u662F" : locale === "en-US" ? "No" : "\u5426";
17570
+ }
17571
+ const opts = (0, slicer_1.extractStaticOptions)(item);
17572
+ if (opts) {
17573
+ if (Array.isArray(value)) {
17574
+ return value.map((v) => opts.find((o) => o.code === String(v))?.name || String(v)).join("\u3001");
17575
+ }
17576
+ const hit = opts.find((o) => o.code === String(value));
17577
+ if (hit)
17578
+ return hit.name;
17579
+ }
17580
+ return Array.isArray(value) ? value.join(", ") : String(value);
17581
+ }
17582
+ function coerceAndValidateValue(item, rawValue) {
17583
+ const opts = (0, slicer_1.extractStaticOptions)(item);
17584
+ if (item.type === "number" || item.type === "stepper" || item.type === "slider") {
17585
+ const num = typeof rawValue === "number" ? rawValue : typeof rawValue === "string" ? Number(rawValue.trim()) : NaN;
17586
+ if (!Number.isFinite(num)) {
17587
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u6709\u6548\u6570\u5B57\u3002` };
17588
+ }
17589
+ const min = typeof item.props?.min === "number" ? item.props.min : -Infinity;
17590
+ const max = typeof item.props?.max === "number" ? item.props.max : Infinity;
17591
+ if (num < min || num > max) {
17592
+ return {
17593
+ ok: false,
17594
+ code: "VALIDATION_FAILED",
17595
+ message: `${item.label || item.key} \u9700\u5728 [${min}, ${max}] \u8303\u56F4\u5185\u3002`
17596
+ };
17597
+ }
17598
+ return { ok: true, value: num };
17599
+ }
17600
+ if (item.type === "switch") {
17601
+ if (typeof rawValue === "boolean")
17602
+ return { ok: true, value: rawValue };
17603
+ if (rawValue === "true" || rawValue === "Y" || rawValue === 1)
17604
+ return { ok: true, value: true };
17605
+ if (rawValue === "false" || rawValue === "N" || rawValue === 0)
17606
+ return { ok: true, value: false };
17607
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u5E03\u5C14\u503C\u3002` };
17608
+ }
17609
+ if (item.type === "checkboxGroup") {
17610
+ const arr = Array.isArray(rawValue) ? rawValue.map(String) : typeof rawValue === "string" ? [rawValue] : null;
17611
+ if (!arr || arr.length === 0) {
17612
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u9009\u9879\u6570\u7EC4\u3002` };
17613
+ }
17614
+ if (opts) {
17615
+ const mapped = arr.map((v) => opts.find((o) => o.code === v || o.name === v)?.code || "");
17616
+ if (mapped.some((m) => !m)) {
17617
+ return { ok: false, code: "INVALID_OPTION", message: `${item.label || item.key} \u5305\u542B\u65E0\u6548\u9009\u9879\u4EE3\u7801\u3002` };
17618
+ }
17619
+ return { ok: true, value: [...new Set(mapped)] };
17620
+ }
17621
+ return { ok: true, value: arr };
17622
+ }
17623
+ if (item.type === "select" || item.type === "radioGroup") {
17624
+ const str2 = String(rawValue ?? "").trim();
17625
+ if (!str2)
17626
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u4E0D\u80FD\u4E3A\u7A7A\u3002` };
17627
+ if (opts) {
17628
+ const hit = opts.find((o) => o.code === str2) || opts.find((o) => o.name === str2);
17629
+ if (!hit) {
17630
+ return { ok: false, code: "INVALID_OPTION", message: `${item.label || item.key} \u9009\u9879\u300C${str2}\u300D\u4E0D\u5728\u5408\u6CD5\u679A\u4E3E\u5185\u3002` };
17631
+ }
17632
+ return { ok: true, value: hit.code };
17633
+ }
17634
+ return { ok: true, value: str2 };
17635
+ }
17636
+ const str = typeof rawValue === "string" ? rawValue.trim() : typeof rawValue === "number" ? String(rawValue) : "";
17637
+ if (!str) {
17638
+ return { ok: false, code: "INVALID_TYPE", message: `${item.label || item.key} \u9700\u8981\u6709\u6548\u6587\u672C\u3002` };
17639
+ }
17640
+ const maxLen = typeof item.props?.maxlength === "number" ? item.props.maxlength : 500;
17641
+ if (str.length > maxLen) {
17642
+ return { ok: false, code: "VALIDATION_FAILED", message: `${item.label || item.key} \u8D85\u51FA\u6700\u5927\u957F\u5EA6 ${maxLen}\u3002` };
17643
+ }
17644
+ for (const rule of item.rules || []) {
17645
+ if (rule && rule.type === "regex" && rule.regex) {
17646
+ try {
17647
+ if (!new RegExp(rule.regex).test(str)) {
17648
+ return { ok: false, code: "VALIDATION_FAILED", message: rule.message || `${item.label || item.key} \u683C\u5F0F\u4E0D\u7B26\u5408\u8981\u6C42\u3002` };
17649
+ }
17650
+ } catch {
17651
+ }
17652
+ }
17653
+ }
17654
+ return { ok: true, value: str };
17655
+ }
17656
+ var IntentFillSession = class {
17657
+ constructor(options) {
17658
+ this.itemsByKey = /* @__PURE__ */ new Map();
17659
+ this.revision = 0;
17660
+ this.sequence = 0;
17661
+ this.activeTicket = null;
17662
+ this.pendingMap = /* @__PURE__ */ new Map();
17663
+ this.touchedKeys = /* @__PURE__ */ new Set();
17664
+ this.recentlyUpdatedKeys = /* @__PURE__ */ new Set();
17665
+ this.schema = options.schema;
17666
+ this.core = options.core;
17667
+ this.adapter = options.adapter;
17668
+ this.mode = options.mode || "smart";
17669
+ this.locale = options.locale === "en-US" ? "en-US" : "zh-CN";
17670
+ this.dictionaryFieldSet = new Set(options.dictionaryFields || []);
17671
+ this.criticalFieldSet = new Set(options.criticalFields || []);
17672
+ this.reviewCritical = options.reviewCritical !== false;
17673
+ this.protectOverwrite = options.protectOverwrite !== false;
17674
+ this.enableFastPath = options.enableFastPath !== false;
17675
+ const items = (0, slicer_1.collectSchemaItems)(this.schema);
17676
+ const mentionKeys = [...this.dictionaryFieldSet];
17677
+ for (const item of items) {
17678
+ this.itemsByKey.set(item.key, item);
17679
+ if ((0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet) === "mention_only") {
17680
+ mentionKeys.push(item.key);
17681
+ }
17682
+ }
17683
+ this.dictionaries = new dictionaries_1.DictionaryMatcher(mentionKeys);
17684
+ }
17685
+ setMode(mode) {
17686
+ if (this.mode !== mode) {
17687
+ this.invalidate();
17688
+ this.mode = mode;
17689
+ }
17690
+ }
17691
+ setLocale(locale) {
17692
+ this.locale = locale === "en-US" ? "en-US" : "zh-CN";
17693
+ }
17694
+ invalidate() {
17695
+ this.sequence++;
17696
+ this.activeTicket = null;
17697
+ }
17698
+ /**
17699
+ * 用户手动编辑某字段时调用:递增版本号,立刻作废所有在途的异步模型抽取结果。
17700
+ */
17701
+ manualEdit(key, value) {
17702
+ this.invalidate();
17703
+ this.pendingMap.delete(key);
17704
+ this.touchedKeys.add(key);
17705
+ this.recentlyUpdatedKeys = /* @__PURE__ */ new Set([key]);
17706
+ this.revision++;
17707
+ this.core.setControlData(key, value);
17708
+ }
17709
+ /**
17710
+ * 焦点卡快捷芯片直达(1ms):视为用户主动点选,直接写入 FormCore 并刷新 BFS 联动与 FillPlan。
17711
+ */
17712
+ applyQuickChip(key, value) {
17713
+ const started = Date.now();
17714
+ const item = this.itemsByKey.get(key);
17715
+ if (!item) {
17716
+ throw new Error(`\u672A\u77E5\u5B57\u6BB5\uFF1A${key}`);
17717
+ }
17718
+ this.invalidate();
17719
+ const ticket = Object.freeze({
17720
+ id: this.sequence,
17721
+ revision: this.revision,
17722
+ text: `[chip:${key}=${String(value)}]`
17723
+ });
17724
+ const f = this.core.fields[key];
17725
+ const prev = f?.value;
17726
+ const visibleBefore = this.snapshotVisibleKeys();
17727
+ this.pendingMap.delete(key);
17728
+ this.core.setControlData(key, value);
17729
+ this.touchedKeys.add(key);
17730
+ this.recentlyUpdatedKeys = /* @__PURE__ */ new Set([key]);
17731
+ this.revision++;
17732
+ const visibleAfter = this.snapshotVisibleKeys();
17733
+ const revealed = [...visibleAfter].filter((k) => !visibleBefore.has(k));
17734
+ const applied = [
17735
+ {
17736
+ key,
17737
+ label: item.label || key,
17738
+ value,
17739
+ displayValue: formatDisplayValue(item, value, this.locale),
17740
+ previousValue: prev,
17741
+ ...revealed.length ? { triggeredReveal: revealed } : {}
17742
+ }
17743
+ ];
17744
+ return {
17745
+ status: "applied",
17746
+ route: "quick-chip",
17747
+ ticket,
17748
+ mode: this.mode,
17749
+ applied,
17750
+ pendingConfirm: this.getPendingProposals(),
17751
+ mentions: [],
17752
+ rejected: [],
17753
+ readiness: this.inspectReadiness(),
17754
+ plan: this.getFillPlan(),
17755
+ metadata: {
17756
+ model: "deterministic-chip",
17757
+ elapsedMs: Date.now() - started,
17758
+ omittedEmptyFields: [],
17759
+ matchedRule: "quick_chip"
17760
+ }
17761
+ };
17762
+ }
17763
+ getFillPlan() {
17764
+ const dictionaryLabelMap = /* @__PURE__ */ new Map();
17765
+ for (const st of this.dictionaries.allStates()) {
17766
+ if (st.status === "resolved" && st.label)
17767
+ dictionaryLabelMap.set(st.key, st.label);
17768
+ }
17769
+ return (0, planner_1.buildFillPlan)(this.schema, this.core.fields, {
17770
+ locale: this.locale,
17771
+ dictionaryFields: [...this.dictionaryFieldSet],
17772
+ criticalFields: [...this.criticalFieldSet],
17773
+ pendingProposals: this.getPendingProposals(),
17774
+ touchedKeys: this.touchedKeys,
17775
+ recentlyUpdatedKeys: this.recentlyUpdatedKeys,
17776
+ dictionaryLabelMap
17777
+ });
17778
+ }
17779
+ loadDictionaries(bundle) {
17780
+ this.invalidate();
17781
+ this.dictionaries.load(bundle);
17782
+ this.revision++;
17783
+ const resolved = [];
17784
+ for (const st of this.dictionaries.allStates()) {
17785
+ if (st.status === "resolved" && st.code) {
17786
+ const f = this.core.fields[st.key];
17787
+ if (f && f.visible !== false && !f.disabled) {
17788
+ this.core.setControlData(st.key, st.value ?? st.code);
17789
+ }
17790
+ resolved.push(st);
17791
+ }
17792
+ }
17793
+ return resolved;
17794
+ }
17795
+ chooseDictionaryCandidate(key, candidateId, token) {
17796
+ this.invalidate();
17797
+ const st = this.dictionaries.choose(key, candidateId, token);
17798
+ this.revision++;
17799
+ if (st.status === "resolved" && st.code) {
17800
+ const f = this.core.fields[key];
17801
+ if (f && f.visible !== false && !f.disabled) {
17802
+ this.core.setControlData(key, st.value ?? st.code);
17803
+ }
17804
+ }
17805
+ return st;
17806
+ }
17807
+ getActiveSlice() {
17808
+ return (0, slicer_1.buildActiveContextSlice)(this.schema, this.core.fields, {
17809
+ locale: this.locale,
17810
+ dictionaryFields: [...this.dictionaryFieldSet],
17811
+ criticalFields: [...this.criticalFieldSet]
17812
+ });
17813
+ }
17814
+ getPendingProposals() {
17815
+ return [...this.pendingMap.values()];
17816
+ }
17817
+ confirmPending(keys) {
17818
+ const targetKeys = keys && keys.length ? keys : [...this.pendingMap.keys()];
17819
+ const applied = [];
17820
+ this.invalidate();
17821
+ const remaining = new Set(targetKeys.filter((k) => this.pendingMap.has(k)));
17822
+ for (let pass = 0; pass < 2 && remaining.size > 0; pass++) {
17823
+ let progressed = false;
17824
+ for (const key of [...remaining]) {
17825
+ const prop = this.pendingMap.get(key);
17826
+ const item = this.itemsByKey.get(key);
17827
+ const f = this.core.fields[key];
17828
+ if (!prop || !item || !f) {
17829
+ remaining.delete(key);
17830
+ this.pendingMap.delete(key);
17831
+ continue;
17832
+ }
17833
+ const isWritable = f.visible !== false && !f.disabled && !item.readonly;
17834
+ if (!isWritable)
17835
+ continue;
17836
+ const visibleBefore = this.snapshotVisibleKeys();
17837
+ const prev = f.value;
17838
+ this.core.setControlData(key, prop.value);
17839
+ this.touchedKeys.add(key);
17840
+ const visibleAfter = this.snapshotVisibleKeys();
17841
+ const revealed = [...visibleAfter].filter((k) => !visibleBefore.has(k));
17842
+ applied.push({
17843
+ key,
17844
+ label: prop.label,
17845
+ value: prop.value,
17846
+ displayValue: prop.displayValue,
17847
+ previousValue: prev,
17848
+ ...revealed.length ? { triggeredReveal: revealed } : {}
17849
+ });
17850
+ this.pendingMap.delete(key);
17851
+ remaining.delete(key);
17852
+ progressed = true;
17853
+ }
17854
+ if (!progressed)
17855
+ break;
17856
+ }
17857
+ if (applied.length > 0) {
17858
+ this.recentlyUpdatedKeys = new Set(applied.map((a) => a.key));
17859
+ this.revision++;
17860
+ }
17861
+ return applied;
17862
+ }
17863
+ rejectPending(keys) {
17864
+ const targetKeys = keys && keys.length ? keys : [...this.pendingMap.keys()];
17865
+ for (const k of targetKeys)
17866
+ this.pendingMap.delete(k);
17867
+ }
17868
+ async extractFromText(text, options) {
17869
+ const clean = String(text || "").trim();
17870
+ if (!clean || clean.length > 2e3) {
17871
+ throw new Error(this.locale === "en-US" ? "Please enter 1\u20132000 characters." : "\u8BF7\u8F93\u5165 1\u20132000 \u5B57\u7684\u586B\u5199\u5185\u5BB9\u3002");
17872
+ }
17873
+ this.invalidate();
17874
+ const ticket = Object.freeze({
17875
+ id: this.sequence,
17876
+ revision: this.revision,
17877
+ text: clean
17878
+ });
17879
+ this.activeTicket = ticket;
17880
+ const slice = this.getActiveSlice();
17881
+ const planBefore = this.getFillPlan();
17882
+ let route = "slm";
17883
+ let matchedRule;
17884
+ let rawResult;
17885
+ const fastStarted = Date.now();
17886
+ const fast = this.enableFastPath ? (0, fastPath_1.tryFastPathExtract)(clean, planBefore.activeBeat, slice) : { matched: false, patch: {}, mentions: {} };
17887
+ if (fast.matched) {
17888
+ route = "fast-path";
17889
+ matchedRule = fast.matchedRule;
17890
+ rawResult = {
17891
+ patch: fast.patch,
17892
+ mentions: fast.mentions,
17893
+ model: "deterministic-fast-path",
17894
+ elapsedMs: Date.now() - fastStarted,
17895
+ omittedEmptyFields: []
17896
+ };
17897
+ } else {
17898
+ rawResult = await this.adapter.extract(clean, slice, {
17899
+ signal: options?.signal,
17900
+ locale: this.locale
17901
+ });
17902
+ }
17903
+ return this.applyRawExtractionResult(rawResult, ticket, route, matchedRule);
17904
+ }
17905
+ /**
17906
+ * 多模态图片直出成卡:支持拍名片、聊天截图、证件/工牌照片直接走本地视觉模型抽槽,
17907
+ * 复用完全相同的 Revision-Ticket、两趟 BFS 联动、主权红线拦截与风险确认矩阵。
17908
+ */
17909
+ async extractFromImage(imageBase64, options) {
17910
+ if (typeof this.adapter.extractFromImage !== "function") {
17911
+ 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`);
17912
+ }
17913
+ const cleanImg = String(imageBase64 || "").trim();
17914
+ if (!cleanImg) {
17915
+ throw new Error(this.locale === "en-US" ? "Image payload is empty." : "\u8BF7\u63D0\u4F9B\u6709\u6548\u7684\u56FE\u7247\u5185\u5BB9\u3002");
17916
+ }
17917
+ this.invalidate();
17918
+ const ticket = Object.freeze({
17919
+ id: this.sequence,
17920
+ revision: this.revision,
17921
+ text: options?.hintText ? `[image:${options.hintText.slice(0, 60)}]` : "[image]"
17922
+ });
17923
+ this.activeTicket = ticket;
17924
+ const slice = this.getActiveSlice();
17925
+ const rawResult = await this.adapter.extractFromImage(cleanImg, slice, {
17926
+ ...options,
17927
+ locale: options?.locale || this.locale
17928
+ });
17929
+ return this.applyRawExtractionResult(rawResult, ticket, "vision", "multimodal_vision");
17930
+ }
17931
+ applyRawExtractionResult(rawResult, ticket, route, matchedRule) {
17932
+ if (this.activeTicket !== ticket || ticket.revision !== this.revision) {
17933
+ return {
17934
+ status: "stale",
17935
+ route,
17936
+ ticket,
17937
+ mode: this.mode,
17938
+ applied: [],
17939
+ pendingConfirm: this.getPendingProposals(),
17940
+ mentions: [],
17941
+ rejected: [],
17942
+ readiness: this.inspectReadiness(),
17943
+ plan: this.getFillPlan(),
17944
+ metadata: {
17945
+ model: rawResult.model,
17946
+ elapsedMs: rawResult.elapsedMs,
17947
+ omittedEmptyFields: rawResult.omittedEmptyFields || [],
17948
+ matchedRule
17949
+ }
17950
+ };
17951
+ }
17952
+ const applied = [];
17953
+ const newPending = [];
17954
+ const rejected = [];
17955
+ const capturedMentions = [];
17956
+ for (const [mKey, mRaw] of Object.entries(rawResult.mentions || {})) {
17957
+ const item = this.itemsByKey.get(mKey);
17958
+ if (!item || (0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet) !== "mention_only") {
17959
+ rejected.push({
17960
+ key: `${mKey}_raw`,
17961
+ value: mRaw,
17962
+ code: "UNKNOWN_FIELD",
17963
+ message: `\u672A\u77E5\u539F\u8BDD\u5B57\u6BB5\uFF1A${mKey}_raw`
17964
+ });
17965
+ continue;
17966
+ }
17967
+ const st = this.dictionaries.capture(mKey, mRaw);
17968
+ capturedMentions.push(st);
17969
+ if (st.status === "resolved" && st.code && this.mode === "smart") {
17970
+ const f = this.core.fields[mKey];
17971
+ if (f && f.visible !== false && !f.disabled) {
17972
+ this.core.setControlData(mKey, st.value ?? st.code);
17973
+ }
17974
+ }
17975
+ }
17976
+ const deferred = [];
17977
+ const entries = Object.entries(rawResult.patch || {});
17978
+ const processEntry = (key, rawVal, allowDefer) => {
17979
+ const item = this.itemsByKey.get(key);
17980
+ if (!item) {
17981
+ rejected.push({
17982
+ key,
17983
+ value: rawVal,
17984
+ code: "UNKNOWN_FIELD",
17985
+ message: `\u6A21\u578B\u8FD4\u56DE\u4E86\u672A\u77E5\u5B57\u6BB5\uFF1A${key}`
17986
+ });
17987
+ return;
17988
+ }
17989
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet);
17990
+ if (policy === "forbidden") {
17991
+ rejected.push({
17992
+ key,
17993
+ value: rawVal,
17994
+ code: "FORBIDDEN_FIELD",
17995
+ 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`
17996
+ });
17997
+ return;
17998
+ }
17999
+ if (policy === "mention_only") {
18000
+ const st = this.dictionaries.capture(key, String(rawVal));
18001
+ capturedMentions.push(st);
18002
+ if (st.status === "resolved" && st.code && this.mode === "smart") {
18003
+ const f2 = this.core.fields[key];
18004
+ if (f2 && f2.visible !== false && !f2.disabled) {
18005
+ this.core.setControlData(key, st.value ?? st.code);
18006
+ }
18007
+ }
18008
+ return;
18009
+ }
18010
+ const f = this.core.fields[key];
18011
+ const isVisible = f ? f.visible !== false : item.visible !== false;
18012
+ const isDisabled = Boolean(f?.disabled ?? item.disabled);
18013
+ const isReadonly = Boolean(item.readonly || item.readOnly);
18014
+ if (!isVisible) {
18015
+ if (allowDefer) {
18016
+ deferred.push([key, rawVal]);
18017
+ } else {
18018
+ rejected.push({
18019
+ key,
18020
+ value: rawVal,
18021
+ code: "FIELD_NOT_WRITABLE",
18022
+ message: `${item.label || key} \u5F53\u524D\u5904\u4E8E\u9690\u85CF\u72B6\u6001\uFF0C\u4E0D\u80FD\u7531\u6A21\u578B\u586B\u5199\u3002`
18023
+ });
18024
+ }
18025
+ return;
18026
+ }
18027
+ if (isDisabled || isReadonly) {
18028
+ rejected.push({
18029
+ key,
18030
+ value: rawVal,
18031
+ code: "FIELD_NOT_WRITABLE",
18032
+ message: `${item.label || key} \u4E3A\u7981\u7528\u6216\u53EA\u8BFB\u5B57\u6BB5\uFF0C\u4E0D\u80FD\u5199\u5165\u3002`
18033
+ });
18034
+ return;
18035
+ }
18036
+ const checked = coerceAndValidateValue(item, rawVal);
18037
+ if (!checked.ok) {
18038
+ rejected.push({ key, value: rawVal, code: checked.code, message: checked.message });
18039
+ return;
18040
+ }
18041
+ const prevValue = f?.value;
18042
+ const sameAsPrev = JSON.stringify(prevValue) === JSON.stringify(checked.value);
18043
+ if (sameAsPrev)
18044
+ return;
18045
+ const risk = (0, slicer_1.classifyFieldRisk)(item, this.criticalFieldSet);
18046
+ const isUntouchedDefault = !this.touchedKeys.has(key) && item.defaultValue !== void 0 && JSON.stringify(prevValue) === JSON.stringify(item.defaultValue);
18047
+ const isOverwrite = !(0, slicer_1.isEmptyFieldValue)(prevValue) && !sameAsPrev && !isUntouchedDefault;
18048
+ let confirmReason = null;
18049
+ if (this.mode === "preview")
18050
+ confirmReason = "PREVIEW_MODE";
18051
+ else if (this.protectOverwrite && isOverwrite)
18052
+ confirmReason = "OVERWRITE_EXISTING";
18053
+ else if (this.reviewCritical && risk === "CRITICAL")
18054
+ confirmReason = "CRITICAL_FIELD";
18055
+ const displayValue = formatDisplayValue(item, checked.value, this.locale);
18056
+ if (confirmReason) {
18057
+ const proposal = {
18058
+ key,
18059
+ label: item.label || key,
18060
+ value: checked.value,
18061
+ displayValue,
18062
+ previousValue: prevValue,
18063
+ risk,
18064
+ reason: confirmReason
18065
+ };
18066
+ this.pendingMap.set(key, proposal);
18067
+ newPending.push(proposal);
18068
+ return;
18069
+ }
18070
+ const visibleBefore = this.snapshotVisibleKeys();
18071
+ this.core.setControlData(key, checked.value);
18072
+ this.touchedKeys.add(key);
18073
+ const visibleAfter = this.snapshotVisibleKeys();
18074
+ const revealed = [...visibleAfter].filter((k) => !visibleBefore.has(k));
18075
+ applied.push({
18076
+ key,
18077
+ label: item.label || key,
18078
+ value: checked.value,
18079
+ displayValue,
18080
+ previousValue: prevValue,
18081
+ ...revealed.length ? { triggeredReveal: revealed } : {}
18082
+ });
18083
+ };
18084
+ for (const [k, v] of entries)
18085
+ processEntry(k, v, true);
18086
+ for (const [k, v] of deferred) {
18087
+ const f = this.core.fields[k];
18088
+ if (this.mode === "preview" && f && f.visible === false && newPending.length > 0) {
18089
+ const item = this.itemsByKey.get(k);
18090
+ if (item) {
18091
+ const checked = coerceAndValidateValue(item, v);
18092
+ if (checked.ok) {
18093
+ const proposal = {
18094
+ key: k,
18095
+ label: item.label || k,
18096
+ value: checked.value,
18097
+ displayValue: formatDisplayValue(item, checked.value, this.locale),
18098
+ previousValue: f.value,
18099
+ risk: (0, slicer_1.classifyFieldRisk)(item, this.criticalFieldSet),
18100
+ reason: "PREVIEW_MODE"
18101
+ };
18102
+ this.pendingMap.set(k, proposal);
18103
+ newPending.push(proposal);
18104
+ continue;
18105
+ }
18106
+ }
18107
+ }
18108
+ processEntry(k, v, false);
18109
+ }
18110
+ if (applied.length > 0 || capturedMentions.length > 0) {
18111
+ this.recentlyUpdatedKeys = new Set(applied.map((a) => a.key));
18112
+ this.revision++;
18113
+ }
18114
+ this.activeTicket = null;
18115
+ const status = applied.length > 0 ? "applied" : newPending.length > 0 || capturedMentions.length > 0 ? "preview" : "empty";
18116
+ return {
18117
+ status,
18118
+ route,
18119
+ ticket,
18120
+ mode: this.mode,
18121
+ applied,
18122
+ pendingConfirm: this.getPendingProposals(),
18123
+ mentions: capturedMentions,
18124
+ rejected,
18125
+ readiness: this.inspectReadiness(),
18126
+ plan: this.getFillPlan(),
18127
+ metadata: {
18128
+ model: rawResult.model,
18129
+ elapsedMs: rawResult.elapsedMs,
18130
+ omittedEmptyFields: rawResult.omittedEmptyFields || [],
18131
+ matchedRule
18132
+ }
18133
+ };
18134
+ }
18135
+ inspectReadiness() {
18136
+ const missingRequired = [];
18137
+ const invalidFields = [];
18138
+ const manualOnlyPending = [];
18139
+ let totalRequiredCount = 0;
18140
+ let filledRequiredCount = 0;
18141
+ for (const item of this.itemsByKey.values()) {
18142
+ const f = this.core.fields[item.key];
18143
+ const visible = typeof f?.visible === "boolean" ? f.visible : item.visible !== false;
18144
+ if (!visible)
18145
+ continue;
18146
+ const required = Boolean(f?.required ?? item.required);
18147
+ const value = f?.value;
18148
+ const policy = (0, slicer_1.classifyFieldPolicy)(item, this.dictionaryFieldSet);
18149
+ const isFilled = item.type === "agreement" ? value === true || value === 1 || value === "1" : !(0, slicer_1.isEmptyFieldValue)(value);
18150
+ if (required) {
18151
+ totalRequiredCount++;
18152
+ if (isFilled)
18153
+ filledRequiredCount++;
18154
+ }
18155
+ if (f?.errMsg) {
18156
+ invalidFields.push({ key: item.key, label: item.label || item.key, reason: String(f.errMsg) });
18157
+ }
18158
+ if (required && !isFilled) {
18159
+ if (policy === "forbidden") {
18160
+ manualOnlyPending.push({ key: item.key, label: item.label || item.key, type: item.type });
18161
+ } else {
18162
+ missingRequired.push({ key: item.key, label: item.label || item.key, type: item.type });
18163
+ }
18164
+ }
18165
+ }
18166
+ const pendingConfirmations = this.getPendingProposals();
18167
+ const pendingMentions = this.dictionaries.allStates().filter((s) => s.raw && s.status !== "resolved");
18168
+ const progressPercent = totalRequiredCount === 0 ? 100 : Math.round(filledRequiredCount / totalRequiredCount * 100);
18169
+ const complete = missingRequired.length === 0 && invalidFields.length === 0 && pendingConfirmations.length === 0 && manualOnlyPending.length === 0;
18170
+ const nextPrompt = this.buildNextPrompt({
18171
+ missingRequired,
18172
+ invalidFields,
18173
+ pendingConfirmations,
18174
+ pendingMentions,
18175
+ manualOnlyPending
18176
+ });
18177
+ return {
18178
+ complete,
18179
+ filledRequiredCount,
18180
+ totalRequiredCount,
18181
+ progressPercent,
18182
+ missingRequired,
18183
+ invalidFields,
18184
+ pendingConfirmations,
18185
+ pendingMentions,
18186
+ manualOnlyPending,
18187
+ nextPrompt
18188
+ };
18189
+ }
18190
+ buildNextPrompt(parts) {
18191
+ const isEn = this.locale === "en-US";
18192
+ if (parts.pendingConfirmations.length > 0) {
18193
+ const names = parts.pendingConfirmations.map((p) => p.label).join(isEn ? ", " : "\u3001");
18194
+ 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`;
18195
+ }
18196
+ if (parts.invalidFields.length > 0) {
18197
+ const first = parts.invalidFields[0];
18198
+ return isEn ? `Please fix "${first.label}": ${first.reason}` : `\u8BF7\u4FEE\u6B63\u300C${first.label}\u300D\uFF1A${first.reason}`;
18199
+ }
18200
+ if (parts.missingRequired.length > 0) {
18201
+ const top = parts.missingRequired.slice(0, 3).map((m) => m.label).join(isEn ? ", " : "\u3001");
18202
+ const more = parts.missingRequired.length > 3 ? isEn ? "\u2026" : "\u7B49" : "";
18203
+ 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`;
18204
+ }
18205
+ if (parts.manualOnlyPending.length > 0) {
18206
+ const names = parts.manualOnlyPending.map((m) => m.label).join(isEn ? ", " : "\u3001");
18207
+ 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`;
18208
+ }
18209
+ if (parts.pendingMentions.length > 0) {
18210
+ const names = parts.pendingMentions.map((m) => `${m.key}(${m.raw})`).join(isEn ? ", " : "\u3001");
18211
+ return isEn ? `Verbatim text captured awaiting dictionary match: ${names}.` : `\u5DF2\u6682\u5B58\u539F\u8BDD\u5F85\u5B57\u5178\u5339\u914D\uFF1A${names}\u3002`;
18212
+ }
18213
+ 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";
18214
+ }
18215
+ snapshotVisibleKeys() {
18216
+ const set = /* @__PURE__ */ new Set();
18217
+ for (const [k, f] of Object.entries(this.core.fields)) {
18218
+ if (f && f.visible !== false)
18219
+ set.add(k);
18220
+ }
18221
+ return set;
18222
+ }
18223
+ };
18224
+ exports2.IntentFillSession = IntentFillSession;
18225
+ }
18226
+ });
18227
+
18228
+ // packages/form-intent-fill/dist/intakeManager.js
18229
+ var require_intakeManager = __commonJS({
18230
+ "packages/form-intent-fill/dist/intakeManager.js"(exports2) {
18231
+ "use strict";
18232
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
18233
+ return mod && mod.__esModule ? mod : { "default": mod };
18234
+ };
18235
+ Object.defineProperty(exports2, "__esModule", { value: true });
18236
+ exports2.intakeStart = intakeStart;
18237
+ exports2.intakeSubmitTurn = intakeSubmitTurn;
18238
+ exports2.intakeConfirm = intakeConfirm;
18239
+ exports2.intakeStatus = intakeStatus;
18240
+ exports2.intakeFinalize = intakeFinalize;
18241
+ exports2.loadIntakeRecordRaw = loadIntakeRecordRaw;
18242
+ exports2.saveIntakeRecordRaw = saveIntakeRecordRaw;
18243
+ var node_crypto_1 = __importDefault(require("node:crypto"));
18244
+ var node_fs_1 = __importDefault(require("node:fs"));
18245
+ var node_os_1 = __importDefault(require("node:os"));
18246
+ var node_path_1 = __importDefault(require("node:path"));
18247
+ var adapters_1 = require_adapters2();
18248
+ var session_1 = require_session();
18249
+ var slicer_1 = require_slicer();
18250
+ function resolveFormCoreCtor() {
18251
+ try {
18252
+ const mod2 = require_dist();
18253
+ if (mod2 && mod2.FormCore)
18254
+ return mod2.FormCore;
18255
+ } catch {
18256
+ }
18257
+ const mod = require(node_path_1.default.resolve(__dirname, "../../../dist/index.js"));
18258
+ return mod.FormCore;
18259
+ }
18260
+ function resolveSessionsDir(dataDir) {
18261
+ 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"));
18262
+ const dir = node_path_1.default.join(base, "intake-sessions");
18263
+ node_fs_1.default.mkdirSync(dir, { recursive: true });
18264
+ return dir;
18265
+ }
18266
+ function sessionFilePath(sessionId, dataDir) {
18267
+ const safeId = String(sessionId || "").replace(/[^a-zA-Z0-9_-]/g, "");
18268
+ if (!safeId)
18269
+ throw Object.assign(new Error("\u65E0\u6548\u7684 intake sessionId"), { code: "INVALID_ARGUMENT" });
18270
+ return node_path_1.default.join(resolveSessionsDir(dataDir), `${safeId}.json`);
18271
+ }
18272
+ function writeJsonAtomic(filePath, payload) {
18273
+ const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`;
18274
+ node_fs_1.default.writeFileSync(tmp, JSON.stringify(payload, null, 2) + "\n", "utf8");
18275
+ node_fs_1.default.renameSync(tmp, filePath);
18276
+ }
18277
+ function loadSchemaInput(input) {
18278
+ if (input.schema && typeof input.schema === "object" && Array.isArray(input.schema.groups)) {
18279
+ return JSON.parse(JSON.stringify(input.schema));
18280
+ }
18281
+ if (input.schemaPath) {
18282
+ const abs = node_path_1.default.resolve(input.schemaPath);
18283
+ if (!node_fs_1.default.existsSync(abs)) {
18284
+ throw Object.assign(new Error(`FormSchema \u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${abs}`), { code: "NOT_FOUND" });
18285
+ }
18286
+ const raw = JSON.parse(node_fs_1.default.readFileSync(abs, "utf8"));
18287
+ const unwrapped = raw && raw.schema && Array.isArray(raw.schema.groups) ? raw.schema : raw;
18288
+ if (!unwrapped || !Array.isArray(unwrapped.groups)) {
18289
+ throw Object.assign(new Error("\u6587\u4EF6\u4E0D\u662F\u5408\u6CD5\u7684 FormSchema\uFF08\u7F3A\u5C11 groups \u6570\u7EC4\uFF09"), { code: "INVALID_ARGUMENT" });
18290
+ }
18291
+ return unwrapped;
18292
+ }
18293
+ throw Object.assign(new Error("\u5FC5\u987B\u63D0\u4F9B schema \u6216 schemaPath"), { code: "INVALID_ARGUMENT" });
18294
+ }
18295
+ async function hydrateRuntime(record, adapter) {
18296
+ const FormCoreCtor = resolveFormCoreCtor();
18297
+ const mem = /* @__PURE__ */ new Map();
18298
+ const core = new FormCoreCtor(JSON.parse(JSON.stringify(record.schema)), {
18299
+ get: (k) => mem.get(k),
18300
+ set: (k, v) => mem.set(k, v),
18301
+ remove: (k) => mem.delete(k)
18302
+ });
18303
+ await core.init({});
18304
+ const entries = Object.entries(record.values || {});
18305
+ for (let pass = 0; pass < 2; pass++) {
18306
+ for (const [k, v] of entries) {
18307
+ if (core.fields[k] && (pass === 0 || core.fields[k].visible !== false)) {
18308
+ try {
18309
+ core.setControlData(k, v);
18310
+ } catch {
18311
+ }
18312
+ }
18313
+ }
18314
+ }
18315
+ const session = new session_1.IntentFillSession({
18316
+ schema: record.schema,
18317
+ core,
18318
+ adapter,
18319
+ mode: record.mode,
18320
+ locale: record.locale,
18321
+ reviewCritical: record.reviewCritical,
18322
+ protectOverwrite: record.protectOverwrite
18323
+ });
18324
+ session.revision = record.revision;
18325
+ for (const k of record.touchedKeys || []) {
18326
+ ;
18327
+ session.touchedKeys.add(k);
18328
+ }
18329
+ for (const prop of record.pendingProposals || []) {
18330
+ ;
18331
+ session.pendingMap.set(prop.key, prop);
18332
+ }
18333
+ if (record.dictionaryBundle) {
18334
+ session.dictionaries.load(record.dictionaryBundle);
18335
+ }
18336
+ for (const [k, raw] of Object.entries(record.dictionaryRawMentions || {})) {
18337
+ if (raw) {
18338
+ const st = session.dictionaries.capture(k, raw);
18339
+ const choice = record.dictionaryChoices?.[k];
18340
+ if (choice) {
18341
+ try {
18342
+ session.dictionaries.choose(k, choice, st.token);
18343
+ } catch {
18344
+ }
18345
+ }
18346
+ }
18347
+ }
18348
+ return { core, session };
18349
+ }
18350
+ function buildAgentQuestion(plan, readiness, locale) {
18351
+ const isEn = locale === "en-US";
18352
+ if (readiness.pendingConfirmations.length > 0) {
18353
+ const list = readiness.pendingConfirmations.map((p) => `${p.label}\uFF08${p.displayValue}\uFF09`).join(isEn ? ", " : "\u3001");
18354
+ 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`;
18355
+ }
18356
+ if (readiness.invalidFields.length > 0) {
18357
+ const f = readiness.invalidFields[0];
18358
+ return isEn ? `Ask the user to correct "${f.label}": ${f.reason}` : `\u8BF7\u5411\u7528\u6237\u6838\u5BF9\u300C${f.label}\u300D\uFF1A${f.reason}`;
18359
+ }
18360
+ if (readiness.missingRequired.length === 0 && readiness.manualOnlyPending.length > 0) {
18361
+ const names = readiness.manualOnlyPending.map((m) => m.label).join(isEn ? ", " : "\u3001");
18362
+ 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`;
18363
+ }
18364
+ if (readiness.complete) {
18365
+ 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";
18366
+ }
18367
+ return plan.activeBeat.guidance;
18368
+ }
18369
+ function snapshotRecordFromRuntime(prev, core, session, extra) {
18370
+ const values = {};
18371
+ for (const item of (0, slicer_1.collectSchemaItems)(prev.schema)) {
18372
+ const f = core.fields[item.key];
18373
+ if (f && !(0, slicer_1.isEmptyFieldValue)(f.value)) {
18374
+ values[item.key] = f.value;
18375
+ }
18376
+ }
18377
+ const dictMentions = {};
18378
+ const dictChoices = {};
18379
+ for (const st of session.dictionaries.allStates()) {
18380
+ if (st.raw)
18381
+ dictMentions[st.key] = st.raw;
18382
+ if (st.status === "resolved" && st.candidates.length > 1 && st.code) {
18383
+ const hit = st.candidates.find((c) => c.code === st.code);
18384
+ if (hit)
18385
+ dictChoices[st.key] = hit.id;
18386
+ }
18387
+ }
18388
+ const readiness = session.inspectReadiness();
18389
+ const nextStatus = extra?.status || (prev.status === "finalized" ? "finalized" : readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.invalidFields.length === 0 ? "ready_for_signoff" : "collecting");
18390
+ return {
18391
+ ...prev,
18392
+ ...extra,
18393
+ status: nextStatus,
18394
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
18395
+ revision: session.revision,
18396
+ values,
18397
+ touchedKeys: [...session.touchedKeys],
18398
+ pendingProposals: session.getPendingProposals(),
18399
+ dictionaryRawMentions: dictMentions,
18400
+ dictionaryChoices: dictChoices
18401
+ };
18402
+ }
18403
+ var NOOP_ADAPTER = {
18404
+ name: "agent-direct",
18405
+ async extract() {
18406
+ return { patch: {}, mentions: {}, elapsedMs: 0, model: "agent-direct" };
18407
+ }
18408
+ };
18409
+ function loadPersistedRecord(sessionId, dataDir) {
18410
+ const fp = sessionFilePath(sessionId, dataDir);
18411
+ if (!node_fs_1.default.existsSync(fp)) {
18412
+ throw Object.assign(new Error(`\u672A\u627E\u5230 Intake \u4F1A\u8BDD\uFF1A${sessionId}`), { code: "NOT_FOUND" });
18413
+ }
18414
+ return JSON.parse(node_fs_1.default.readFileSync(fp, "utf8"));
18415
+ }
18416
+ async function intakeStart(input) {
18417
+ const schema = loadSchemaInput(input);
18418
+ const locale = input.locale === "en-US" ? "en-US" : "zh-CN";
18419
+ const mode = input.mode || "smart";
18420
+ 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")}`;
18421
+ const initialRecord = {
18422
+ version: 1,
18423
+ sessionId,
18424
+ status: "collecting",
18425
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
18426
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
18427
+ locale,
18428
+ mode,
18429
+ reviewCritical: input.reviewCritical !== false,
18430
+ protectOverwrite: input.protectOverwrite !== false,
18431
+ schema,
18432
+ values: {},
18433
+ touchedKeys: [],
18434
+ pendingProposals: [],
18435
+ dictionaryBundle: input.dictionaryBundle || null,
18436
+ dictionaryRawMentions: {},
18437
+ dictionaryChoices: {},
18438
+ revision: 0,
18439
+ finalSubmission: null
18440
+ };
18441
+ const { core, session } = await hydrateRuntime(initialRecord, NOOP_ADAPTER);
18442
+ const saved = snapshotRecordFromRuntime(initialRecord, core, session);
18443
+ writeJsonAtomic(sessionFilePath(sessionId, input.dataDir), saved);
18444
+ const plan = session.getFillPlan();
18445
+ const readiness = session.inspectReadiness();
18446
+ const slice = session.getActiveSlice();
18447
+ return {
18448
+ status: "started",
18449
+ sessionId,
18450
+ sessionStatus: saved.status,
18451
+ schemaTitle: schema.title || "",
18452
+ locale,
18453
+ archetype: plan.archetype,
18454
+ revision: saved.revision,
18455
+ activeContextSlice: slice,
18456
+ plan,
18457
+ readiness,
18458
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, locale),
18459
+ handoffRecommended: readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.manualOnlyPending.length > 0
18460
+ };
18461
+ }
18462
+ async function intakeSubmitTurn(input) {
18463
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
18464
+ if (record.status === "finalized") {
18465
+ 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" });
18466
+ }
18467
+ const hasDirectPatch = Boolean(input.patch && Object.keys(input.patch).length > 0 || input.mentions && Object.keys(input.mentions).length > 0);
18468
+ const hasText = typeof input.text === "string" && input.text.trim().length > 0;
18469
+ let resolvedImageBase64 = typeof input.imageBase64 === "string" ? input.imageBase64.trim() : "";
18470
+ let resolvedMimeType = input.imageMimeType;
18471
+ if (!resolvedImageBase64 && input.imagePath) {
18472
+ const absImg = node_path_1.default.resolve(input.imagePath);
18473
+ if (!node_fs_1.default.existsSync(absImg)) {
18474
+ throw Object.assign(new Error(`\u56FE\u7247\u6587\u4EF6\u4E0D\u5B58\u5728\uFF1A${absImg}`), { code: "NOT_FOUND" });
18475
+ }
18476
+ resolvedImageBase64 = node_fs_1.default.readFileSync(absImg).toString("base64");
18477
+ if (!resolvedMimeType) {
18478
+ const ext = node_path_1.default.extname(absImg).toLowerCase();
18479
+ resolvedMimeType = ext === ".jpg" || ext === ".jpeg" ? "image/jpeg" : ext === ".webp" ? "image/webp" : "image/png";
18480
+ }
18481
+ }
18482
+ const hasImage = Boolean(resolvedImageBase64);
18483
+ if (!hasDirectPatch && !hasText && !hasImage) {
18484
+ 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"), {
18485
+ code: "INVALID_ARGUMENT"
18486
+ });
18487
+ }
18488
+ let adapter = input.adapter || NOOP_ADAPTER;
18489
+ let turnText = hasText ? String(input.text).trim() : "[agent-patch]";
18490
+ let enableFastPath = true;
18491
+ if (hasDirectPatch) {
18492
+ enableFastPath = false;
18493
+ adapter = {
18494
+ name: "agent-direct-patch",
18495
+ async extract() {
18496
+ return {
18497
+ patch: input.patch || {},
18498
+ mentions: input.mentions || {},
18499
+ elapsedMs: 0,
18500
+ model: "agent-direct-patch"
18501
+ };
18502
+ }
18503
+ };
18504
+ } else if (input.useLocalSlm !== false && !input.adapter) {
18505
+ adapter = (0, adapters_1.createOllamaIntentAdapter)({
18506
+ baseUrl: input.ollamaUrl || process.env.OLLAMA_URL || "http://127.0.0.1:11434",
18507
+ model: input.model || process.env.INTENT_FILL_MODEL || "qwen3.5:4b-q4_K_M",
18508
+ visionModel: input.visionModel || process.env.INTENT_FILL_VISION_MODEL || input.model || process.env.INTENT_FILL_MODEL || "qwen3.5:4b-q4_K_M",
18509
+ think: false
18510
+ });
18511
+ }
18512
+ const { core, session } = await hydrateRuntime(record, adapter);
18513
+ session.enableFastPath = enableFastPath;
18514
+ const turn = !hasDirectPatch && hasImage ? await session.extractFromImage(resolvedImageBase64, {
18515
+ mimeType: resolvedMimeType,
18516
+ hintText: hasText ? String(input.text).trim() : void 0
18517
+ }) : await session.extractFromText(turnText);
18518
+ const saved = snapshotRecordFromRuntime(record, core, session);
18519
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), saved);
18520
+ const plan = turn.plan;
18521
+ const readiness = turn.readiness;
18522
+ const handoffRecommended = readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.invalidFields.length === 0 && readiness.manualOnlyPending.length > 0;
18523
+ return {
18524
+ status: turn.status,
18525
+ sessionId: record.sessionId,
18526
+ sessionStatus: saved.status,
18527
+ revision: saved.revision,
18528
+ route: hasDirectPatch ? "agent-patch" : turn.route,
18529
+ applied: turn.applied,
18530
+ pendingConfirm: turn.pendingConfirm,
18531
+ mentions: turn.mentions,
18532
+ rejected: turn.rejected,
18533
+ readiness,
18534
+ plan,
18535
+ activeContextSlice: session.getActiveSlice(),
18536
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, record.locale),
18537
+ handoffRecommended,
18538
+ metadata: turn.metadata
18539
+ };
18540
+ }
18541
+ async function intakeConfirm(input) {
18542
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
18543
+ if (record.status === "finalized") {
18544
+ throw Object.assign(new Error("\u8BE5 Intake \u4F1A\u8BDD\u5DF2\u5B8C\u6210\u6700\u7EC8\u63D0\u4EA4\u3002"), { code: "INVALID_STATE" });
18545
+ }
18546
+ const { core, session } = await hydrateRuntime(record, NOOP_ADAPTER);
18547
+ let nextDictBundle = record.dictionaryBundle;
18548
+ let resolvedDictionaries = [];
18549
+ if (input.dictionaryBundle) {
18550
+ nextDictBundle = input.dictionaryBundle;
18551
+ resolvedDictionaries = session.loadDictionaries(input.dictionaryBundle);
18552
+ }
18553
+ if (input.chooseCandidate) {
18554
+ const chosen = session.chooseDictionaryCandidate(input.chooseCandidate.key, input.chooseCandidate.candidateId, input.chooseCandidate.token);
18555
+ resolvedDictionaries.push(chosen);
18556
+ }
18557
+ if (Array.isArray(input.rejectKeys) && input.rejectKeys.length > 0) {
18558
+ session.rejectPending(input.rejectKeys);
18559
+ }
18560
+ const confirmed = input.confirmKeys === void 0 || input.confirmKeys.length > 0 ? session.confirmPending(input.confirmKeys) : [];
18561
+ const saved = snapshotRecordFromRuntime(record, core, session, { dictionaryBundle: nextDictBundle });
18562
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), saved);
18563
+ const plan = session.getFillPlan();
18564
+ const readiness = session.inspectReadiness();
18565
+ const handoffRecommended = readiness.missingRequired.length === 0 && readiness.pendingConfirmations.length === 0 && readiness.invalidFields.length === 0 && readiness.manualOnlyPending.length > 0;
18566
+ return {
18567
+ status: "confirmed",
18568
+ sessionId: record.sessionId,
18569
+ sessionStatus: saved.status,
18570
+ revision: saved.revision,
18571
+ confirmed,
18572
+ resolvedDictionaries,
18573
+ pendingConfirm: session.getPendingProposals(),
18574
+ readiness,
18575
+ plan,
18576
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, record.locale),
18577
+ handoffRecommended
18578
+ };
18579
+ }
18580
+ async function intakeStatus(input) {
18581
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
18582
+ const { session } = await hydrateRuntime(record, NOOP_ADAPTER);
18583
+ const plan = session.getFillPlan();
18584
+ const readiness = session.inspectReadiness();
18585
+ const mask = input.maskPii !== false;
18586
+ const collectedSummary = plan.crystallizedFields.map((f) => ({
18587
+ key: f.key,
18588
+ label: f.label,
18589
+ value: mask && f.isPii ? f.maskedDisplayValue : f.displayValue,
18590
+ isPii: f.isPii
18591
+ }));
18592
+ return {
18593
+ status: record.status,
18594
+ sessionId: record.sessionId,
18595
+ schemaTitle: record.schema.title || "",
18596
+ revision: record.revision,
18597
+ collectedSummary,
18598
+ pendingConfirm: session.getPendingProposals(),
18599
+ dictionaries: session.dictionaries.allStates(),
18600
+ readiness,
18601
+ plan,
18602
+ activeContextSlice: (0, slicer_1.buildActiveContextSlice)(record.schema, session.core.fields, { locale: record.locale }),
18603
+ nextQuestionForUser: buildAgentQuestion(plan, readiness, record.locale),
18604
+ finalSubmission: record.finalSubmission || null
18605
+ };
18606
+ }
18607
+ async function intakeFinalize(input) {
18608
+ const record = loadPersistedRecord(input.sessionId, input.dataDir);
18609
+ const { core, session } = await hydrateRuntime(record, NOOP_ADAPTER);
18610
+ if (input.manualValues && typeof input.manualValues === "object") {
18611
+ for (const [k, v] of Object.entries(input.manualValues)) {
18612
+ if (core.fields[k]) {
18613
+ session.manualEdit(k, v);
18614
+ }
18615
+ }
18616
+ }
18617
+ const readiness = session.inspectReadiness();
18618
+ const coreOk = core.validateAll();
18619
+ if (!readiness.complete || !coreOk) {
18620
+ const savedPartial = snapshotRecordFromRuntime(record, core, session);
18621
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), savedPartial);
18622
+ return {
18623
+ status: "blocked",
18624
+ sessionId: record.sessionId,
18625
+ sessionStatus: savedPartial.status,
18626
+ reason: readiness.nextPrompt,
18627
+ readiness,
18628
+ nextQuestionForUser: buildAgentQuestion(session.getFillPlan(), readiness, record.locale)
18629
+ };
18630
+ }
18631
+ const data = core.collectFormData({ skipVerify: true });
18632
+ const submissionId = `sub_${Date.now().toString(36)}_${node_crypto_1.default.randomBytes(3).toString("hex")}`;
18633
+ const finalSubmission = {
18634
+ submissionId,
18635
+ submittedAt: (/* @__PURE__ */ new Date()).toISOString(),
18636
+ storageKey: record.schema.storageKey || "",
18637
+ schemaVersion: record.schema.version || "1.0.0",
18638
+ data
18639
+ };
18640
+ const saved = snapshotRecordFromRuntime(record, core, session, {
18641
+ status: "finalized",
18642
+ finalSubmission
18643
+ });
18644
+ writeJsonAtomic(sessionFilePath(record.sessionId, input.dataDir), saved);
18645
+ const plan = session.getFillPlan();
18646
+ return {
18647
+ status: "finalized",
18648
+ sessionId: record.sessionId,
18649
+ sessionStatus: "finalized",
18650
+ submission: finalSubmission,
18651
+ readableSummary: plan.crystallizedFields.map((f) => ({
18652
+ key: f.key,
18653
+ label: f.label,
18654
+ displayValue: f.isPii ? f.maskedDisplayValue : f.displayValue
18655
+ }))
18656
+ };
18657
+ }
18658
+ function loadIntakeRecordRaw(sessionId, dataDir) {
18659
+ return loadPersistedRecord(sessionId, dataDir);
18660
+ }
18661
+ function saveIntakeRecordRaw(record, dataDir) {
18662
+ writeJsonAtomic(sessionFilePath(record.sessionId, dataDir), record);
18663
+ }
18664
+ }
18665
+ });
18666
+
16279
18667
  // packages/form-agent/src/v2Core.cjs
16280
18668
  var require_v2Core = __commonJS({
16281
18669
  "packages/form-agent/src/v2Core.cjs"(exports2, module2) {
16282
18670
  "use strict";
16283
18671
  var fs = require("node:fs");
18672
+ var os2 = require("node:os");
16284
18673
  var path2 = require("node:path");
16285
18674
  var crypto = require("node:crypto");
16286
18675
  var { FormCore } = require_dist();
@@ -16300,6 +18689,7 @@ var require_v2Core = __commonJS({
16300
18689
  buildSubmissionEnvelope
16301
18690
  } = require_dataContract();
16302
18691
  var dataHub = require_dataHubStore();
18692
+ var intake = require_intakeManager();
16303
18693
  var VALID_SKINS = ["fin-minimal", "clean-outline", "bank-card", "tdesign"];
16304
18694
  var VALID_MODES = ["flat", "collapsible", "step"];
16305
18695
  var VALID_DENSITIES = ["comfortable", "compact"];
@@ -16677,7 +19067,18 @@ var require_v2Core = __commonJS({
16677
19067
  function escapeInlineScript(text) {
16678
19068
  return String(text).replace(/<\/(script)/gi, "<\\/$1");
16679
19069
  }
16680
- function renderStandaloneHtml({ schema, themeConfig, mode, locale, assetsDir }) {
19070
+ function normalizeSubmitUrl(raw) {
19071
+ if (raw === void 0 || raw === null) return "";
19072
+ const trimmed = String(raw).trim();
19073
+ if (!trimmed) return "";
19074
+ if (!/^https?:\/\//i.test(trimmed)) {
19075
+ throw Object.assign(new Error(`\u65E0\u6548\u7684 submitUrl\uFF1A${trimmed}\uFF08\u4EC5\u652F\u6301 http:// \u6216 https:// \u5730\u5740\uFF09`), {
19076
+ code: "INVALID_ARGUMENT"
19077
+ });
19078
+ }
19079
+ return trimmed;
19080
+ }
19081
+ function renderStandaloneHtml({ schema, themeConfig, mode, locale, submitUrl, assetsDir }) {
16681
19082
  const normalizedTheme = themeConfig ? { ...themeConfig } : { version: "1.0.0", skin: "fin-minimal", override: {}, formMode: "flat", showProgressBar: true };
16682
19083
  const effectiveMode = mode === "final" || normalizedTheme.mode === "final" ? "final" : "preview";
16683
19084
  if (effectiveMode === "final") {
@@ -16687,6 +19088,7 @@ var require_v2Core = __commonJS({
16687
19088
  if (locale !== void 0 || normalizedTheme.locale) {
16688
19089
  normalizedTheme.locale = effectiveLocale;
16689
19090
  }
19091
+ const effectiveSubmitUrl = normalizeSubmitUrl(submitUrl);
16690
19092
  const jsPath = path2.join(assetsDir, "modern-preview.iife.js");
16691
19093
  const cssPath = path2.join(assetsDir, "modern-preview.css");
16692
19094
  if (!fs.existsSync(jsPath) || !fs.existsSync(cssPath)) {
@@ -16698,6 +19100,8 @@ var require_v2Core = __commonJS({
16698
19100
  const cssCode = fs.readFileSync(cssPath, "utf8");
16699
19101
  const safeTitle = String(schema.title || (effectiveLocale === "en-US" ? "FormSchema Live Preview" : "FormSchema \u5B9E\u65F6\u9884\u89C8")).replace(/[<>&"]/g, "");
16700
19102
  const pageTitle = effectiveMode === "final" ? safeTitle : `${safeTitle} \xB7 FormSchema Preview`;
19103
+ const submitUrlScriptLine = effectiveSubmitUrl ? `
19104
+ window.__AGENT_SUBMIT_URL__ = ${escapeInlineScript(JSON.stringify(effectiveSubmitUrl))};` : "";
16701
19105
  const html = `<!DOCTYPE html>
16702
19106
  <html lang="${effectiveLocale}">
16703
19107
  <head>
@@ -16709,7 +19113,7 @@ var require_v2Core = __commonJS({
16709
19113
  <body>
16710
19114
  <div id="app"></div>
16711
19115
  <script>
16712
- window.__AGENT_PREVIEW_MODE__ = ${JSON.stringify(effectiveMode)};
19116
+ window.__AGENT_PREVIEW_MODE__ = ${JSON.stringify(effectiveMode)};${submitUrlScriptLine}
16713
19117
  window.__AGENT_FORM_SCHEMA__ = ${escapeInlineScript(JSON.stringify(schema))};
16714
19118
  window.__AGENT_THEME_CONFIG__ = ${escapeInlineScript(JSON.stringify(normalizedTheme))};
16715
19119
  </script>
@@ -16717,16 +19121,22 @@ var require_v2Core = __commonJS({
16717
19121
  </body>
16718
19122
  </html>
16719
19123
  `;
16720
- return { html, mode: effectiveMode, locale: effectiveLocale };
19124
+ return { html, mode: effectiveMode, locale: effectiveLocale, submitUrl: effectiveSubmitUrl || null };
16721
19125
  }
16722
- function previewExportHtml({ schemaPath, themePath, out, mode, locale, assetsDir }) {
19126
+ function previewExportHtml({ schemaPath, themePath, out, mode, locale, submitUrl, assetsDir }) {
16723
19127
  const schema = normalizeSchemaEnvelope(readJsonFile(schemaPath, "FormSchema \u6587\u4EF6"));
16724
19128
  const themeConfig = themePath ? readJsonFile(themePath, "ThemeConfigJson \u6587\u4EF6") : { version: "1.0.0", skin: "fin-minimal", override: {}, formMode: "flat", showProgressBar: true };
16725
- const { html, mode: effectiveMode, locale: effectiveLocale } = renderStandaloneHtml({
19129
+ const {
19130
+ html,
19131
+ mode: effectiveMode,
19132
+ locale: effectiveLocale,
19133
+ submitUrl: effectiveSubmitUrl
19134
+ } = renderStandaloneHtml({
16726
19135
  schema,
16727
19136
  themeConfig,
16728
19137
  mode,
16729
19138
  locale,
19139
+ submitUrl,
16730
19140
  assetsDir
16731
19141
  });
16732
19142
  const absOut = path2.resolve(out);
@@ -16737,6 +19147,7 @@ var require_v2Core = __commonJS({
16737
19147
  status: "exported",
16738
19148
  mode: effectiveMode,
16739
19149
  locale: effectiveLocale,
19150
+ submitUrl: effectiveSubmitUrl,
16740
19151
  path: absOut,
16741
19152
  sizeKb,
16742
19153
  fileUrl: `file://${absOut}`
@@ -16802,8 +19213,10 @@ module.exports = ${JSON.stringify(payload, null, 2)}
16802
19213
  outDir,
16803
19214
  keyStyle = "snake_case",
16804
19215
  includeHtml = true,
19216
+ submitUrl,
16805
19217
  assetsDir
16806
19218
  }) {
19219
+ const effectiveSubmitUrl = normalizeSubmitUrl(submitUrl);
16807
19220
  const schema = normalizeSchemaEnvelope(readJsonFile(schemaPath, "FormSchema \u6587\u4EF6"));
16808
19221
  const governance = validateFormSchemaGovernance(schema);
16809
19222
  if (!governance.valid) {
@@ -16841,7 +19254,7 @@ module.exports = ${JSON.stringify(payload, null, 2)}
16841
19254
  let finalHtmlOut = null;
16842
19255
  let finalHtmlSizeKb = null;
16843
19256
  if (includeHtml !== false && assetsDir) {
16844
- const { html } = renderStandaloneHtml({ schema, themeConfig, mode: "final", assetsDir });
19257
+ const { html } = renderStandaloneHtml({ schema, themeConfig, mode: "final", submitUrl: effectiveSubmitUrl, assetsDir });
16845
19258
  finalHtmlOut = path2.join(absDir, "final.html");
16846
19259
  fs.writeFileSync(finalHtmlOut, html, "utf8");
16847
19260
  finalHtmlSizeKb = Math.round(fs.statSync(finalHtmlOut).size / 1024);
@@ -16858,6 +19271,7 @@ module.exports = ${JSON.stringify(payload, null, 2)}
16858
19271
  piiFields: contract.piiSummary.map((p) => p.key),
16859
19272
  governanceValid: governance.valid,
16860
19273
  presetAuditCount: auditFieldPresetCoverage(schema).length,
19274
+ ...effectiveSubmitUrl ? { submitUrl: effectiveSubmitUrl } : {},
16861
19275
  artifacts: {
16862
19276
  schema: { file: "form.schema.json", sha256: sha256(schemaOut) },
16863
19277
  theme: { file: "theme.config.json", sha256: sha256(themeOut) },
@@ -16929,22 +19343,148 @@ module.exports = ${JSON.stringify(payload, null, 2)}
16929
19343
  if (!name.endsWith("Form")) name += "Form";
16930
19344
  return name;
16931
19345
  }
19346
+ function tryReadJsonSafe(filePath) {
19347
+ try {
19348
+ if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) return null;
19349
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
19350
+ } catch (_) {
19351
+ return null;
19352
+ }
19353
+ }
19354
+ function findNearestExistingDir(targetPath) {
19355
+ let cur = path2.resolve(targetPath || process.cwd());
19356
+ for (let i = 0; i < 12; i++) {
19357
+ try {
19358
+ if (fs.existsSync(cur)) {
19359
+ return fs.statSync(cur).isDirectory() ? cur : path2.dirname(cur);
19360
+ }
19361
+ } catch (_) {
19362
+ }
19363
+ const parent = path2.dirname(cur);
19364
+ if (parent === cur) break;
19365
+ cur = parent;
19366
+ }
19367
+ return process.cwd();
19368
+ }
19369
+ function detectHostEnvironment({ projectDir, outDir } = {}) {
19370
+ const startDir = findNearestExistingDir(projectDir || outDir || process.cwd());
19371
+ const homeDir = path2.resolve(os2.homedir());
19372
+ const tmpDirs = /* @__PURE__ */ new Set([path2.resolve(os2.tmpdir())]);
19373
+ try {
19374
+ tmpDirs.add(fs.realpathSync(os2.tmpdir()));
19375
+ } catch (_) {
19376
+ }
19377
+ let cur = startDir;
19378
+ for (let depth = 0; depth < 6; depth++) {
19379
+ if (depth > 0 && (cur === homeDir || tmpDirs.has(cur))) break;
19380
+ const wxProj = tryReadJsonSafe(path2.join(cur, "project.config.json"));
19381
+ if (wxProj && (wxProj.appid !== void 0 || wxProj.miniprogramRoot !== void 0 || wxProj.compileType === "miniprogram")) {
19382
+ return {
19383
+ resolvedPlatform: "miniapp",
19384
+ confidence: "high",
19385
+ projectRoot: cur,
19386
+ signals: ["project.config.json"],
19387
+ summary: "Detected WeChat Miniapp project via project.config.json"
19388
+ };
19389
+ }
19390
+ const wxApp = tryReadJsonSafe(path2.join(cur, "app.json"));
19391
+ if (wxApp && Array.isArray(wxApp.pages)) {
19392
+ return {
19393
+ resolvedPlatform: "miniapp",
19394
+ confidence: "high",
19395
+ projectRoot: cur,
19396
+ signals: ["app.json(pages)"],
19397
+ summary: "Detected WeChat Miniapp project via app.json"
19398
+ };
19399
+ }
19400
+ const pkg = tryReadJsonSafe(path2.join(cur, "package.json"));
19401
+ if (pkg && typeof pkg === "object") {
19402
+ const deps = { ...pkg.dependencies || {}, ...pkg.devDependencies || {} };
19403
+ const hasVue = Boolean(deps.vue || deps.nuxt || deps["@vitejs/plugin-vue"]);
19404
+ const hasReact = Boolean(deps.react || deps["react-dom"] || deps.next || deps["@vitejs/plugin-react"]);
19405
+ if (hasVue && !hasReact) {
19406
+ const signals = ["package.json", deps.nuxt ? "dep:nuxt" : "dep:vue"];
19407
+ return {
19408
+ resolvedPlatform: "vue3",
19409
+ confidence: "high",
19410
+ projectRoot: cur,
19411
+ signals,
19412
+ summary: `Detected Vue 3 host project (${signals.join(", ")})`
19413
+ };
19414
+ }
19415
+ if (hasReact && !hasVue) {
19416
+ const signals = ["package.json", deps.next ? "dep:next" : "dep:react"];
19417
+ return {
19418
+ resolvedPlatform: "react18",
19419
+ confidence: "high",
19420
+ projectRoot: cur,
19421
+ signals,
19422
+ summary: `Detected React 18 host project (${signals.join(", ")})`
19423
+ };
19424
+ }
19425
+ if (hasVue && hasReact) {
19426
+ if (fs.existsSync(path2.join(cur, "src/App.vue"))) {
19427
+ return {
19428
+ resolvedPlatform: "vue3",
19429
+ confidence: "high",
19430
+ projectRoot: cur,
19431
+ signals: ["package.json", "src/App.vue"],
19432
+ summary: "Detected Vue 3 host project via src/App.vue"
19433
+ };
19434
+ }
19435
+ if (fs.existsSync(path2.join(cur, "src/App.tsx")) || fs.existsSync(path2.join(cur, "src/App.jsx"))) {
19436
+ return {
19437
+ resolvedPlatform: "react18",
19438
+ confidence: "high",
19439
+ projectRoot: cur,
19440
+ signals: ["package.json", "src/App.tsx"],
19441
+ summary: "Detected React 18 host project via src/App.tsx"
19442
+ };
19443
+ }
19444
+ }
19445
+ }
19446
+ const parent = path2.dirname(cur);
19447
+ if (parent === cur) break;
19448
+ cur = parent;
19449
+ }
19450
+ return {
19451
+ resolvedPlatform: "standalone",
19452
+ confidence: "fallback",
19453
+ projectRoot: startDir,
19454
+ signals: ["no-frontend-framework-detected"],
19455
+ summary: "No Vue/React/Miniapp host detected \u2014 delivering zero-dependency standalone HTML bundle"
19456
+ };
19457
+ }
16932
19458
  function scaffoldHost({
16933
19459
  schemaPath,
16934
19460
  themePath,
16935
- platform,
19461
+ platform = "auto",
16936
19462
  outDir,
19463
+ projectDir,
16937
19464
  componentName,
16938
19465
  keyStyle = "snake_case",
16939
- packageScope = "@agentprismform"
19466
+ packageScope = "@agentprismform",
19467
+ submitUrl,
19468
+ assetsDir
16940
19469
  }) {
16941
- const VALID_PLATFORMS = ["vue3", "react18", "miniapp", "headless"];
16942
- if (!VALID_PLATFORMS.includes(platform)) {
19470
+ const VALID_PLATFORMS = ["auto", "vue3", "react18", "miniapp", "standalone", "headless"];
19471
+ const requestedPlatform = platform || "auto";
19472
+ if (!VALID_PLATFORMS.includes(requestedPlatform)) {
16943
19473
  throw Object.assign(
16944
- new Error(`\u4E0D\u652F\u6301\u7684\u76EE\u6807\u5E73\u53F0\uFF1A${platform}\uFF08\u53EF\u9009\uFF1A${VALID_PLATFORMS.join(", ")}\uFF09`),
19474
+ new Error(`\u4E0D\u652F\u6301\u7684\u76EE\u6807\u5E73\u53F0\uFF1A${requestedPlatform}\uFF08\u53EF\u9009\uFF1A${VALID_PLATFORMS.join(", ")}\uFF09`),
16945
19475
  { code: "INVALID_ARGUMENT" }
16946
19476
  );
16947
19477
  }
19478
+ const effectiveSubmitUrl = normalizeSubmitUrl(submitUrl);
19479
+ const detection = requestedPlatform === "auto" ? { requestedPlatform: "auto", ...detectHostEnvironment({ projectDir, outDir }) } : {
19480
+ requestedPlatform,
19481
+ resolvedPlatform: requestedPlatform,
19482
+ confidence: "explicit",
19483
+ projectRoot: findNearestExistingDir(projectDir || outDir || process.cwd()),
19484
+ signals: ["explicit-platform"],
19485
+ summary: `Explicit platform requested: ${requestedPlatform}`
19486
+ };
19487
+ const resolvedPlatform = detection.resolvedPlatform;
16948
19488
  const schema = normalizeSchemaEnvelope(readJsonFile(schemaPath, "FormSchema \u6587\u4EF6"));
16949
19489
  const rawTheme = themePath ? readJsonFile(themePath, "ThemeConfigJson \u6587\u4EF6") : { version: "1.0.0", skin: "fin-minimal", override: {}, formMode: "flat", showProgressBar: true };
16950
19490
  const themeConfig = { ...rawTheme, mode: "final" };
@@ -16958,7 +19498,8 @@ module.exports = ${JSON.stringify(payload, null, 2)}
16958
19498
  format: "agentprismform-mobile-bundle/v1",
16959
19499
  exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
16960
19500
  schema,
16961
- themeConfig
19501
+ themeConfig,
19502
+ ...effectiveSubmitUrl ? { submitUrl: effectiveSubmitUrl } : {}
16962
19503
  };
16963
19504
  const bundleOut = writeJsonAtomic(path2.join(absDir, "form.bundle.json"), bundle, { overwrite: true });
16964
19505
  const typesOut = path2.join(absDir, "types.d.ts");
@@ -16967,7 +19508,7 @@ module.exports = ${JSON.stringify(payload, null, 2)}
16967
19508
  let packages = [];
16968
19509
  let entryFile = "";
16969
19510
  let mountSnippet = "";
16970
- if (platform === "vue3") {
19511
+ if (resolvedPlatform === "vue3") {
16971
19512
  packages = [`${scope}/render-vue`];
16972
19513
  entryFile = path2.join(absDir, `${compName}.vue`);
16973
19514
  const vueCode = `<script setup lang="ts">
@@ -17012,7 +19553,7 @@ const emit = defineEmits<{
17012
19553
  fs.writeFileSync(entryFile, vueCode, "utf8");
17013
19554
  files.component = entryFile;
17014
19555
  mountSnippet = `<${compName} :host-handlers="hostHandlers" :custom-controls="{}" @submit="handleSubmit" />`;
17015
- } else if (platform === "react18") {
19556
+ } else if (resolvedPlatform === "react18") {
17016
19557
  packages = [`${scope}/render-web`];
17017
19558
  entryFile = path2.join(absDir, `${compName}.tsx`);
17018
19559
  const reactCode = `import React from 'react'
@@ -17058,7 +19599,7 @@ export function ${compName}({
17058
19599
  fs.writeFileSync(entryFile, reactCode, "utf8");
17059
19600
  files.component = entryFile;
17060
19601
  mountSnippet = `<${compName} hostHandlers={hostHandlers} customControls={{}} onSubmit={handleSubmit} />`;
17061
- } else if (platform === "headless") {
19602
+ } else if (resolvedPlatform === "headless") {
17062
19603
  packages = [`${scope}/core`, `${scope}/render`];
17063
19604
  entryFile = path2.join(absDir, `${compName}.tsx`);
17064
19605
  const headlessCode = `import React, { useEffect, useRef, useState } from 'react'
@@ -17144,8 +19685,23 @@ export function ${compName}({ onSubmit }: ${compName}Props) {
17144
19685
  fs.writeFileSync(entryFile, headlessCode, "utf8");
17145
19686
  files.component = entryFile;
17146
19687
  mountSnippet = `<${compName} onSubmit={handleSubmit} />`;
19688
+ } else if (resolvedPlatform === "standalone") {
19689
+ packages = [];
19690
+ const resolvedAssetsDir = assetsDir || path2.resolve(__dirname, "../preview");
19691
+ const { html } = renderStandaloneHtml({
19692
+ schema,
19693
+ themeConfig,
19694
+ mode: "final",
19695
+ submitUrl: effectiveSubmitUrl,
19696
+ assetsDir: resolvedAssetsDir
19697
+ });
19698
+ entryFile = path2.join(absDir, "index.html");
19699
+ fs.writeFileSync(entryFile, html, "utf8");
19700
+ files.html = entryFile;
19701
+ mountSnippet = effectiveSubmitUrl ? `# Deploy index.html to any static host (Cloudflare Pages / Vercel / Nginx / OSS)
19702
+ # 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)`;
17147
19703
  } else {
17148
- packages = [`${scope}/core`, `${scope}/render`, `${scope}/render-miniapp`];
19704
+ packages = [`${scope}/render-miniapp`];
17149
19705
  const dataFile = path2.join(absDir, "preview-data.js");
17150
19706
  const jsonFile = path2.join(absDir, "index.json");
17151
19707
  const wxmlFile = path2.join(absDir, "index.wxml");
@@ -17175,6 +19731,7 @@ export function ${compName}({ onSubmit }: ${compName}Props) {
17175
19731
  `,
17176
19732
  "utf8"
17177
19733
  );
19734
+ const defaultMiniappUrl = effectiveSubmitUrl || "https://api.example.com/forms/submit";
17178
19735
  fs.writeFileSync(
17179
19736
  jsFile,
17180
19737
  `const bundle = require('./preview-data.js')
@@ -17187,7 +19744,7 @@ Page({
17187
19744
  onFormSubmit(ev) {
17188
19745
  this.setData({ submitting: true })
17189
19746
  wx.request({
17190
- url: (this.data.schema && this.data.schema.submitApi) || 'https://api.example.com/forms/submit',
19747
+ url: bundle.submitUrl || (this.data.schema && this.data.schema.submitApi) || ${JSON.stringify(defaultMiniappUrl)},
17191
19748
  method: 'POST',
17192
19749
  header: { 'Idempotency-Key': 'wx_' + Date.now() },
17193
19750
  data: ev.detail,
@@ -17205,14 +19762,19 @@ Page({
17205
19762
  files.pageJs = jsFile;
17206
19763
  mountSnippet = `// Register "${path2.basename(absDir)}/index" inside WeChat Miniapp app.json -> "pages"`;
17207
19764
  }
17208
- const localInstallCmd = "npm install --install-links " + packages.map((p) => `<path-to-AgentPrismForm>/packages/${p.split("/")[1]}`).join(" ");
17209
- const npmInstallCmd = `npm install ${packages.join(" ")}`;
17210
- const integrationDoc = path2.join(absDir, "INTEGRATION.md");
17211
- fs.writeFileSync(
17212
- integrationDoc,
17213
- `# ${compName} Integration Guide / \u63A5\u5165\u6307\u5357
19765
+ const localInstallCmd = packages.length ? "npm install --install-links " + packages.map((p) => `<path-to-AgentPrismForm>/packages/${p.split("/")[1]}`).join(" ") : "";
19766
+ const npmInstallCmd = packages.length ? `npm install ${packages.join(" ")}` : "";
19767
+ const submitNote = effectiveSubmitUrl ? `
19768
+ ## Submit Endpoint / \u63D0\u4EA4\u63A5\u53E3\u51FA\u53E3
19769
+
19770
+ Configured \`submitUrl\`: \`${effectiveSubmitUrl}\`
17214
19771
 
17215
- ## 1. Install Required Packages / \u5B89\u88C5\u4F9D\u8D56\u5305
19772
+ Payload envelope sent via \`POST\` (with \`Idempotency-Key\` header):
19773
+ \`\`\`json
19774
+ { "submissionId": "sub_...", "schemaVersion": "1.0.0", "storageKey": "${schema.storageKey || ""}", "submittedAt": "...", "channel": "web-mobile", "data": { ... } }
19775
+ \`\`\`
19776
+ ` : "";
19777
+ const installSection = packages.length ? `## 1. Install Required Packages / \u5B89\u88C5\u4F9D\u8D56\u5305
17216
19778
 
17217
19779
  **Option A \u2014 From npm registry / \u4ECE npm \u5B98\u65B9\u6E90\u76F4\u63A5\u5B89\u88C5\uFF08\u63A8\u8350\uFF09:**
17218
19780
  \`\`\`bash
@@ -17223,24 +19785,37 @@ ${npmInstallCmd}
17223
19785
  \`\`\`bash
17224
19786
  ${localInstallCmd}
17225
19787
  \`\`\`
19788
+ ` : `## 1. Zero-Dependency Standalone Delivery / \u96F6\u4F9D\u8D56\u72EC\u7ACB\u4EA4\u4ED8
19789
+
19790
+ 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).
19791
+ `;
19792
+ const integrationDoc = path2.join(absDir, "INTEGRATION.md");
19793
+ fs.writeFileSync(
19794
+ integrationDoc,
19795
+ `# ${compName} Integration Guide / \u63A5\u5165\u6307\u5357
19796
+
19797
+ > **Resolved Delivery Target**: \`${resolvedPlatform}\` (${detection.summary})
17226
19798
 
17227
- ## 2. Mount in Your App / \u5728\u4E1A\u52A1\u9875\u9762\u6302\u8F7D
19799
+ ${installSection}
19800
+ ## 2. Mount or Deploy / \u6302\u8F7D\u6216\u90E8\u7F72
17228
19801
 
17229
19802
  \`\`\`tsx
17230
19803
  ${mountSnippet}
17231
19804
  \`\`\`
17232
-
19805
+ ${submitNote}
17233
19806
  ## 3. Files Generated / \u751F\u6210\u6587\u4EF6\u6E05\u5355
17234
19807
  - \`form.bundle.json\` \u2014 Finalized FormSchema + locked ThemeConfig
17235
19808
  - \`types.d.ts\` \u2014 TypeScript DTO derived from FormSchema
17236
- - \`${path2.basename(entryFile)}\` \u2014 Ready-to-run ${platform} page/component (supports \`hostHandlers\` & \`customControls\`)
19809
+ - \`${path2.basename(entryFile)}\` \u2014 Ready-to-run ${resolvedPlatform} deliverable
17237
19810
  `,
17238
19811
  "utf8"
17239
19812
  );
17240
19813
  files.integrationGuide = integrationDoc;
17241
19814
  return {
17242
19815
  status: "scaffolded",
17243
- platform,
19816
+ platform: resolvedPlatform,
19817
+ detection,
19818
+ submitUrl: effectiveSubmitUrl || null,
17244
19819
  componentName: compName,
17245
19820
  outDir: absDir,
17246
19821
  packages,
@@ -17251,6 +19826,7 @@ ${mountSnippet}
17251
19826
  }
17252
19827
  module2.exports = {
17253
19828
  listSnippetsAndPresets,
19829
+ detectHostEnvironment,
17254
19830
  schemaInit,
17255
19831
  schemaSet,
17256
19832
  schemaPatch,
@@ -17271,7 +19847,12 @@ ${mountSnippet}
17271
19847
  hubIngest: dataHub.ingestSubmission,
17272
19848
  hubQuery: dataHub.querySubmissions,
17273
19849
  hubExportCsv: dataHub.exportInboxCsv,
17274
- hubWebhook: dataHub.deliverWebhook
19850
+ hubWebhook: dataHub.deliverWebhook,
19851
+ intakeStart: intake.intakeStart,
19852
+ intakeTurn: intake.intakeSubmitTurn,
19853
+ intakeConfirm: intake.intakeConfirm,
19854
+ intakeStatus: intake.intakeStatus,
19855
+ intakeFinalize: intake.intakeFinalize
17275
19856
  };
17276
19857
  }
17277
19858
  });
@@ -17407,7 +19988,7 @@ var TOOLS = [
17407
19988
  },
17408
19989
  {
17409
19990
  name: "form_preview_html",
17410
- description: '1 \u79D2\u5BFC\u51FA\u96F6\u4F9D\u8D56\u3001\u65E0\u9700\u542F\u52A8\u670D\u52A1\u7684\u79BB\u7EBF\u5355\u6587\u4EF6 HTML\uFF1B\u652F\u6301 mode="preview"\uFF08\u5E26\u6837\u5F0F/\u952E\u76D8\u8C03\u8BD5\u5DE5\u5177\u680F\uFF09\u4E0E mode="final"\uFF08\u96F6\u8C03\u8BD5\u680F\u3001\u6837\u5F0F\u4E0E\u4EA4\u4E92\u5DF2\u6C89\u6DC0\u9501\u5B9A\u7684\u6700\u7EC8\u4EA4\u4ED8\u6210\u54C1\uFF09\uFF0C\u652F\u6301 locale="zh-CN"|"en-US"',
19991
+ description: '1 \u79D2\u5BFC\u51FA\u96F6\u4F9D\u8D56\u3001\u65E0\u9700\u542F\u52A8\u670D\u52A1\u7684\u79BB\u7EBF\u5355\u6587\u4EF6 HTML\uFF1B\u652F\u6301 mode="preview"\uFF08\u5E26\u6837\u5F0F/\u952E\u76D8\u8C03\u8BD5\u5DE5\u5177\u680F\uFF09\u4E0E mode="final"\uFF08\u96F6\u8C03\u8BD5\u680F\u3001\u6837\u5F0F\u4E0E\u4EA4\u4E92\u5DF2\u6C89\u6DC0\u9501\u5B9A\u7684\u6700\u7EC8\u4EA4\u4ED8\u6210\u54C1\uFF09\uFF0C\u652F\u6301 locale="zh-CN"|"en-US" \u4EE5\u53CA\u53EF\u9009 submitUrl \u63D0\u4EA4\u51FA\u53E3',
17411
19992
  inputSchema: {
17412
19993
  type: "object",
17413
19994
  required: ["schemaPath", "out"],
@@ -17416,7 +19997,8 @@ var TOOLS = [
17416
19997
  themePath: { type: "string" },
17417
19998
  out: { type: "string" },
17418
19999
  mode: { type: "string", enum: ["preview", "final"], default: "preview" },
17419
- locale: { type: "string", enum: ["zh-CN", "en-US"], description: "\u53EF\u9009\u8986\u76D6\u5BFC\u51FA HTML \u7684 UI \u8BED\u8A00\uFF08\u9ED8\u8BA4\u8DDF\u968F theme.locale \u6216 zh-CN\uFF09" }
20000
+ locale: { type: "string", enum: ["zh-CN", "en-US"], description: "\u53EF\u9009\u8986\u76D6\u5BFC\u51FA HTML \u7684 UI \u8BED\u8A00\uFF08\u9ED8\u8BA4\u8DDF\u968F theme.locale \u6216 zh-CN\uFF09" },
20001
+ submitUrl: { type: "string", description: "\u53EF\u9009\uFF1A\u663E\u5F0F\u914D\u7F6E\u72EC\u7ACB\u5B9A\u7A3F HTML \u7684 POST JSON \u63D0\u4EA4\u63A5\u53E3\uFF08http/https\uFF09\uFF1B\u7559\u7A7A\u5219 100% \u79BB\u7EBF\u672C\u5730\u56DE\u6267\u3001\u4E0D\u5916\u53D1\u4EFB\u4F55\u6570\u636E" }
17420
20002
  }
17421
20003
  }
17422
20004
  },
@@ -17445,7 +20027,8 @@ var TOOLS = [
17445
20027
  mappingPath: { type: "string" },
17446
20028
  outDir: { type: "string", description: "\u6700\u7EC8\u4EA4\u4ED8\u5305\u8F93\u51FA\u76EE\u5F55" },
17447
20029
  keyStyle: { type: "string", enum: ["snake_case", "camelCase"], default: "snake_case" },
17448
- includeHtml: { type: "boolean", default: true }
20030
+ includeHtml: { type: "boolean", default: true },
20031
+ submitUrl: { type: "string", description: "\u53EF\u9009\uFF1A\u4E3A\u5BFC\u51FA\u7684 final.html \u6CE8\u5165 POST JSON \u63D0\u4EA4\u51FA\u53E3\uFF08http/https\uFF09\uFF1B\u7559\u7A7A\u5219\u7EAF\u79BB\u7EBF" }
17449
20032
  }
17450
20033
  }
17451
20034
  },
@@ -17559,18 +20142,98 @@ var TOOLS = [
17559
20142
  },
17560
20143
  {
17561
20144
  name: "form_scaffold_host",
17562
- description: "\u4E00\u952E\u5C06\u5B9A\u7A3F\u8868\u5355\u811A\u624B\u67B6\u6CE8\u5165\u5230\u76EE\u6807\u5BBF\u4E3B\u5DE5\u7A0B\uFF08vue3 / react18 / miniapp / headless\uFF09\uFF0C\u81EA\u52A8\u751F\u6210 form.bundle.json\u3001types.d.ts\u3001\u63A5\u597D FormCore/\u5355\u5B57\u6BB5\u5931\u7126\u6821\u9A8C/hostHandlers/customControls \u7684\u53EF\u76F4\u63A5\u6302\u8F7D\u9875\u9762\u7EC4\u4EF6\u53CA INTEGRATION.md \u5B89\u88C5\u6307\u5F15",
20145
+ description: 'Agent-First \u4E00\u952E\u81EA\u52A8\u51B3\u7B56\u5E76\u843D\u5730\u6700\u7EC8\u4EA4\u4ED8\u7269\uFF1A\u9ED8\u8BA4 platform="auto" \u81EA\u52A8\u626B\u63CF\u5BBF\u4E3B\u76EE\u5F55\uFF08Vue 3 / React 18 / \u5FAE\u4FE1\u5C0F\u7A0B\u5E8F / \u65E0\u5DE5\u7A0B\u65F6\u81EA\u52A8\u964D\u7EA7\u4E3A\u72EC\u7ACB\u96F6\u4F9D\u8D56 HTML\uFF09\uFF0C\u81EA\u52A8\u751F\u6210 form.bundle.json\u3001types.d.ts\u3001\u53EF\u76F4\u63A5\u6302\u8F7D\u9875\u9762\u6216\u72EC\u7ACB index.html \u53CA INTEGRATION.md',
17563
20146
  inputSchema: {
17564
20147
  type: "object",
17565
- required: ["schemaPath", "platform", "outDir"],
20148
+ required: ["schemaPath", "outDir"],
17566
20149
  properties: {
17567
20150
  schemaPath: { type: "string" },
17568
20151
  themePath: { type: "string" },
17569
- platform: { type: "string", enum: ["vue3", "react18", "miniapp", "headless"] },
17570
- outDir: { type: "string", description: "\u76EE\u6807\u4E1A\u52A1\u5DE5\u7A0B\u5185\u7684\u76EE\u5F55\u8DEF\u5F84\uFF0C\u5982 ./src/forms/event-reg" },
20152
+ platform: {
20153
+ type: "string",
20154
+ enum: ["auto", "vue3", "react18", "miniapp", "standalone", "headless"],
20155
+ default: "auto",
20156
+ description: "\u76EE\u6807\u4EA4\u4ED8\u5F62\u6001\uFF1B\u9ED8\u8BA4 auto \u81EA\u52A8\u63A2\u6D4B\u9879\u76EE\u6280\u672F\u6808\uFF08\u65E0\u524D\u7AEF\u4ED3\u5E93\u65F6\u81EA\u52A8\u4EA7\u51FA\u96F6\u4F9D\u8D56 standalone index.html\uFF09"
20157
+ },
20158
+ projectDir: { type: "string", description: "\u53EF\u9009\uFF1A\u7528\u4E8E auto \u63A2\u6D4B\u7684\u5BBF\u4E3B\u5DE5\u7A0B\u6839\u76EE\u5F55\uFF08\u9ED8\u8BA4\u4ECE outDir \u5411\u4E0A\u626B\u63CF\uFF09" },
20159
+ outDir: { type: "string", description: "\u76EE\u6807\u4EA4\u4ED8\u76EE\u5F55\u8DEF\u5F84\uFF0C\u5982 ./src/forms/event-reg \u6216 ./dist-form" },
17571
20160
  componentName: { type: "string", description: "\u53EF\u9009\u7EC4\u4EF6\u540D\uFF08PascalCase\uFF09" },
17572
20161
  keyStyle: { type: "string", enum: ["snake_case", "camelCase"], default: "snake_case" },
17573
- packageScope: { type: "string", default: "@agentprismform" }
20162
+ packageScope: { type: "string", default: "@agentprismform" },
20163
+ submitUrl: { type: "string", description: "\u53EF\u9009\uFF1A\u663E\u5F0F\u914D\u7F6E\u63D0\u4EA4\u63A5\u6536\u7AEF\u70B9\uFF08http/https\uFF09\uFF0C\u7528\u4E8E\u72EC\u7ACB HTML \u6216\u5C0F\u7A0B\u5E8F\u9ED8\u8BA4\u63D0\u4EA4\u63A5\u53E3" }
20164
+ }
20165
+ }
20166
+ },
20167
+ {
20168
+ name: "form_intake_start",
20169
+ description: "\u3010Agent \u5B9E\u65F6\u4FE1\u606F\u6536\u96C6 \xB7 \u542F\u52A8\u3011\u8F7D\u5165\u4EFB\u610F FormSchema \u5E76\u521D\u59CB\u5316\u786E\u5B9A\u6027 FormCore \u91C7\u96C6\u4F1A\u8BDD\uFF0C\u8FD4\u56DE\u5F53\u524D\u53EF\u89C1\u53EF\u5199\u5B57\u6BB5\u5207\u7247\u3001\u5206\u5C94\u89C4\u5212\uFF08FillPlan\uFF09\u4E0E\u9996\u53E5\u81EA\u7136\u5F15\u5BFC\u95EE\u9898",
20170
+ inputSchema: {
20171
+ type: "object",
20172
+ required: ["schemaPath"],
20173
+ properties: {
20174
+ schemaPath: { type: "string", description: "FormSchema JSON \u6587\u4EF6\u8DEF\u5F84" },
20175
+ locale: { type: "string", enum: ["zh-CN", "en-US"], default: "zh-CN" },
20176
+ mode: { type: "string", enum: ["smart", "preview"], default: "smart" },
20177
+ reviewCritical: { type: "boolean", default: true, description: "\u662F\u5426\u8981\u6C42\u9AD8\u5371 PII\uFF08\u624B\u673A\u53F7/\u8EAB\u4EFD\u8BC1\u7B49\uFF09\u5148\u7ECF\u7528\u6237\u786E\u8BA4" },
20178
+ protectOverwrite: { type: "boolean", default: true, description: "\u8986\u76D6\u5DF2\u6709\u975E\u7A7A\u503C\u65F6\u662F\u5426\u8981\u6C42\u786E\u8BA4" },
20179
+ sessionId: { type: "string", description: "\u53EF\u9009\u81EA\u5B9A\u4E49\u4F1A\u8BDD ID" }
20180
+ }
20181
+ }
20182
+ },
20183
+ {
20184
+ name: "form_intake_turn",
20185
+ description: "\u3010Agent \u5B9E\u65F6\u4FE1\u606F\u6536\u96C6 \xB7 \u5355\u8F6E\u586B\u69FD\u3011\u652F\u6301\u4E09\u79CD\u96F6\u6469\u64E6\u6A21\u5F0F\uFF1A\u2460 Agent \u5DF2\u4ECE\u5BF9\u8BDD\u7406\u89E3\u7528\u6237\u610F\u56FE\u65F6\u76F4\u63A5\u4F20 patch/mentions\uFF080ms \u7ECF FormCore \u6821\u9A8C+BFS \u8054\u52A8+\u98CE\u9669\u77E9\u9635\uFF09\uFF1B\u2461 \u4F20\u7528\u6237\u539F\u8BDD text \u8D70 1ms \u5FEB\u901A\u9053\u6216\u672C\u5730 Ollama SLM \u9690\u79C1\u62BD\u69FD\uFF1B\u2462 \u4F20\u540D\u7247/\u804A\u5929\u622A\u56FE imagePath \u6216 imageBase64 \u8D70\u672C\u5730\u591A\u6A21\u6001\u89C6\u89C9\u6A21\u578B\u76F4\u51FA\u62BD\u69FD\u3002\u8FD4\u56DE\u5DF2\u843D\u4F4D\u9879\u3001\u5F85\u786E\u8BA4\u9879\u3001\u62E6\u622A\u9879\u3001\u7CBE\u51C6\u7F3A\u53E3\u4E0E nextQuestionForUser",
20186
+ inputSchema: {
20187
+ type: "object",
20188
+ required: ["sessionId"],
20189
+ properties: {
20190
+ sessionId: { type: "string" },
20191
+ patch: { type: "object", description: '\u65B9\u5F0F A\uFF08\u63A8\u8350\uFF09\uFF1AAgent \u76F4\u63A5\u8F93\u51FA\u7684\u7ED3\u6784\u5316\u7A00\u758F\u8865\u4E01\uFF0C\u5982 {"full_name":"\u6797\u5C0F\u79BE","team_mode":"team","team_size":4}' },
20192
+ mentions: { type: "object", description: '\u65B9\u5F0F A \u53EF\u9009\uFF1A\u5927\u8BCD\u8868/\u5916\u90E8\u5B57\u5178\u539F\u8BDD\u6682\u5B58\uFF0C\u5982 {"edu":"\u672C\u79D1"}' },
20193
+ text: { type: "string", description: "\u65B9\u5F0F B\uFF1A\u7528\u6237\u539F\u59CB\u53E3\u8BED\u6587\u672C\uFF08\u8D70 1ms \u5FEB\u901A\u9053\u6216\u672C\u5730 SLM \u9690\u79C1\u62BD\u69FD\uFF09" },
20194
+ imagePath: { type: "string", description: "\u65B9\u5F0F C\uFF1A\u672C\u5730\u540D\u7247/\u622A\u56FE\u56FE\u7247\u8DEF\u5F84\uFF08\u8D70\u672C\u5730\u591A\u6A21\u6001\u89C6\u89C9\u6A21\u578B\u62BD\u69FD\uFF09" },
20195
+ imageBase64: { type: "string", description: "\u65B9\u5F0F C\uFF1A\u540D\u7247/\u622A\u56FE Base64 \u6216 data:image/... URL" },
20196
+ useLocalSlm: { type: "boolean", default: true },
20197
+ model: { type: "string", description: "\u53EF\u9009\u672C\u5730 Ollama \u6A21\u578B\u540D\uFF08\u9ED8\u8BA4 qwen3.5:4b-q4_K_M\uFF09" },
20198
+ visionModel: { type: "string", description: "\u53EF\u9009\u672C\u5730\u591A\u6A21\u6001\u89C6\u89C9\u6A21\u578B\u540D\uFF08\u9ED8\u8BA4\u4E0E model \u76F8\u540C\uFF09" }
20199
+ }
20200
+ }
20201
+ },
20202
+ {
20203
+ name: "form_intake_confirm",
20204
+ description: "\u3010Agent \u5B9E\u65F6\u4FE1\u606F\u6536\u96C6 \xB7 \u786E\u8BA4/\u5B57\u5178\u3011\u5728\u7528\u6237\u53E3\u5934\u6216\u70B9\u51FB\u786E\u8BA4\u540E\uFF0C\u63D0\u4EA4/\u4E22\u5F03\u5F85\u786E\u8BA4\u7684\u9AD8\u5371\u6216\u8986\u5199\u9879\uFF0C\u6216\u52A0\u8F7D\u7248\u672C\u5316\u5B57\u5178\u89E3\u6790\u539F\u8BDD",
20205
+ inputSchema: {
20206
+ type: "object",
20207
+ required: ["sessionId"],
20208
+ properties: {
20209
+ sessionId: { type: "string" },
20210
+ confirmKeys: { type: "array", items: { type: "string" }, description: "\u786E\u8BA4\u5199\u5165\u7684\u5B57\u6BB5 key \u5217\u8868\uFF08\u7701\u7565\u5219\u786E\u8BA4\u5168\u90E8\u5F85\u786E\u8BA4\u9879\uFF09" },
20211
+ rejectKeys: { type: "array", items: { type: "string" }, description: "\u4E22\u5F03\u7684\u5F85\u786E\u8BA4\u5B57\u6BB5 key \u5217\u8868" },
20212
+ dictionaryBundle: { type: "object", description: "\u53EF\u9009\uFF1A\u663E\u5F0F\u52A0\u8F7D\u7684\u7248\u672C\u5316\u5916\u90E8\u5B57\u5178\u5305" }
20213
+ }
20214
+ }
20215
+ },
20216
+ {
20217
+ name: "form_intake_status",
20218
+ description: "\u3010Agent \u5B9E\u65F6\u4FE1\u606F\u6536\u96C6 \xB7 \u8FDB\u5EA6\u67E5\u8BE2\u3011\u53EA\u8BFB\u67E5\u770B\u5F53\u524D\u91C7\u96C6\u4F1A\u8BDD\u7684\u8131\u654F\u5DF2\u6536\u6458\u8981\u3001\u5F85\u786E\u8BA4\u9879\u3001\u5269\u4F59\u5FC5\u586B\u7F3A\u53E3\u53CA\u672C\u4EBA\u4E3B\u6743\u9879\u6E05\u5355",
20219
+ inputSchema: {
20220
+ type: "object",
20221
+ required: ["sessionId"],
20222
+ properties: {
20223
+ sessionId: { type: "string" },
20224
+ maskPii: { type: "boolean", default: true }
20225
+ }
20226
+ }
20227
+ },
20228
+ {
20229
+ name: "form_intake_finalize",
20230
+ description: "\u3010Agent \u5B9E\u65F6\u4FE1\u606F\u6536\u96C6 \xB7 \u7EC8\u5C40\u5C01\u7BB1\u3011\u6267\u884C FormCore \u5168\u91CF\u95E8\u7981\u6821\u9A8C\uFF1B\u82E5\u6709\u7F3A\u9879/\u5F85\u786E\u8BA4/\u672A\u5B8C\u6210\u7684\u534F\u8BAE\u6216\u7B7E\u540D\u5219 fail-closed \u62E6\u622A\uFF0C\u5168\u90E8\u901A\u8FC7\u540E\u8F93\u51FA\u6807\u51C6 SubmissionEnvelope",
20231
+ inputSchema: {
20232
+ type: "object",
20233
+ required: ["sessionId"],
20234
+ properties: {
20235
+ sessionId: { type: "string" },
20236
+ manualValues: { type: "object", description: "\u53EF\u9009\uFF1A\u8BB0\u5F55\u7ECF\u4EBA\u7C7B\u672C\u4EBA\u660E\u786E\u6388\u6743\u5B8C\u6210\u7684\u534F\u8BAE/\u7B7E\u540D\u503C" }
17574
20237
  }
17575
20238
  }
17576
20239
  }
@@ -17618,7 +20281,17 @@ async function callTool(name, args = {}) {
17618
20281
  case "form_hub_webhook":
17619
20282
  return await v2.hubWebhook(args);
17620
20283
  case "form_scaffold_host":
17621
- return v2.scaffoldHost(args);
20284
+ return v2.scaffoldHost({ ...args, assetsDir });
20285
+ case "form_intake_start":
20286
+ return await v2.intakeStart({ ...args, dataDir });
20287
+ case "form_intake_turn":
20288
+ return await v2.intakeTurn({ ...args, dataDir });
20289
+ case "form_intake_confirm":
20290
+ return await v2.intakeConfirm({ ...args, dataDir });
20291
+ case "form_intake_status":
20292
+ return await v2.intakeStatus({ ...args, dataDir });
20293
+ case "form_intake_finalize":
20294
+ return await v2.intakeFinalize({ ...args, dataDir });
17622
20295
  default:
17623
20296
  throw Object.assign(new Error(`\u672A\u77E5 MCP \u5DE5\u5177\uFF1A${name}`), { code: "INVALID_ARGUMENT" });
17624
20297
  }