page-agent-sdk 2.20.0 → 2.20.1

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.
@@ -14897,11 +14897,13 @@ function w_(e) {
14897
14897
  if (!e.length) return;
14898
14898
  let t = e.some((e) => e.parentId || e.deps && e.deps.length), n = [];
14899
14899
  if (t) {
14900
- let t = (t) => e.filter((e) => e.parentId === t), r = (t) => e.find((e) => e.id === t)?.status === "completed" ? "✓" : "⏳", i = (e, a) => {
14901
- let o = " ".repeat(a), s = e.deps?.length ? ` (依赖:${e.deps.map((e) => r(e)).join("")})` : "", c = e.evidence ? ` [证据:${e.evidence}]` : "", l = e.criteria ? ` [标准:${e.criteria}]` : "";
14902
- n.push(`${o}- #${e.id} [${e.status}] ${e.content}${l}${s}${c}`), t(e.id).forEach((e) => i(e, a + 1));
14900
+ let t = (t) => e.filter((e) => e.parentId === t), r = (t) => e.find((e) => e.id === t)?.status === "completed" ? "✓" : "⏳", i = (e, a, o) => {
14901
+ if (o.has(e.id)) return;
14902
+ o.add(e.id);
14903
+ let s = " ".repeat(a), c = e.deps?.length ? ` (依赖:${e.deps.map((e) => r(e)).join("")})` : "", l = e.evidence ? ` [证据:${e.evidence}]` : "", u = e.criteria ? ` [标准:${e.criteria}]` : "";
14904
+ n.push(`${s}- #${e.id} [${e.status}] ${e.content}${u}${c}${l}`), t(e.id).forEach((e) => i(e, a + 1, o));
14903
14905
  };
14904
- e.filter((e) => !e.parentId).forEach((e) => i(e, 0));
14906
+ e.filter((e) => !e.parentId).forEach((e) => i(e, 0, /* @__PURE__ */ new Set()));
14905
14907
  } else e.forEach((e, t) => {
14906
14908
  let r = e.evidence ? ` [证据:${e.evidence}]` : "";
14907
14909
  n.push(`${t + 1}. #${e.id} [${e.status}] ${e.content}${r}`);
@@ -15456,7 +15458,7 @@ function iv(e) {
15456
15458
  importStack(e) {
15457
15459
  t.length = 0;
15458
15460
  let n = Array.isArray(e) ? e : [];
15459
- for (let e of n) e && typeof e == "object" && "id" in e && "messages" in e && t.push(e);
15461
+ 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);
15460
15462
  r = t.reduce((e, t) => Math.max(e, t.id), 0) + 1;
15461
15463
  }
15462
15464
  };
@@ -17848,8 +17850,38 @@ var $b = [
17848
17850
  "try { self.EventSource = undefined } catch {}",
17849
17851
  "try { self.BroadcastChannel = undefined } catch {}",
17850
17852
  "if (self.navigator && self.navigator.sendBeacon) self.navigator.sendBeacon = () => { throw new Error('sendBeacon 已被沙箱禁用') }"
17851
- ].join("\n");
17852
- function ex(e, t, n = 3e3) {
17853
+ ].join("\n"), ex = [
17854
+ {
17855
+ re: /\bimport\s*\(/,
17856
+ msg: "动态 import() 拉外网模块"
17857
+ },
17858
+ {
17859
+ re: /\bimport\s+[\w'"]/,
17860
+ msg: "import 语句"
17861
+ },
17862
+ {
17863
+ re: /\beval\s*\(/,
17864
+ msg: "eval() 动态执行"
17865
+ },
17866
+ {
17867
+ re: /\bFunction\s*\(/,
17868
+ msg: "Function() 构造"
17869
+ },
17870
+ {
17871
+ re: /new\s+Function\b/,
17872
+ msg: "new Function() 构造"
17873
+ },
17874
+ {
17875
+ re: /\brequire\s*\(/,
17876
+ msg: "require() 拉模块"
17877
+ }
17878
+ ];
17879
+ function tx(e, t, n = 3e3) {
17880
+ for (let { re: e, msg: n } of ex) if (e.test(t)) return Promise.resolve({
17881
+ ok: !1,
17882
+ error: `沙箱拒绝执行:脚本含禁用模式(${n})`,
17883
+ elapsedMs: 0
17884
+ });
17853
17885
  return new Promise((r) => {
17854
17886
  let i = Date.now(), a = !1, o = (e) => {
17855
17887
  if (!a) {
@@ -17862,7 +17894,7 @@ function ex(e, t, n = 3e3) {
17862
17894
  elapsedMs: Date.now() - i
17863
17895
  });
17864
17896
  }
17865
- }, s = $b + "\nself.onmessage = async (e) => {\n try {\n const fn = new Function(\"data\", e.data.script);\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;
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;
17866
17898
  try {
17867
17899
  let e = new Blob([s], { type: "application/javascript" });
17868
17900
  c = URL.createObjectURL(e), l = new Worker(c);
@@ -17897,7 +17929,7 @@ function ex(e, t, n = 3e3) {
17897
17929
  }
17898
17930
  //#endregion
17899
17931
  //#region src/core/tools/dataOps.ts
17900
- var tx = /* @__PURE__ */ new Set([
17932
+ var nx = /* @__PURE__ */ new Set([
17901
17933
  "describe_data",
17902
17934
  "get_data",
17903
17935
  "set_data",
@@ -17909,11 +17941,11 @@ var tx = /* @__PURE__ */ new Set([
17909
17941
  "diff_data",
17910
17942
  "draft_write",
17911
17943
  "draft_commit"
17912
- ]), nx = /* @__PURE__ */ new Set(["read", "write"]);
17913
- function rx(e, t = "simple") {
17914
- return t === "advanced" ? e : t === "minimal" ? e.filter((e) => nx.has(e.name)) : e.filter((e) => !tx.has(e.name));
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));
17915
17947
  }
17916
- function ix(e) {
17948
+ function ax(e) {
17917
17949
  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);
17918
17950
  if (!u.success) return {
17919
17951
  ok: !1,
@@ -17949,7 +17981,7 @@ function ix(e) {
17949
17981
  data: u.data
17950
17982
  };
17951
17983
  }
17952
- function ax(e, n = {}) {
17984
+ function ox(e, n = {}) {
17953
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 = {
17954
17986
  get: () => ({
17955
17987
  schema: i,
@@ -18030,7 +18062,7 @@ function ax(e, n = {}) {
18030
18062
  if (n !== null) return n;
18031
18063
  let r = gb(e);
18032
18064
  if (r.parseError) return Ug("", e, r.parseError);
18033
- let o = ix({
18065
+ let o = ax({
18034
18066
  bindRef: a,
18035
18067
  value: r.parsed,
18036
18068
  schema: i,
@@ -18312,7 +18344,7 @@ function ax(e, n = {}) {
18312
18344
  e && (o = iy(o, e));
18313
18345
  }
18314
18346
  } else o = s ? ay(a, s) : a;
18315
- let c = hb(o), l = await ex(c, e, r && JSON.stringify(c).length > 1e5 ? 8e3 : 3e3);
18347
+ let c = hb(o), l = await tx(c, e, r && JSON.stringify(c).length > 1e5 ? 8e3 : 3e3);
18316
18348
  if (!l.ok) {
18317
18349
  let t = /超时/.test(l.error || "");
18318
18350
  return $({
@@ -18630,7 +18662,7 @@ function ax(e, n = {}) {
18630
18662
  if (b.parseError) return Ug("", _, b.parseError);
18631
18663
  let x = await h("set", y);
18632
18664
  if (x !== null) return x;
18633
- let S = ix({
18665
+ let S = ax({
18634
18666
  bindRef: a,
18635
18667
  value: b.parsed,
18636
18668
  schema: i,
@@ -18753,7 +18785,7 @@ function ax(e, n = {}) {
18753
18785
  }
18754
18786
  });
18755
18787
  }
18756
- let f = ix({
18788
+ let f = ax({
18757
18789
  bindRef: a,
18758
18790
  value: d,
18759
18791
  schema: i,
@@ -18799,8 +18831,8 @@ function ax(e, n = {}) {
18799
18831
  }
18800
18832
  //#endregion
18801
18833
  //#region src/core/tools/fetchDoc.ts
18802
- var ox = 3e4, sx = [r(async ({ url: e, as: t }) => {
18803
- let n = new AbortController(), r = setTimeout(() => n.abort(), ox);
18834
+ var sx = 3e4, cx = [r(async ({ url: e, as: t }) => {
18835
+ let n = new AbortController(), r = setTimeout(() => n.abort(), sx);
18804
18836
  try {
18805
18837
  let r = await fetch(e, {
18806
18838
  method: "GET",
@@ -18817,7 +18849,7 @@ var ox = 3e4, sx = [r(async ({ url: e, as: t }) => {
18817
18849
  ].join("\n");
18818
18850
  } catch (t) {
18819
18851
  let r = t?.message || String(t);
18820
- return n.signal.aborted ? `获取失败:请求超时(${ox}ms,${e})。` : /Failed to fetch|NetworkError|CORS|blocked/i.test(r) ? `获取失败:可能是 CORS 跨域拦截或网络错误(${r})。浏览器仅能 GET 同源或服务端已配置 CORS 的资源;跨域抓取需后端代理。` : `获取失败:${r}`;
18852
+ return n.signal.aborted ? `获取失败:请求超时(${sx}ms,${e})。` : /Failed to fetch|NetworkError|CORS|blocked/i.test(r) ? `获取失败:可能是 CORS 跨域拦截或网络错误(${r})。浏览器仅能 GET 同源或服务端已配置 CORS 的资源;跨域抓取需后端代理。` : `获取失败:${r}`;
18821
18853
  } finally {
18822
18854
  clearTimeout(r);
18823
18855
  }
@@ -18828,7 +18860,7 @@ var ox = 3e4, sx = [r(async ({ url: e, as: t }) => {
18828
18860
  url: t.string().describe("要抓取的 URL(同源或已配 CORS)"),
18829
18861
  as: t.enum(["text", "markdown"]).optional().describe("返回格式标签,默认 text")
18830
18862
  })
18831
- })], cx = [
18863
+ })], lx = [
18832
18864
  "id",
18833
18865
  "class",
18834
18866
  "href",
@@ -18840,12 +18872,12 @@ var ox = 3e4, sx = [r(async ({ url: e, as: t }) => {
18840
18872
  "aria-label",
18841
18873
  "name",
18842
18874
  "type"
18843
- ];
18844
- function lx(e, t) {
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) {
18845
18877
  if (!e) return null;
18846
- let { depth: n, attrs: r, includeText: i = !0 } = t, a = r !== void 0, o = r ?? cx, s = (e) => {
18878
+ let { depth: n, attrs: r, includeText: i = !0 } = t, a = r !== void 0, o = r ?? lx, s = (e) => {
18847
18879
  let t = {};
18848
- for (let n of Array.from(e.attributes)) (a ? o.includes(n.name) : o.includes(n.name) || n.name.startsWith("data-")) && (t[n.name] = n.value);
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));
18849
18881
  return t;
18850
18882
  }, c = (e, t) => {
18851
18883
  let n = {
@@ -18861,10 +18893,10 @@ function lx(e, t) {
18861
18893
  };
18862
18894
  return c(e, n);
18863
18895
  }
18864
- var ux = r(({ selector: e, depth: t, attrs: n, includeText: r }) => {
18896
+ var px = r(({ selector: e, depth: t, attrs: n, includeText: r }) => {
18865
18897
  let i = e ? document.querySelector(e) : document.body;
18866
18898
  if (!i) return `未找到匹配元素:selector="${e}"`;
18867
- let a = lx(i, {
18899
+ let a = fx(i, {
18868
18900
  depth: t ?? 3,
18869
18901
  attrs: n,
18870
18902
  includeText: r ?? !0
@@ -18879,14 +18911,14 @@ var ux = r(({ selector: e, depth: t, attrs: n, includeText: r }) => {
18879
18911
  attrs: t.array(t.string()).optional().describe("属性白名单(传了 = 严格白名单;不传 = 默认常用 + data-*)"),
18880
18912
  includeText: t.boolean().optional().describe("是否包含直接文本(默认 true)")
18881
18913
  })
18882
- }), dx = [ux];
18914
+ }), mx = [px];
18883
18915
  //#endregion
18884
18916
  //#region src/core/tools/envTool.ts
18885
- function fx(e) {
18917
+ function hx(e) {
18886
18918
  let t = e;
18887
18919
  return typeof t.tagName == "string" || typeof t.nodeType == "number" && typeof t.nodeName == "string";
18888
18920
  }
18889
- function px(e, t = 3, n = 2e3, r) {
18921
+ function gx(e, t = 3, n = 2e3, r) {
18890
18922
  if (e == null) return e;
18891
18923
  if (typeof e == "string") return e.length > n ? e.slice(0, n) + "…(已截断)" : e;
18892
18924
  if (typeof e == "number" || typeof e == "boolean") return e;
@@ -18895,14 +18927,14 @@ function px(e, t = 3, n = 2e3, r) {
18895
18927
  if (typeof e == "bigint") return `${e.toString()}n`;
18896
18928
  if (typeof e != "object") return String(e);
18897
18929
  let i = e;
18898
- if (fx(i)) {
18930
+ if (hx(i)) {
18899
18931
  let e = i;
18900
18932
  return e.tagName ? `[Element: <${e.tagName.toLowerCase()}>]` : `[Node: ${e.nodeName}]`;
18901
18933
  }
18902
18934
  if (r?.has(i)) return "[Circular]";
18903
18935
  let a = r ?? /* @__PURE__ */ new WeakSet();
18904
18936
  if (a.add(i), Array.isArray(e)) {
18905
- let r = e.slice(0, 100).map((e) => px(e, t - 1, n, a));
18937
+ let r = e.slice(0, 100).map((e) => gx(e, t - 1, n, a));
18906
18938
  return e.length > 100 && r.push(`…(共 ${e.length} 项,已截断)`), r;
18907
18939
  }
18908
18940
  if (t < 0) return "(对象,已截断)";
@@ -18914,14 +18946,14 @@ function px(e, t = 3, n = 2e3, r) {
18914
18946
  break;
18915
18947
  }
18916
18948
  try {
18917
- o[r] = px(i[r], t - 1, n, a);
18949
+ o[r] = gx(i[r], t - 1, n, a);
18918
18950
  } catch {
18919
18951
  o[r] = "(getter 抛错)";
18920
18952
  }
18921
18953
  }
18922
18954
  return o;
18923
18955
  }
18924
- function mx(e) {
18956
+ function _x(e) {
18925
18957
  let t = e ?? (typeof window < "u" ? window : {}), n = t.navigator, r = t.location, i = t.document;
18926
18958
  return {
18927
18959
  location: {
@@ -18954,25 +18986,30 @@ function mx(e) {
18954
18986
  } : "(无 document)"
18955
18987
  };
18956
18988
  }
18957
- var hx = r(({ key: e }) => {
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 }) => {
18958
18990
  if (e) {
18991
+ if (vx.test(e) || yx.test(e)) return JSON.stringify({
18992
+ key: e,
18993
+ denied: !0,
18994
+ reason: "安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏"
18995
+ }, null, 2);
18959
18996
  let t = (typeof window < "u" ? window : {})[e];
18960
18997
  return JSON.stringify({
18961
18998
  key: e,
18962
18999
  exists: t !== void 0,
18963
19000
  type: typeof t,
18964
- value: px(t)
19001
+ value: gx(t)
18965
19002
  }, null, 2);
18966
19003
  }
18967
- return JSON.stringify(mx(), null, 2);
19004
+ return JSON.stringify(_x(), null, 2);
18968
19005
  }, {
18969
19006
  name: "inspect_env",
18970
19007
  description: "读取宿主页面环境信息(排查调试用,默认开启)。不传参 = 返回环境摘要(location 的 URL/origin/path、navigator 的浏览器/语言、viewport 视口尺寸、document 的 title/readyState);传 key = 读取指定 window 属性值(如 inspect_env({key:\"appConfig\"}) 读集成方挂的调试变量 window.appConfig)。用于排查「当前页面在哪/什么浏览器/视口多大/调试变量值是什么」。轻量只读,大结果自动外存 vfs。",
18971
19008
  schema: t.object({ key: t.string().optional().describe("要读取的 window 属性名(如 \"appConfig\"/\"__DEBUG__\");不传 = 返回环境摘要") })
18972
- }), gx = [hx];
19009
+ }), xx = [bx];
18973
19010
  //#endregion
18974
19011
  //#region src/core/harness/budget.ts
18975
- function _x(e, t, n) {
19012
+ function Sx(e, t, n) {
18976
19013
  let r = 0;
18977
19014
  return {
18978
19015
  name: "budget",
@@ -18997,12 +19034,12 @@ function _x(e, t, n) {
18997
19034
  }
18998
19035
  //#endregion
18999
19036
  //#region src/core/sdk/actions.ts
19000
- var vx = /^[a-zA-Z][a-zA-Z0-9_]*$/;
19001
- function yx(e) {
19037
+ var Cx = /^[a-zA-Z][a-zA-Z0-9_]*$/;
19038
+ function wx(e) {
19002
19039
  let n = [];
19003
19040
  for (let [i, a] of Object.entries(e)) {
19004
- if (!vx.test(i)) {
19005
- console.warn(`[page-agent-sdk][actions] 动作名 "${i}" 非法(须匹配 ${vx}),已跳过`);
19041
+ if (!Cx.test(i)) {
19042
+ console.warn(`[page-agent-sdk][actions] 动作名 "${i}" 非法(须匹配 ${Cx}),已跳过`);
19006
19043
  continue;
19007
19044
  }
19008
19045
  let e = a.description || `宿主动作 ${i}`;
@@ -19022,9 +19059,9 @@ function yx(e) {
19022
19059
  }
19023
19060
  return n;
19024
19061
  }
19025
- function bx(e) {
19062
+ function Tx(e) {
19026
19063
  let t = {};
19027
- for (let [n, r] of Object.entries(e)) vx.test(n) && (t[n] = {
19064
+ for (let [n, r] of Object.entries(e)) Cx.test(n) && (t[n] = {
19028
19065
  description: r.description,
19029
19066
  hasParams: !!r.params
19030
19067
  });
@@ -19032,11 +19069,11 @@ function bx(e) {
19032
19069
  }
19033
19070
  //#endregion
19034
19071
  //#region src/core/toolsets.ts
19035
- var xx = sx, Sx = dx;
19036
- function Cx(e, t) {
19037
- return ax(e, t);
19072
+ var Ex = cx, Dx = mx;
19073
+ function Ox(e, t) {
19074
+ return ox(e, t);
19038
19075
  }
19039
- function wx(e, t, n, r, i) {
19076
+ function kx(e, t, n, r, i) {
19040
19077
  let a = e?.dataOps !== !1, o = e?.fetch !== !1, s = e?.domInspect === !0, c = e?.inspectEnv !== !1;
19041
19078
  return [
19042
19079
  ...a ? t : [],
@@ -19047,15 +19084,15 @@ function wx(e, t, n, r, i) {
19047
19084
  }
19048
19085
  //#endregion
19049
19086
  //#region src/core/harness/usageHints.ts
19050
- var Tx = .7;
19051
- function Ex(e, t, n = "simple") {
19087
+ var Ax = .7;
19088
+ function jx(e, t, n = "simple") {
19052
19089
  let r = n !== "advanced";
19053
19090
  return {
19054
19091
  name: "usageHints",
19055
19092
  augmentPrompt: () => {
19056
19093
  let n = [];
19057
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) {
19058
- let t = e.subagents.filter((e) => (e.temperature ?? 0) >= Tx || /规划|创意|设计|方案|brainstorm|plan/i.test(e.description)), i = e.subagents.filter((e) => (e.temperature ?? 0) < Tx && /反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));
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));
19059
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(" · 简单/明确任务(如\"标题改红色\")直接执行,不必走规划-反思。");
19060
19097
  }
19061
19098
  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;
@@ -19064,15 +19101,15 @@ function Ex(e, t, n = "simple") {
19064
19101
  }
19065
19102
  //#endregion
19066
19103
  //#region src/core/backends/skillStore.ts
19067
- var Dx = "v:1::skill-store", Ox = "chat-sdk";
19068
- function kx(e, t, n) {
19069
- return `${Dx}::${e}::${t}::${n}`;
19104
+ var Mx = "v:1::skill-store", Nx = "chat-sdk";
19105
+ function Px(e, t, n) {
19106
+ return `${Mx}::${e}::${t}::${n}`;
19070
19107
  }
19071
- function Ax(e, t) {
19072
- return `${Dx}::${e}::${t}::`;
19108
+ function Fx(e, t) {
19109
+ return `${Mx}::${e}::${t}::`;
19073
19110
  }
19074
- function jx(e = {}) {
19075
- let t = e.dbName ?? Ox, n = e.backend ?? "indexed", r = e.id ?? "", i, a, o = new Promise((e) => {
19111
+ function Ix(e = {}) {
19112
+ let t = e.dbName ?? Nx, n = e.backend ?? "indexed", r = e.id ?? "", i, a, o = new Promise((e) => {
19076
19113
  a = e;
19077
19114
  });
19078
19115
  return (async () => {
@@ -19094,42 +19131,42 @@ function jx(e = {}) {
19094
19131
  ready: o,
19095
19132
  async list() {
19096
19133
  let e = [];
19097
- return await i.scan(Ax(t, r), (t, n) => {
19134
+ return await i.scan(Fx(t, r), (t, n) => {
19098
19135
  e.push(n);
19099
19136
  }), e;
19100
19137
  },
19101
19138
  async get(e) {
19102
- return await i.get(kx(t, r, e));
19139
+ return await i.get(Px(t, r, e));
19103
19140
  },
19104
19141
  async put(e) {
19105
19142
  try {
19106
- await i.set(kx(t, r, e.name), e);
19143
+ await i.set(Px(t, r, e.name), e);
19107
19144
  } catch (e) {
19108
19145
  Hy(e) && (i = Xy());
19109
19146
  }
19110
19147
  },
19111
19148
  async remove(e) {
19112
- let n = kx(t, r, e);
19149
+ let n = Px(t, r, e);
19113
19150
  return await i.get(n) != null && (await i.del(n), !0);
19114
19151
  },
19115
19152
  async clear() {
19116
- await i.clearPrefix(Ax(t, r));
19153
+ await i.clearPrefix(Fx(t, r));
19117
19154
  },
19118
19155
  dispose() {}
19119
19156
  };
19120
19157
  }
19121
19158
  //#endregion
19122
19159
  //#region src/core/sdk/createChatSdk.ts
19123
- var Mx = 50, Nx = /* @__PURE__ */ new Map();
19124
- function Px(e, t) {
19160
+ var Lx = 50, Rx = /* @__PURE__ */ new Map();
19161
+ function zx(e, t) {
19125
19162
  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;
19126
19163
  }
19127
- function Fx(e, t, n, r) {
19164
+ function Bx(e, t, n, r) {
19128
19165
  let i = 0;
19129
19166
  return {
19130
19167
  name: "sdk-events",
19131
19168
  wrapToolCall: async (t, r) => {
19132
- let i = await r(t), a = Px(t.name, t.args);
19169
+ let i = await r(t), a = zx(t.name, t.args);
19133
19170
  return a && e({
19134
19171
  type: "data_change",
19135
19172
  operation: a,
@@ -19164,7 +19201,7 @@ function Fx(e, t, n, r) {
19164
19201
  }
19165
19202
  };
19166
19203
  }
19167
- function Ix(e, i) {
19204
+ function Vx(e, i) {
19168
19205
  let a = {
19169
19206
  prompt_tokens: 0,
19170
19207
  completion_tokens: 0,
@@ -19194,18 +19231,18 @@ function Ix(e, i) {
19194
19231
  getTodos: () => y.current?.getState?.()?.todos ?? [],
19195
19232
  messages: p,
19196
19233
  maxCheckpoints: x && typeof x == "object" ? x.maxCheckpoints : void 0
19197
- }) : 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 ? ax(b, {
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, {
19198
19235
  onAudit: e.onAudit ?? (e.debug ? (e) => console.log("[page-agent-sdk][data audit]", e) : void 0),
19199
19236
  maxSnapshots: e.maxSnapshots,
19200
19237
  onConflict: o.set,
19201
19238
  autoLock: e.autoLock,
19202
19239
  interceptors: e.interceptors,
19203
19240
  vfsStore: D ? m : void 0
19204
- }) : [], M = E ? rx(j, e.toolMode) : [], ee = E && b ? j.controller ?? null : null, N = () => ee?.get() ?? b, P = /* @__PURE__ */ new Map(), F = wx(T, M, sx, dx, gx);
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);
19205
19242
  F.forEach((e) => P.set(e.name, "builtin"));
19206
19243
  let I = [...e.tools || []];
19207
19244
  I.forEach((e) => P.set(e.name, "user"));
19208
- let te = yx(e.actions ?? {});
19245
+ let te = wx(e.actions ?? {});
19209
19246
  te.forEach((e) => P.set(e.name, "action"));
19210
19247
  let L = [], R = e.humanConfirm !== !1 && (!e.approval || e.approval.humanConfirmTool !== !1), ne = R ? X_() : null;
19211
19248
  ne && P.set(J_, "builtin");
@@ -19276,7 +19313,7 @@ function Ix(e, i) {
19276
19313
  llm: e.llm,
19277
19314
  tools: xe
19278
19315
  } : void 0
19279
- }) : void 0, Ce = Ex({
19316
+ }) : void 0, Ce = jx({
19280
19317
  ...T,
19281
19318
  humanConfirm: R,
19282
19319
  subagents: e.subagents?.map((e) => ({
@@ -19308,7 +19345,7 @@ function Ix(e, i) {
19308
19345
  name: e.name,
19309
19346
  description: e.description,
19310
19347
  getContent: () => e.content
19311
- }), Ne = e.skillStorage === !1 ? null : jx({
19348
+ }), Ne = e.skillStorage === !1 ? null : Ix({
19312
19349
  ...typeof e.skillStorage == "object" ? e.skillStorage : {},
19313
19350
  id: e.skillStorage && typeof e.skillStorage == "object" && e.skillStorage.id ? e.skillStorage.id : `agent::${i}`
19314
19351
  }), Pe = () => {
@@ -19355,12 +19392,12 @@ function Ix(e, i) {
19355
19392
  ...ve ? [ve] : [],
19356
19393
  ...Te ? [Te] : [],
19357
19394
  ...e.middleware || [],
19358
- ...k ? [_x(a, {
19395
+ ...k ? [Sx(a, {
19359
19396
  tokenBudget: e.tokenBudget,
19360
19397
  timeBudgetMs: e.timeBudgetMs
19361
19398
  }, Oe)] : [],
19362
- Fx(Oe, p, N, a)
19363
- ]), Le = e.maxMemoryRounds ?? Mx, B = {
19399
+ Bx(Oe, p, N, a)
19400
+ ]), Le = e.maxMemoryRounds ?? Lx, B = {
19364
19401
  agentId: i,
19365
19402
  store: c,
19366
19403
  messages: p,
@@ -19408,7 +19445,7 @@ function Ix(e, i) {
19408
19445
  Be(), Ve();
19409
19446
  },
19410
19447
  async send(e, t) {
19411
- await B.initDone, t?.mission && oe && g.setMission(t.mission);
19448
+ await B.initDone, t ??= {}, t?.mission && oe && g.setMission(t.mission);
19412
19449
  let n = e;
19413
19450
  if (t.interceptors?.input) try {
19414
19451
  let r = t.interceptors.input(e);
@@ -19536,7 +19573,7 @@ function Ix(e, i) {
19536
19573
  if (B.refCount--, B.refCount <= 0) {
19537
19574
  c && (m.flush?.(), c.flush(), c.dispose()), Ne && Ne.dispose();
19538
19575
  let e = B.mcpClosers.splice(0);
19539
- e.length && Promise.allSettled(e.map((e) => e())), Nx.delete(i);
19576
+ e.length && Promise.allSettled(e.map((e) => e())), Rx.delete(i);
19540
19577
  }
19541
19578
  },
19542
19579
  resolveConflict: o.resolve,
@@ -19629,7 +19666,7 @@ function Ix(e, i) {
19629
19666
  spans: B.agent.spans.value,
19630
19667
  metrics: r_(B.agent.spans.value)
19631
19668
  } : void 0,
19632
- actions: bx(e.actions ?? {}),
19669
+ actions: Tx(e.actions ?? {}),
19633
19670
  subagent: {
19634
19671
  enabled: !!_e,
19635
19672
  maxDepth: e.subagent?.maxDepth ?? 1,
@@ -19758,11 +19795,11 @@ function Ix(e, i) {
19758
19795
  });
19759
19796
  })(), B;
19760
19797
  }
19761
- function Lx(e) {
19798
+ function Hx(e) {
19762
19799
  let t = e.id ?? Ay();
19763
19800
  e.id || console.warn(`[page-agent-sdk] 未传 options.id,已生成随机 id "${t}"。刷新后持久化数据无法恢复,请传稳定 id。`);
19764
- let n = e.streaming ?? !0, r = e.ui ?? "default", i, a = e.shareContext ? Nx.get(t) : void 0;
19765
- a ? i = a : (i = Ix(e, t), e.shareContext && Nx.set(t, i)), i.refCount++;
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++;
19766
19803
  let o = null, s = null, c = nb(e), l = null, u = null;
19767
19804
  async function d(t) {
19768
19805
  if (await i.initDone, o) {
@@ -19943,7 +19980,7 @@ function Lx(e) {
19943
19980
  }
19944
19981
  //#endregion
19945
19982
  //#region src/core/sdk/defineTool.ts
19946
- function Rx(e) {
19983
+ function Ux(e) {
19947
19984
  return r(async (t) => {
19948
19985
  let n = await e.handler(t);
19949
19986
  return typeof n == "string" ? n : JSON.stringify(n);
@@ -19954,4 +19991,4 @@ function Rx(e) {
19954
19991
  });
19955
19992
  }
19956
19993
  //#endregion
19957
- 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, bx as actionsToInspectInfo, yx as actionsToTools, Kg as agentError, Sb as applyPatchToClone, Cb as applyPatchToLive, Gg as asAgentError, Cy as buildDataPrompt, wy as buildSystemPrompt, ix as commitSetToBind, Lv as connectMcp, wl as copyText, x_ as createAgent, q_ as createApprovalMiddleware, Lx as createChatSdk, iv as createCheckpointManager, av as createCheckpointMiddleware, ky as createConflictManager, ax as createDataOps, Z_ as createHumanConfirmMiddleware, X_ as createHumanConfirmTool, Xy as createMemoryBackend, B_ as createMemoryMiddleware, v as createProxyLlm, rb as createSdkEvents, eb as createSessionStore, jx as createSkillStore, _v as createSubagentMiddleware, bv as createSubagentsMiddleware, Ex as createUsageHintsMiddleware, xv as createVerifyMiddleware, Ab as createVfs, Qy as createWebStorageBackend, Dv as createWriteBackCheck, hb as deepClone, Cx as defineDataToolset, N_ as defineSkill, Rx as defineTool, mb as deleteByPath, dy as describeSchemaNode, p_ as detectGarbledToolCall, Eb as diffObjects, lx as domToStructure, dx as domTools, Sx as domToolsStatic, qv as estimateMessageTokens, Jv as estimateRoundTokens, e_ as estimateTokens, xy as extractSchemaHint, Pv as extractText, sx as fetchDocTools, xx as fetchTools, rx as filterByToolMode, fy as formatConstraints, Vg as formatZodIssues, fb as getByPath, ux as getDomTool, mx as getEnvSummary, ry as getSchemaAtPath, ey as getSchemaTopKeys, r_ as getTraceMetrics, xb as hashValue, Yv as indexSummarize, hx as inspectEnvTool, gx 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, ex as runSandboxedScript, db as safeMerge, px as safeSerialize, yb as safeStringify, Zb as searchJson, wx 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 };
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 };