page-agent-sdk 2.20.1 → 2.22.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.
@@ -22,11 +22,14 @@ function v(e) {
22
22
  let t = e.model || "gpt-3.5-turbo", r = e.temperature, i = e.maxTokens, a = e.baseUrl;
23
23
  if (e.mode === "direct") {
24
24
  try {
25
- typeof location < "u" && location.protocol === "https:" && ![
25
+ if (typeof location < "u" && location.protocol === "https:" && ![
26
26
  "localhost",
27
27
  "127.0.0.1",
28
28
  "0.0.0.0"
29
- ].includes(location.hostname) && console.warn("[page-agent-sdk][proxyLlm] direct 模式在生产环境会泄露 apiKey,建议改用 proxy 模式");
29
+ ].includes(location.hostname)) {
30
+ if (e.throwOnDirectInProduction) throw Error("[page-agent-sdk][proxyLlm] direct 模式在生产环境(https + 非本地)会泄露 apiKey(进 bundle),建议改用 proxy 模式(throwOnDirectInProduction 已启用强安全闸;若确需生产直连,设为 false 显式承认风险)");
31
+ console.warn("[page-agent-sdk][proxyLlm] direct 模式在生产环境(https + 非本地)会泄露 apiKey(进 bundle),建议改用 proxy 模式");
32
+ }
30
33
  } catch {}
31
34
  if (!e.apiKey) throw Error("[page-agent-sdk][proxyLlm] direct 模式需提供 apiKey(开发环境用真实 key)");
32
35
  return new n({
@@ -14044,12 +14047,12 @@ function Hg(e, t) {
14044
14047
  });
14045
14048
  }
14046
14049
  function Ug(e, t, n) {
14047
- let r = n?.message || String(n);
14050
+ let r = n?.message || String(n), i = typeof t == "string" ? t : JSON.stringify(t);
14048
14051
  return $({
14049
14052
  code: "JSON_PARSE",
14050
14053
  ...e === void 0 ? {} : { path: e },
14051
14054
  message: `value 不是合法 JSON:${r}`,
14052
- hint: `检查引号/逗号/括号是否闭合;字符串值需双引号包裹(如 '"dark"' 表示字符串 dark,数字直接写如 5);预览前 80 字符:${t.slice(0, 80)}`
14055
+ hint: `检查引号/逗号/括号是否闭合;字符串值需双引号包裹(如 '"dark"' 表示字符串 dark,数字直接写如 5);预览前 80 字符:${i.slice(0, 80)}`
14053
14056
  });
14054
14057
  }
14055
14058
  function Wg(e) {
@@ -14629,7 +14632,7 @@ function x_(e) {
14629
14632
  return y_(e, t);
14630
14633
  }
14631
14634
  function de(e) {
14632
- return e.map((e) => {
14635
+ return !E && !S ? [] : e.map((e) => {
14633
14636
  let t = le(e), n = { role: t === "human" ? "user" : t === "ai" ? "assistant" : t }, r = typeof e.content == "string" ? e.content : JSON.stringify(e.content);
14634
14637
  r && (n.content = r.length > v_ ? r.slice(0, v_) + `…(截断 ${r.length - v_} 字符)` : r);
14635
14638
  let i = e.tool_calls;
@@ -15408,24 +15411,25 @@ function rv(e) {
15408
15411
  return t;
15409
15412
  }
15410
15413
  function iv(e) {
15411
- let t = [], n = e.maxCheckpoints ?? 5, r = 1;
15414
+ let t = [], n = e.maxCheckpoints ?? 5, r = 1, i, a;
15412
15415
  return {
15413
- save(i) {
15414
- let a = rv(e.messages), o = {};
15415
- if (e.getData) o[""] = Q_(e.getData());
15416
- else for (let t of e.slotPaths ?? []) o[t] = Q_($_(window, t));
15417
- let s = {
15416
+ save(o) {
15417
+ let s = rv(e.messages), c = {};
15418
+ if (e.getData) ((e.consumeDataDirty?.() ?? !0) || a === void 0) && (a = Q_(e.getData())), c[""] = a;
15419
+ else for (let t of e.slotPaths ?? []) c[t] = Q_($_(window, t));
15420
+ ((e.vfsStore.consumeDirty?.() ?? !0) || i === void 0) && (i = Q_(e.vfsStore.files));
15421
+ let l = {
15418
15422
  id: r++,
15419
- label: i,
15423
+ label: o,
15420
15424
  timestamp: Date.now(),
15421
- messages: Q_(a),
15422
- windowVals: o,
15423
- vfs: Q_(e.vfsStore.files),
15425
+ messages: Q_(s),
15426
+ windowVals: c,
15427
+ vfs: i,
15424
15428
  todos: Q_(e.getTodos()),
15425
- messageCount: a.length
15429
+ messageCount: s.length
15426
15430
  };
15427
- for (t.push(s); t.length > n;) t.shift();
15428
- return s.id;
15431
+ for (t.push(l); t.length > n;) t.shift();
15432
+ return l.id;
15429
15433
  },
15430
15434
  list() {
15431
15435
  return t.map((e) => ({
@@ -15448,15 +15452,15 @@ function iv(e) {
15448
15452
  typeof n == "object" && n && tv(n, Q_(t));
15449
15453
  }
15450
15454
  } else for (let [e, t] of Object.entries(r.windowVals)) nv(e, Q_(t));
15451
- let i = e.vfsStore.files;
15452
- for (let e of Object.keys(i)) delete i[e];
15453
- return Object.assign(i, Q_(r.vfs)), e.todosMw.reset(Q_(r.todos)), !0;
15455
+ let o = e.vfsStore.files;
15456
+ for (let e of Object.keys(o)) delete o[e];
15457
+ return Object.assign(o, Q_(r.vfs)), e.todosMw.reset(Q_(r.todos)), a = void 0, i = void 0, !0;
15454
15458
  },
15455
15459
  exportStack() {
15456
15460
  return Q_(t);
15457
15461
  },
15458
15462
  importStack(e) {
15459
- t.length = 0;
15463
+ t.length = 0, i = void 0, a = void 0;
15460
15464
  let n = Array.isArray(e) ? e : [];
15461
15465
  for (let e of n) e && typeof e == "object" && "id" in e && "messages" in e && typeof e.id == "number" && Number.isFinite(e.id) && t.push(e);
15462
15466
  r = t.reduce((e, t) => Math.max(e, t.id), 0) + 1;
@@ -16383,9 +16387,21 @@ var _y = {
16383
16387
  "3. 不确定某字段结构时,read({ jsonPath }) 返回含格式说明,字段以返回为准;",
16384
16388
  "4. 写入若被 schema 校验拒绝(返回结构化错误含字段名与期望类型),按错误修正后重试,不要放弃;",
16385
16389
  "5. 优先用 write 的 patch 增量改(只发改动,如 write({ value, patch:{ op, jsonPath } })),避免整体重传大 JSON 被截断。"
16386
- ].join("\n") }, yy = 15, by = 4e3;
16387
- function xy(e, t) {
16390
+ ].join("\n") }, yy = 15, by = 4e3, xy = /* @__PURE__ */ new WeakMap();
16391
+ function Sy(e, t) {
16388
16392
  if (!e) return "";
16393
+ let n = t ? `${t.maxKeys ?? ""}|${t.maxChars ?? ""}` : "";
16394
+ if (typeof e == "object") {
16395
+ let t = xy.get(e);
16396
+ if (t && t.optsKey === n) return t.hint;
16397
+ }
16398
+ let r = Cy(e, t);
16399
+ return typeof e == "object" && xy.set(e, {
16400
+ optsKey: n,
16401
+ hint: r
16402
+ }), r;
16403
+ }
16404
+ function Cy(e, t) {
16389
16405
  let n = my(e);
16390
16406
  if (n) {
16391
16407
  let r = t?.maxKeys ?? yy, i = t?.maxChars ?? by;
@@ -16399,36 +16415,36 @@ function xy(e, t) {
16399
16415
  }
16400
16416
  //#endregion
16401
16417
  //#region src/core/sdk/promptBuilder.ts
16402
- var Sy = [
16418
+ var wy = [
16403
16419
  "你是一个 JSON 操作助手。集成方声明了一个主数据对象(含 zod schema 校验),你通过专用工具安全地读写它来完成任务。",
16404
16420
  "所有写操作都经范围控制(仅 schema 声明字段内)与 schema 校验(不合法会返回结构化错误而非写入),并自动留快照可回退。",
16405
16421
  "大对象/数组优先用增量 patch(只发改动)而非整体重传,避免输出被截断。",
16406
16422
  "---",
16407
16423
  vy.reliableWriteRules
16408
16424
  ].join("\n\n");
16409
- function Cy(e, t) {
16425
+ function Ty(e, t) {
16410
16426
  if (!e) return "";
16411
- let n = xy(e.schema, t);
16427
+ let n = Sy(e.schema, t);
16412
16428
  return `\n\n## 可操作数据(字段以 read 工具返回的实际值为准)\n${e.description ? e.description + "\n" : ""}${n}`;
16413
16429
  }
16414
- function wy(e) {
16430
+ function Ey(e) {
16415
16431
  let t = e.appendReliableWriteRules !== !1;
16416
- return e.systemPrompt ? t ? e.systemPrompt + "\n\n---\n\n" + vy.reliableWriteRules : e.systemPrompt : Sy;
16432
+ return e.systemPrompt ? t ? e.systemPrompt + "\n\n---\n\n" + vy.reliableWriteRules : e.systemPrompt : wy;
16417
16433
  }
16418
16434
  //#endregion
16419
16435
  //#region src/core/sdk/llmResolver.ts
16420
- function Ty(e) {
16436
+ function Dy(e) {
16421
16437
  return !!e && typeof e == "object" && typeof e.invoke == "function" && typeof e.stream == "function";
16422
16438
  }
16423
- function Ey(e) {
16439
+ function Oy(e) {
16424
16440
  let t = e.content;
16425
16441
  return typeof t == "string" ? t : Array.isArray(t) ? t.map((e) => typeof e == "string" ? e : e?.text ?? "").join("") : String(t ?? "");
16426
16442
  }
16427
- function Dy(e) {
16443
+ function ky(e) {
16428
16444
  let t = e.summaryLlm ?? e.llm;
16429
16445
  if (!t) return;
16430
16446
  let r = e.summaryTemperature ?? .3, i = e.summaryMaxTokens ?? 1024, s = e.summaryTimeoutMs ?? 15e3, c;
16431
- if (Ty(t)) c = t;
16447
+ if (Dy(t)) c = t;
16432
16448
  else {
16433
16449
  let a = t;
16434
16450
  if (!a.apiKey) {
@@ -16450,26 +16466,26 @@ function Dy(e) {
16450
16466
  return async (e) => {
16451
16467
  let t = new AbortController(), n = setTimeout(() => t.abort(), s);
16452
16468
  try {
16453
- return Ey(await c.invoke([new o("你是对话历史压缩助手。把下面按轮次索引的对话要点,改写成一段连贯、紧凑的中文摘要,保留关键事实、用户意图与已用工具,不要编造。直接输出摘要正文。"), new a(e)], { signal: t.signal })).trim();
16469
+ return Oy(await c.invoke([new o("你是对话历史压缩助手。把下面按轮次索引的对话要点,改写成一段连贯、紧凑的中文摘要,保留关键事实、用户意图与已用工具,不要编造。直接输出摘要正文。"), new a(e)], { signal: t.signal })).trim();
16454
16470
  } finally {
16455
16471
  clearTimeout(n);
16456
16472
  }
16457
16473
  };
16458
16474
  }
16459
- function Oy(e) {
16460
- let t = Ty(e.llm) ? void 0 : e.llm;
16475
+ function Ay(e) {
16476
+ let t = Dy(e.llm) ? void 0 : e.llm;
16461
16477
  return {
16462
16478
  modelCaps: $g({
16463
16479
  model: t?.model,
16464
16480
  contextWindow: e.contextWindow ?? t?.contextWindow,
16465
16481
  maxOutputTokens: e.maxOutputTokens ?? t?.maxOutputTokens
16466
16482
  }),
16467
- summaryLlmInvoke: Dy(e)
16483
+ summaryLlmInvoke: ky(e)
16468
16484
  };
16469
16485
  }
16470
16486
  //#endregion
16471
16487
  //#region src/core/sdk/conflictManager.ts
16472
- function ky(e) {
16488
+ function jy(e) {
16473
16489
  let t = /* @__PURE__ */ U(null), n = 0;
16474
16490
  function r(r) {
16475
16491
  return new Promise((i) => {
@@ -16480,7 +16496,9 @@ function ky(e) {
16480
16496
  id: ++n,
16481
16497
  resolve: i
16482
16498
  };
16483
- t.value = o, e?.()({
16499
+ t.value = o;
16500
+ let s = e?.();
16501
+ s?.({
16484
16502
  type: "conflict",
16485
16503
  conflict: o
16486
16504
  });
@@ -16498,7 +16516,7 @@ function ky(e) {
16498
16516
  }
16499
16517
  //#endregion
16500
16518
  //#region src/core/utils/id.ts
16501
- function Ay() {
16519
+ function My() {
16502
16520
  try {
16503
16521
  if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
16504
16522
  } catch {}
@@ -16506,57 +16524,59 @@ function Ay() {
16506
16524
  }
16507
16525
  //#endregion
16508
16526
  //#region src/core/backends/storage.ts
16509
- var jy = "chat-sdk", My = 52428800, Ny = 4194304, Py = 10485760, Fy = .9, Iy = 500, Ly = 300, Ry = "__meta__", zy = "v:1", By = [
16527
+ var Ny = "chat-sdk", Py = 52428800, Fy = 4194304, Iy = 10485760, Ly = .9, Ry = 500, zy = 300, By = "__meta__", Vy = "v:1", Hy = [
16510
16528
  "messages",
16511
16529
  "vfs",
16512
16530
  "todos",
16513
- "memory"
16531
+ "memory",
16532
+ "checkpoints",
16533
+ "usage"
16514
16534
  ];
16515
- function Vy(e) {
16516
- return e === "local" || e === "session" ? Ny : My;
16535
+ function Uy(e) {
16536
+ return e === "local" || e === "session" ? Fy : Py;
16517
16537
  }
16518
- function Hy(e) {
16538
+ function Wy(e) {
16519
16539
  if (typeof e != "object" || !e) return !1;
16520
16540
  let t = e;
16521
16541
  return t.name === "QuotaExceededError" || t.name === "NS_ERROR_DOM_QUOTA_REACHED" || t.code === 22 || t.code === 1014;
16522
16542
  }
16523
- function Uy(e, t, n, r) {
16543
+ function Gy(e, t, n, r) {
16524
16544
  return [
16525
- zy,
16545
+ Vy,
16526
16546
  e,
16527
16547
  t,
16528
16548
  n,
16529
16549
  r
16530
16550
  ].join("::");
16531
16551
  }
16532
- function Wy(e, t, n) {
16552
+ function Ky(e, t, n) {
16533
16553
  return [
16534
- zy,
16554
+ Vy,
16535
16555
  e,
16536
16556
  t,
16537
16557
  n
16538
16558
  ].join("::") + "::";
16539
16559
  }
16540
- function Gy(e, t) {
16560
+ function qy(e, t) {
16541
16561
  return [
16542
- zy,
16562
+ Vy,
16543
16563
  e,
16544
16564
  t
16545
16565
  ].join("::") + "::";
16546
16566
  }
16547
- function Ky(e) {
16548
- return [zy, e].join("::") + "::";
16549
- }
16550
- var qy = null;
16551
16567
  function Jy(e) {
16552
- qy ||= new TextEncoder();
16568
+ return [Vy, e].join("::") + "::";
16569
+ }
16570
+ var Yy = null;
16571
+ function Xy(e) {
16572
+ Yy ||= new TextEncoder();
16553
16573
  try {
16554
- return qy.encode(JSON.stringify(e)).length;
16574
+ return Yy.encode(JSON.stringify(e)).length;
16555
16575
  } catch {
16556
16576
  return 0;
16557
16577
  }
16558
16578
  }
16559
- function Yy(e, t, n) {
16579
+ function Zy(e, t, n) {
16560
16580
  let r = e.reduce((e, t) => e + t.bytes, 0);
16561
16581
  if (r <= t) return [];
16562
16582
  let i = t * n, a = [...e].sort((e, t) => e.lastAccessed - t.lastAccessed), o = [];
@@ -16566,7 +16586,7 @@ function Yy(e, t, n) {
16566
16586
  }
16567
16587
  return o;
16568
16588
  }
16569
- function Xy() {
16589
+ function Qy() {
16570
16590
  let e = /* @__PURE__ */ new Map();
16571
16591
  return {
16572
16592
  async get(t) {
@@ -16586,7 +16606,7 @@ function Xy() {
16586
16606
  }
16587
16607
  };
16588
16608
  }
16589
- function Zy(e) {
16609
+ function $y(e) {
16590
16610
  return new Promise((t, n) => {
16591
16611
  if (typeof indexedDB > "u") {
16592
16612
  n(/* @__PURE__ */ Error("indexedDB 不可用"));
@@ -16647,7 +16667,7 @@ function Zy(e) {
16647
16667
  }, r.onerror = () => n(r.error);
16648
16668
  });
16649
16669
  }
16650
- function Qy(e) {
16670
+ function eb(e) {
16651
16671
  return {
16652
16672
  async get(t) {
16653
16673
  let n = e.getItem(t);
@@ -16681,12 +16701,12 @@ function Qy(e) {
16681
16701
  }
16682
16702
  };
16683
16703
  }
16684
- function $y(e, t, n) {
16704
+ function tb(e, t, n) {
16685
16705
  let r = (e.get(t) ?? Promise.resolve()).then(n, n);
16686
16706
  return e.set(t, r.then(() => void 0, () => void 0)), r;
16687
16707
  }
16688
- function eb(e = {}) {
16689
- let t = e.dbName ?? jy, n = e.backend ?? "indexed", r = e.maxBytes ?? Vy(n), i = e.maxBytesPerSession ?? Py, a = e.evictionWatermark ?? Fy, o = e.debounceMs ?? Iy, s = /* @__PURE__ */ new Set();
16708
+ function nb(e = {}) {
16709
+ let t = e.dbName ?? Ny, n = e.backend ?? "indexed", r = e.maxBytes ?? Uy(n), i = e.maxBytesPerSession ?? Iy, a = e.evictionWatermark ?? Ly, o = e.debounceMs ?? Ry, s = /* @__PURE__ */ new Set();
16690
16710
  function c(e) {
16691
16711
  for (let t of s) try {
16692
16712
  t(e);
@@ -16699,16 +16719,16 @@ function eb(e = {}) {
16699
16719
  try {
16700
16720
  if (n === "indexed") {
16701
16721
  if (typeof indexedDB > "u") throw Error("indexedDB 不可用");
16702
- l = await Zy(t), d(!0);
16722
+ l = await $y(t), d(!0);
16703
16723
  } else if (n === "session") {
16704
16724
  if (typeof sessionStorage > "u") throw Error("sessionStorage 不可用");
16705
- l = Qy(sessionStorage), d(!0);
16725
+ l = eb(sessionStorage), d(!0);
16706
16726
  } else if (n === "local") {
16707
16727
  if (typeof localStorage > "u") throw Error("localStorage 不可用");
16708
- l = Qy(localStorage), d(!0);
16709
- } else l = Xy(), d(!1);
16728
+ l = eb(localStorage), d(!0);
16729
+ } else l = Qy(), d(!1);
16710
16730
  } catch (e) {
16711
- l = Xy();
16731
+ l = Qy();
16712
16732
  let t = e instanceof Error ? e.message : String(e);
16713
16733
  d(!1), Promise.resolve().then(() => c({
16714
16734
  type: "degraded",
@@ -16718,10 +16738,10 @@ function eb(e = {}) {
16718
16738
  })();
16719
16739
  let p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map();
16720
16740
  function g(e, n, r, a) {
16721
- let o = Uy(t, r, a, Ry);
16722
- return $y(h, o, async () => {
16741
+ let o = Gy(t, r, a, By);
16742
+ return tb(h, o, async () => {
16723
16743
  let t = async () => {
16724
- let t = await l.get(o), s = await l.get(e), u = s == null ? 0 : Jy(s), d = Jy(n), f = (t?.bytes ?? 0) + (d - u);
16744
+ let t = await l.get(o), s = await l.get(e), u = s == null ? 0 : Xy(s), d = Xy(n), f = (t?.bytes ?? 0) + (d - u);
16725
16745
  if (f > i) {
16726
16746
  c({
16727
16747
  type: "quota",
@@ -16743,12 +16763,12 @@ function eb(e = {}) {
16743
16763
  try {
16744
16764
  await t();
16745
16765
  } catch (e) {
16746
- if (Hy(e) && !u) {
16766
+ if (Wy(e) && !u) {
16747
16767
  u = !0;
16748
16768
  try {
16749
16769
  await b();
16750
16770
  } catch {}
16751
- l = Xy(), Promise.resolve().then(() => c({
16771
+ l = Qy(), Promise.resolve().then(() => c({
16752
16772
  type: "degraded",
16753
16773
  reason: "存储配额超限(QuotaExceededError),已淘汰最旧会话并降级内存"
16754
16774
  }));
@@ -16760,7 +16780,7 @@ function eb(e = {}) {
16760
16780
  });
16761
16781
  }
16762
16782
  function _(e, n, r, i) {
16763
- let a = Uy(t, e, n, r), s = p.get(a);
16783
+ let a = Gy(t, e, n, r), s = p.get(a);
16764
16784
  s && s.resolve();
16765
16785
  let c = m.get(a);
16766
16786
  return c && clearTimeout(c), new Promise((t) => {
@@ -16787,15 +16807,15 @@ function eb(e = {}) {
16787
16807
  function y() {
16788
16808
  v ||= setTimeout(() => {
16789
16809
  v = null, b();
16790
- }, Ly);
16810
+ }, zy);
16791
16811
  }
16792
16812
  async function b() {
16793
16813
  let e = [];
16794
- await l.scan(Ky(t), (t, n) => {
16814
+ await l.scan(Jy(t), (t, n) => {
16795
16815
  t.endsWith("::__meta__") && e.push(n);
16796
16816
  });
16797
- let n = Yy(e, r, a);
16798
- for (let e of n) await l.clearPrefix(Wy(t, e.agentId, e.sessionId)), c({
16817
+ let n = Zy(e, r, a);
16818
+ for (let e of n) await l.clearPrefix(Ky(t, e.agentId, e.sessionId)), c({
16799
16819
  type: "evicted",
16800
16820
  agentId: e.agentId,
16801
16821
  sessionId: e.sessionId,
@@ -16806,13 +16826,13 @@ function eb(e = {}) {
16806
16826
  ready: f,
16807
16827
  async listSessions(e) {
16808
16828
  let n = [];
16809
- return await l.scan(Gy(t, e), (e, t) => {
16829
+ return await l.scan(qy(t, e), (e, t) => {
16810
16830
  e.endsWith("::__meta__") && n.push(t);
16811
16831
  }), n.sort((e, t) => t.lastAccessed - e.lastAccessed);
16812
16832
  },
16813
16833
  async load(e, n) {
16814
- let r = Uy(t, e, n, Ry);
16815
- return await $y(h, r, async () => {
16834
+ let r = Gy(t, e, n, By);
16835
+ return await tb(h, r, async () => {
16816
16836
  let i = await l.get(r);
16817
16837
  if (!i) return;
16818
16838
  let a = {
@@ -16821,8 +16841,8 @@ function eb(e = {}) {
16821
16841
  todos: [],
16822
16842
  memory: ""
16823
16843
  };
16824
- for (let r of By) {
16825
- let i = await l.get(Uy(t, e, n, r));
16844
+ for (let r of Hy) {
16845
+ let i = await l.get(Gy(t, e, n, r));
16826
16846
  i != null && (a[r] = i);
16827
16847
  }
16828
16848
  return i.lastAccessed = Date.now(), await l.set(r, i), a;
@@ -16830,7 +16850,7 @@ function eb(e = {}) {
16830
16850
  },
16831
16851
  async save(e, t, n) {
16832
16852
  let r = [];
16833
- for (let i of By) n[i] !== void 0 && r.push(_(e, t, i, n[i]));
16853
+ for (let i of Hy) n[i] !== void 0 && r.push(_(e, t, i, n[i]));
16834
16854
  await Promise.all(r);
16835
16855
  },
16836
16856
  async flush() {
@@ -16844,10 +16864,10 @@ function eb(e = {}) {
16844
16864
  })), c({ type: "flush" }), await b();
16845
16865
  },
16846
16866
  async deleteSession(e, n) {
16847
- await l.clearPrefix(Wy(t, e, n));
16867
+ await l.clearPrefix(Ky(t, e, n));
16848
16868
  },
16849
16869
  async createSession(e, n, r) {
16850
- let i = r ?? Ay(), a = Date.now(), o = {
16870
+ let i = r ?? My(), a = Date.now(), o = {
16851
16871
  agentId: e,
16852
16872
  sessionId: i,
16853
16873
  createdAt: a,
@@ -16855,7 +16875,7 @@ function eb(e = {}) {
16855
16875
  bytes: 0,
16856
16876
  title: n
16857
16877
  };
16858
- return await l.set(Uy(t, e, i, Ry), o), i;
16878
+ return await l.set(Gy(t, e, i, By), o), i;
16859
16879
  },
16860
16880
  onEvent(e) {
16861
16881
  s.add(e);
@@ -16870,15 +16890,102 @@ function eb(e = {}) {
16870
16890
  }
16871
16891
  //#endregion
16872
16892
  //#region src/core/sdk/optionsResolver.ts
16873
- function tb(e) {
16874
- return e === void 0 || e === !1 ? null : typeof e == "string" ? eb({ backend: e }) : e.enabled === !1 ? null : eb(e);
16893
+ function rb(e) {
16894
+ return e === void 0 || e === !1 ? null : typeof e == "string" ? nb({ backend: e }) : e.enabled === !1 ? null : nb(e);
16875
16895
  }
16876
- function nb(e) {
16896
+ function ib(e) {
16877
16897
  return e.dialog ?? {};
16878
16898
  }
16879
16899
  //#endregion
16900
+ //#region src/core/capabilities.ts
16901
+ var ab = [
16902
+ {
16903
+ name: "dataOps",
16904
+ defaultOn: !0
16905
+ },
16906
+ {
16907
+ name: "fetch",
16908
+ defaultOn: !0
16909
+ },
16910
+ {
16911
+ name: "planning",
16912
+ defaultOn: !0
16913
+ },
16914
+ {
16915
+ name: "missionAnchor",
16916
+ defaultOn: !0
16917
+ },
16918
+ {
16919
+ name: "workingMemory",
16920
+ defaultOn: !0
16921
+ },
16922
+ {
16923
+ name: "skills",
16924
+ defaultOn: !0
16925
+ },
16926
+ {
16927
+ name: "vfs",
16928
+ defaultOn: !0
16929
+ },
16930
+ {
16931
+ name: "summarization",
16932
+ defaultOn: !0
16933
+ },
16934
+ {
16935
+ name: "memory",
16936
+ defaultOn: !0
16937
+ },
16938
+ {
16939
+ name: "subagent",
16940
+ defaultOn: !0
16941
+ },
16942
+ {
16943
+ name: "inspectEnv",
16944
+ defaultOn: !0
16945
+ },
16946
+ {
16947
+ name: "verify",
16948
+ defaultOn: !1
16949
+ },
16950
+ {
16951
+ name: "domInspect",
16952
+ defaultOn: !1
16953
+ },
16954
+ {
16955
+ name: "draftWrite",
16956
+ defaultOn: !1,
16957
+ requires: ["dataOps", "vfs"]
16958
+ },
16959
+ {
16960
+ name: "tracing",
16961
+ defaultOn: !1
16962
+ },
16963
+ {
16964
+ name: "todoDeps",
16965
+ defaultOn: !1
16966
+ },
16967
+ {
16968
+ name: "automation",
16969
+ defaultOn: !1
16970
+ }
16971
+ ];
16972
+ function ob(e) {
16973
+ let t = {};
16974
+ for (let n of ab) {
16975
+ let r = e?.[n.name];
16976
+ t[n.name] = n.defaultOn ? r !== !1 : r === !0;
16977
+ }
16978
+ for (let e of ab) if (e.requires && t[e.name]) {
16979
+ for (let n of e.requires) if (!t[n]) {
16980
+ t[e.name] = !1;
16981
+ break;
16982
+ }
16983
+ }
16984
+ return t;
16985
+ }
16986
+ //#endregion
16880
16987
  //#region src/core/sdk/events.ts
16881
- function rb(e) {
16988
+ function sb(e) {
16882
16989
  let t = /* @__PURE__ */ new Set(), n = (n) => {
16883
16990
  if (n.type !== "approval_request") {
16884
16991
  if (e) try {
@@ -16904,7 +17011,7 @@ function rb(e) {
16904
17011
  }
16905
17012
  //#endregion
16906
17013
  //#region src/core/sdk/contextPreset.ts
16907
- var ib = {
17014
+ var cb = {
16908
17015
  auto: {
16909
17016
  summaryThresholdRatio: .5,
16910
17017
  windowRatio: .4,
@@ -16932,7 +17039,7 @@ var ib = {
16932
17039
  enableRecall: !0,
16933
17040
  enableLLMSummary: !0
16934
17041
  }
16935
- }, ab = {
17042
+ }, lb = {
16936
17043
  auto: ["describe_data", "read"],
16937
17044
  conservative: ["describe_data"],
16938
17045
  aggressive: ["describe_data", "read"],
@@ -16943,8 +17050,8 @@ var ib = {
16943
17050
  "search_data"
16944
17051
  ]
16945
17052
  };
16946
- function ob(e, t) {
16947
- let n = ib[e.contextPreset ?? "auto"] ?? {}, r = e.contextOptions === !1 ? {} : e.contextOptions ?? {};
17053
+ function ub(e, t) {
17054
+ let n = cb[e.contextPreset ?? "auto"] ?? {}, r = e.contextOptions === !1 ? {} : e.contextOptions ?? {};
16948
17055
  return {
16949
17056
  ...n,
16950
17057
  ...r,
@@ -16954,7 +17061,7 @@ function ob(e, t) {
16954
17061
  }
16955
17062
  //#endregion
16956
17063
  //#region src/core/sdk/middlewareStack.ts
16957
- var sb = {
17064
+ var db = {
16958
17065
  dataHint: 10,
16959
17066
  usageHints: 20,
16960
17067
  todos: 30,
@@ -16971,29 +17078,29 @@ var sb = {
16971
17078
  subagents: 140,
16972
17079
  augmentSystem: 150
16973
17080
  };
16974
- function cb(e) {
17081
+ function fb(e) {
16975
17082
  return e.map((e, t) => ({
16976
17083
  m: e,
16977
17084
  i: t,
16978
- p: sb[e.name] ?? Infinity
17085
+ p: db[e.name] ?? Infinity
16979
17086
  })).sort((e, t) => e.p - t.p || e.i - t.i).map((e) => e.m);
16980
17087
  }
16981
17088
  //#endregion
16982
17089
  //#region src/core/tools/jsonUtils.ts
16983
- var lb = /* @__PURE__ */ new Set([
17090
+ var pb = /* @__PURE__ */ new Set([
16984
17091
  "__proto__",
16985
17092
  "constructor",
16986
17093
  "prototype"
16987
17094
  ]);
16988
- function ub(e) {
16989
- return e.split(".").some((e) => lb.has(e));
17095
+ function mb(e) {
17096
+ return e.split(".").some((e) => pb.has(e));
16990
17097
  }
16991
- function db(e, t) {
16992
- if (!(!t || typeof t != "object" || Array.isArray(t))) for (let n of Object.keys(t)) lb.has(n) || (e[n] = t[n]);
17098
+ function hb(e, t) {
17099
+ if (!(!t || typeof t != "object" || Array.isArray(t))) for (let n of Object.keys(t)) pb.has(n) || (e[n] = t[n]);
16993
17100
  }
16994
- function fb(e, t) {
17101
+ function gb(e, t) {
16995
17102
  if (!t) return e;
16996
- if (ub(t)) return;
17103
+ if (mb(t)) return;
16997
17104
  let n = t.split("."), r = e;
16998
17105
  for (let e of n) {
16999
17106
  if (r == null) return;
@@ -17001,8 +17108,8 @@ function fb(e, t) {
17001
17108
  }
17002
17109
  return r;
17003
17110
  }
17004
- function pb(e, t, n) {
17005
- if (!t || ub(t)) return;
17111
+ function _b(e, t, n) {
17112
+ if (!t || mb(t)) return;
17006
17113
  let r = t.split("."), i = e;
17007
17114
  for (let e = 0; e < r.length - 1; e++) {
17008
17115
  let t = r[e];
@@ -17010,8 +17117,8 @@ function pb(e, t, n) {
17010
17117
  }
17011
17118
  i[r[r.length - 1]] = n;
17012
17119
  }
17013
- function mb(e, t) {
17014
- if (!t || ub(t)) return !1;
17120
+ function vb(e, t) {
17121
+ if (!t || mb(t)) return !1;
17015
17122
  let n = t.split("."), r = e;
17016
17123
  for (let e = 0; e < n.length - 1; e++) {
17017
17124
  if (r == null) return !1;
@@ -17020,10 +17127,10 @@ function mb(e, t) {
17020
17127
  let i = n[n.length - 1];
17021
17128
  return r == null || !(i in r) ? !1 : (Array.isArray(r) && /^\d+$/.test(i) ? r.splice(Number(i), 1) : delete r[i], !0);
17022
17129
  }
17023
- function hb(e) {
17130
+ function yb(e) {
17024
17131
  return e === void 0 ? void 0 : JSON.parse(JSON.stringify(e));
17025
17132
  }
17026
- function gb(e) {
17133
+ function bb(e) {
17027
17134
  if (typeof e != "string") return { parsed: e };
17028
17135
  let t = e.trim();
17029
17136
  if (!t) return { parsed: e };
@@ -17034,23 +17141,23 @@ function gb(e) {
17034
17141
  return n ? { parseError: t } : { parsed: e };
17035
17142
  }
17036
17143
  }
17037
- function _b(e, t) {
17144
+ function xb(e, t) {
17038
17145
  if (typeof e != "object" || !e) return e;
17039
17146
  let n = new Set(t);
17040
- if (Array.isArray(e)) return e.map((e) => _b(e, t));
17147
+ if (Array.isArray(e)) return e.map((e) => xb(e, t));
17041
17148
  let r = {};
17042
17149
  for (let t of Object.keys(e)) n.has(t) && (r[t] = e[t]);
17043
17150
  return r;
17044
17151
  }
17045
- function vb(e, t) {
17152
+ function Sb(e, t) {
17046
17153
  if (typeof e != "object" || !e) return e;
17047
17154
  if (t <= 0) return Array.isArray(e) ? `[...${e.length}]` : "{...}";
17048
- if (Array.isArray(e)) return e.map((e) => vb(e, t - 1));
17155
+ if (Array.isArray(e)) return e.map((e) => Sb(e, t - 1));
17049
17156
  let n = {};
17050
- for (let r of Object.keys(e)) n[r] = vb(e[r], t - 1);
17157
+ for (let r of Object.keys(e)) n[r] = Sb(e[r], t - 1);
17051
17158
  return n;
17052
17159
  }
17053
- function yb(e, t = Infinity) {
17160
+ function Cb(e, t = Infinity) {
17054
17161
  let n = /* @__PURE__ */ new WeakSet(), r;
17055
17162
  try {
17056
17163
  r = JSON.stringify(e, (e, t) => {
@@ -17069,7 +17176,7 @@ function yb(e, t = Infinity) {
17069
17176
  }
17070
17177
  return r.length > t && (r = r.slice(0, t) + `\n…[已截断,原长度 ${r.length}]`), r;
17071
17178
  }
17072
- function bb(e, t = 0) {
17179
+ function wb(e, t = 0) {
17073
17180
  let n = 3735928559 ^ t, r = 1103547991 ^ t;
17074
17181
  for (let t = 0; t < e.length; t++) {
17075
17182
  let i = e.charCodeAt(t);
@@ -17077,32 +17184,32 @@ function bb(e, t = 0) {
17077
17184
  }
17078
17185
  return n = Math.imul(n ^ n >>> 16, 2246822507) ^ Math.imul(r ^ r >>> 13, 3266489909), r = Math.imul(r ^ r >>> 16, 2246822507) ^ Math.imul(n ^ n >>> 13, 3266489909), 4294967296 * (2097151 & r) + (n >>> 0);
17079
17186
  }
17080
- function xb(e) {
17081
- return bb(yb(e)).toString(36);
17187
+ function Tb(e) {
17188
+ return wb(Cb(e)).toString(36);
17082
17189
  }
17083
- function Sb(e, t, n, r) {
17084
- if (t === "set") return n ? (pb(e, n, r), null) : "set 操作需要 jsonPath(整体替换请用 set_data)";
17085
- if (t === "remove") return n ? (mb(e, n), null) : "remove 操作需要 jsonPath";
17190
+ function Eb(e, t, n, r) {
17191
+ if (t === "set") return n ? (_b(e, n, r), null) : "set 操作需要 jsonPath(整体替换请用 set_data)";
17192
+ if (t === "remove") return n ? (vb(e, n), null) : "remove 操作需要 jsonPath";
17086
17193
  if (t === "merge") {
17087
- let t = n ? fb(e, n) : e;
17088
- return typeof t != "object" || !t || Array.isArray(t) ? `merge 目标${n ? `(${n})` : "(根)"}不是对象` : (db(t, r), null);
17194
+ let t = n ? gb(e, n) : e;
17195
+ return typeof t != "object" || !t || Array.isArray(t) ? `merge 目标${n ? `(${n})` : "(根)"}不是对象` : (hb(t, r), null);
17089
17196
  }
17090
- let i = n ? fb(e, n) : e;
17197
+ let i = n ? gb(e, n) : e;
17091
17198
  return Array.isArray(i) ? (Array.isArray(r) ? i.push(...r) : i.push(r), null) : `append 目标${n ? `(${n})` : "(根)"}不是数组`;
17092
17199
  }
17093
- function Cb(e, t, n, r) {
17094
- if (t === "set") pb(e, n, r);
17095
- else if (t === "remove") mb(e, n);
17096
- else if (t === "merge") db(n ? fb(e, n) : e, r);
17200
+ function Db(e, t, n, r) {
17201
+ if (t === "set") _b(e, n, r);
17202
+ else if (t === "remove") vb(e, n);
17203
+ else if (t === "merge") hb(n ? gb(e, n) : e, r);
17097
17204
  else {
17098
- let t = n ? fb(e, n) : e;
17205
+ let t = n ? gb(e, n) : e;
17099
17206
  Array.isArray(r) ? t.push(...r) : t.push(r);
17100
17207
  }
17101
17208
  }
17102
- function wb(e, t) {
17103
- typeof e == "object" && e && Tb(e, t);
17209
+ function Ob(e, t) {
17210
+ typeof e == "object" && e && kb(e, t);
17104
17211
  }
17105
- function Tb(e, t) {
17212
+ function kb(e, t) {
17106
17213
  if (Array.isArray(e)) {
17107
17214
  e.length = 0, Array.isArray(t) && e.push(...t);
17108
17215
  return;
@@ -17111,7 +17218,7 @@ function Tb(e, t) {
17111
17218
  for (let t of Object.keys(e)) t in n || delete e[t];
17112
17219
  for (let t of Object.keys(n)) e[t] = n[t];
17113
17220
  }
17114
- function Eb(e, t, n = "") {
17221
+ function Ab(e, t, n = "") {
17115
17222
  let r = [];
17116
17223
  if (!(typeof e == "object" && e) || !(typeof t == "object" && t) || Array.isArray(e) !== Array.isArray(t)) return e !== t && r.push({
17117
17224
  path: n || "(root)",
@@ -17130,14 +17237,14 @@ function Eb(e, t, n = "") {
17130
17237
  path: i,
17131
17238
  from: e[a],
17132
17239
  to: void 0
17133
- }) : r.push(...Eb(e[a], t[a], i));
17240
+ }) : r.push(...Ab(e[a], t[a], i));
17134
17241
  }
17135
17242
  return r;
17136
17243
  }
17137
17244
  let i = e, a = t, o = /* @__PURE__ */ new Set([...Object.keys(i), ...Object.keys(a)]);
17138
17245
  for (let e of o) {
17139
17246
  let t = n ? `${n}.${e}` : e;
17140
- e in i ? e in a ? r.push(...Eb(i[e], a[e], t)) : r.push({
17247
+ e in i ? e in a ? r.push(...Ab(i[e], a[e], t)) : r.push({
17141
17248
  path: t,
17142
17249
  from: i[e],
17143
17250
  to: void 0
@@ -17149,91 +17256,98 @@ function Eb(e, t, n = "") {
17149
17256
  }
17150
17257
  return r;
17151
17258
  }
17152
- var Db = {
17259
+ var jb = {
17153
17260
  largeResults: 4194304,
17154
17261
  drafts: 2097152,
17155
17262
  userFiles: 2097152
17156
- }, Ob = [
17263
+ }, Mb = [
17157
17264
  "largeResults",
17158
17265
  "drafts",
17159
17266
  "userFiles"
17160
- ], kb = .9;
17161
- function Ab(e, t = {}) {
17267
+ ], Nb = .9;
17268
+ function Pb(e, t = {}) {
17162
17269
  let n = Object.create(null);
17163
- if (e) for (let [t, r] of Object.entries(e)) n[Pb(t)] = {
17270
+ if (e) for (let [t, r] of Object.entries(e)) n[Rb(t)] = {
17164
17271
  content: r,
17165
- updatedAt: Ib()
17272
+ updatedAt: Bb()
17166
17273
  };
17167
17274
  let { persist: r } = t, i = t.maxBytes ?? 8388608, a = {
17168
- ...Db,
17275
+ ...jb,
17169
17276
  ...t.poolBytes ?? {}
17170
17277
  };
17171
17278
  function o(e) {
17172
- let t = Pb(e);
17279
+ let t = Rb(e);
17173
17280
  return t.startsWith("large_results/") ? "largeResults" : t.startsWith("drafts/") ? "drafts" : "userFiles";
17174
17281
  }
17175
17282
  function s(e) {
17176
17283
  let t = 0;
17177
- for (let [r, i] of Object.entries(n)) o(r) === e && (t += Mb(i.content));
17284
+ for (let [r, i] of Object.entries(n)) o(r) === e && (t += Ib(i.content));
17178
17285
  return t;
17179
17286
  }
17180
17287
  function c() {
17181
- for (let e of Ob) {
17288
+ for (let e of Mb) {
17182
17289
  let t = a[e];
17183
17290
  if (s(e) <= t) continue;
17184
- let r = t * kb, i = Object.entries(n).filter(([t]) => o(t) === e).sort((e, t) => e[1].updatedAt - t[1].updatedAt);
17291
+ let r = t * Nb, i = Object.entries(n).filter(([t]) => o(t) === e).sort((e, t) => e[1].updatedAt - t[1].updatedAt);
17185
17292
  for (let [t] of i) if (delete n[t], s(e) <= r) break;
17186
17293
  }
17187
- if (Nb(n) > i) {
17188
- let e = i * kb, t = Object.entries(n).sort((e, t) => e[1].updatedAt - t[1].updatedAt);
17189
- for (let [r] of t) if (delete n[r], Nb(n) <= e) break;
17294
+ if (Lb(n) > i) {
17295
+ let e = i * Nb, t = Object.entries(n).sort((e, t) => e[1].updatedAt - t[1].updatedAt);
17296
+ for (let [r] of t) if (delete n[r], Lb(n) <= e) break;
17190
17297
  }
17191
17298
  }
17192
- let l = null;
17193
- function u() {
17299
+ let l = !0, u = null;
17300
+ function d() {
17194
17301
  if (!r?.save) return;
17195
17302
  let e = {};
17196
17303
  for (let [t, r] of Object.entries(n)) e[t] = { ...r };
17197
17304
  r.save(e);
17198
17305
  }
17199
- function d() {
17200
- r?.save && (l && clearTimeout(l), l = setTimeout(() => {
17201
- l = null, u();
17306
+ function f() {
17307
+ r?.save && (u && clearTimeout(u), u = setTimeout(() => {
17308
+ u = null, d();
17202
17309
  }, 800));
17203
17310
  }
17204
- let f = { files: new Proxy(n, {
17205
- set(e, t, n) {
17206
- let r = Reflect.set(e, t, n);
17207
- return r && (c(), d()), r;
17208
- },
17209
- deleteProperty(e, t) {
17210
- let n = Reflect.deleteProperty(e, t);
17211
- return n && d(), n;
17212
- }
17213
- }) };
17214
- return r && (f.hydrate = (e) => {
17215
- for (let [t, r] of Object.entries(e)) n[Pb(t)] = r;
17216
- c();
17217
- }, f.flush = () => {
17218
- l &&= (clearTimeout(l), null), u();
17219
- }, f.clear = () => {
17311
+ let p = {
17312
+ files: new Proxy(n, {
17313
+ set(e, t, n) {
17314
+ let r = Reflect.set(e, t, n);
17315
+ return r && (l = !0, c(), f()), r;
17316
+ },
17317
+ deleteProperty(e, t) {
17318
+ let n = Reflect.deleteProperty(e, t);
17319
+ return n && (l = !0, f()), n;
17320
+ }
17321
+ }),
17322
+ isDirty: () => l,
17323
+ consumeDirty: () => {
17324
+ let e = l;
17325
+ return l = !1, e;
17326
+ }
17327
+ };
17328
+ return r && (p.hydrate = (e) => {
17329
+ for (let [t, r] of Object.entries(e)) n[Rb(t)] = r;
17330
+ c(), l = !0;
17331
+ }, p.flush = () => {
17332
+ u &&= (clearTimeout(u), null), d();
17333
+ }, p.clear = () => {
17220
17334
  for (let e of Object.keys(n)) delete n[e];
17221
- d();
17222
- }), f;
17335
+ f(), l = !0;
17336
+ }), p;
17223
17337
  }
17224
- var jb = null;
17225
- function Mb(e) {
17226
- return jb ||= new TextEncoder(), jb.encode(e).length;
17338
+ var Fb = null;
17339
+ function Ib(e) {
17340
+ return Fb ||= new TextEncoder(), Fb.encode(e).length;
17227
17341
  }
17228
- function Nb(e) {
17342
+ function Lb(e) {
17229
17343
  let t = 0;
17230
- for (let n of Object.values(e)) t += Mb(n.content);
17344
+ for (let n of Object.values(e)) t += Ib(n.content);
17231
17345
  return t;
17232
17346
  }
17233
- function Pb(e) {
17347
+ function Rb(e) {
17234
17348
  return e.replace(/^\/+/, "").replace(/\/+/g, "/");
17235
17349
  }
17236
- function Fb(e) {
17350
+ function zb(e) {
17237
17351
  let t = "";
17238
17352
  for (let n = 0; n < e.length; n++) {
17239
17353
  let r = e[n];
@@ -17241,10 +17355,10 @@ function Fb(e) {
17241
17355
  }
17242
17356
  return RegExp("^" + t + "$");
17243
17357
  }
17244
- function Ib() {
17358
+ function Bb() {
17245
17359
  return Date.now();
17246
17360
  }
17247
- var Lb = [
17361
+ var Vb = [
17248
17362
  "vfs_read",
17249
17363
  "vfs_write",
17250
17364
  "vfs_edit",
@@ -17254,10 +17368,10 @@ var Lb = [
17254
17368
  "vfs_json_read",
17255
17369
  "vfs_json_patch"
17256
17370
  ];
17257
- function Rb(e) {
17371
+ function Hb(e) {
17258
17372
  return [
17259
17373
  r(async ({ path: t, offset: n, limit: r }) => {
17260
- let i = e.files[Pb(t)];
17374
+ let i = e.files[Rb(t)];
17261
17375
  if (!i) return $({
17262
17376
  code: "NOT_FOUND",
17263
17377
  path: t,
@@ -17286,9 +17400,9 @@ function Rb(e) {
17286
17400
  hint: "jsonString=true 要求 content 是合法 JSON;检查引号/逗号/括号配对;或省略 jsonString 写纯文本"
17287
17401
  });
17288
17402
  }
17289
- return e.files[Pb(t)] = {
17403
+ return e.files[Rb(t)] = {
17290
17404
  content: n,
17291
- updatedAt: Ib()
17405
+ updatedAt: Bb()
17292
17406
  }, `已写入 ${t}(${n.length} 字符)${r ? "(JSON 校验通过)" : ""}`;
17293
17407
  }, {
17294
17408
  name: "vfs_write",
@@ -17300,7 +17414,7 @@ function Rb(e) {
17300
17414
  })
17301
17415
  }),
17302
17416
  r(async ({ path: t, oldString: n, newString: r }) => {
17303
- let i = Pb(t), a = e.files[i];
17417
+ let i = Rb(t), a = e.files[i];
17304
17418
  if (!a) return $({
17305
17419
  code: "NOT_FOUND",
17306
17420
  path: t,
@@ -17330,7 +17444,7 @@ function Rb(e) {
17330
17444
  }
17331
17445
  return e.files[i] = {
17332
17446
  content: a.content.replace(n, r),
17333
- updatedAt: Ib()
17447
+ updatedAt: Bb()
17334
17448
  }, `已替换 ${t} 中 1 处。`;
17335
17449
  }, {
17336
17450
  name: "vfs_edit",
@@ -17352,7 +17466,7 @@ function Rb(e) {
17352
17466
  r(async ({ pattern: t }) => {
17353
17467
  let n;
17354
17468
  try {
17355
- n = Fb(t);
17469
+ n = zb(t);
17356
17470
  } catch (e) {
17357
17471
  return $({
17358
17472
  code: "GLOB_INVALID",
@@ -17381,7 +17495,7 @@ function Rb(e) {
17381
17495
  details: { pattern: t }
17382
17496
  });
17383
17497
  }
17384
- let i = n ? [Pb(n)] : Object.keys(e.files), a = [];
17498
+ let i = n ? [Rb(n)] : Object.keys(e.files), a = [];
17385
17499
  for (let t of i) {
17386
17500
  let n = e.files[t];
17387
17501
  n && n.content.split("\n").forEach((e, n) => {
@@ -17398,7 +17512,7 @@ function Rb(e) {
17398
17512
  })
17399
17513
  }),
17400
17514
  r(async ({ path: t, jsonPath: n }) => {
17401
- let r = Pb(t), i = e.files[r];
17515
+ let r = Rb(t), i = e.files[r];
17402
17516
  if (!i) return $({
17403
17517
  code: "NOT_FOUND",
17404
17518
  path: t,
@@ -17417,7 +17531,7 @@ function Rb(e) {
17417
17531
  });
17418
17532
  }
17419
17533
  if (n) {
17420
- let e = fb(a, n);
17534
+ let e = gb(a, n);
17421
17535
  return e === void 0 ? $({
17422
17536
  code: "VFS_PATH_NOT_FOUND",
17423
17537
  path: t,
@@ -17435,7 +17549,7 @@ function Rb(e) {
17435
17549
  })
17436
17550
  }),
17437
17551
  r(async ({ path: t, patches: n }) => {
17438
- let r = Pb(t), i = e.files[r];
17552
+ let r = Rb(t), i = e.files[r];
17439
17553
  if (!i) return $({
17440
17554
  code: "NOT_FOUND",
17441
17555
  path: t,
@@ -17453,9 +17567,9 @@ function Rb(e) {
17453
17567
  hint: "vfs_json_patch 要求文件内容是合法 JSON"
17454
17568
  });
17455
17569
  }
17456
- let o = hb(a), s = [];
17570
+ let o = yb(a), s = [];
17457
17571
  for (let e of n) {
17458
- let n = Sb(o, e.op, e.jsonPath, e.value);
17572
+ let n = Eb(o, e.op, e.jsonPath, e.value);
17459
17573
  if (n) return $({
17460
17574
  code: "PATCH_FAILED",
17461
17575
  path: t,
@@ -17468,7 +17582,7 @@ function Rb(e) {
17468
17582
  let c = JSON.stringify(o);
17469
17583
  return e.files[r] = {
17470
17584
  content: c,
17471
- updatedAt: Ib()
17585
+ updatedAt: Bb()
17472
17586
  }, `已对 ${t} 应用 ${n.length} 个 patch(影响 ${s.length} 处:${s.join(", ")}),文件现 ${c.length} 字符`;
17473
17587
  }, {
17474
17588
  name: "vfs_json_patch",
@@ -17489,17 +17603,17 @@ function Rb(e) {
17489
17603
  })
17490
17604
  ];
17491
17605
  }
17492
- function zb(e) {
17606
+ function Ub(e) {
17493
17607
  return {
17494
17608
  name: "vfs",
17495
- tools: Rb(e),
17609
+ tools: Hb(e),
17496
17610
  beforeAgent: () => ({ files: e.files })
17497
17611
  };
17498
17612
  }
17499
17613
  //#endregion
17500
17614
  //#region src/core/tools/dataSlotQuery.ts
17501
- var Bb = /[\w$-]/;
17502
- function Vb(e) {
17615
+ var Wb = /[\w$-]/;
17616
+ function Gb(e) {
17503
17617
  let t = [], n = e.trim(), r = +(n[0] === "$");
17504
17618
  for (; r < n.length;) {
17505
17619
  let e = n[r];
@@ -17510,7 +17624,7 @@ function Vb(e) {
17510
17624
  continue;
17511
17625
  }
17512
17626
  let e = "";
17513
- for (; r < n.length && Bb.test(n[r]);) e += n[r++];
17627
+ for (; r < n.length && Wb.test(n[r]);) e += n[r++];
17514
17628
  if (!e) throw Error("JSONPath: .. 后缺属性名");
17515
17629
  t.push({
17516
17630
  type: "descendKey",
@@ -17523,7 +17637,7 @@ function Vb(e) {
17523
17637
  continue;
17524
17638
  }
17525
17639
  let e = "";
17526
- for (; r < n.length && Bb.test(n[r]);) e += n[r++];
17640
+ for (; r < n.length && Wb.test(n[r]);) e += n[r++];
17527
17641
  if (!e) throw Error("JSONPath: . 后缺属性名");
17528
17642
  t.push({
17529
17643
  type: "key",
@@ -17579,7 +17693,7 @@ function Vb(e) {
17579
17693
  }
17580
17694
  return t;
17581
17695
  }
17582
- function Hb(e) {
17696
+ function Kb(e) {
17583
17697
  let t = [], n = 0, r = e.trim();
17584
17698
  for (; n < r.length;) {
17585
17699
  let e = r[n];
@@ -17624,7 +17738,7 @@ function Hb(e) {
17624
17738
  }
17625
17739
  return t;
17626
17740
  }
17627
- var Ub = class {
17741
+ var qb = class {
17628
17742
  toks;
17629
17743
  item;
17630
17744
  pos = 0;
@@ -17660,12 +17774,12 @@ var Ub = class {
17660
17774
  return this.next(), e;
17661
17775
  }
17662
17776
  let e = this.operand(), t = this.peek();
17663
- return t === "==" || t === "!=" || t === "<" || t === "<=" || t === ">" || t === ">=" ? (this.next(), Kb(t, e, this.operand())) : Wb(e);
17777
+ return t === "==" || t === "!=" || t === "<" || t === "<=" || t === ">" || t === ">=" ? (this.next(), Xb(t, e, this.operand())) : Jb(e);
17664
17778
  }
17665
17779
  operand() {
17666
17780
  let e = this.next();
17667
17781
  if (e === void 0) throw Error("过滤表达式:缺操作数");
17668
- if (e.startsWith("@")) return Gb(e, this.item);
17782
+ if (e.startsWith("@")) return Yb(e, this.item);
17669
17783
  if (e[0] === "'" || e[0] === "\"") return e.slice(1, -1);
17670
17784
  if (e === "true") return !0;
17671
17785
  if (e === "false") return !1;
@@ -17675,10 +17789,10 @@ var Ub = class {
17675
17789
  throw Error(`过滤表达式:未知操作数 '${e}'`);
17676
17790
  }
17677
17791
  };
17678
- function Wb(e) {
17792
+ function Jb(e) {
17679
17793
  return !!e && e !== 0 && e !== "" && e !== null;
17680
17794
  }
17681
- function Gb(e, t) {
17795
+ function Yb(e, t) {
17682
17796
  let n = e.split(".").filter((e) => e && e !== "@"), r = t;
17683
17797
  for (let e of n) {
17684
17798
  if (typeof r != "object" || !r) return;
@@ -17686,7 +17800,7 @@ function Gb(e, t) {
17686
17800
  }
17687
17801
  return r;
17688
17802
  }
17689
- function Kb(e, t, n) {
17803
+ function Xb(e, t, n) {
17690
17804
  switch (e) {
17691
17805
  case "==": return t === n;
17692
17806
  case "!=": return t !== n;
@@ -17697,47 +17811,47 @@ function Kb(e, t, n) {
17697
17811
  default: return !1;
17698
17812
  }
17699
17813
  }
17700
- function qb(e, t) {
17701
- return new Ub(Hb(e), t).parse();
17814
+ function Zb(e, t) {
17815
+ return new qb(Kb(e), t).parse();
17702
17816
  }
17703
- function Jb(e, t) {
17817
+ function Qb(e, t) {
17704
17818
  return e ? `${e}.${t}` : String(t);
17705
17819
  }
17706
- function Yb(e, t) {
17820
+ function $b(e, t) {
17707
17821
  let n = [{
17708
17822
  path: "",
17709
17823
  value: e
17710
17824
  }];
17711
- for (let e of Vb(t)) {
17825
+ for (let e of Gb(t)) {
17712
17826
  let t = [];
17713
17827
  if (e.type === "key") for (let r of n) r.value != null && typeof r.value == "object" && e.key in r.value && t.push({
17714
- path: Jb(r.path, e.key),
17828
+ path: Qb(r.path, e.key),
17715
17829
  value: r.value[e.key]
17716
17830
  });
17717
17831
  else if (e.type === "index") {
17718
17832
  for (let r of n) if (Array.isArray(r.value)) {
17719
17833
  let n = r.value[e.index];
17720
17834
  e.index >= 0 && e.index < r.value.length && t.push({
17721
- path: Jb(r.path, e.index),
17835
+ path: Qb(r.path, e.index),
17722
17836
  value: n,
17723
17837
  index: e.index
17724
17838
  });
17725
17839
  }
17726
17840
  } else if (e.type === "wildcard") {
17727
17841
  for (let e of n) if (Array.isArray(e.value)) e.value.forEach((n, r) => t.push({
17728
- path: Jb(e.path, r),
17842
+ path: Qb(e.path, r),
17729
17843
  value: n,
17730
17844
  index: r
17731
17845
  }));
17732
17846
  else if (e.value != null && typeof e.value == "object") for (let n of Object.keys(e.value)) t.push({
17733
- path: Jb(e.path, n),
17847
+ path: Qb(e.path, n),
17734
17848
  value: e.value[n]
17735
17849
  });
17736
17850
  } else if (e.type === "descendKey") {
17737
17851
  let r = e.key, i = (e) => {
17738
17852
  if (e.value != null && typeof e.value == "object") for (let n of Object.keys(e.value)) {
17739
17853
  let a = {
17740
- path: Jb(e.path, n),
17854
+ path: Qb(e.path, n),
17741
17855
  value: e.value[n]
17742
17856
  };
17743
17857
  n === r && t.push(a), i(a);
@@ -17748,7 +17862,7 @@ function Yb(e, t) {
17748
17862
  let e = (n) => {
17749
17863
  if (n.value != null && typeof n.value == "object") for (let r of Object.keys(n.value)) {
17750
17864
  let i = {
17751
- path: Jb(n.path, r),
17865
+ path: Qb(n.path, r),
17752
17866
  value: n.value[r]
17753
17867
  };
17754
17868
  t.push(i), e(i);
@@ -17757,16 +17871,16 @@ function Yb(e, t) {
17757
17871
  for (let t of n) e(t);
17758
17872
  } else if (e.type === "filter") {
17759
17873
  for (let r of n) if (Array.isArray(r.value)) r.value.forEach((n, i) => {
17760
- qb(e.filter, n) && t.push({
17761
- path: Jb(r.path, i),
17874
+ Zb(e.filter, n) && t.push({
17875
+ path: Qb(r.path, i),
17762
17876
  value: n,
17763
17877
  index: i
17764
17878
  });
17765
17879
  });
17766
17880
  else if (r.value != null && typeof r.value == "object") for (let n of Object.keys(r.value)) {
17767
17881
  let i = r.value[n];
17768
- qb(e.filter, i) && t.push({
17769
- path: Jb(r.path, n),
17882
+ Zb(e.filter, i) && t.push({
17883
+ path: Qb(r.path, n),
17770
17884
  value: i
17771
17885
  });
17772
17886
  }
@@ -17775,7 +17889,7 @@ function Yb(e, t) {
17775
17889
  }
17776
17890
  return n;
17777
17891
  }
17778
- function Xb(e, t) {
17892
+ function ex(e, t) {
17779
17893
  let n = e.length, r = t.length;
17780
17894
  if (!n) return r;
17781
17895
  if (!r) return n;
@@ -17791,7 +17905,7 @@ function Xb(e, t) {
17791
17905
  }
17792
17906
  return i[r];
17793
17907
  }
17794
- function Zb(e, t, n = {}) {
17908
+ function tx(e, t, n = {}) {
17795
17909
  let r = n.mode || "substring", i = n.limit ?? 50, a = n.matchKey !== !1, o = [], s = null;
17796
17910
  if (r === "regex") try {
17797
17911
  s = new RegExp(t, "i");
@@ -17801,11 +17915,11 @@ function Zb(e, t, n = {}) {
17801
17915
  let c = (e, l, u) => {
17802
17916
  if (o.length >= i || e == null) return;
17803
17917
  if (typeof e == "object") {
17804
- if (Array.isArray(e)) e.forEach((e, t) => c(e, Jb(l, t), String(t)));
17805
- else for (let t of Object.keys(e)) c(e[t], Jb(l, t), t);
17918
+ if (Array.isArray(e)) e.forEach((e, t) => c(e, Qb(l, t), String(t)));
17919
+ else for (let t of Object.keys(e)) c(e[t], Qb(l, t), t);
17806
17920
  return;
17807
17921
  }
17808
- let d = String(e), f = Qb(d, t, r, n.fuzzyThreshold ?? 2, s);
17922
+ let d = String(e), f = nx(d, t, r, n.fuzzyThreshold ?? 2, s);
17809
17923
  if (f) {
17810
17924
  o.push({
17811
17925
  path: l,
@@ -17816,7 +17930,7 @@ function Zb(e, t, n = {}) {
17816
17930
  return;
17817
17931
  }
17818
17932
  if (a && u) {
17819
- let e = Qb(u, t, r, n.fuzzyThreshold ?? 2, s);
17933
+ let e = nx(u, t, r, n.fuzzyThreshold ?? 2, s);
17820
17934
  e && o.push({
17821
17935
  path: l,
17822
17936
  key: u,
@@ -17827,18 +17941,18 @@ function Zb(e, t, n = {}) {
17827
17941
  };
17828
17942
  return c(e, ""), o;
17829
17943
  }
17830
- function Qb(e, t, n, r, i) {
17944
+ function nx(e, t, n, r, i) {
17831
17945
  let a = e.toLowerCase(), o = t.toLowerCase();
17832
17946
  if (n === "substring") return a.includes(o) ? 1 : null;
17833
17947
  if (n === "regex") return i && i.test(e) ? 1 : null;
17834
17948
  if (n === "fuzzy") {
17835
17949
  if (a.includes(o)) return 2;
17836
- let e = Xb(a, o);
17950
+ let e = ex(a, o);
17837
17951
  return e <= r ? r - e + 1 : null;
17838
17952
  }
17839
17953
  return null;
17840
17954
  }
17841
- var $b = [
17955
+ var rx = [
17842
17956
  "self.fetch = () => { throw new Error('fetch 已被沙箱禁用') }",
17843
17957
  "self.XMLHttpRequest = function(){ throw new Error('XMLHttpRequest 已被沙箱禁用') }",
17844
17958
  "self.importScripts = () => { throw new Error('importScripts 已被沙箱禁用') }",
@@ -17850,7 +17964,7 @@ var $b = [
17850
17964
  "try { self.EventSource = undefined } catch {}",
17851
17965
  "try { self.BroadcastChannel = undefined } catch {}",
17852
17966
  "if (self.navigator && self.navigator.sendBeacon) self.navigator.sendBeacon = () => { throw new Error('sendBeacon 已被沙箱禁用') }"
17853
- ].join("\n"), ex = [
17967
+ ].join("\n"), ix = [
17854
17968
  {
17855
17969
  re: /\bimport\s*\(/,
17856
17970
  msg: "动态 import() 拉外网模块"
@@ -17876,8 +17990,8 @@ var $b = [
17876
17990
  msg: "require() 拉模块"
17877
17991
  }
17878
17992
  ];
17879
- function tx(e, t, n = 3e3) {
17880
- for (let { re: e, msg: n } of ex) if (e.test(t)) return Promise.resolve({
17993
+ function ax(e, t, n = 3e3) {
17994
+ for (let { re: e, msg: n } of ix) if (e.test(t)) return Promise.resolve({
17881
17995
  ok: !1,
17882
17996
  error: `沙箱拒绝执行:脚本含禁用模式(${n})`,
17883
17997
  elapsedMs: 0
@@ -17894,7 +18008,7 @@ function tx(e, t, n = 3e3) {
17894
18008
  elapsedMs: Date.now() - i
17895
18009
  });
17896
18010
  }
17897
- }, s = $b + "\nself.onmessage = async (e) => {\n try {\n const fn = new Function(\"data\", e.data.script);\n try { self.eval = undefined; self.Function = undefined; } catch {}\n let result = fn(e.data.data);\n if (result && typeof result.then === \"function\") result = await result;\n self.postMessage({ ok: true, result });\n } catch (err) {\n self.postMessage({ ok: false, error: String((err && err.message) || err) });\n }\n};", c = "", l;
18011
+ }, s = rx + "\nself.onmessage = async (e) => {\n try {\n const fn = new Function(\"data\", e.data.script);\n try { self.eval = undefined; self.Function = undefined; } catch {}\n let result = fn(e.data.data);\n if (result && typeof result.then === \"function\") result = await result;\n self.postMessage({ ok: true, result });\n } catch (err) {\n self.postMessage({ ok: false, error: String((err && err.message) || err) });\n }\n};", c = "", l;
17898
18012
  try {
17899
18013
  let e = new Blob([s], { type: "application/javascript" });
17900
18014
  c = URL.createObjectURL(e), l = new Worker(c);
@@ -17929,7 +18043,7 @@ function tx(e, t, n = 3e3) {
17929
18043
  }
17930
18044
  //#endregion
17931
18045
  //#region src/core/tools/dataOps.ts
17932
- var nx = /* @__PURE__ */ new Set([
18046
+ var ox = /* @__PURE__ */ new Set([
17933
18047
  "describe_data",
17934
18048
  "get_data",
17935
18049
  "set_data",
@@ -17941,11 +18055,11 @@ var nx = /* @__PURE__ */ new Set([
17941
18055
  "diff_data",
17942
18056
  "draft_write",
17943
18057
  "draft_commit"
17944
- ]), rx = /* @__PURE__ */ new Set(["read", "write"]);
17945
- function ix(e, t = "simple") {
17946
- return t === "advanced" ? e : t === "minimal" ? e.filter((e) => rx.has(e.name)) : e.filter((e) => !nx.has(e.name));
18058
+ ]), sx = /* @__PURE__ */ new Set(["read", "write"]);
18059
+ function cx(e, t = "simple") {
18060
+ return t === "advanced" ? e : t === "minimal" ? e.filter((e) => sx.has(e.name)) : e.filter((e) => !ox.has(e.name));
17947
18061
  }
17948
- function ax(e) {
18062
+ function lx(e) {
17949
18063
  let { bindRef: t, value: n, schema: r, allowKeys: i, snapshots: a, maxSnapshots: o, audit: s, dryRun: c, op: l = "set" } = e, u = r.safeParse(n);
17950
18064
  if (!u.success) return {
17951
18065
  ok: !1,
@@ -17964,41 +18078,132 @@ function ax(e) {
17964
18078
  hint: "主数据 bind 必须为对象/数组;叶子值请用对象包裹(如 {value:\"x\"})或集成方通过 sdk.setData 替换 bind"
17965
18079
  })
17966
18080
  };
17967
- let d = hb(t), f = a.length ? a[a.length - 1].id + 1 : 1;
18081
+ let d = yb(t), f = a.length ? a[a.length - 1].id + 1 : 1;
17968
18082
  for (a.push({
17969
18083
  id: f,
17970
18084
  ts: Date.now(),
17971
18085
  op: l,
17972
18086
  value: d
17973
18087
  }); a.length > o;) a.shift();
17974
- return u.data !== null && typeof u.data == "object" && (i ? db(t, u.data) : Tb(t, u.data)), s({
18088
+ return u.data !== null && typeof u.data == "object" && (i ? hb(t, u.data) : kb(t, u.data)), s({
17975
18089
  op: l,
17976
18090
  value: u.data,
17977
18091
  timestamp: Date.now()
17978
- }), {
18092
+ }), e.onWrite?.(), {
17979
18093
  ok: !0,
17980
- hash: xb(t),
18094
+ hash: Tb(t),
17981
18095
  data: u.data
17982
18096
  };
17983
18097
  }
17984
- function ox(e, n = {}) {
17985
- let i = e.schema, a = e.bind, o = e.description ?? "主数据对象", s = ey(i), c = [], l = n.maxSnapshots ?? 20, u, d = n.autoLock !== !1, f = {
18098
+ function ux(e) {
18099
+ let { bindRef: t, patches: n, schema: r, allowKeys: i, snapshots: a, maxSnapshots: o, markDataDirty: s, schemaErrorMode: c = "zod", snapshotLabel: l, dryRun: u } = e, d = yb(t), f = [];
18100
+ for (let e = 0; e < n.length; e++) {
18101
+ let t = n[e], a = t.jsonPath || "";
18102
+ if (mb(a)) return {
18103
+ ok: !1,
18104
+ error: $({
18105
+ code: "PATH_UNSAFE",
18106
+ message: `patches[${e}] jsonPath "${a}" 含非法段`,
18107
+ hint: "使用正常属性路径,如 components.0.text"
18108
+ })
18109
+ };
18110
+ if (!ty(a, r, i)) return {
18111
+ ok: !1,
18112
+ error: $({
18113
+ code: "PATH_DENIED",
18114
+ message: `patches[${e}] @ "${a}" 不在 schema 声明字段内`,
18115
+ hint: "仅 schema 声明的 key 可写"
18116
+ })
18117
+ };
18118
+ let o = t.op ?? "set", s;
18119
+ if (o !== "remove") {
18120
+ if (t.value === void 0 || t.value === "") return {
18121
+ ok: !1,
18122
+ error: $({
18123
+ code: "MISSING_VALUE",
18124
+ message: `patches[${e}] ${o} 操作需要 value`,
18125
+ hint: `op 为 ${o} 时 value 必填;删除请用 op:'remove'`
18126
+ })
18127
+ };
18128
+ let n = bb(t.value);
18129
+ if (n.parseError) return {
18130
+ ok: !1,
18131
+ error: Ug(`patches[${e}]`, t.value, n.parseError)
18132
+ };
18133
+ s = n.parsed;
18134
+ }
18135
+ let c = Eb(d, o, a, s);
18136
+ if (c) return {
18137
+ ok: !1,
18138
+ error: $({
18139
+ code: "PATCH_FAILED",
18140
+ message: `patches[${e}]: ${c}`,
18141
+ hint: "检查 op 与目标类型:merge 需对象,append 需数组"
18142
+ })
18143
+ };
18144
+ f.push({
18145
+ op: o,
18146
+ jp: a,
18147
+ value: s
18148
+ });
18149
+ }
18150
+ let p = r.safeParse(d);
18151
+ if (!p.success) return {
18152
+ ok: !1,
18153
+ error: c === "schema_invalid" ? $({
18154
+ code: "SCHEMA_INVALID",
18155
+ message: "patches 应用后整体校验失败,未写入",
18156
+ hint: "确认 patches 合并后整体仍符合 schema",
18157
+ details: Vg(p.error.issues)
18158
+ }) : Hg("", p.error.issues)
18159
+ };
18160
+ if (u) return {
18161
+ ok: !0,
18162
+ applied: f,
18163
+ clone: d
18164
+ };
18165
+ let m = a.length ? a[a.length - 1].id + 1 : 1;
18166
+ for (a.push({
18167
+ id: m,
18168
+ ts: Date.now(),
18169
+ op: "edit",
18170
+ value: yb(t),
18171
+ ...l ? { label: l } : {}
18172
+ }); a.length > o;) a.shift();
18173
+ for (let e of f) Db(t, e.op, e.jp, e.value);
18174
+ return s?.(), {
18175
+ ok: !0,
18176
+ applied: f,
18177
+ clone: d
18178
+ };
18179
+ }
18180
+ function dx(e, n = {}) {
18181
+ let i = e.schema, a = e.bind, o = e.description ?? "主数据对象", s = ey(i), c = [], l = n.maxSnapshots ?? 20, u, d = n.autoLock !== !1, f = !0;
18182
+ function p() {
18183
+ f = !0;
18184
+ }
18185
+ let m = {
17986
18186
  get: () => ({
17987
18187
  schema: i,
17988
18188
  bind: a,
17989
18189
  description: o
17990
18190
  }),
17991
18191
  set: (e) => {
17992
- i = e.schema, a = e.bind, o = e.description ?? "主数据对象", s = ey(i), c.length = 0, u = void 0;
18192
+ i = e.schema, a = e.bind, o = e.description ?? "主数据对象", s = ey(i), c.length = 0, u = void 0, p();
17993
18193
  },
17994
18194
  update: (e) => {
17995
- a = e, c.length = 0, u = void 0;
18195
+ a = e, c.length = 0, u = void 0, p();
18196
+ },
18197
+ markDataDirty: p,
18198
+ consumeDataDirty: () => {
18199
+ let e = f;
18200
+ return f = !1, e;
17996
18201
  }
17997
- }, p = (e) => {
18202
+ }, h = (e) => {
17998
18203
  n.onAudit?.(e);
17999
18204
  };
18000
- function m(e, t) {
18001
- let n = hb(a), r = c.length ? c[c.length - 1].id + 1 : 1;
18205
+ function g(e, t) {
18206
+ let n = yb(a), r = c.length ? c[c.length - 1].id + 1 : 1;
18002
18207
  for (c.push({
18003
18208
  id: r,
18004
18209
  ts: Date.now(),
@@ -18008,14 +18213,14 @@ function ox(e, n = {}) {
18008
18213
  }); c.length > l;) c.shift();
18009
18214
  return r;
18010
18215
  }
18011
- async function h(e, t, r) {
18216
+ async function _(e, t, r) {
18012
18217
  if (!t || t === "") return null;
18013
- let i = xb(a);
18218
+ let i = Tb(a);
18014
18219
  if (i === t) return null;
18015
18220
  if (!n.onConflict) return $({
18016
18221
  code: "VERSION_CONFLICT",
18017
18222
  message: `乐观锁冲突:expectedHash=${t} 但当前 hash=${i}。主数据在你 read 之后已被修改(外部代码/其他 agent/用户手动改)。`,
18018
- hint: `重新 read 拿最新值与 hash,基于最新值修改后再写入(传新的 expectedHash)。当前值:${yb(a, 400)}`
18223
+ hint: `重新 read 拿最新值与 hash,基于最新值修改后再写入(传新的 expectedHash)。当前值:${Cb(a, 400)}`
18019
18224
  });
18020
18225
  let o = await n.onConflict({
18021
18226
  op: e,
@@ -18025,21 +18230,21 @@ function ox(e, n = {}) {
18025
18230
  expectedHash: t,
18026
18231
  snapshotId: 0
18027
18232
  });
18028
- if (o.action === "keep_external") return `已保留外部修改(未写入)。当前值:${yb(a, 400)} (hash=${i})。请重新 read 拿最新值与 hash 再改。`;
18233
+ if (o.action === "keep_external") return `已保留外部修改(未写入)。当前值:${Cb(a, 400)} (hash=${i})。请重新 read 拿最新值与 hash 再改。`;
18029
18234
  if (o.action === "restore") {
18030
- if (!c.length) return `无历史快照可回退(本次为首次操作)。当前值:${yb(a, 400)} (hash=${i})。请重新 read 再改或选「强制覆盖」。`;
18235
+ if (!c.length) return `无历史快照可回退(本次为首次操作)。当前值:${Cb(a, 400)} (hash=${i})。请重新 read 再改或选「强制覆盖」。`;
18031
18236
  let e = c[c.length - 1];
18032
- return wb(a, hb(e.value)), `已回退主数据到历史快照 #${e.id}[${e.op}]。当前值:${yb(a, 400)} (hash=${xb(a)})。请基于回退后的值重写或停止。`;
18237
+ return Ob(a, yb(e.value)), p(), `已回退主数据到历史快照 #${e.id}[${e.op}]。当前值:${Cb(a, 400)} (hash=${Tb(a)})。请基于回退后的值重写或停止。`;
18033
18238
  }
18034
18239
  return null;
18035
18240
  }
18036
- let g = r(async () => [`说明: ${o}`, "格式: 写入值需为 JSON,且通过声明的 schema 校验(校验失败时 set_data/edit_data 会返回结构化错误,含具体字段与期望类型)。"].join("\n"), {
18241
+ let v = r(async () => [`说明: ${o}`, "格式: 写入值需为 JSON,且通过声明的 schema 校验(校验失败时 set_data/edit_data 会返回结构化错误,含具体字段与期望类型)。"].join("\n"), {
18037
18242
  name: "describe_data",
18038
18243
  description: "获取主数据的说明与格式要求。",
18039
18244
  schema: t.object({})
18040
- }), _ = r(async ({ jsonPath: e }) => {
18245
+ }), y = r(async ({ jsonPath: e }) => {
18041
18246
  let t = e || "";
18042
- if (ub(t)) return $({
18247
+ if (mb(t)) return $({
18043
18248
  code: "PATH_UNSAFE",
18044
18249
  message: `jsonPath "${t}" 含非法段(__proto__/constructor/prototype)`,
18045
18250
  hint: "使用正常属性路径,如 components.0.text(数组索引用数字)"
@@ -18049,29 +18254,30 @@ function ox(e, n = {}) {
18049
18254
  message: `get_data @ "${t}" 不在 schema 声明字段内(仅 schema 声明的 key 可读)`,
18050
18255
  hint: "主数据仅暴露 schema 声明的字段;若需操作该字段,集成方需在 schema 中声明它"
18051
18256
  });
18052
- let n = t ? fb(a, t) : a;
18257
+ let n = t ? gb(a, t) : a;
18053
18258
  t || (n = ay(n, s));
18054
- let r = xb(a);
18055
- return u = r, n === void 0 ? `主数据${t ? ` @ ${t}` : ""} = (undefined) (hash=${r})` : `主数据${t ? ` @ ${t}` : ""} = ${yb(n)} (hash=${r})`;
18259
+ let r = Tb(a);
18260
+ return u = r, n === void 0 ? `主数据${t ? ` @ ${t}` : ""} = (undefined) (hash=${r})` : `主数据${t ? ` @ ${t}` : ""} = ${Cb(n)} (hash=${r})`;
18056
18261
  }, {
18057
18262
  name: "get_data",
18058
18263
  description: "读取主数据的当前值(安全序列化:函数/DOM/循环引用做摘要;大结果由系统自动外存,提示用 vfs_read 回读)。返回含 hash(乐观锁):改前先 read/get 拿 hash,写入时传 expectedHash 回传,系统对比当前 hash 防\"基于过期值覆盖\"。jsonPath 可选:读整个主数据不传,读子路径传(如 components.0.text)。",
18059
18264
  schema: t.object({ jsonPath: t.string().optional().describe("相对主数据根的点号路径(如 components.0.text);不传则读整个主数据") })
18060
- }), v = r(async ({ value: e, expectedHash: t }) => {
18061
- let n = await h("set", t || (d ? u : void 0));
18265
+ }), b = r(async ({ value: e, expectedHash: t }) => {
18266
+ let n = await _("set", t || (d ? u : void 0));
18062
18267
  if (n !== null) return n;
18063
- let r = gb(e);
18268
+ let r = bb(e);
18064
18269
  if (r.parseError) return Ug("", e, r.parseError);
18065
- let o = ax({
18270
+ let o = lx({
18066
18271
  bindRef: a,
18067
18272
  value: r.parsed,
18068
18273
  schema: i,
18069
18274
  allowKeys: s,
18070
18275
  snapshots: c,
18071
18276
  maxSnapshots: l,
18072
- audit: p
18277
+ audit: h,
18278
+ onWrite: p
18073
18279
  });
18074
- return o.ok ? (u = o.hash, `已设置主数据 = ${yb(o.data, 600)} (新 hash=${o.hash})${s ? "(白名单模式:仅更新 schema 声明字段,未声明字段保留)" : ""}`) : o.error;
18280
+ return o.ok ? (u = o.hash, `已设置主数据 = ${Cb(o.data, 600)} (新 hash=${o.hash})${s ? "(白名单模式:仅更新 schema 声明字段,未声明字段保留)" : ""}`) : o.error;
18075
18281
  }, {
18076
18282
  name: "set_data",
18077
18283
  description: "设置主数据的值(整体替换)。value 为 JSON 对象(或 JSON 字符串),需通过 schema 校验。校验失败会返回错误而非写入。expectedHash(可选):改前 read/get 返回的 hash,传入则启用乐观锁;不传时系统自动用你最后一次读到的 hash 比对(autoLock,默认开)。大对象/数组强烈建议改用 edit_data 增量 patch。白名单模式(schema 为 ZodObject 子集):set 为根级浅合并,深层子对象整体替换(未传字段丢失);保留深层字段请用 edit_data({op:\"merge\", jsonPath:\"子路径\", value:{...}})局部合并。",
@@ -18079,55 +18285,53 @@ function ox(e, n = {}) {
18079
18285
  value: t.unknown().describe("JSON 对象(推荐直传,如 {title:\"x\"}),或 JSON 字符串;需符合 schema"),
18080
18286
  expectedHash: t.string().optional().describe("乐观锁:改前 read/get 返回的 hash;传入则校验,不一致拒绝写入防覆盖。不传则自动用你最后读到的 hash(autoLock)")
18081
18287
  })
18082
- }), y = r(async (e) => {
18288
+ }), x = r(async (e) => {
18083
18289
  let t = e.op ?? e.patch?.op, n = e.jsonPath ?? e.patch?.jsonPath, r = e.value ?? e.patch?.value, o = e.expectedHash;
18084
18290
  if (!t) return $({
18085
18291
  code: "MISSING_VALUE",
18086
18292
  message: "edit_data 需要 op(set/remove/merge/append)",
18087
18293
  hint: "顶层 op 或 patch.op 至少传一个"
18088
18294
  });
18089
- let c = n || "";
18090
- if (ub(c)) return $({
18295
+ let f = n || "";
18296
+ if (mb(f)) return $({
18091
18297
  code: "PATH_UNSAFE",
18092
- message: `jsonPath "${c}" 含非法段(__proto__/constructor/prototype)`,
18298
+ message: `jsonPath "${f}" 含非法段(__proto__/constructor/prototype)`,
18093
18299
  hint: "使用正常的属性路径,如 components.0.text(数组索引用数字)"
18094
18300
  });
18095
- if (!ty(c, i, s)) return $({
18301
+ if (!ty(f, i, s)) return $({
18096
18302
  code: "PATH_DENIED",
18097
- message: `edit_data @ "${c}" 不在 schema 声明字段内`,
18303
+ message: `edit_data @ "${f}" 不在 schema 声明字段内`,
18098
18304
  hint: "仅 schema 声明的 key 可写;若需操作该字段,集成方需在 schema 中声明它"
18099
18305
  });
18100
- let l = await h("edit", o || (d ? u : void 0));
18101
- if (l !== null) return l;
18306
+ let m = await _("edit", o || (d ? u : void 0));
18307
+ if (m !== null) return m;
18102
18308
  if (typeof a != "object" || !a) return $({
18103
18309
  code: "NOT_OBJECT",
18104
18310
  message: `edit 仅适用于对象/数组主数据,当前是 ${a === void 0 ? "undefined" : typeof a}`,
18105
18311
  hint: "叶子(原始类型)请用 set_data 整体设置"
18106
18312
  });
18107
- let f;
18108
- if (t !== "remove") {
18109
- if (r === void 0 || r === "") return $({
18110
- code: "MISSING_VALUE",
18111
- message: `${t} 操作需要 value`,
18112
- hint: `op 为 ${t} 时 value 必填;删除请用 op:'remove'`
18113
- });
18114
- let e = gb(r);
18115
- if (e.parseError) return Ug("", r, e.parseError);
18116
- f = e.parsed;
18117
- }
18118
- let g = hb(a), _ = Sb(g, t, c, f);
18119
- if (_) return $({
18120
- code: "PATCH_FAILED",
18121
- message: _,
18122
- hint: "检查 op 与目标类型:merge 需对象,append 需数组;jsonPath 指向需存在"
18313
+ let g = ux({
18314
+ bindRef: a,
18315
+ patches: [{
18316
+ op: t,
18317
+ jsonPath: f,
18318
+ value: r
18319
+ }],
18320
+ schema: i,
18321
+ allowKeys: s,
18322
+ snapshots: c,
18323
+ maxSnapshots: l,
18324
+ markDataDirty: p,
18325
+ schemaErrorMode: "zod"
18123
18326
  });
18124
- let v = i.safeParse(g);
18125
- return v.success ? (m("edit"), Cb(a, t, c, f), p({
18327
+ if (!g.ok) return g.error;
18328
+ let v = g.applied[0];
18329
+ return h({
18126
18330
  op: "edit",
18127
- detail: `${t}${c ? "@" + c : ""}`,
18128
- value: f,
18331
+ detail: `${v.op}${f ? "@" + f : ""}`,
18332
+ value: v.value,
18129
18333
  timestamp: Date.now()
18130
- }), u = xb(a), `已 edit 主数据(${t}${c ? " @ " + c : ""})。当前值:${yb(a, 600)} (新 hash=${xb(a)})`) : Hg("", v.error.issues);
18334
+ }), u = Tb(a), `已 edit 主数据(${v.op}${f ? " @ " + f : ""})。当前值:${Cb(a, 600)} (新 hash=${Tb(a)})`;
18131
18335
  }, {
18132
18336
  name: "edit_data",
18133
18337
  description: "增量编辑主数据(对象/数组),只发改动的 patch,无需重传整个大对象。op:set(在 jsonPath 设值)、remove(删 jsonPath)、merge(把 value 合并到 jsonPath 指向的对象,默认根)、append(把 value 追加到 jsonPath 指向的数组,默认根)。jsonPath 为相对主数据根的点号路径(数组索引用数字,如 components.0.text);value 为 JSON 对象(推荐直传)或 JSON 字符串。整体仍经 schema 校验,失败不写入。expectedHash(可选):改前 read/get 返回的 hash;不传时自动用你最后读到的 hash(autoLock,默认开)防\"基于过期值覆盖\"。",
@@ -18152,13 +18356,13 @@ function ox(e, n = {}) {
18152
18356
  value: t.unknown().optional()
18153
18357
  }).optional().describe("容错:误传 write 的 {patch:{op,jsonPath,value}} 形式时从此取值(顶层优先)。正常用顶层 op/jsonPath/value 即可")
18154
18358
  })
18155
- }), b = r(async ({ jsonPath: e, expectedHash: t }) => {
18359
+ }), S = r(async ({ jsonPath: e, expectedHash: t }) => {
18156
18360
  if (!e) return $({
18157
18361
  code: "MISSING_VALUE",
18158
18362
  message: "delete_data 需要 jsonPath 指定要删的子路径(主数据整体不可删,用 set_data 整体替换)",
18159
18363
  hint: "如 jsonPath:\"components.0\" 删数组首项"
18160
18364
  });
18161
- if (ub(e)) return $({
18365
+ if (mb(e)) return $({
18162
18366
  code: "PATH_UNSAFE",
18163
18367
  message: `jsonPath "${e}" 含非法段`,
18164
18368
  hint: "使用正常属性路径"
@@ -18168,15 +18372,15 @@ function ox(e, n = {}) {
18168
18372
  message: `delete_data @ "${e}" 不在 schema 声明字段内`,
18169
18373
  hint: "仅 schema 声明的 key 可删"
18170
18374
  });
18171
- let n = await h("delete", t || (d ? u : void 0));
18375
+ let n = await _("delete", t || (d ? u : void 0));
18172
18376
  if (n !== null) return n;
18173
- m("delete");
18174
- let r = mb(a, e);
18175
- return p({
18377
+ g("delete");
18378
+ let r = vb(a, e);
18379
+ return p(), h({
18176
18380
  op: "delete",
18177
18381
  detail: e,
18178
18382
  timestamp: Date.now()
18179
- }), u = xb(a), r ? `已删除主数据 @ ${e}` : `主数据 @ ${e} 不存在(无需删除)`;
18383
+ }), u = Tb(a), r ? `已删除主数据 @ ${e}` : `主数据 @ ${e} 不存在(无需删除)`;
18180
18384
  }, {
18181
18385
  name: "delete_data",
18182
18386
  description: "删除主数据的某个子路径(jsonPath)。主数据整体不可删(用 set_data 整体替换)。expectedHash(可选):改前 read/get 返回的 hash;不传时自动用你最后读到的 hash(autoLock,默认开)防\"基于过期值删除\"。",
@@ -18184,11 +18388,11 @@ function ox(e, n = {}) {
18184
18388
  jsonPath: t.string().describe("要删除的子路径(相对主数据根,如 components.0)"),
18185
18389
  expectedHash: t.string().optional().describe("乐观锁:改前 read/get 返回的 hash;传入则校验,不一致拒绝删除防覆盖")
18186
18390
  })
18187
- }), x = r(async ({ label: e }) => `已为主数据创建快照 #${m("manual", e)}${e ? `(${e})` : ""}。可用 list_data_snapshots 查看、restore_data 回退。`, {
18391
+ }), C = r(async ({ label: e }) => `已为主数据创建快照 #${g("manual", e)}${e ? `(${e})` : ""}。可用 list_data_snapshots 查看、restore_data 回退。`, {
18188
18392
  name: "snapshot_data",
18189
18393
  description: "为主数据手动创建一个命名快照(检查点)。set/edit/delete 也会自动存快照。",
18190
18394
  schema: t.object({ label: t.string().optional().describe("可选的快照标签,便于识别") })
18191
- }), S = r(async () => {
18395
+ }), w = r(async () => {
18192
18396
  if (!c.length) return "无快照。set/edit/delete 会自动存快照,也可用 snapshot_data 手动创建检查点。";
18193
18397
  let e = c.map((e) => {
18194
18398
  let t = JSON.stringify(e.value ?? "").length, n = new Date(e.ts).toLocaleTimeString("zh-CN", { hour12: !1 });
@@ -18199,7 +18403,7 @@ function ox(e, n = {}) {
18199
18403
  name: "list_data_snapshots",
18200
18404
  description: "列出主数据的快照时间线(序号、操作类型、标签、大小)。",
18201
18405
  schema: t.object({})
18202
- }), C = r(async ({ id: e }) => {
18406
+ }), T = r(async ({ id: e }) => {
18203
18407
  if (!c.length) return $({
18204
18408
  code: "NO_SNAPSHOT",
18205
18409
  message: "无快照可回退",
@@ -18212,11 +18416,11 @@ function ox(e, n = {}) {
18212
18416
  hint: "用 list_data_snapshots 查看可用快照序号"
18213
18417
  });
18214
18418
  let n = i.safeParse(t.value);
18215
- return n.success ? (wb(a, hb(t.value)), p({
18419
+ return n.success ? (Ob(a, yb(t.value)), p(), h({
18216
18420
  op: "restore",
18217
18421
  detail: `#${t.id}`,
18218
18422
  timestamp: Date.now()
18219
- }), u = xb(a), `已回退主数据到快照 #${t.id}[${t.op}]${t.label ? `(${t.label})` : ""}。`) : $({
18423
+ }), u = Tb(a), `已回退主数据到快照 #${t.id}[${t.op}]${t.label ? `(${t.label})` : ""}。`) : $({
18220
18424
  code: "SNAPSHOT_SCHEMA_INVALID",
18221
18425
  message: `快照 #${t.id} 的值不符合当前 schema,无法回退`,
18222
18426
  hint: "schema 可能已变更;该快照已过期,选其他快照或重新设置",
@@ -18226,7 +18430,7 @@ function ox(e, n = {}) {
18226
18430
  name: "restore_data",
18227
18431
  description: "把主数据回退到某个快照(就地还原,保留响应式)。不传 id 则回退最近一次(快速回退)。可用 list_data_snapshots 查看快照列表。",
18228
18432
  schema: t.object({ id: t.number().int().optional().describe("指定快照序号;不传则回退最近一次") })
18229
- }), w = r(async ({ id: e, jsonPath: t }) => {
18433
+ }), E = r(async ({ id: e, jsonPath: t }) => {
18230
18434
  if (!c.length) return $({
18231
18435
  code: "NO_SNAPSHOT",
18232
18436
  message: "无历史快照可查看",
@@ -18238,9 +18442,9 @@ function ox(e, n = {}) {
18238
18442
  message: `未找到快照 #${e}`,
18239
18443
  hint: "不传 id 查看最近一次;或用 list_data_snapshots(advanced) 查看可用序号"
18240
18444
  });
18241
- let r = hb(n.value), a = t || "";
18445
+ let r = yb(n.value), a = t || "";
18242
18446
  if (a) {
18243
- if (ub(a)) return $({
18447
+ if (mb(a)) return $({
18244
18448
  code: "PATH_UNSAFE",
18245
18449
  message: `jsonPath "${a}" 含非法段`,
18246
18450
  hint: "使用正常属性路径"
@@ -18250,11 +18454,11 @@ function ox(e, n = {}) {
18250
18454
  message: `history_data @ "${a}" 不在 schema 声明字段内`,
18251
18455
  hint: "仅 schema 声明的 key 可读"
18252
18456
  });
18253
- r = fb(r, a);
18457
+ r = gb(r, a);
18254
18458
  let e = ry(i, a);
18255
18459
  e && (r = iy(r, e));
18256
18460
  } else s && (r = iy(r, i));
18257
- return `快照 #${n.id}[${n.op}]${n.label ? `(${n.label})` : ""}${a ? ` @ ${a}` : ""} = ${yb(r)}`;
18461
+ return `快照 #${n.id}[${n.op}]${n.label ? `(${n.label})` : ""}${a ? ` @ ${a}` : ""} = ${Cb(r)}`;
18258
18462
  }, {
18259
18463
  name: "history_data",
18260
18464
  description: "只读查看某次快照(默认最近一次)的内容,不回退当前主数据。看上一版长啥样而不影响当前(冲突诊断/verify 自纠/用户问\"刚才改了啥\")。可选 id 指定快照序号、jsonPath 只看子路径(按 schema 投影)。",
@@ -18262,7 +18466,7 @@ function ox(e, n = {}) {
18262
18466
  id: t.number().int().optional().describe("快照序号;不传则最近一次"),
18263
18467
  jsonPath: t.string().optional().describe("只看快照的某子路径(相对主数据根);不传则整个快照")
18264
18468
  })
18265
- }), T = r(async ({ expr: e, limit: t }) => {
18469
+ }), D = r(async ({ expr: e, limit: t }) => {
18266
18470
  if (typeof a != "object" || !a) return $({
18267
18471
  code: "NOT_OBJECT",
18268
18472
  message: `主数据不是对象/数组,无法查询(当前为 ${a === void 0 ? "undefined" : typeof a})`,
@@ -18270,7 +18474,7 @@ function ox(e, n = {}) {
18270
18474
  });
18271
18475
  let n = s ? ay(a, s) : a, r;
18272
18476
  try {
18273
- r = Yb(n, e);
18477
+ r = $b(n, e);
18274
18478
  } catch (t) {
18275
18479
  return $({
18276
18480
  code: "JSONPATH_SYNTAX",
@@ -18279,7 +18483,7 @@ function ox(e, n = {}) {
18279
18483
  details: { expr: e }
18280
18484
  });
18281
18485
  }
18282
- let i = t ?? 50, o = r.slice(0, i), c = o.map((e) => `{"path":${JSON.stringify(e.path)},"index":${e.index === void 0 ? "null" : e.index},"value":${yb(e.value)}}`);
18486
+ let i = t ?? 50, o = r.slice(0, i), c = o.map((e) => `{"path":${JSON.stringify(e.path)},"index":${e.index === void 0 ? "null" : e.index},"value":${Cb(e.value)}}`);
18283
18487
  return `{"matched":${r.length},"returned":${o.length},"truncated":${r.length > i},"results":[${c.join(",")}]}`;
18284
18488
  }, {
18285
18489
  name: "query_data",
@@ -18288,19 +18492,19 @@ function ox(e, n = {}) {
18288
18492
  expr: t.string().describe("JSONPath 表达式,如 $.components[?(@.type==\"card\" && @.price<100)] 或 $..title(递归找所有 title)"),
18289
18493
  limit: t.number().int().min(1).max(200).optional().describe("返回结果上限,默认 50")
18290
18494
  })
18291
- }), E = r(async ({ query: e, mode: t, fuzzyThreshold: n, matchKey: r, limit: i }) => {
18495
+ }), O = r(async ({ query: e, mode: t, fuzzyThreshold: n, matchKey: r, limit: i }) => {
18292
18496
  if (a == null) return $({
18293
18497
  code: "EMPTY",
18294
18498
  message: "主数据为空,无可搜索内容"
18295
18499
  });
18296
18500
  try {
18297
- let o = Zb(s ? ay(a, s) : a, e, {
18501
+ let o = tx(s ? ay(a, s) : a, e, {
18298
18502
  mode: t,
18299
18503
  fuzzyThreshold: n,
18300
18504
  matchKey: r,
18301
18505
  limit: i ?? 50
18302
18506
  });
18303
- return yb({
18507
+ return Cb({
18304
18508
  matched: o.length,
18305
18509
  results: o
18306
18510
  });
@@ -18326,7 +18530,7 @@ function ox(e, n = {}) {
18326
18530
  matchKey: t.boolean().optional().describe("是否同时匹配 key 名,默认 true"),
18327
18531
  limit: t.number().int().min(1).max(200).optional().describe("返回上限,默认 50")
18328
18532
  })
18329
- }), D = r(async ({ script: e, mode: t, jsonPath: n }) => {
18533
+ }), k = r(async ({ script: e, mode: t, jsonPath: n }) => {
18330
18534
  if (e.length > 8e3) return $({
18331
18535
  code: "SCRIPT_TOO_LARGE",
18332
18536
  message: `脚本过长(${e.length} 字符,上限 8000)`,
@@ -18339,44 +18543,47 @@ function ox(e, n = {}) {
18339
18543
  message: `eval_script @ "${r}" 不在 schema 声明字段内`,
18340
18544
  hint: "仅 schema 声明的 key 可作为子树"
18341
18545
  });
18342
- if (o = fb(a, r), s) {
18546
+ if (o = gb(a, r), s) {
18343
18547
  let e = ry(i, r);
18344
18548
  e && (o = iy(o, e));
18345
18549
  }
18346
18550
  } else o = s ? ay(a, s) : a;
18347
- let c = hb(o), l = await tx(c, e, r && JSON.stringify(c).length > 1e5 ? 8e3 : 3e3);
18348
- if (!l.ok) {
18349
- let t = /超时/.test(l.error || "");
18551
+ let d = yb(o), f = await ax(d, e, r && JSON.stringify(d).length > 1e5 ? 8e3 : 3e3);
18552
+ if (!f.ok) {
18553
+ let t = /超时/.test(f.error || "");
18350
18554
  return $({
18351
18555
  code: t ? "SCRIPT_TIMEOUT" : "SCRIPT_ERROR",
18352
- message: `脚本执行失败: ${l.error}`,
18556
+ message: `脚本执行失败: ${f.error}`,
18353
18557
  hint: t ? "脚本可能有死循环或过重计算;加边界检查/分批;transform 返回完整新值勿返回巨大中间结果" : "检查脚本语法与运行时错误;入参为 data(主数据深拷贝),沙箱内禁用 fetch/XHR/WebSocket",
18354
18558
  details: {
18355
- elapsedMs: l.elapsedMs,
18559
+ elapsedMs: f.elapsedMs,
18356
18560
  scriptLen: e.length
18357
18561
  }
18358
18562
  });
18359
18563
  }
18360
18564
  if (t === "transform") {
18361
- let e = l.result;
18565
+ let e = f.result;
18362
18566
  if (r) {
18363
- let t = hb(a), n = Sb(t, "set", r, e);
18364
- if (n) return $({
18365
- code: "PATCH_FAILED",
18366
- message: `eval 子树 transform @ "${r}" 失败: ${n}`,
18367
- hint: "检查子路径:set 需父为对象/数组"
18567
+ let t = ux({
18568
+ bindRef: a,
18569
+ patches: [{
18570
+ op: "set",
18571
+ jsonPath: r,
18572
+ value: e
18573
+ }],
18574
+ schema: i,
18575
+ allowKeys: s,
18576
+ snapshots: c,
18577
+ maxSnapshots: l,
18578
+ markDataDirty: p,
18579
+ schemaErrorMode: "schema_invalid",
18580
+ snapshotLabel: "eval_transform_subtree"
18368
18581
  });
18369
- let o = i.safeParse(t);
18370
- return o.success ? (m("edit", "eval_transform_subtree"), Cb(a, "set", r, e), p({
18582
+ return t.ok ? (h({
18371
18583
  op: "edit",
18372
18584
  detail: `eval_transform_subtree @ ${r}`,
18373
18585
  timestamp: Date.now()
18374
- }), u = xb(a), `已通过脚本 transform 子树 @ ${r} 更新(耗时 ${l.elapsedMs}ms)。当前值: ${yb(a, 600)}`) : $({
18375
- code: "SCHEMA_INVALID",
18376
- message: `脚本返回值作为子树 @ "${r}" 后整体校验失败,未写入`,
18377
- hint: `确认返回值符合 ${r} 处的子 schema`,
18378
- details: Vg(o.error.issues)
18379
- });
18586
+ }), u = Tb(a), `已通过脚本 transform 子树 @ ${r} 更新(耗时 ${f.elapsedMs}ms)。当前值: ${Cb(a, 600)}`) : t.error;
18380
18587
  }
18381
18588
  if (e && typeof e == "object" && !Array.isArray(e) && "patches" in e && Array.isArray(e.patches)) {
18382
18589
  if (typeof a != "object" || !a) return $({
@@ -18384,77 +18591,43 @@ function ox(e, n = {}) {
18384
18591
  message: `主数据 bind 为原始类型(${a === null ? "null" : typeof a}),eval transform(patches) 无法就地替换`,
18385
18592
  hint: "主数据 bind 必须为对象/数组;叶子值请用对象包裹或集成方通过 sdk.setData 替换 bind"
18386
18593
  });
18387
- let t = e.patches, n = hb(a), r = [];
18388
- for (let e = 0; e < t.length; e++) {
18389
- let a = t[e], o = a.jsonPath || "";
18390
- if (ub(o)) return $({
18391
- code: "PATH_UNSAFE",
18392
- message: `patches[${e}] jsonPath "${o}" 含非法段`,
18393
- hint: "使用正常属性路径"
18394
- });
18395
- if (!ty(o, i, s)) return $({
18396
- code: "PATH_DENIED",
18397
- message: `patches[${e}] @ "${o}" 不在 schema 声明字段内`,
18398
- hint: "仅 schema 声明的 key 可写"
18399
- });
18400
- let c = a.op, l;
18401
- if (c !== "remove") {
18402
- if (a.value === void 0 || a.value === "") return $({
18403
- code: "MISSING_VALUE",
18404
- message: `patches[${e}] ${c} 操作需要 value`,
18405
- hint: `op 为 ${c} 时 value 必填`
18406
- });
18407
- let t = gb(a.value);
18408
- if (t.parseError) return Ug(`patches[${e}]`, a.value, t.parseError);
18409
- l = t.parsed;
18410
- }
18411
- let u = Sb(n, c, o, l);
18412
- if (u) return $({
18413
- code: "PATCH_FAILED",
18414
- message: `patches[${e}]: ${u}`,
18415
- hint: "检查 op 与目标类型:merge 需对象,append 需数组"
18416
- });
18417
- r.push({
18418
- op: c,
18419
- jp: o,
18420
- value: l
18421
- });
18422
- }
18423
- let o = i.safeParse(n);
18424
- if (!o.success) return $({
18425
- code: "SCHEMA_INVALID",
18426
- message: "脚本 patches 应用后整体校验失败,未写入",
18427
- hint: "确认 patches 合并后整体仍符合 schema",
18428
- details: Vg(o.error.issues)
18594
+ let t = ux({
18595
+ bindRef: a,
18596
+ patches: e.patches,
18597
+ schema: i,
18598
+ allowKeys: s,
18599
+ snapshots: c,
18600
+ maxSnapshots: l,
18601
+ markDataDirty: p,
18602
+ schemaErrorMode: "schema_invalid",
18603
+ snapshotLabel: "eval_transform"
18429
18604
  });
18430
- m("edit", "eval_transform");
18431
- for (let e of r) Cb(a, e.op, e.jp, e.value);
18432
- return p({
18605
+ return t.ok ? (h({
18433
18606
  op: "edit",
18434
- detail: `eval_transform(${r.length} patches)`,
18607
+ detail: `eval_transform(${t.applied.length} patches)`,
18435
18608
  timestamp: Date.now()
18436
- }), u = xb(a), `已通过脚本 transform(patches) 更新主数据(${r.length} 个 patch,耗时 ${l.elapsedMs}ms)。当前值: ${yb(a, 600)}`;
18609
+ }), u = Tb(a), `已通过脚本 transform(patches) 更新主数据(${t.applied.length} 个 patch,耗时 ${f.elapsedMs}ms)。当前值: ${Cb(a, 600)}`) : t.error;
18437
18610
  }
18438
18611
  let t = i.safeParse(e);
18439
18612
  return t.success ? typeof a != "object" || !a ? $({
18440
18613
  code: "LEAF_BIND",
18441
18614
  message: `主数据 bind 为原始类型(${a === null ? "null" : typeof a}),eval transform 无法就地替换外部持有的值引用`,
18442
18615
  hint: "主数据 bind 必须为对象/数组;叶子值请用对象包裹或集成方通过 sdk.setData 替换 bind"
18443
- }) : (m("edit", "eval_transform"), t.data !== null && typeof t.data == "object" && (s ? db(a, t.data) : Tb(a, t.data)), p({
18616
+ }) : (g("edit", "eval_transform"), t.data !== null && typeof t.data == "object" && (s ? hb(a, t.data) : kb(a, t.data)), p(), h({
18444
18617
  op: "edit",
18445
18618
  detail: "eval_transform",
18446
18619
  timestamp: Date.now()
18447
- }), u = xb(a), `已通过脚本 transform 更新主数据(耗时 ${l.elapsedMs}ms)。当前值: ${yb(a, 600)}`) : $({
18620
+ }), u = Tb(a), `已通过脚本 transform 更新主数据(耗时 ${f.elapsedMs}ms)。当前值: ${Cb(a, 600)}`) : $({
18448
18621
  code: "SCHEMA_INVALID",
18449
18622
  message: "脚本返回值校验失败,未写入(transform 模式要求返回主数据的完整新值且符合 schema)",
18450
18623
  hint: "确认脚本 return 了完整新值(非部分);或返回 {patches:[...]} 走增量模式;按 describe_data() 查看格式",
18451
18624
  details: Vg(t.error.issues)
18452
18625
  });
18453
18626
  }
18454
- return yb({
18627
+ return Cb({
18455
18628
  ok: !0,
18456
- result: l.result,
18457
- elapsedMs: l.elapsedMs
18629
+ result: f.result,
18630
+ elapsedMs: f.elapsedMs
18458
18631
  });
18459
18632
  }, {
18460
18633
  name: "eval_script",
@@ -18464,13 +18637,13 @@ function ox(e, n = {}) {
18464
18637
  mode: t.enum(["query", "transform"]).optional().describe("query=只读返回结果(默认),transform=校验后落地为新值"),
18465
18638
  jsonPath: t.string().optional().describe("子树模式:仅对 jsonPath 指向的子树执行(降低大 JSON 成本);transform 时返回值作为该子树新值")
18466
18639
  })
18467
- }), O = r(async ({ jsonPath: e, jsonPaths: t, fields: r, depth: c, offset: l, limit: d }) => {
18468
- let f = xb(a);
18640
+ }), A = r(async ({ jsonPath: e, jsonPaths: t, fields: r, depth: c, offset: l, limit: d }) => {
18641
+ let f = Tb(a);
18469
18642
  if (u = f, t && t.length) {
18470
18643
  let e = t.map((e) => {
18471
18644
  let t = e || "";
18472
18645
  if (!ty(t, i, s)) return `- ${t || "(根)"}: [PATH_DENIED: 不在 schema 声明字段内]`;
18473
- let o = t ? fb(a, t) : a;
18646
+ let o = t ? gb(a, t) : a;
18474
18647
  if (!t) o = ay(o, s);
18475
18648
  else if (s) {
18476
18649
  let e = ry(i, t);
@@ -18482,12 +18655,12 @@ function ox(e, n = {}) {
18482
18655
  } catch (e) {
18483
18656
  return `- ${t}: [READ_INTERCEPT: ${e.message}]`;
18484
18657
  }
18485
- return r && r.length && (l = _b(l, r)), c != null && (l = vb(l, c)), l === void 0 ? `- ${t} = (undefined)` : `- ${t} = ${yb(l)}`;
18658
+ return r && r.length && (l = xb(l, r)), c != null && (l = Sb(l, c)), l === void 0 ? `- ${t} = (undefined)` : `- ${t} = ${Cb(l)}`;
18486
18659
  });
18487
18660
  return `多路径读取(共 ${t.length} 项,hash=${f}):\n${e.join("\n")}`;
18488
18661
  }
18489
18662
  let p = e || "";
18490
- if (ub(p)) return $({
18663
+ if (mb(p)) return $({
18491
18664
  code: "PATH_UNSAFE",
18492
18665
  message: `jsonPath "${p}" 含非法段(__proto__/constructor/prototype)`,
18493
18666
  hint: "使用正常属性路径,如 components.0.text(数组索引数字)"
@@ -18497,7 +18670,7 @@ function ox(e, n = {}) {
18497
18670
  message: `read @ "${p}" 不在 schema 声明字段内`,
18498
18671
  hint: "主数据仅暴露 schema 声明的字段;若需操作该字段,集成方需在 schema 中声明它"
18499
18672
  });
18500
- let m = p ? fb(a, p) : a;
18673
+ let m = p ? gb(a, p) : a;
18501
18674
  if (!p) m = ay(m, s);
18502
18675
  else if (s) {
18503
18676
  let e = ry(i, p);
@@ -18512,13 +18685,13 @@ function ox(e, n = {}) {
18512
18685
  message: `read 拦截器抛错: ${e.message}`
18513
18686
  });
18514
18687
  }
18515
- r && r.length && (h = _b(h, r)), c != null && (h = vb(h, c));
18688
+ r && r.length && (h = xb(h, r)), c != null && (h = Sb(h, c));
18516
18689
  let g = e ? "" : `主数据说明: ${o}\n格式: 写入值需为 JSON,且通过声明的 schema 校验(校验失败时 write 会返回结构化错误)。字段约束(类型/min/max/enum/必填/默认)见 systemPrompt「可操作数据」段,或用 schema_data({ jsonPath }) 按需查。\n\n`, _ = r && r.length ? `(字段裁剪:${r.join(",")})` : "", v = c == null ? "" : `(深度≤${c})`, y = _ || v ? ` ${_}${v}` : "";
18517
18690
  if ((l !== void 0 || d !== void 0) && Array.isArray(h)) {
18518
18691
  let e = h.length, t = Math.max(0, l ?? 0), n = Math.min(200, Math.max(1, d ?? 50)), r = h.slice(t, t + n), i = t + n < e;
18519
- return `${g}主数据${p ? ` @ ${p}` : ""} 数组分页[offset=${t},limit=${n}]${y} = ${yb(r)} (total=${e}, hasMore=${i}) (hash=${f})`;
18692
+ return `${g}主数据${p ? ` @ ${p}` : ""} 数组分页[offset=${t},limit=${n}]${y} = ${Cb(r)} (total=${e}, hasMore=${i}) (hash=${f})`;
18520
18693
  }
18521
- return h === void 0 ? `${g}主数据${p ? ` @ ${p}` : ""}${y} = (undefined) (hash=${f})` : `${g}主数据${p ? ` @ ${p}` : ""}${y} = ${yb(h)} (hash=${f})`;
18694
+ return h === void 0 ? `${g}主数据${p ? ` @ ${p}` : ""}${y} = (undefined) (hash=${f})` : `${g}主数据${p ? ` @ ${p}` : ""}${y} = ${Cb(h)} (hash=${f})`;
18522
18695
  }, {
18523
18696
  name: "read",
18524
18697
  description: "读取主数据(高层入口,合并 describe/get)。不传 jsonPath → 返回主数据说明 + 格式提示(含字段约束);传 jsonPath → 返回该子路径当前值 + hash;传 jsonPaths → 一次读多个不相关子路径(省多轮往返)。hash 用于乐观锁(默认 autoLock,write 时自动比对,无需手动传)。fields(字段裁剪)/depth(深度截断)减体积;offset+limit 对数组目标分页(返回切片 + total/hasMore)。集成方可能经 read 拦截器对返回值脱敏/派生。",
@@ -18530,51 +18703,51 @@ function ox(e, n = {}) {
18530
18703
  offset: t.number().int().min(0).optional().describe("数组分页起始偏移(仅当读取目标是数组时生效,默认 0),配合 limit 分页读大数组"),
18531
18704
  limit: t.number().int().min(1).max(200).optional().describe("数组分页每页条数(默认 50,上限 200;仅数组时生效),返回切片 + total/hasMore")
18532
18705
  })
18533
- }), k = r(async ({ value: e, patch: t, patches: r, del: o, dryRun: f }) => {
18534
- let g = "set";
18535
- o ? g = "delete" : (r && r.length || t) && (g = "edit");
18536
- let _ = t?.value === void 0 ? e : t.value, v;
18706
+ }), j = r(async ({ value: e, patch: t, patches: r, del: o, dryRun: f }) => {
18707
+ let m = "set";
18708
+ o ? m = "delete" : (r && r.length || t) && (m = "edit");
18709
+ let v = t?.value === void 0 ? e : t.value, y;
18537
18710
  if (n.interceptors?.write) try {
18538
- let i = g === "delete" ? {
18711
+ let i = m === "delete" ? {
18539
18712
  del: !0,
18540
18713
  jsonPath: t?.jsonPath
18541
- } : g === "edit" && r && r.length ? { patches: r } : g === "edit" ? {
18714
+ } : m === "edit" && r && r.length ? { patches: r } : m === "edit" ? {
18542
18715
  op: t.op ?? "set",
18543
18716
  jsonPath: t.jsonPath || "",
18544
- value: _
18717
+ value: v
18545
18718
  } : e, o = n.interceptors.write(i, a);
18546
18719
  if (o && typeof o == "object" && "error" in o) return $({
18547
18720
  code: "WRITE_INTERCEPT",
18548
18721
  message: `write 拦截器拒绝: ${o.error}`
18549
18722
  });
18550
- if (g !== "delete") if (g === "edit" && r && r.length) v = o && Array.isArray(o) ? o : r;
18551
- else if (g === "edit") if (o && typeof o == "object" && "op" in o && "jsonPath" in o) {
18723
+ if (m !== "delete") if (m === "edit" && r && r.length) y = o && Array.isArray(o) ? o : r;
18724
+ else if (m === "edit") if (o && typeof o == "object" && "op" in o && "jsonPath" in o) {
18552
18725
  let e = o;
18553
- e.op && (t.op = e.op), e.jsonPath !== void 0 && (t.jsonPath = e.jsonPath), _ = e.value;
18554
- } else _ = o;
18555
- else _ = o;
18726
+ e.op && (t.op = e.op), e.jsonPath !== void 0 && (t.jsonPath = e.jsonPath), v = e.value;
18727
+ } else v = o;
18728
+ else v = o;
18556
18729
  } catch (e) {
18557
18730
  return $({
18558
18731
  code: "WRITE_INTERCEPT",
18559
18732
  message: `write 拦截器抛错: ${e.message}`
18560
18733
  });
18561
18734
  }
18562
- let y = d ? u : void 0;
18563
- if (f && y !== void 0) {
18564
- let e = xb(a);
18565
- if (e !== y) return $({
18735
+ let b = d ? u : void 0;
18736
+ if (f && b !== void 0) {
18737
+ let e = Tb(a);
18738
+ if (e !== b) return $({
18566
18739
  code: "VERSION_CONFLICT",
18567
- message: `dryRun 预检发现乐观锁冲突: expectedHash=${y} 当前 hash=${e}(主数据在你 read 后被改)`,
18740
+ message: `dryRun 预检发现乐观锁冲突: expectedHash=${b} 当前 hash=${e}(主数据在你 read 后被改)`,
18568
18741
  hint: "重新 read 拿最新 hash 再预检/写"
18569
18742
  });
18570
18743
  }
18571
- if (g === "delete") {
18744
+ if (m === "delete") {
18572
18745
  if (!t?.jsonPath) return $({
18573
18746
  code: "MISSING_VALUE",
18574
18747
  message: "delete 需要 patch.jsonPath 指定要删的子路径(主数据整体不可删,用 write(value) 整体替换)",
18575
18748
  hint: "如 patch:{jsonPath:\"components.0\"}, del:true"
18576
18749
  });
18577
- if (ub(t.jsonPath)) return $({
18750
+ if (mb(t.jsonPath)) return $({
18578
18751
  code: "PATH_UNSAFE",
18579
18752
  message: `jsonPath "${t.jsonPath}" 含非法段`,
18580
18753
  hint: "使用正常属性路径"
@@ -18584,95 +18757,66 @@ function ox(e, n = {}) {
18584
18757
  message: `write delete @ "${t.jsonPath}" 不在 schema 声明字段内`,
18585
18758
  hint: "仅 schema 声明的 key 可删"
18586
18759
  });
18587
- let e = await h("delete", y);
18760
+ let e = await _("delete", b);
18588
18761
  if (e !== null) return e;
18589
18762
  if (f) {
18590
- let e = hb(a);
18591
- return mb(e, t.jsonPath) ? `dryRun(delete): 将删除 @ ${t.jsonPath}。预览剩余:${yb(e, 600)}。未实际写入、未入快照。` : `dryRun(delete): @ ${t.jsonPath} 不存在(无需删除)。未实际写入。`;
18763
+ let e = yb(a);
18764
+ return vb(e, t.jsonPath) ? `dryRun(delete): 将删除 @ ${t.jsonPath}。预览剩余:${Cb(e, 600)}。未实际写入、未入快照。` : `dryRun(delete): @ ${t.jsonPath} 不存在(无需删除)。未实际写入。`;
18592
18765
  }
18593
- m("delete");
18594
- let n = mb(a, t.jsonPath);
18595
- return p({
18766
+ g("delete");
18767
+ let n = vb(a, t.jsonPath);
18768
+ return p(), h({
18596
18769
  op: "delete",
18597
18770
  detail: t.jsonPath,
18598
18771
  timestamp: Date.now()
18599
- }), u = xb(a), n ? `已删除主数据 @ ${t.jsonPath}` : `主数据 @ ${t.jsonPath} 不存在(无需删除)`;
18772
+ }), u = Tb(a), n ? `已删除主数据 @ ${t.jsonPath}` : `主数据 @ ${t.jsonPath} 不存在(无需删除)`;
18600
18773
  }
18601
- if (g === "edit") {
18774
+ if (m === "edit") {
18602
18775
  if (typeof a != "object" || !a) return $({
18603
18776
  code: "NOT_OBJECT",
18604
18777
  message: `edit 仅适用于对象/数组主数据,当前是 ${a === void 0 ? "undefined" : typeof a}`,
18605
18778
  hint: "叶子用 write(value) 整体设置"
18606
18779
  });
18607
- let e = await h("edit", y);
18780
+ let e = await _("edit", b);
18608
18781
  if (e !== null) return e;
18609
- let n = v || (r && r.length ? r : [{
18782
+ let n = y || (r && r.length ? r : [{
18610
18783
  op: t.op ?? "set",
18611
18784
  jsonPath: t.jsonPath || "",
18612
- value: _
18613
- }]), o = hb(a), c = [];
18614
- for (let e = 0; e < n.length; e++) {
18615
- let t = n[e], r = t.jsonPath || "";
18616
- if (ub(r)) return $({
18617
- code: "PATH_UNSAFE",
18618
- message: `patches[${e}] jsonPath "${r}" 含非法段`,
18619
- hint: "使用正常属性路径,如 components.0.text"
18620
- });
18621
- if (!ty(r, i, s)) return $({
18622
- code: "PATH_DENIED",
18623
- message: `patches[${e}] @ "${r}" 不在 schema 声明字段内`,
18624
- hint: "仅 schema 声明的 key 可写"
18625
- });
18626
- let a = t.op, l;
18627
- if (a !== "remove") {
18628
- if (t.value === void 0 || t.value === "") return $({
18629
- code: "MISSING_VALUE",
18630
- message: `patches[${e}] ${a} 操作需要 value`,
18631
- hint: `op 为 ${a} 时 value 必填;删除请用 op:'remove'`
18632
- });
18633
- let n = gb(t.value);
18634
- if (n.parseError) return Ug(`patches[${e}]`, t.value, n.parseError);
18635
- l = n.parsed;
18636
- }
18637
- let u = Sb(o, a, r, l);
18638
- if (u) return $({
18639
- code: "PATCH_FAILED",
18640
- message: `patches[${e}]: ${u}`,
18641
- hint: "检查 op 与目标类型:merge 需对象,append 需数组"
18642
- });
18643
- c.push({
18644
- op: a,
18645
- jp: r,
18646
- value: l
18647
- });
18648
- }
18649
- let l = i.safeParse(o);
18650
- if (!l.success) return Hg("", l.error.issues);
18651
- if (f) return `dryRun(edit): ${c.length} 个 patch 预检通过(schema 校验 OK)。预览结果:${yb(o, 600)}。未实际写入、未入快照。`;
18652
- m("edit");
18653
- for (let e of c) Cb(a, e.op, e.jp, e.value);
18654
- return p({
18785
+ value: v
18786
+ }]), o = ux({
18787
+ bindRef: a,
18788
+ patches: n,
18789
+ schema: i,
18790
+ allowKeys: s,
18791
+ snapshots: c,
18792
+ maxSnapshots: l,
18793
+ markDataDirty: p,
18794
+ schemaErrorMode: "zod",
18795
+ dryRun: f
18796
+ });
18797
+ return o.ok ? f ? `dryRun(edit): ${o.applied.length} 个 patch 预检通过(schema 校验 OK)。预览结果:${Cb(o.clone, 600)}。未实际写入、未入快照。` : (h({
18655
18798
  op: "edit",
18656
- detail: `${c.length} 个 patch${c.length > 1 ? "(批量)" : ""}`,
18657
- value: c.map((e) => `${e.op}@${e.jp}`),
18799
+ detail: `${o.applied.length} 个 patch${o.applied.length > 1 ? "(批量)" : ""}`,
18800
+ value: o.applied.map((e) => `${e.op}@${e.jp}`),
18658
18801
  timestamp: Date.now()
18659
- }), u = xb(a), `已 write(edit) 主数据(${c.length} 个 patch)。当前值:${yb(a, 600)} (新 hash=${xb(a)})`;
18802
+ }), u = Tb(a), `已 write(edit) 主数据(${o.applied.length} 个 patch)。当前值:${Cb(a, 600)} (新 hash=${Tb(a)})`) : o.error;
18660
18803
  }
18661
- let b = gb(_);
18662
- if (b.parseError) return Ug("", _, b.parseError);
18663
- let x = await h("set", y);
18664
- if (x !== null) return x;
18665
- let S = ax({
18804
+ let x = bb(v);
18805
+ if (x.parseError) return Ug("", v, x.parseError);
18806
+ let S = await _("set", b);
18807
+ if (S !== null) return S;
18808
+ let C = lx({
18666
18809
  bindRef: a,
18667
- value: b.parsed,
18810
+ value: x.parsed,
18668
18811
  schema: i,
18669
18812
  allowKeys: s,
18670
18813
  snapshots: c,
18671
18814
  maxSnapshots: l,
18672
- audit: p,
18673
- dryRun: f
18815
+ audit: h,
18816
+ dryRun: f,
18817
+ onWrite: p
18674
18818
  });
18675
- return S.ok ? f ? `dryRun(set): schema 校验通过。预览新值:${yb(S.data, 600)}。未实际写入、未入快照。` : (u = S.hash, `已 write(set) 主数据 = ${yb(S.data, 600)} (新 hash=${S.hash})${s ? "(白名单模式:仅更新 schema 声明字段,未声明字段保留)" : ""}`) : S.error;
18819
+ return C.ok ? f ? `dryRun(set): schema 校验通过。预览新值:${Cb(C.data, 600)}。未实际写入、未入快照。` : (u = C.hash, `已 write(set) 主数据 = ${Cb(C.data, 600)} (新 hash=${C.hash})${s ? "(白名单模式:仅更新 schema 声明字段,未声明字段保留)" : ""}`) : C.error;
18676
18820
  }, {
18677
18821
  name: "write",
18678
18822
  description: "写入主数据(高层入口,合并 set/edit/delete + 自动乐观锁 + 自动快照)。四种意图:① 整体替换 write({ value }) value 为整个 JSON 对象(推荐)或字符串;② 单个增量 patch write({ patch:{op,jsonPath,value} }) op=set/remove/merge/append,jsonPath 相对主数据根(如 components.0.props.title),patch.value 是该 patch 的值(自带,与 patches 一致——string/number 直传该字段新值,勿包成 {字段:值} 对象);也兼容 write({ value, patch:{op,jsonPath} }) 顶层 value 形式(向后兼容,但优先用 patch.value 避免与①整体 set 的 value 语义混淆);③ 批量增量 write({ patches:[{op,jsonPath,value},...] }) 一次原子应用多个 patch(任一失败整体不写入,适合一次改多处);④ 删除 write({ patch:{jsonPath}, del:true })。写入自动经 schema 校验(失败不写)+ 自动存快照(可 restore_data 回退)+ 自动乐观锁(autoLock,用你最后 read 到的 hash 比对,冲突则 VERSION_CONFLICT)。集成方可能经 write 拦截器校验/转换/拒绝(批量模式拦截器收到 {patches},返回新 patches 数组或 {error})。dryRun(可选):预检模式,走完整校验链(schema + 白名单 + patch 应用到 clone)但不落盘/入快照,返回预览(四意图均支持,复杂改动先看会改成啥、能否过 schema)。",
@@ -18701,9 +18845,9 @@ function ox(e, n = {}) {
18701
18845
  del: t.boolean().optional().describe("true 则删除 patch.jsonPath 指定的子路径(等价 delete_data)"),
18702
18846
  dryRun: t.boolean().optional().describe("预检模式:走完整校验链(schema + 白名单 + patch 应用到 clone)但不落盘、不入快照,返回预览。四意图(value/patch/patches/del)均支持;乐观锁冲突照常检测(返回 VERSION_CONFLICT 不挂起)")
18703
18847
  })
18704
- }), A = r(async ({ jsonPath: e }) => {
18848
+ }), M = r(async ({ jsonPath: e }) => {
18705
18849
  let t = e || "", n = t ? ry(i, t) : i;
18706
- return n ? `schema${t ? ` @ ${t}` : ""} = ${yb(dy(n))}` : $({
18850
+ return n ? `schema${t ? ` @ ${t}` : ""} = ${Cb(dy(n))}` : $({
18707
18851
  code: "PATH_DENIED",
18708
18852
  message: `schema @ "${t}" 不存在`,
18709
18853
  hint: "jsonPath 需在 schema 声明字段内(用 read() 不传 jsonPath 查看顶层字段)"
@@ -18712,12 +18856,12 @@ function ox(e, n = {}) {
18712
18856
  name: "schema_data",
18713
18857
  description: "查看主数据(或子路径)的字段约束:类型/min/max/enum/必填/默认值/嵌套 shape。写前查约束,避免写错重试。不传 jsonPath 查根;传子路径(如 components.0)查该位置约束。",
18714
18858
  schema: t.object({ jsonPath: t.string().optional().describe("要查约束的子路径;不传查根 schema") })
18715
- }), j = r(async ({ snapshotId: e, against: t }) => {
18859
+ }), ee = r(async ({ snapshotId: e, against: t }) => {
18716
18860
  let n = t != null, r, i;
18717
18861
  if (n) {
18718
18862
  let e = t;
18719
18863
  if (typeof e == "string") {
18720
- let t = gb(e);
18864
+ let t = bb(e);
18721
18865
  t.parseError || (e = t.parsed);
18722
18866
  }
18723
18867
  r = e, i = "against";
@@ -18735,8 +18879,8 @@ function ox(e, n = {}) {
18735
18879
  });
18736
18880
  r = t.value, i = `快照 #${t.id}`;
18737
18881
  }
18738
- let o = s ? ay(a, s) : a, l = Eb(r, hb(o));
18739
- return l.length ? `差异(当前 vs ${i},共 ${l.length} 处):\n${l.map((e) => ` ${e.path}: ${yb(e.from)} → ${yb(e.to)}`).join("\n")}` : `无差异:当前主数据与 ${i} 完全相同。`;
18882
+ let o = s ? ay(a, s) : a, l = Ab(r, yb(o));
18883
+ return l.length ? `差异(当前 vs ${i},共 ${l.length} 处):\n${l.map((e) => ` ${e.path}: ${Cb(e.from)} → ${Cb(e.to)}`).join("\n")}` : `无差异:当前主数据与 ${i} 完全相同。`;
18740
18884
  }, {
18741
18885
  name: "diff_data",
18742
18886
  description: "对比当前主数据与某快照(默认最近)或一段 JSON(against)的差异,返回结构化 {path, from→to} 列表。供 verify 自纠/冲突诊断/操作审计(\"刚才改了啥\")。snapshotId 指定快照;against 传一段 JSON 值(与 snapshotId 互斥,传则忽略快照)。",
@@ -18744,7 +18888,7 @@ function ox(e, n = {}) {
18744
18888
  snapshotId: t.number().int().optional().describe("对比的快照序号;不传则最近一次"),
18745
18889
  against: t.unknown().optional().describe("对比的一段 JSON 值(与 snapshotId 互斥;传则忽略快照)")
18746
18890
  })
18747
- }), M = [];
18891
+ }), N = [];
18748
18892
  if (n.vfsStore) {
18749
18893
  let e = n.vfsStore, o = (e) => `drafts/${e}.json`, d = r(({ draftId: t, chunk: n, mode: r }) => {
18750
18894
  let i = o(t), a = e.files[i], s = r === "append" && a, c = s ? a.content + n : n;
@@ -18785,27 +18929,26 @@ function ox(e, n = {}) {
18785
18929
  }
18786
18930
  });
18787
18931
  }
18788
- let f = ax({
18932
+ let f = lx({
18789
18933
  bindRef: a,
18790
18934
  value: d,
18791
18935
  schema: i,
18792
18936
  allowKeys: s,
18793
18937
  snapshots: c,
18794
18938
  maxSnapshots: l,
18795
- audit: p,
18796
- op: "draft_commit"
18939
+ audit: h,
18940
+ op: "draft_commit",
18941
+ onWrite: p
18797
18942
  });
18798
- return f.ok ? (u = f.hash, delete e.files[n], `已 draft_commit 草稿 "${t}" → 主数据 = ${yb(f.data, 600)} (新 hash=${f.hash})${s ? "(白名单模式:仅更新 schema 声明字段)" : ""}。草稿已清理。`) : f.error;
18943
+ return f.ok ? (u = f.hash, delete e.files[n], `已 draft_commit 草稿 "${t}" → 主数据 = ${Cb(f.data, 600)} (新 hash=${f.hash})${s ? "(白名单模式:仅更新 schema 声明字段)" : ""}。草稿已清理。`) : f.error;
18799
18944
  }, {
18800
18945
  name: "draft_commit",
18801
18946
  description: "把 draft_write 累积的草稿合并 + schema 校验 + 原子提交到主数据(失败不污染 bind,草稿保留供修后重试)。流程:读 drafts/{draftId}.json → JSON.parse(失败 JSON_INVALID,草稿保留)→ schema 校验(失败 SCHEMA_INVALID,草稿保留)→ 写 bind + 自动快照(与 write(set)/set_data 共用 commitSetToBind,restore_data 可回退)→ 清草稿。适合从零生成大 JSON(如 50+ 组件页面):分块 draft_write 累积 → draft_commit 一次提交。小改仍用 write/patch(无需 draft)。",
18802
18947
  schema: t.object({ draftId: t.string().describe("要提交的草稿标识(对应 draft_write 的 draftId)") })
18803
18948
  });
18804
- M.push(d, f);
18949
+ N.push(d, f);
18805
18950
  }
18806
- let ee = [
18807
- g,
18808
- _,
18951
+ let P = [
18809
18952
  v,
18810
18953
  y,
18811
18954
  b,
@@ -18820,19 +18963,21 @@ function ox(e, n = {}) {
18820
18963
  k,
18821
18964
  A,
18822
18965
  j,
18823
- ...M
18966
+ M,
18967
+ ee,
18968
+ ...N
18824
18969
  ];
18825
- return Object.defineProperty(ee, "controller", {
18826
- value: f,
18970
+ return Object.defineProperty(P, "controller", {
18971
+ value: m,
18827
18972
  enumerable: !1,
18828
18973
  configurable: !1,
18829
18974
  writable: !1
18830
- }), ee;
18975
+ }), P;
18831
18976
  }
18832
18977
  //#endregion
18833
18978
  //#region src/core/tools/fetchDoc.ts
18834
- var sx = 3e4, cx = [r(async ({ url: e, as: t }) => {
18835
- let n = new AbortController(), r = setTimeout(() => n.abort(), sx);
18979
+ var fx = 3e4, px = [r(async ({ url: e, as: t }) => {
18980
+ let n = new AbortController(), r = setTimeout(() => n.abort(), fx);
18836
18981
  try {
18837
18982
  let r = await fetch(e, {
18838
18983
  method: "GET",
@@ -18849,7 +18994,7 @@ var sx = 3e4, cx = [r(async ({ url: e, as: t }) => {
18849
18994
  ].join("\n");
18850
18995
  } catch (t) {
18851
18996
  let r = t?.message || String(t);
18852
- return n.signal.aborted ? `获取失败:请求超时(${sx}ms,${e})。` : /Failed to fetch|NetworkError|CORS|blocked/i.test(r) ? `获取失败:可能是 CORS 跨域拦截或网络错误(${r})。浏览器仅能 GET 同源或服务端已配置 CORS 的资源;跨域抓取需后端代理。` : `获取失败:${r}`;
18997
+ return n.signal.aborted ? `获取失败:请求超时(${fx}ms,${e})。` : /Failed to fetch|NetworkError|CORS|blocked/i.test(r) ? `获取失败:可能是 CORS 跨域拦截或网络错误(${r})。浏览器仅能 GET 同源或服务端已配置 CORS 的资源;跨域抓取需后端代理。` : `获取失败:${r}`;
18853
18998
  } finally {
18854
18999
  clearTimeout(r);
18855
19000
  }
@@ -18860,7 +19005,7 @@ var sx = 3e4, cx = [r(async ({ url: e, as: t }) => {
18860
19005
  url: t.string().describe("要抓取的 URL(同源或已配 CORS)"),
18861
19006
  as: t.enum(["text", "markdown"]).optional().describe("返回格式标签,默认 text")
18862
19007
  })
18863
- })], lx = [
19008
+ })], mx = [
18864
19009
  "id",
18865
19010
  "class",
18866
19011
  "href",
@@ -18872,12 +19017,12 @@ var sx = 3e4, cx = [r(async ({ url: e, as: t }) => {
18872
19017
  "aria-label",
18873
19018
  "name",
18874
19019
  "type"
18875
- ], ux = /^(value|srcdoc|formaction|on\w+)$/i, dx = /token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session/i;
18876
- function fx(e, t) {
19020
+ ], hx = /^(value|srcdoc|formaction|on\w+)$/i, gx = /token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session/i;
19021
+ function _x(e, t) {
18877
19022
  if (!e) return null;
18878
- let { depth: n, attrs: r, includeText: i = !0 } = t, a = r !== void 0, o = r ?? lx, s = (e) => {
19023
+ let { depth: n, attrs: r, includeText: i = !0 } = t, a = r !== void 0, o = r ?? mx, s = (e) => {
18879
19024
  let t = {};
18880
- for (let n of Array.from(e.attributes)) (a ? o.includes(n.name) : o.includes(n.name) || n.name.startsWith("data-")) && (ux.test(n.name) || dx.test(n.name) || (t[n.name] = n.value));
19025
+ for (let n of Array.from(e.attributes)) (a ? o.includes(n.name) : o.includes(n.name) || n.name.startsWith("data-")) && (hx.test(n.name) || gx.test(n.name) || (t[n.name] = n.value));
18881
19026
  return t;
18882
19027
  }, c = (e, t) => {
18883
19028
  let n = {
@@ -18893,10 +19038,10 @@ function fx(e, t) {
18893
19038
  };
18894
19039
  return c(e, n);
18895
19040
  }
18896
- var px = r(({ selector: e, depth: t, attrs: n, includeText: r }) => {
19041
+ var vx = r(({ selector: e, depth: t, attrs: n, includeText: r }) => {
18897
19042
  let i = e ? document.querySelector(e) : document.body;
18898
19043
  if (!i) return `未找到匹配元素:selector="${e}"`;
18899
- let a = fx(i, {
19044
+ let a = _x(i, {
18900
19045
  depth: t ?? 3,
18901
19046
  attrs: n,
18902
19047
  includeText: r ?? !0
@@ -18911,14 +19056,14 @@ var px = r(({ selector: e, depth: t, attrs: n, includeText: r }) => {
18911
19056
  attrs: t.array(t.string()).optional().describe("属性白名单(传了 = 严格白名单;不传 = 默认常用 + data-*)"),
18912
19057
  includeText: t.boolean().optional().describe("是否包含直接文本(默认 true)")
18913
19058
  })
18914
- }), mx = [px];
19059
+ }), yx = [vx];
18915
19060
  //#endregion
18916
19061
  //#region src/core/tools/envTool.ts
18917
- function hx(e) {
19062
+ function bx(e) {
18918
19063
  let t = e;
18919
19064
  return typeof t.tagName == "string" || typeof t.nodeType == "number" && typeof t.nodeName == "string";
18920
19065
  }
18921
- function gx(e, t = 3, n = 2e3, r) {
19066
+ function xx(e, t = 3, n = 2e3, r) {
18922
19067
  if (e == null) return e;
18923
19068
  if (typeof e == "string") return e.length > n ? e.slice(0, n) + "…(已截断)" : e;
18924
19069
  if (typeof e == "number" || typeof e == "boolean") return e;
@@ -18927,14 +19072,14 @@ function gx(e, t = 3, n = 2e3, r) {
18927
19072
  if (typeof e == "bigint") return `${e.toString()}n`;
18928
19073
  if (typeof e != "object") return String(e);
18929
19074
  let i = e;
18930
- if (hx(i)) {
19075
+ if (bx(i)) {
18931
19076
  let e = i;
18932
19077
  return e.tagName ? `[Element: <${e.tagName.toLowerCase()}>]` : `[Node: ${e.nodeName}]`;
18933
19078
  }
18934
19079
  if (r?.has(i)) return "[Circular]";
18935
19080
  let a = r ?? /* @__PURE__ */ new WeakSet();
18936
19081
  if (a.add(i), Array.isArray(e)) {
18937
- let r = e.slice(0, 100).map((e) => gx(e, t - 1, n, a));
19082
+ let r = e.slice(0, 100).map((e) => xx(e, t - 1, n, a));
18938
19083
  return e.length > 100 && r.push(`…(共 ${e.length} 项,已截断)`), r;
18939
19084
  }
18940
19085
  if (t < 0) return "(对象,已截断)";
@@ -18946,14 +19091,14 @@ function gx(e, t = 3, n = 2e3, r) {
18946
19091
  break;
18947
19092
  }
18948
19093
  try {
18949
- o[r] = gx(i[r], t - 1, n, a);
19094
+ o[r] = xx(i[r], t - 1, n, a);
18950
19095
  } catch {
18951
19096
  o[r] = "(getter 抛错)";
18952
19097
  }
18953
19098
  }
18954
19099
  return o;
18955
19100
  }
18956
- function _x(e) {
19101
+ function Sx(e) {
18957
19102
  let t = e ?? (typeof window < "u" ? window : {}), n = t.navigator, r = t.location, i = t.document;
18958
19103
  return {
18959
19104
  location: {
@@ -18986,9 +19131,9 @@ function _x(e) {
18986
19131
  } : "(无 document)"
18987
19132
  };
18988
19133
  }
18989
- var vx = /^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/, yx = /token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i, bx = r(({ key: e }) => {
19134
+ var Cx = /^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/, wx = /token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i, Tx = r(({ key: e }) => {
18990
19135
  if (e) {
18991
- if (vx.test(e) || yx.test(e)) return JSON.stringify({
19136
+ if (Cx.test(e) || wx.test(e)) return JSON.stringify({
18992
19137
  key: e,
18993
19138
  denied: !0,
18994
19139
  reason: "安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏"
@@ -18998,18 +19143,18 @@ var vx = /^(localStorage|sessionStorage|cookie|document|frames|frameElement|open
18998
19143
  key: e,
18999
19144
  exists: t !== void 0,
19000
19145
  type: typeof t,
19001
- value: gx(t)
19146
+ value: xx(t)
19002
19147
  }, null, 2);
19003
19148
  }
19004
- return JSON.stringify(_x(), null, 2);
19149
+ return JSON.stringify(Sx(), null, 2);
19005
19150
  }, {
19006
19151
  name: "inspect_env",
19007
19152
  description: "读取宿主页面环境信息(排查调试用,默认开启)。不传参 = 返回环境摘要(location 的 URL/origin/path、navigator 的浏览器/语言、viewport 视口尺寸、document 的 title/readyState);传 key = 读取指定 window 属性值(如 inspect_env({key:\"appConfig\"}) 读集成方挂的调试变量 window.appConfig)。用于排查「当前页面在哪/什么浏览器/视口多大/调试变量值是什么」。轻量只读,大结果自动外存 vfs。",
19008
19153
  schema: t.object({ key: t.string().optional().describe("要读取的 window 属性名(如 \"appConfig\"/\"__DEBUG__\");不传 = 返回环境摘要") })
19009
- }), xx = [bx];
19154
+ }), Ex = [Tx];
19010
19155
  //#endregion
19011
19156
  //#region src/core/harness/budget.ts
19012
- function Sx(e, t, n) {
19157
+ function Dx(e, t, n) {
19013
19158
  let r = 0;
19014
19159
  return {
19015
19160
  name: "budget",
@@ -19034,12 +19179,12 @@ function Sx(e, t, n) {
19034
19179
  }
19035
19180
  //#endregion
19036
19181
  //#region src/core/sdk/actions.ts
19037
- var Cx = /^[a-zA-Z][a-zA-Z0-9_]*$/;
19038
- function wx(e) {
19182
+ var Ox = /^[a-zA-Z][a-zA-Z0-9_]*$/;
19183
+ function kx(e) {
19039
19184
  let n = [];
19040
19185
  for (let [i, a] of Object.entries(e)) {
19041
- if (!Cx.test(i)) {
19042
- console.warn(`[page-agent-sdk][actions] 动作名 "${i}" 非法(须匹配 ${Cx}),已跳过`);
19186
+ if (!Ox.test(i)) {
19187
+ console.warn(`[page-agent-sdk][actions] 动作名 "${i}" 非法(须匹配 ${Ox}),已跳过`);
19043
19188
  continue;
19044
19189
  }
19045
19190
  let e = a.description || `宿主动作 ${i}`;
@@ -19059,9 +19204,9 @@ function wx(e) {
19059
19204
  }
19060
19205
  return n;
19061
19206
  }
19062
- function Tx(e) {
19207
+ function Ax(e) {
19063
19208
  let t = {};
19064
- for (let [n, r] of Object.entries(e)) Cx.test(n) && (t[n] = {
19209
+ for (let [n, r] of Object.entries(e)) Ox.test(n) && (t[n] = {
19065
19210
  description: r.description,
19066
19211
  hasParams: !!r.params
19067
19212
  });
@@ -19069,31 +19214,31 @@ function Tx(e) {
19069
19214
  }
19070
19215
  //#endregion
19071
19216
  //#region src/core/toolsets.ts
19072
- var Ex = cx, Dx = mx;
19073
- function Ox(e, t) {
19074
- return ox(e, t);
19217
+ var jx = px, Mx = yx;
19218
+ function Nx(e, t) {
19219
+ return dx(e, t);
19075
19220
  }
19076
- function kx(e, t, n, r, i) {
19077
- let a = e?.dataOps !== !1, o = e?.fetch !== !1, s = e?.domInspect === !0, c = e?.inspectEnv !== !1;
19221
+ function Px(e, t, n, r, i) {
19222
+ let a = ob(e);
19078
19223
  return [
19079
- ...a ? t : [],
19080
- ...o ? n : [],
19081
- ...s && r ? r : [],
19082
- ...c && i ? i : []
19224
+ ...a.dataOps ? t : [],
19225
+ ...a.fetch ? n : [],
19226
+ ...a.domInspect && r ? r : [],
19227
+ ...a.inspectEnv && i ? i : []
19083
19228
  ];
19084
19229
  }
19085
19230
  //#endregion
19086
19231
  //#region src/core/harness/usageHints.ts
19087
- var Ax = .7;
19088
- function jx(e, t, n = "simple") {
19089
- let r = n !== "advanced";
19232
+ var Fx = .7;
19233
+ function Ix(e, t, n = "simple") {
19234
+ let r = ob(e), i = n !== "advanced";
19090
19235
  return {
19091
19236
  name: "usageHints",
19092
19237
  augmentPrompt: () => {
19093
19238
  let n = [];
19094
- if (e?.planning !== !1 && (n.push("【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:"), n.push(" · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。"), n.push(" · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。"), n.push(" · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。"), n.push(" · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。"), n.push(" · 规划阶段有轮次预算(maxPlanRevisions,默认 5):勿反复调研/改计划而不执行,规划充分后即开始 write 落地。")), t && (r ? (n.push("读写主数据用 read/write(高层入口,自动乐观锁 + 自动快照)。read({jsonPath}) 读子路径当前值(返回含 hash,write 时自动比对,无需手动传);read() 不传读整个主数据 + 说明。write 改值两姿势:① 改单个字段/子路径用 write({patch:{op:\"set\", jsonPath:\"路径.字段\", value:新值}})——patch.value 就是该字段的新值(类型匹配:string 直传字符串、number 传数字、对象传对象),不要包成 {字段:值} 对象(字段名已在 jsonPath);也兼容 write({value:新值, patch:{op,jsonPath}}) 顶层 value(向后兼容,但优先 patch.value,避免与整体 set 的 value 混淆);② 替换整个对象用 write({value:{整个新对象}})。op:set 设值 / remove 删 / merge 合并对象 / append 追加数组;批量多改动 write({patches:[{op,jsonPath,value},...]});删子路径 write({patch:{jsonPath:\"路径\"}, del:true})。写入自动经 schema 校验(失败不写,按错误提示改值类型/形状后重试)+ 自动存快照(出错可用 restore_data 回退)。"), n.push("修改大对象/数组优先用 write 的 patch 增量(只发改动部分),避免整体重传被 max_tokens 截断致 JSON 不完整。"), n.push("读大数组(read 返回 hasMore=true)用 read({jsonPath,offset,limit}) 分页(offset+=limit 续读,默认 limit=50);一次读多个不相关子路径用 read({jsonPaths:[...]}) 省轮次;复杂 patches 改动先 write({patches,dryRun:true}) 预检(走完整校验不落盘)。"), n.push("查历史快照值(看上一版长啥样 / 冲突诊断 / 用户问\"刚才改了啥\")用 history_data({id?,jsonPath?})(只读不改当前);对比当前与历史快照的差异需切 advanced 用 diff_data(返回结构化 path→from/to)。"), n.push("在大数组里按条件筛选用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素 path/index;定位后用 write patch 改。找名字记不清的元素用 search_data(substring/regex/fuzzy)。批量过滤/映射/聚合/重写大数组用 eval_script(沙箱脚本,mode=query 只读/transform 落地)。")) : (n.push("改主数据前先 get_data({jsonPath}) 读其当前真实值与 hash(返回末尾 hash=xxx),基于真实值改,不要凭记忆。写入(set/edit/delete)时回传 expectedHash=该 hash 启用乐观锁——若主数据在你 get 之后被外部代码/其他 agent/用户手动改过,会触发冲突:集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 get 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 get 拿最新值与 hash 再改。"), n.push("不确定主数据字段结构时用 describe_data 查看说明。"), n.push("修改大对象/数组优先用 edit_data 增量 patch(只发改动部分),避免 set_data 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。"), n.push("修改主数据出错时可用 restore_data 回退最近一次。"), n.push("在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素的 path/index;定位后再 edit_data 改。"), n.push("找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。"), n.push("需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。"), n.push("读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。"), n.push("对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/\"刚才改了啥\");只读查历史快照值用 history_data({id?,jsonPath?})。"))), e?.subagent !== !1 && n.push("独立子任务可 spawn_agent 委派(只读工具,过程不占主上下文)。"), e?.inspectEnv !== !1 && n.push("排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:\"appConfig\"}) 读 window.appConfig)。改完数据看渲染、定位\"为何没生效\"时用它(只读,不改数据)。"), e?.draftWrite && n.push("生成超大 JSON(如 50+ 组件页面,单次 write 受 max_tokens 限制装不下)用 draft_write 分块构建 → draft_commit 原子提交:draft_write({draftId, chunk, mode}) mode:\"start\" 新建/\"append\" 追加(拼 JSON 片段到 drafts 池);累积完 draft_commit({draftId}) 合并 + schema 校验 + 写主数据(失败草稿保留可修后重试,成功自动清草稿)。小改仍用 write patch,只在大 JSON 从零生成时用 draft。"), e?.todoDeps && n.push("复杂任务可用 todos 层级依赖:write_todos 时给 todo 传 parentId(父任务 id,表达层级)+ deps(依赖的 todo id 数组,必须先完成)。有依赖的任务,deps 全 completed 后再标 in_progress;完成时 update_todo({id, status:\"completed\", evidence:\"完成证据\"}) 记证据。无依赖关系的任务不传 parentId/deps(扁平)。"), e?.subagents?.length) {
19095
- let t = e.subagents.filter((e) => (e.temperature ?? 0) >= Ax || /规划|创意|设计|方案|brainstorm|plan/i.test(e.description)), i = e.subagents.filter((e) => (e.temperature ?? 0) < Ax && /反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));
19096
- n.push("【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:"), t.length && (n.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map((e) => "use_" + e.id).join("/")} 出 2-3 套方案(高温创意),`), n.push(" 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。")), i.length && n.push(` · 严谨/易错/校验类 → 可先调 ${i.map((e) => "use_" + e.id).join("/")} 反思挑刺(低温审查),据反馈修订。`), n.push(r ? " · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。" : " · 方案定稿后,由你(主 agent)用 edit_data 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。"), n.push(" · 简单/明确任务(如\"标题改红色\")直接执行,不必走规划-反思。");
19239
+ if (r.planning && (n.push("【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:"), n.push(" · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。"), n.push(" · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。"), n.push(" · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。"), n.push(" · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。"), n.push(" · 规划阶段有轮次预算(maxPlanRevisions,默认 5):勿反复调研/改计划而不执行,规划充分后即开始 write 落地。")), t && (i ? (n.push("读写主数据用 read/write(高层入口,自动乐观锁 + 自动快照)。read({jsonPath}) 读子路径当前值(返回含 hash,write 时自动比对,无需手动传);read() 不传读整个主数据 + 说明。write 改值两姿势:① 改单个字段/子路径用 write({patch:{op:\"set\", jsonPath:\"路径.字段\", value:新值}})——patch.value 就是该字段的新值(类型匹配:string 直传字符串、number 传数字、对象传对象),不要包成 {字段:值} 对象(字段名已在 jsonPath);也兼容 write({value:新值, patch:{op,jsonPath}}) 顶层 value(向后兼容,但优先 patch.value,避免与整体 set 的 value 混淆);② 替换整个对象用 write({value:{整个新对象}})。op:set 设值 / remove 删 / merge 合并对象 / append 追加数组;批量多改动 write({patches:[{op,jsonPath,value},...]});删子路径 write({patch:{jsonPath:\"路径\"}, del:true})。写入自动经 schema 校验(失败不写,按错误提示改值类型/形状后重试)+ 自动存快照(出错可用 restore_data 回退)。"), n.push("修改大对象/数组优先用 write 的 patch 增量(只发改动部分),避免整体重传被 max_tokens 截断致 JSON 不完整。"), n.push("读大数组(read 返回 hasMore=true)用 read({jsonPath,offset,limit}) 分页(offset+=limit 续读,默认 limit=50);一次读多个不相关子路径用 read({jsonPaths:[...]}) 省轮次;复杂 patches 改动先 write({patches,dryRun:true}) 预检(走完整校验不落盘)。"), n.push("查历史快照值(看上一版长啥样 / 冲突诊断 / 用户问\"刚才改了啥\")用 history_data({id?,jsonPath?})(只读不改当前);对比当前与历史快照的差异需切 advanced 用 diff_data(返回结构化 path→from/to)。"), n.push("在大数组里按条件筛选用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素 path/index;定位后用 write patch 改。找名字记不清的元素用 search_data(substring/regex/fuzzy)。批量过滤/映射/聚合/重写大数组用 eval_script(沙箱脚本,mode=query 只读/transform 落地)。")) : (n.push("改主数据前先 get_data({jsonPath}) 读其当前真实值与 hash(返回末尾 hash=xxx),基于真实值改,不要凭记忆。写入(set/edit/delete)时回传 expectedHash=该 hash 启用乐观锁——若主数据在你 get 之后被外部代码/其他 agent/用户手动改过,会触发冲突:集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 get 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 get 拿最新值与 hash 再改。"), n.push("不确定主数据字段结构时用 describe_data 查看说明。"), n.push("修改大对象/数组优先用 edit_data 增量 patch(只发改动部分),避免 set_data 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。"), n.push("修改主数据出错时可用 restore_data 回退最近一次。"), n.push("在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素的 path/index;定位后再 edit_data 改。"), n.push("找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。"), n.push("需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。"), n.push("读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。"), n.push("对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/\"刚才改了啥\");只读查历史快照值用 history_data({id?,jsonPath?})。"))), r.subagent && n.push("独立子任务可 spawn_agent 委派(只读工具,过程不占主上下文)。"), r.inspectEnv && n.push("排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:\"appConfig\"}) 读 window.appConfig)。改完数据看渲染、定位\"为何没生效\"时用它(只读,不改数据)。"), r.draftWrite && n.push("生成超大 JSON(如 50+ 组件页面,单次 write 受 max_tokens 限制装不下)用 draft_write 分块构建 → draft_commit 原子提交:draft_write({draftId, chunk, mode}) mode:\"start\" 新建/\"append\" 追加(拼 JSON 片段到 drafts 池);累积完 draft_commit({draftId}) 合并 + schema 校验 + 写主数据(失败草稿保留可修后重试,成功自动清草稿)。小改仍用 write patch,只在大 JSON 从零生成时用 draft。"), r.todoDeps && n.push("复杂任务可用 todos 层级依赖:write_todos 时给 todo 传 parentId(父任务 id,表达层级)+ deps(依赖的 todo id 数组,必须先完成)。有依赖的任务,deps 全 completed 后再标 in_progress;完成时 update_todo({id, status:\"completed\", evidence:\"完成证据\"}) 记证据。无依赖关系的任务不传 parentId/deps(扁平)。"), e?.subagents?.length) {
19240
+ let t = e.subagents.filter((e) => (e.temperature ?? 0) >= Fx || /规划|创意|设计|方案|brainstorm|plan/i.test(e.description)), r = e.subagents.filter((e) => (e.temperature ?? 0) < Fx && /反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));
19241
+ n.push("【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:"), t.length && (n.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map((e) => "use_" + e.id).join("/")} 出 2-3 套方案(高温创意),`), n.push(" 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。")), r.length && n.push(` · 严谨/易错/校验类 → 可先调 ${r.map((e) => "use_" + e.id).join("/")} 反思挑刺(低温审查),据反馈修订。`), n.push(i ? " · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。" : " · 方案定稿后,由你(主 agent)用 edit_data 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。"), n.push(" · 简单/明确任务(如\"标题改红色\")直接执行,不必走规划-反思。");
19097
19242
  }
19098
19243
  return e?.humanConfirm && (n.push("【人工确认·必读】以下情形必须先调 request_human_confirmation 征询用户、拿到答复后再继续,不要自行拍板:"), n.push(" 1) 用户让你「给方案/列选项/我来选/挑一个」时:把每个方案作为一个 option,调 request_human_confirmation(question=简述, options=[方案A,方案B,...], recommendation=你推荐的)。不要只回文字罗列方案让用户自己回复——要用工具把选项做成可点选按钮。"), n.push(" 2) 需求有歧义/不确定时:调工具问清楚(options 不传则用户答同意或拒绝)。"), n.push(" 3) 即将执行高风险不可逆操作(删除/覆盖/批量改动)前:调工具确认。"), n.push(" 4) 规划出多步方案需用户确认时:把整个方案(或关键分步)作为 option 调 request_human_confirmation,确认后再执行。"), n.push("用户在选项里选了哪个,就按那个方案继续;选「拒绝」则停止并询问如何调整。")), n.length && n.unshift("调用工具务必用标准 function calling(工具调用)格式发起,不要在回复正文里输出伪 XML/标签(如 deepseek 的 tool_calls 标签、invoke、function_call、tool_call 等)或 JSON 文本——那不会被识别为工具调用,会被当普通文字,工具不执行。"), n.length ? "## 能力使用提示\n" + n.join("\n") : void 0;
19099
19244
  }
@@ -19101,72 +19246,72 @@ function jx(e, t, n = "simple") {
19101
19246
  }
19102
19247
  //#endregion
19103
19248
  //#region src/core/backends/skillStore.ts
19104
- var Mx = "v:1::skill-store", Nx = "chat-sdk";
19105
- function Px(e, t, n) {
19106
- return `${Mx}::${e}::${t}::${n}`;
19249
+ var Lx = "v:1::skill-store", Rx = "chat-sdk";
19250
+ function zx(e, t, n) {
19251
+ return `${Lx}::${e}::${t}::${n}`;
19107
19252
  }
19108
- function Fx(e, t) {
19109
- return `${Mx}::${e}::${t}::`;
19253
+ function Bx(e, t) {
19254
+ return `${Lx}::${e}::${t}::`;
19110
19255
  }
19111
- function Ix(e = {}) {
19112
- let t = e.dbName ?? Nx, n = e.backend ?? "indexed", r = e.id ?? "", i, a, o = new Promise((e) => {
19256
+ function Vx(e = {}) {
19257
+ let t = e.dbName ?? Rx, n = e.backend ?? "indexed", r = e.id ?? "", i, a, o = new Promise((e) => {
19113
19258
  a = e;
19114
19259
  });
19115
19260
  return (async () => {
19116
19261
  try {
19117
19262
  if (n === "indexed") {
19118
19263
  if (typeof indexedDB > "u") throw Error("indexedDB 不可用");
19119
- i = await Zy(t), a(!0);
19264
+ i = await $y(t), a(!0);
19120
19265
  } else if (n === "session") {
19121
19266
  if (typeof sessionStorage > "u") throw Error("sessionStorage 不可用");
19122
- i = Qy(sessionStorage), a(!0);
19267
+ i = eb(sessionStorage), a(!0);
19123
19268
  } else if (n === "local") {
19124
19269
  if (typeof localStorage > "u") throw Error("localStorage 不可用");
19125
- i = Qy(localStorage), a(!0);
19126
- } else i = Xy(), a(!1);
19270
+ i = eb(localStorage), a(!0);
19271
+ } else i = Qy(), a(!1);
19127
19272
  } catch {
19128
- i = Xy(), a(!1);
19273
+ i = Qy(), a(!1);
19129
19274
  }
19130
19275
  })(), {
19131
19276
  ready: o,
19132
19277
  async list() {
19133
19278
  let e = [];
19134
- return await i.scan(Fx(t, r), (t, n) => {
19279
+ return await i.scan(Bx(t, r), (t, n) => {
19135
19280
  e.push(n);
19136
19281
  }), e;
19137
19282
  },
19138
19283
  async get(e) {
19139
- return await i.get(Px(t, r, e));
19284
+ return await i.get(zx(t, r, e));
19140
19285
  },
19141
19286
  async put(e) {
19142
19287
  try {
19143
- await i.set(Px(t, r, e.name), e);
19288
+ await i.set(zx(t, r, e.name), e);
19144
19289
  } catch (e) {
19145
- Hy(e) && (i = Xy());
19290
+ Wy(e) && (i = Qy());
19146
19291
  }
19147
19292
  },
19148
19293
  async remove(e) {
19149
- let n = Px(t, r, e);
19294
+ let n = zx(t, r, e);
19150
19295
  return await i.get(n) != null && (await i.del(n), !0);
19151
19296
  },
19152
19297
  async clear() {
19153
- await i.clearPrefix(Fx(t, r));
19298
+ await i.clearPrefix(Bx(t, r));
19154
19299
  },
19155
19300
  dispose() {}
19156
19301
  };
19157
19302
  }
19158
19303
  //#endregion
19159
19304
  //#region src/core/sdk/createChatSdk.ts
19160
- var Lx = 50, Rx = /* @__PURE__ */ new Map();
19161
- function zx(e, t) {
19305
+ var Hx = 50, Ux = /* @__PURE__ */ new Map();
19306
+ function Wx(e, t) {
19162
19307
  return e === "set_data" ? "set" : e === "edit_data" ? "edit" : e === "delete_data" ? "delete" : e === "restore_data" ? "restore" : e === "write" ? t?.del ? "delete" : t?.patch ? "edit" : "set" : null;
19163
19308
  }
19164
- function Bx(e, t, n, r) {
19309
+ function Gx(e, t, n, r) {
19165
19310
  let i = 0;
19166
19311
  return {
19167
19312
  name: "sdk-events",
19168
19313
  wrapToolCall: async (t, r) => {
19169
- let i = await r(t), a = zx(t.name, t.args);
19314
+ let i = await r(t), a = Wx(t.name, t.args);
19170
19315
  return a && e({
19171
19316
  type: "data_change",
19172
19317
  operation: a,
@@ -19201,18 +19346,18 @@ function Bx(e, t, n, r) {
19201
19346
  }
19202
19347
  };
19203
19348
  }
19204
- function Vx(e, i) {
19349
+ function Kx(e, i) {
19205
19350
  let a = {
19206
19351
  prompt_tokens: 0,
19207
19352
  completion_tokens: 0,
19208
19353
  total_tokens: 0
19209
- }, o = ky(() => Oe), s = /* @__PURE__ */ U(0), c = tb(e.storage);
19354
+ }, o = jy(() => Oe), s = /* @__PURE__ */ U(0), c = rb(e.storage);
19210
19355
  e.debug && c && c.onEvent((e) => console.log("[page-agent-sdk][storage]", e));
19211
- let { modelCaps: l, summaryLlmInvoke: u } = Oy(e), d = l;
19356
+ let { modelCaps: l, summaryLlmInvoke: u } = Ay(e), d = l;
19212
19357
  e.debug && console.log("[page-agent-sdk][modelCaps]", d);
19213
19358
  let f = e.llm;
19214
19359
  e.debug && !u && console.warn("[page-agent-sdk][summarization] 未构造 llmInvoke(apiKey 缺失?),摘要回退零成本索引摘要");
19215
- let p = /* @__PURE__ */ tn([]), m = Ab(e.vfs?.initialFiles, {
19360
+ let p = /* @__PURE__ */ tn([]), m = Pb(e.vfs?.initialFiles, {
19216
19361
  persist: c ? { save: (e) => {
19217
19362
  B.sessionId && c && c.save(i, B.sessionId, { vfs: e });
19218
19363
  } } : void 0,
@@ -19225,24 +19370,25 @@ function Vx(e, i) {
19225
19370
  description: e.data.description ?? "主数据对象"
19226
19371
  } : void 0, x = e.checkpoint, S = x !== void 0 && x !== !1, C = S ? iv({
19227
19372
  getData: () => N()?.bind,
19373
+ consumeDataDirty: () => ee?.consumeDataDirty?.() ?? !0,
19228
19374
  slotPaths: b ? [""] : [],
19229
19375
  vfsStore: m,
19230
19376
  todosMw: h,
19231
19377
  getTodos: () => y.current?.getState?.()?.todos ?? [],
19232
19378
  messages: p,
19233
19379
  maxCheckpoints: x && typeof x == "object" ? x.maxCheckpoints : void 0
19234
- }) : null, w = !x || typeof x != "object" || x.auto !== !1, T = e.capabilities, E = T?.dataOps !== !1, D = T?.draftWrite === !0, O = T?.tracing === !0, k = T?.automation === !0, A = wy(e), j = E && b ? ox(b, {
19380
+ }) : null, w = !x || typeof x != "object" || x.auto !== !1, T = ob(e.capabilities), E = T.dataOps, D = T.draftWrite, O = T.tracing, k = T.automation, A = Ey(e), j = E && b ? dx(b, {
19235
19381
  onAudit: e.onAudit ?? (e.debug ? (e) => console.log("[page-agent-sdk][data audit]", e) : void 0),
19236
19382
  maxSnapshots: e.maxSnapshots,
19237
19383
  onConflict: o.set,
19238
19384
  autoLock: e.autoLock,
19239
19385
  interceptors: e.interceptors,
19240
19386
  vfsStore: D ? m : void 0
19241
- }) : [], M = E ? ix(j, e.toolMode) : [], ee = E && b ? j.controller ?? null : null, N = () => ee?.get() ?? b, P = /* @__PURE__ */ new Map(), F = kx(T, M, cx, mx, xx);
19387
+ }) : [], M = E ? cx(j, e.toolMode) : [], ee = E && b ? j.controller ?? null : null, N = () => ee?.get() ?? b, P = /* @__PURE__ */ new Map(), F = Px(T, M, px, yx, Ex);
19242
19388
  F.forEach((e) => P.set(e.name, "builtin"));
19243
19389
  let I = [...e.tools || []];
19244
19390
  I.forEach((e) => P.set(e.name, "user"));
19245
- let te = wx(e.actions ?? {});
19391
+ let te = kx(e.actions ?? {});
19246
19392
  te.forEach((e) => P.set(e.name, "action"));
19247
19393
  let L = [], R = e.humanConfirm !== !1 && (!e.approval || e.approval.humanConfirmTool !== !1), ne = R ? X_() : null;
19248
19394
  ne && P.set(J_, "builtin");
@@ -19279,11 +19425,11 @@ function Vx(e, i) {
19279
19425
  ...L
19280
19426
  ];
19281
19427
  }
19282
- let ae = T?.planning !== !1, oe = T?.missionAnchor !== !1, se = T?.workingMemory !== !1, ce = T?.skills !== !1, le = T?.vfs !== !1;
19283
- if (le) for (let e of Lb) P.set(e, "builtin");
19428
+ let ae = T.planning, oe = T.missionAnchor, se = T.workingMemory, ce = T.skills, le = T.vfs;
19429
+ if (le) for (let e of Vb) P.set(e, "builtin");
19284
19430
  if (ae) for (let e of h.tools ?? []) P.set(e.name, "builtin");
19285
- let ue = T?.summarization !== !1, de = T?.memory !== !1, fe = T?.subagent !== !1, pe = e.verify?.maxAttempts ?? 2, me = T?.verify === !0 && e.verify?.enabled !== !1 && pe > 0;
19286
- e.verify?.check && T?.verify !== !0 && console.warn("[page-agent-sdk][verify] 检测到 verify.check 但 capabilities.verify 未开启,verify 未装载");
19431
+ let ue = T.summarization, de = T.memory, fe = T.subagent, pe = e.verify?.maxAttempts ?? 2, me = T.verify && e.verify?.enabled !== !1 && pe > 0;
19432
+ e.verify?.check && !T.verify && console.warn("[page-agent-sdk][verify] 检测到 verify.check 但 capabilities.verify 未开启,verify 未装载");
19287
19433
  let he = e.subagent, ge = he?.allowedTools ?? [], _e = !fe || he?.enabled === !1 ? void 0 : _v({
19288
19434
  llm: he?.llm ?? e.llm,
19289
19435
  allTools: z,
@@ -19313,7 +19459,7 @@ function Vx(e, i) {
19313
19459
  llm: e.llm,
19314
19460
  tools: xe
19315
19461
  } : void 0
19316
- }) : void 0, Ce = jx({
19462
+ }) : void 0, Ce = Ix({
19317
19463
  ...T,
19318
19464
  humanConfirm: R,
19319
19465
  subagents: e.subagents?.map((e) => ({
@@ -19323,7 +19469,7 @@ function Vx(e, i) {
19323
19469
  }))
19324
19470
  }, E && !!b, e.toolMode), we = b ? {
19325
19471
  name: "dataHint",
19326
- augmentPrompt: () => Cy(N(), e.schemaHint) || void 0
19472
+ augmentPrompt: () => Ty(N(), e.schemaHint) || void 0
19327
19473
  } : null, Te = e.augmentSystem ? {
19328
19474
  name: "augmentSystem",
19329
19475
  augmentPrompt: (t) => {
@@ -19337,7 +19483,7 @@ function Vx(e, i) {
19337
19483
  return;
19338
19484
  }
19339
19485
  }
19340
- } : null, Ee = e.onEvent, De = rb(e.onEvent), Oe = De.emit, ke, Ae = [], je = (e) => ({
19486
+ } : null, Ee = e.onEvent, De = sb(e.onEvent), Oe = De.emit, ke, Ae = [], je = (e) => ({
19341
19487
  name: e.name,
19342
19488
  description: e.description,
19343
19489
  content: typeof e.getContent == "function" ? e.getContent() : ""
@@ -19345,7 +19491,7 @@ function Vx(e, i) {
19345
19491
  name: e.name,
19346
19492
  description: e.description,
19347
19493
  getContent: () => e.content
19348
- }), Ne = e.skillStorage === !1 ? null : Ix({
19494
+ }), Ne = e.skillStorage === !1 ? null : Vx({
19349
19495
  ...typeof e.skillStorage == "object" ? e.skillStorage : {},
19350
19496
  id: e.skillStorage && typeof e.skillStorage == "object" && e.skillStorage.id ? e.skillStorage.id : `agent::${i}`
19351
19497
  }), Pe = () => {
@@ -19368,18 +19514,18 @@ function Vx(e, i) {
19368
19514
  B.infoTick.value++;
19369
19515
  }
19370
19516
  } catch {}
19371
- }, Ie = cb([
19517
+ }, Ie = fb([
19372
19518
  ...we ? [we] : [],
19373
19519
  Ce,
19374
19520
  ...oe ? [g] : [],
19375
19521
  ...ae ? [h] : [],
19376
19522
  ...ce ? [ke = z_(e.skills || [], { readVfs: le ? (e) => m.files[e]?.content : void 0 })] : [],
19377
- ...le ? [zb(m)] : [],
19523
+ ...le ? [Ub(m)] : [],
19378
19524
  ...ue ? [$v({
19379
- ...ob(e, d.contextWindow),
19525
+ ...ub(e, d.contextWindow),
19380
19526
  llmInvoke: u,
19381
19527
  getRegisteredData: () => N() ? [{ description: N().description ?? "主数据对象" }] : [],
19382
- preserveLastToolResults: (e.contextOptions && e.contextOptions.preserveLastToolResults) ?? ab[e.contextPreset ?? "auto"]
19528
+ preserveLastToolResults: (e.contextOptions && e.contextOptions.preserveLastToolResults) ?? lb[e.contextPreset ?? "auto"]
19383
19529
  })] : [],
19384
19530
  ...se ? [_] : [],
19385
19531
  ...de ? [v] : [],
@@ -19392,12 +19538,12 @@ function Vx(e, i) {
19392
19538
  ...ve ? [ve] : [],
19393
19539
  ...Te ? [Te] : [],
19394
19540
  ...e.middleware || [],
19395
- ...k ? [Sx(a, {
19541
+ ...k ? [Dx(a, {
19396
19542
  tokenBudget: e.tokenBudget,
19397
19543
  timeBudgetMs: e.timeBudgetMs
19398
19544
  }, Oe)] : [],
19399
- Bx(Oe, p, N, a)
19400
- ]), Le = e.maxMemoryRounds ?? Lx, B = {
19545
+ Gx(Oe, p, N, a)
19546
+ ]), Le = e.maxMemoryRounds ?? Hx, B = {
19401
19547
  agentId: i,
19402
19548
  store: c,
19403
19549
  messages: p,
@@ -19500,6 +19646,7 @@ function Vx(e, i) {
19500
19646
  for (let r = 0; r < e.length; r++) {
19501
19647
  let i = e[r];
19502
19648
  C && C.save(`batch:${r}`);
19649
+ let a = p.length;
19503
19650
  try {
19504
19651
  p.push({
19505
19652
  role: "user",
@@ -19522,11 +19669,12 @@ function Vx(e, i) {
19522
19669
  task: i,
19523
19670
  ok: !0
19524
19671
  });
19525
- } catch (a) {
19526
- let o = Gg(a, "fatal");
19672
+ } catch (o) {
19673
+ p.length > a && p.splice(a);
19674
+ let s = Gg(o, "fatal");
19527
19675
  Oe({
19528
19676
  type: "error",
19529
- message: `批量任务 ${r + 1}/${e.length} 失败:${o.message}`,
19677
+ message: `批量任务 ${r + 1}/${e.length} 失败:${s.message}`,
19530
19678
  severity: "observable",
19531
19679
  code: "BATCH_TASK_FAILED",
19532
19680
  context: {
@@ -19536,7 +19684,7 @@ function Vx(e, i) {
19536
19684
  }), n.push({
19537
19685
  index: r,
19538
19686
  task: i,
19539
- error: o.message,
19687
+ error: s.message,
19540
19688
  ok: !1
19541
19689
  }), t?.({
19542
19690
  done: r + 1,
@@ -19573,7 +19721,7 @@ function Vx(e, i) {
19573
19721
  if (B.refCount--, B.refCount <= 0) {
19574
19722
  c && (m.flush?.(), c.flush(), c.dispose()), Ne && Ne.dispose();
19575
19723
  let e = B.mcpClosers.splice(0);
19576
- e.length && Promise.allSettled(e.map((e) => e())), Rx.delete(i);
19724
+ e.length && Promise.allSettled(e.map((e) => e())), Ux.delete(i);
19577
19725
  }
19578
19726
  },
19579
19727
  resolveConflict: o.resolve,
@@ -19590,7 +19738,7 @@ function Vx(e, i) {
19590
19738
  return t < 0 ? !1 : (I.splice(t, 1), z = ie(), B.agent && B.agent.setTools(z), B.infoTick.value++, !0);
19591
19739
  },
19592
19740
  setLlm(t) {
19593
- let r = Ty(t) ? t : new n({
19741
+ let r = Dy(t) ? t : new n({
19594
19742
  apiKey: t.apiKey,
19595
19743
  model: t.model,
19596
19744
  temperature: t.temperature,
@@ -19631,8 +19779,8 @@ function Vx(e, i) {
19631
19779
  getInfo() {
19632
19780
  return {
19633
19781
  id: i,
19634
- model: Ty(f) ? f.model ?? f.modelName : f.model,
19635
- systemPrompt: B.agent?.getEffectiveSystemPrompt?.() ?? A + Cy(N(), e.schemaHint),
19782
+ model: Dy(f) ? f.model ?? f.modelName : f.model,
19783
+ systemPrompt: B.agent?.getEffectiveSystemPrompt?.() ?? A + Ty(N(), e.schemaHint),
19636
19784
  tools: (B.agent?.allTools ?? z).map((e) => ({
19637
19785
  name: e.name,
19638
19786
  description: e.description,
@@ -19666,7 +19814,7 @@ function Vx(e, i) {
19666
19814
  spans: B.agent.spans.value,
19667
19815
  metrics: r_(B.agent.spans.value)
19668
19816
  } : void 0,
19669
- actions: Tx(e.actions ?? {}),
19817
+ actions: Ax(e.actions ?? {}),
19670
19818
  subagent: {
19671
19819
  enabled: !!_e,
19672
19820
  maxDepth: e.subagent?.maxDepth ?? 1,
@@ -19754,7 +19902,7 @@ function Vx(e, i) {
19754
19902
  }), z = ie(), e.debug && console.log(`[page-agent-sdk][mcp] 注入 ${n.length} 个工具,${B.mcpServers.length} 个 server`);
19755
19903
  }
19756
19904
  B.agent = x_({
19757
- ...Ty(e.llm) ? { llm: e.llm } : {
19905
+ ...Dy(e.llm) ? { llm: e.llm } : {
19758
19906
  apiKey: e.llm.apiKey,
19759
19907
  baseUrl: e.llm.baseUrl,
19760
19908
  model: e.llm.model,
@@ -19773,7 +19921,7 @@ function Vx(e, i) {
19773
19921
  maxOutputTokens: d.maxOutputTokens,
19774
19922
  maxVerifyAttempts: me ? pe : 0,
19775
19923
  onLlmChange: (t) => {
19776
- let n = Ty(t) ? void 0 : t;
19924
+ let n = Dy(t) ? void 0 : t;
19777
19925
  d = $g({
19778
19926
  model: n?.model ?? t.model ?? t.modelName,
19779
19927
  contextWindow: e.contextWindow ?? n?.contextWindow,
@@ -19795,12 +19943,12 @@ function Vx(e, i) {
19795
19943
  });
19796
19944
  })(), B;
19797
19945
  }
19798
- function Hx(e) {
19799
- let t = e.id ?? Ay();
19946
+ function qx(e) {
19947
+ let t = e.id ?? My();
19800
19948
  e.id || console.warn(`[page-agent-sdk] 未传 options.id,已生成随机 id "${t}"。刷新后持久化数据无法恢复,请传稳定 id。`);
19801
- let n = e.streaming ?? !0, r = e.ui ?? "default", i, a = e.shareContext ? Rx.get(t) : void 0;
19802
- a ? i = a : (i = Vx(e, t), e.shareContext && Rx.set(t, i)), i.refCount++;
19803
- let o = null, s = null, c = nb(e), l = null, u = null;
19949
+ let n = e.streaming ?? !0, r = e.ui ?? "default", i, a = e.shareContext ? Ux.get(t) : void 0;
19950
+ a ? i = a : (i = Kx(e, t), e.shareContext && Ux.set(t, i)), i.refCount++;
19951
+ let o = null, s = null, c = ib(e), l = null, u = null;
19804
19952
  async function d(t) {
19805
19953
  if (await i.initDone, o) {
19806
19954
  m();
@@ -19839,7 +19987,7 @@ function Hx(e) {
19839
19987
  i.afterRound(), i.store && await i.store.flush();
19840
19988
  },
19841
19989
  onClear: () => {
19842
- i.store && (i.sessionId = Ay(), i.vfsStore.clear?.(), i.todosMw.reset([]), e.memory || i.memoryMw.reset(""), i.agent.debugLogs.value = [], i.store.createSession(i.agentId, e.session?.title, i.sessionId));
19990
+ i.store && (i.sessionId = My(), i.vfsStore.clear?.(), i.todosMw.reset([]), e.memory || i.memoryMw.reset(""), i.agent.debugLogs.value = [], i.store.createSession(i.agentId, e.session?.title, i.sessionId));
19843
19991
  },
19844
19992
  pendingConflict: i.pendingConflict.value,
19845
19993
  onResolveConflict: (e) => i.resolveConflict(e),
@@ -19958,7 +20106,7 @@ function Hx(e) {
19958
20106
  error: "schema 校验失败:" + (t.error?.message ?? "未知错误")
19959
20107
  };
19960
20108
  }
19961
- return tv(r, e), t?.emit !== !1 && i.emit({
20109
+ return tv(r, e), i.dataOpsController?.markDataDirty?.(), t?.emit !== !1 && i.emit({
19962
20110
  type: "data_change",
19963
20111
  operation: "set",
19964
20112
  value: r
@@ -19980,7 +20128,7 @@ function Hx(e) {
19980
20128
  }
19981
20129
  //#endregion
19982
20130
  //#region src/core/sdk/defineTool.ts
19983
- function Ux(e) {
20131
+ function Jx(e) {
19984
20132
  return r(async (t) => {
19985
20133
  let n = await e.handler(t);
19986
20134
  return typeof n == "string" ? n : JSON.stringify(n);
@@ -19991,4 +20139,4 @@ function Ux(e) {
19991
20139
  });
19992
20140
  }
19993
20141
  //#endregion
19994
- export { ib as CONTEXT_PRESETS, Bg as ChatDialog, nf as CodePreview, Sy as DEFAULT_SYSTEM_PROMPT, J_ as HUMAN_CONFIRM_TOOL_NAME, af as MessageContent, Gv as STOP_WORDS, xh as SkillPanel, lb as UNSAFE_KEYS, Tx as actionsToInspectInfo, wx as actionsToTools, Kg as agentError, Sb as applyPatchToClone, Cb as applyPatchToLive, Gg as asAgentError, Cy as buildDataPrompt, wy as buildSystemPrompt, ax as commitSetToBind, Lv as connectMcp, wl as copyText, x_ as createAgent, q_ as createApprovalMiddleware, Hx as createChatSdk, iv as createCheckpointManager, av as createCheckpointMiddleware, ky as createConflictManager, ox as createDataOps, Z_ as createHumanConfirmMiddleware, X_ as createHumanConfirmTool, Xy as createMemoryBackend, B_ as createMemoryMiddleware, v as createProxyLlm, rb as createSdkEvents, eb as createSessionStore, Ix as createSkillStore, _v as createSubagentMiddleware, bv as createSubagentsMiddleware, jx as createUsageHintsMiddleware, xv as createVerifyMiddleware, Ab as createVfs, Qy as createWebStorageBackend, Dv as createWriteBackCheck, hb as deepClone, Ox as defineDataToolset, N_ as defineSkill, Ux as defineTool, mb as deleteByPath, dy as describeSchemaNode, p_ as detectGarbledToolCall, Eb as diffObjects, fx as domToStructure, mx as domTools, Dx as domToolsStatic, qv as estimateMessageTokens, Jv as estimateRoundTokens, e_ as estimateTokens, xy as extractSchemaHint, Pv as extractText, cx as fetchDocTools, Ex as fetchTools, ix as filterByToolMode, fy as formatConstraints, Vg as formatZodIssues, fb as getByPath, px as getDomTool, _x as getEnvSummary, ry as getSchemaAtPath, ey as getSchemaTopKeys, r_ as getTraceMetrics, xb as hashValue, Yv as indexSummarize, bx as inspectEnvTool, xx as inspectTools, Ty as isChatModel, ty as isPathAllowed, Hy as isQuotaError, ub as isUnsafePath, Yb as jpEval, Ug as jsonParseError, vb as limitDepth, gb as maybeParseValue, n_ as offloadPassThroughChars, t_ as offloadThresholdChars, _y as presets, ay as projectBySchema, iy as projectBySchemaDeep, _b as projectFields, Xv as recallRounds, py as renderSchemaHint, my as renderSchemaOverview, gy as renderSchemaShallow, ob as resolveContextOptions, nb as resolveDialogConfig, Oy as resolveLlm, $g as resolveModelCaps, tb as resolveStorage, Tb as restoreInPlace, wb as restoreLive, Wg as routeError, tx as runSandboxedScript, db as safeMerge, gx as safeSerialize, yb as safeStringify, Zb as searchJson, kx as selectBuiltinTools, pb as setByPath, vy as systemPromptHelpers, Kv as tokenize, $ as toolError, ny as unwrapSchema, Cl as useChat, e as z, Hg as zodError };
20142
+ export { ab as CAPABILITIES, cb as CONTEXT_PRESETS, Bg as ChatDialog, nf as CodePreview, wy as DEFAULT_SYSTEM_PROMPT, J_ as HUMAN_CONFIRM_TOOL_NAME, af as MessageContent, Gv as STOP_WORDS, xh as SkillPanel, pb as UNSAFE_KEYS, Ax as actionsToInspectInfo, kx as actionsToTools, Kg as agentError, Eb as applyPatchToClone, Db as applyPatchToLive, Gg as asAgentError, Ty as buildDataPrompt, Ey as buildSystemPrompt, lx as commitSetToBind, Lv as connectMcp, wl as copyText, x_ as createAgent, q_ as createApprovalMiddleware, qx as createChatSdk, iv as createCheckpointManager, av as createCheckpointMiddleware, jy as createConflictManager, dx as createDataOps, Z_ as createHumanConfirmMiddleware, X_ as createHumanConfirmTool, Qy as createMemoryBackend, B_ as createMemoryMiddleware, v as createProxyLlm, sb as createSdkEvents, nb as createSessionStore, Vx as createSkillStore, _v as createSubagentMiddleware, bv as createSubagentsMiddleware, Ix as createUsageHintsMiddleware, xv as createVerifyMiddleware, Pb as createVfs, eb as createWebStorageBackend, Dv as createWriteBackCheck, yb as deepClone, Nx as defineDataToolset, N_ as defineSkill, Jx as defineTool, vb as deleteByPath, dy as describeSchemaNode, p_ as detectGarbledToolCall, Ab as diffObjects, _x as domToStructure, yx as domTools, Mx as domToolsStatic, qv as estimateMessageTokens, Jv as estimateRoundTokens, e_ as estimateTokens, Sy as extractSchemaHint, Pv as extractText, px as fetchDocTools, jx as fetchTools, cx as filterByToolMode, fy as formatConstraints, Vg as formatZodIssues, gb as getByPath, vx as getDomTool, Sx as getEnvSummary, ry as getSchemaAtPath, ey as getSchemaTopKeys, r_ as getTraceMetrics, Tb as hashValue, Yv as indexSummarize, Tx as inspectEnvTool, Ex as inspectTools, Dy as isChatModel, ty as isPathAllowed, Wy as isQuotaError, mb as isUnsafePath, $b as jpEval, Ug as jsonParseError, Sb as limitDepth, bb as maybeParseValue, n_ as offloadPassThroughChars, t_ as offloadThresholdChars, _y as presets, ay as projectBySchema, iy as projectBySchemaDeep, xb as projectFields, Xv as recallRounds, py as renderSchemaHint, my as renderSchemaOverview, gy as renderSchemaShallow, ob as resolveCapabilities, ub as resolveContextOptions, ib as resolveDialogConfig, Ay as resolveLlm, $g as resolveModelCaps, rb as resolveStorage, kb as restoreInPlace, Ob as restoreLive, Wg as routeError, ax as runSandboxedScript, hb as safeMerge, xx as safeSerialize, Cb as safeStringify, tx as searchJson, Px as selectBuiltinTools, _b as setByPath, vy as systemPromptHelpers, Kv as tokenize, $ as toolError, ny as unwrapSchema, Cl as useChat, e as z, Hg as zodError };