page-agent-sdk 4.24.1 → 4.24.3

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.
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  [![npm](https://img.shields.io/npm/v/page-agent-sdk.svg)](https://www.npmjs.com/package/page-agent-sdk)
10
10
  [![license](https://img.shields.io/badge/license-ISC-blue.svg)](https://github.com/whyymj/page-agent-sdk/blob/master/LICENSE)
11
- [![tests](https://img.shields.io/badge/self%20tests-3782%20asserts-brightgreen.svg)](#self-tests)
11
+ [![tests](https://img.shields.io/badge/self%20tests-3786%20asserts-brightgreen.svg)](#self-tests)
12
12
 
13
13
  ---
14
14
 
package/README.zh-CN.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  [![npm](https://img.shields.io/npm/v/page-agent-sdk.svg)](https://www.npmjs.com/package/page-agent-sdk)
10
10
  [![license](https://img.shields.io/badge/license-ISC-blue.svg)](https://github.com/whyymj/page-agent-sdk/blob/master/LICENSE)
11
- [![tests](https://img.shields.io/badge/self%20tests-3782%20asserts-brightgreen.svg)](#自测)
11
+ [![tests](https://img.shields.io/badge/self%20tests-3786%20asserts-brightgreen.svg)](#自测)
12
12
 
13
13
  ---
14
14
 
@@ -5321,6 +5321,8 @@ var dc = {
5321
5321
  " → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。",
5322
5322
  " 页面没写不构成不答的理由。",
5323
5323
  "",
5324
+ "已懂不查:已是通用知识或对话里已读过的内容,直接用 —— 不必为同一信息再读页面;",
5325
+ "只有要断言「页面上写了什么」时才需要读页核实。",
5324
5326
  "出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、",
5325
5327
  "过渡句一律不标。「没找到」的说明压成一句,不报检索过程。"
5326
5328
  ].join("\n"),
@@ -5336,6 +5338,8 @@ var dc = {
5336
5338
  " → Give your judgment and reasoning directly; keep the notes' stance and your own view separate (\"this page's position is ...; my take is ...\").",
5337
5339
  " The page not covering it is never a reason to refuse.",
5338
5340
  "",
5341
+ "Known means no lookup: use general knowledge you already master, and anything already read in this conversation,",
5342
+ "directly — never re-read the page for information you already have; only claims about \"what the page says\" require reading to verify.",
5339
5343
  "Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,",
5340
5344
  "personal opinions, and transitions get none. Compress \"not found\" statements to one sentence; never narrate the search process."
5341
5345
  ].join("\n"),
@@ -14548,15 +14552,15 @@ function n_(e, t, n = {}) {
14548
14552
  let o = Math.min(a.length, r);
14549
14553
  return {
14550
14554
  hits: a.slice(0, o).map((e) => {
14551
- let n = Array.from(e.childNodes).filter((e) => e.nodeType === 3).map((e) => e.textContent || "").join("").trim();
14552
- if (i === "text" && !n) {
14553
- let r = (e.textContent || "").trim(), i = r.indexOf(t);
14554
- n = r.slice(Math.max(0, i - 20), i + t.length + 40);
14555
+ let n = (typeof e.textContent == "string" && e.textContent ? e.textContent : Array.from(e.childNodes ?? []).filter((e) => e.nodeType === 3).map((e) => e.textContent || "").join("")).replace(/\s+/g, " ").trim(), r = n.slice(0, 120);
14556
+ if (i !== "selector" && t) {
14557
+ let e = n.indexOf(String(t));
14558
+ e >= 0 && (r = (e > 100 ? "…" : "") + n.slice(Math.max(0, e - 100), e + 120) + (e + 120 < n.length ? "…" : ""));
14555
14559
  }
14556
14560
  return {
14557
14561
  selector: t_(e),
14558
14562
  tag: e.tagName.toLowerCase(),
14559
- text: n.slice(0, 120)
14563
+ text: r
14560
14564
  };
14561
14565
  }),
14562
14566
  total: a.length,
@@ -14927,10 +14931,10 @@ function j_(e, t, n) {
14927
14931
  augmentPrompt: (i) => {
14928
14932
  let a = [];
14929
14933
  if (r.planning && (a.push("【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:"), a.push(" · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。"), a.push(" · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。"), a.push(" · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。"), a.push(" · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 \"components.2\"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。"), e?.humanConfirm ? a.push(" · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。") : a.push(" · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。"), a.push(" · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。")), t && (a.push("改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。"), a.push("读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。"), a.push("修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。"), a.push("修改主数据出错时可用 restore_data 回退最近一次。"), a.push("在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。"), a.push("找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。"), a.push("需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。"), a.push("读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。"), a.push("【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:\"set\",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。"), a.push("读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:\"该子树路径\"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。"), a.push("对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/\"刚才改了啥\");只读查历史快照值用 history_data({id?,jsonPath?})。")), r.subagent && a.push("独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。"), r.inspectEnv && a.push("排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:\"appConfig\"}) 读 window.appConfig)。改完数据看渲染、定位\"为何没生效\"时用它(只读,不改数据)。"), r.domInspect) {
14930
- let n = t && e?.hasActions ? "配合宿主 actions(save_draft/publish 等)形成\"改数据→截图/get_dom 看渲染→触发动作\"闭环。" : t ? "改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。" : "";
14931
- a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}`);
14934
+ let n = t && e?.hasActions ? "配合宿主 actions(save_draft/publish 等)形成\"改数据→截图/get_dom 看渲染→触发动作\"闭环。" : t ? "改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。" : "", r = e?.skills ? "长文按关键词定位(找某术语/某节在哪)先 load_skill(\"dom-inspect\") 取得 dom_search 文本检索,命中后窄读那一节 —— 勿整页翻页找。" : "";
14935
+ a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}${r}`);
14932
14936
  }
14933
- if (e?.screenshot && a.push("视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。"), e?.domEdit && a.push("修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。"), e?.viewImage && a.push("看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。"), e?.hasProposals && a.push("【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。"), r.draftWrite && (a.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。"), a.push("⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。")), r.focus && (a.push("【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:"), a.push(" · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:\"该子树路径\"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。"), a.push(" · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。"), a.push(" · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。"), a.push(" · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。"), a.push(" · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。")), e?.subagents?.length) {
14937
+ if (e?.screenshot && a.push("视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。"), e?.domEdit && a.push("修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。"), e?.viewImage && a.push("看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。"), e?.hasProposals && a.push("【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。"), r.draftWrite && (a.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。"), a.push("⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。")), r.focus && t && (a.push("【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:"), a.push(" · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:\"该子树路径\"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。"), a.push(" · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。"), a.push(" · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。"), a.push(" · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。"), a.push(" · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。")), e?.subagents?.length) {
14934
14938
  let t = e.subagents.filter((e) => (e.temperature ?? 0) >= D_ || /规划|创意|设计|方案|brainstorm|plan/i.test(e.description)), n = e.subagents.filter((e) => (e.temperature ?? 0) < D_ && /反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));
14935
14939
  a.push("【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:"), t.length && (a.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map((e) => "use_" + e.id).join("/")} 出 2-3 套方案(高温创意),`), a.push(e?.humanConfirm ? " 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。" : " 不要自己拍板;拿到方案后以文字列出选项等用户回复(humanConfirm 未开,勿调不存在工具)。")), n.length && a.push(` · 严谨/易错/校验类 → 可先调 ${n.map((e) => "use_" + e.id).join("/")} 反思挑刺(低温审查),据反馈修订。`), a.push(" · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。"), a.push(" · 简单/明确任务(如\"标题改红色\")直接执行,不必走规划-反思。");
14936
14940
  }
@@ -15387,7 +15391,7 @@ function X_(e, n, r) {
15387
15391
  schema: t.object({}).optional()
15388
15392
  })] : [];
15389
15393
  qe.forEach((e) => Ee.set(e.name, "builtin"));
15390
- let Je = V.focus, Ye = s(async ({ path: e, label: t }) => {
15394
+ let Je = V.focus && he, Ye = s(async ({ path: e, label: t }) => {
15391
15395
  let n = W()?.schema;
15392
15396
  return n ? Is(n, e) ? (j.setFocus(M({
15393
15397
  path: e,
@@ -188,8 +188,8 @@ self.onmessage = async (e) => {
188
188
  `)}catch{}return``}var MG={pageBuilder:{systemPrompt:`你是页面构建助手。按用户意图读写主数据(经 data 声明 + schema 校验),改完页面实时更新。`},researcher:{systemPrompt:`你是调研助手。多路调研用 spawn_agents 并行委派子 agent(各负责一个方向);单份资料用 fetch_document 抓取;最后结构化汇总,给出结论与依据。`,subagent:{maxParallel:4}},minimal:{capabilities:{planning:!1,skills:!1,vfs:!1,summarization:!1,memory:!1,subagent:!1}}};function NG(e,t=`code`,n=!0){let r=`use_${e}`;return[`【先判意图(防长对话误路由)】先判断用户是「问」还是「要生成/改」:**提问类**(这是什么组件/怎么用/某字段什么意思/为什么这样/解释代码)→ 用 read / list_components / rag_component_docs **直接回答**,绝不委派 ${r};**生成/修改类**(做一个/生成/改成/加一个 XX 组件)才按下面纪律委派 ${r}。长对话里上文全是生成记录时尤须警惕,不要把新问题当成延续旧任务。`,`【多方案征询=先文本】用户要「出几套/两套方案我来选」「给几个选择」「先出方案看看」→ **本轮只出文本方案**(每套一两句:布局/配色/交互差异),经 request_human_confirmation 的 options 让用户点选(或等用户回复选定);**选定后才**委派 ${r} 建所选方案。禁止先并发多个子 agent 把每套方案都生成出来再让用户挑(子 agent 产物当不了选项清单,且烧 token;真 LLM 实测踩过:「出两套方案」被路由成两个 use_${e} 委派)。`,`【执行纪律(最重要)】收到代码组件任务后:**新建类直接委派**(追加组件无需通读/翻页现有数组,子 agent 自会采样一个组件看结构;**新建组件由子 agent 全权创建** —— 它自己把整个组件(含 ${t})写进数组,你不需要也不能替它创建/追加/落地代码)→ 修改类才 read 定位(by name)→ 调 ${r} 委派 → read 核对 → 回复用户。**中间绝不输出过渡性文字** —— 「我先看看…」「稍后委派」「接下来我会…」这类计划性回复等于任务没做就结束了(回复即本轮终止);所有调研和委派在本轮内连续完成,完成后才回复总结。`,`【产物形态】每个组件是完整、自包含的 HTML 页面(含 style/script,可独立成页);你只负责委派和收尾,不关心宿主如何渲染(v-html / iframe / SFC 是集成方的事)。`,`【主 agent 职责边界(硬规则)】禁止直接 read/write 代码组件的 ${t} 字段(read 只得 <code Nkb> 摘要没用;write 绕过 vfs/verify 危险)—— 生成/修改/排查代码一律经 ${r},收尾 read 核对。**委派返回即已落地**:${r} 的结论说「已创建组件 X」= 组件已在数组里,**不要再 write/append 一遍**(子 agent 已自己创建,你再写 = 造出重复组件,还得花轮次删;真 LLM 实测踩过:主 agent 把返回的 code 又追加了一次 → 索引 8/9 重复)。核对方式 = read 该数组尾部(确认新组件存在 + name 唯一),仅此而已。`,`【多组件委派(防上下文污染)】一次要多个组件:① write_todos 列出(每项 name + 要点)② **不同组件可在同一轮并行发多个 ${r} 委派**(每组件一次 ${r},task 只写该组件 name + 要点 + 主题/风格;每次委派是独立子 agent 实例,互不共享上下文);**同一组件同一时间只能有一个委派在途**,勿对同一组件同轮发两个委派 ③ 委派返回后逐个 read 核对(确认已生成 + 名称对)+ update_todo 标完成 ④ 主题/风格在每次 task 里转述(每个子 agent 全新上下文,不知其他组件)。一次 task 塞多个组件仍禁止(同一子 agent 共享上下文生成多个 → class/样式冲突污染);主 agent 自己的 write(普通组件属性)可与委派同轮发出,不必等委派返回。`,`【委派 task 规格化(收窄子 agent 决策,防开放任务致装饰穷举)】委派 ${r} 的 task 必须含:① 组件定位(by name)② 视觉风格(配色/质感/字体;**给 1-2 个具体视觉锚** —— 主色 hex **取自平台 UI/设计规范 skill 的定义值**(有规范类 skill 先 load 再引用其 hex,勿凭页面观察自造近似色;无规范才自定,如「金黄 #F7C948」)、主体占比(如「杯高约画布 60%」)或装饰密度(如「仅 2 类背景装饰」)—— 细节空间收窄,子 agent 不在装饰细节上展开推演)③ 内容(文案/数据/图)④ 交互意图(动效/状态/触发)⑤ 历史偏好(可选):聊天上下文中有与该组件相关的用户历史偏好/反馈(如「用户偏好深色系」「上轮嫌动画太快」),提炼一句附 task 末尾(新子 agent 无记忆,全靠 task);**不含技术实现**(SVG vs CSS / keyframes vs transition 归子 agent 选)。❌「生成啤酒杯动画」→ ✅「啤酒杯倒酒(beer):金黄啤酒 #F7C948 从上方倒入透明杯(杯高约画布 60%),深绿背景,液体循环下落 2s,hover 杯子放大」。规格简练(4 要素各半句),远省子 agent 思考 token。`,`【委派失败重试】${r} 返回乱码/内部标记(如 <|DSML|)/空结论或报错 = 子 agent 异常,**重新委派一次**(task 附「上次失败,这次先把代码写短些/分步」);连续两次失败才降级告知用户。**不要因此自己直接 write/edit ${t} 字段**(绕过 vfs/格式校验,且你拿不到规范全文)。`,...n?[`【设计品味引导】子 agent 内置 web-design-engineer 设计 skill(设计系统先声明/反 AI 俗套/25 风格配方/5 维自评;**挂在子 agent 侧,你自己 load 不到也不必尝试**)。委派 task 的视觉锚可直接引用配方名 —— linear / apple-hig / muji / pentagram / bloomberg-terminal / aesop 等(如「Linear 风格:暖深色+发丝线」),子 agent 会按名取配方参数照做;用户未指定风格时勿写「随便/好看就行」,给一条具体方向(流派或参考品牌),子 agent 按其 skill 流程选配方并在结论里声明设计系统与假设。`]:[],`【预算将尽暂停】组件很多、接近工具轮次上限不要硬扛:完成手头这个后报告「已生成 K/N,还剩 M 个」,等用户确认后从 todos 剩余项继续(勿重复已完成)。`].join(`
189
189
  `)}var PG={reliableWriteRules:[`【可靠写入规则】`,`1. 改任何字段前,先用 read({ jsonPath }) 读其当前真实值,基于真实值改,不要凭记忆;`,`2. 若不确定可操作哪些字段,先 read() 不传 jsonPath 查看主数据说明 + schema 声明字段(集成方可经 sdk.setData 运行时替换 schema,以工具返回为准,勿凭旧记忆);`,`3. 不确定某字段结构时,read({ jsonPath }) 返回含格式说明,字段以返回为准;`,`4. 写入若被 schema 校验拒绝(返回结构化错误含字段名与期望类型),按错误修正后重试,不要放弃;`,`5. 优先用 write 的 patch 增量改(只发改动,如 write({ value, patch:{ op, jsonPath } })),避免整体重传大 JSON 被截断;`,`6. 写入若触发乐观锁冲突(返回 VERSION_CONFLICT 或工具挂起等用户决定):等工具返回结果后按其指示继续(保留外部值 → 重新 read 再改;已覆盖/已回退 → 基于结果重写),不要放弃任务。`].join(`
190
190
  `),reliableWriteRulesEn:[`[Reliable write rules]`,`1. Before changing any field, read its current real value with read({ jsonPath }) and edit based on that value, never from memory;`,`2. If unsure which fields are operable, call read() without jsonPath first to see the data description + schema-declared fields (the integrator can replace the schema at runtime via sdk.setData; trust the tool response over stale memory);`,`3. When unsure about a field structure, the read({ jsonPath }) response includes a format description; treat the response as the source of truth;`,`4. If a write is rejected by schema validation (the structured error names the field and expected type), fix it per the error and retry; do not give up;`,`5. Prefer incremental write patches (send only the change, e.g. write({ value, patch:{ op, jsonPath } })) over resending the whole large JSON, which risks truncation;`,`6. If a write hits an optimistic-lock conflict (VERSION_CONFLICT returned, or the tool suspends awaiting the user decision): after the tool returns, follow its instruction (keep external → re-read then edit; overwritten/restored → continue from the result); do not abandon the task.`].join(`
191
- `),answerLanes:[`【作答车道:先判问题形态,再选纪律】`,`用户的问题分三类,判错车道是最大的答非所问:`,`A. 问页面内容(「这页写了什么 / 哪里提到 / 原文是什么 / 这段在说什么」)`,` → 以页面实料为准并点明出处;页面内容与你的先验知识冲突时以页面为准;页面没写就说没写,一句话即可,不列举查过哪些节。`,`B. 问概念术语(「X 是什么 / 啥意思 / X 和 Y 什么区别」)`,` → 页面有语境就先按页面语境讲;页面没有也必须直接用自己的知识解释,`,` 开头一句「本页未提及,以下是通用解释:」即可 —— 不许把「页面上没有」当答案。`,`C. 求观点经验(「你觉得呢 / 按你的经验 / 是不是很难 / 该怎么选」)`,` → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。`,` 页面没写不构成不答的理由。`,``,`出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、`,`过渡句一律不标。「没找到」的说明压成一句,不报检索过程。`].join(`
192
- `),answerLanesEn:[`[Answer lanes: classify the question first, then pick the discipline]`,`User questions fall into three categories; picking the wrong lane is the biggest way to miss the point:`,`A. Asking about page content ("what does this page say / where is it mentioned / what is the original text / what does this passage mean")`,` → Ground answers in what the page actually says and cite where it came from; when the page conflicts with your prior knowledge, the page wins; if the page does not say it, say so in one sentence — do not enumerate which sections you searched.`,`B. Asking about a concept or term ("what is X / what does it mean / how do X and Y differ")`,` → If the page has context for it, explain in that context first; if the page does not, you MUST still explain it directly from your own knowledge,`,` opening with one line like "Not covered on this page — general explanation:" — never treat "it is not on the page" as the answer.`,`C. Asking for your opinion or experience ("what do you think / in your experience / is it hard to match / which should I choose")`,` → Give your judgment and reasoning directly; keep the notes' stance and your own view separate ("this page's position is ...; my take is ...").`,` The page not covering it is never a reason to refuse.`,``,`Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,`,`personal opinions, and transitions get none. Compress "not found" statements to one sentence; never narrate the search process.`].join(`
191
+ `),answerLanes:[`【作答车道:先判问题形态,再选纪律】`,`用户的问题分三类,判错车道是最大的答非所问:`,`A. 问页面内容(「这页写了什么 / 哪里提到 / 原文是什么 / 这段在说什么」)`,` → 以页面实料为准并点明出处;页面内容与你的先验知识冲突时以页面为准;页面没写就说没写,一句话即可,不列举查过哪些节。`,`B. 问概念术语(「X 是什么 / 啥意思 / X 和 Y 什么区别」)`,` → 页面有语境就先按页面语境讲;页面没有也必须直接用自己的知识解释,`,` 开头一句「本页未提及,以下是通用解释:」即可 —— 不许把「页面上没有」当答案。`,`C. 求观点经验(「你觉得呢 / 按你的经验 / 是不是很难 / 该怎么选」)`,` → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。`,` 页面没写不构成不答的理由。`,``,`已懂不查:已是通用知识或对话里已读过的内容,直接用 —— 不必为同一信息再读页面;`,`只有要断言「页面上写了什么」时才需要读页核实。`,`出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、`,`过渡句一律不标。「没找到」的说明压成一句,不报检索过程。`].join(`
192
+ `),answerLanesEn:[`[Answer lanes: classify the question first, then pick the discipline]`,`User questions fall into three categories; picking the wrong lane is the biggest way to miss the point:`,`A. Asking about page content ("what does this page say / where is it mentioned / what is the original text / what does this passage mean")`,` → Ground answers in what the page actually says and cite where it came from; when the page conflicts with your prior knowledge, the page wins; if the page does not say it, say so in one sentence — do not enumerate which sections you searched.`,`B. Asking about a concept or term ("what is X / what does it mean / how do X and Y differ")`,` → If the page has context for it, explain in that context first; if the page does not, you MUST still explain it directly from your own knowledge,`,` opening with one line like "Not covered on this page — general explanation:" — never treat "it is not on the page" as the answer.`,`C. Asking for your opinion or experience ("what do you think / in your experience / is it hard to match / which should I choose")`,` → Give your judgment and reasoning directly; keep the notes' stance and your own view separate ("this page's position is ...; my take is ...").`,` The page not covering it is never a reason to refuse.`,``,`Known means no lookup: use general knowledge you already master, and anything already read in this conversation,`,`directly — never re-read the page for information you already have; only claims about "what the page says" require reading to verify.`,`Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,`,`personal opinions, and transitions get none. Compress "not found" statements to one sentence; never narrate the search process.`].join(`
193
193
  `),htmlPageOrchestrator:NG(`html`),htmlPageProposeFirst:[`【新建/创意类请求】先用简短文字给出 2~3 套方案(每套一两句风格/配色/结构要点),询问用户选哪套;选定前不要委派生成代码、不要写 components。`,`【方案切换】已生成某套方案后改选另一套:不重新罗列,直接依据之前描述重新委派生成并覆盖相应组件(委派工具见编排段 use_<id>)。`].join(`
194
194
  `),htmlDirectWriteFallback:[`【纯代码组件 · 你直接写】当前未配备 html 子 agent,纯代码组件的代码字段(code,以 schema 声明为准)由你直接 write(普通字段,经 schema 校验 + 乐观锁 + 快照栈,与改其他字段无异;无 vfs 工作副本 / 无格式校验门禁)。`,`【HTML 生成规范】代码字段必须是完整、自包含的 HTML 页面(含 <style>/<script>,可独立成页):标签正确闭合、style/script 集中放置(如 <head> 内)、class 加前缀防冲突;可引外部 JS/CSS(CDN/字体)。安全底线:禁 eval/new Function、不引可疑外部脚本、不访问 document.cookie 等敏感属性。`,`【修改而非重写】改已有代码:先 read({jsonPath}) 取当前代码字段 → 基于当前值增量改(只动要改的部分,如换配色/文案/某段结构),不要整体重写整个代码字段(易丢已有内容、token 浪费)。`,`【质量自检】无格式校验门禁,写完自查标签闭合 / 结构完整;代码进 data 由集成方渲染层(v-html/iframe)呈现。如需代码资产机制(vfs 工作副本 + 格式校验 + 增量 commit),注册 createHtmlSubagent。`].join(`
195
195
  `)},FG=15,IG=4e3,LG=new WeakMap;function RG(e,t){if(!e)return``;let n=t?`${t.maxKeys??``}|${t.maxChars??``}`:``;if(typeof e==`object`){let t=LG.get(e);if(t&&t.optsKey===n)return t.hint}let r=zG(e,t);return typeof e==`object`&&LG.set(e,{optsKey:n,hint:r}),r}function zG(e,t){let n=OG(e);if(n){let r=t?.maxKeys??FG,i=t?.maxChars??IG;if(n.split(`
@@ -3142,9 +3142,9 @@ ${`- 输出形态:完整、自包含的 HTML 页面(.${r},可独立成页)`}
3142
3142
 
3143
3143
  `).trim();t&&r.push(t)},a=e=>{for(let r of Array.from(e.children??[])){let e=r,o=String(e.tagName??``).toLowerCase();if(!(t(e)||dge.has(o))){if(!n(e)){i(e);continue}a(e)}}};return a(e),r.join(`
3144
3144
 
3145
- `).trim()}function hge(e){try{return e.querySelector?.(fge)!=null||e.querySelector?.(`.chat-dialog, .chat-mask, .debug-drawer, .skill-mask, .skill-panel, .chat-selection-menu`)!=null}catch{return!0}}var U4=[H4,IF(({selector:e,offset:t,limit:n})=>{if(typeof document>`u`)return`ERROR: read_page 仅在浏览器环境可用(当前运行在 node/服务端,无 DOM)。请基于用户消息中的引用原文回答。`;let r,i;if(e){if(r=document.querySelector(e),!r)return`未找到匹配元素:selector="${e}"`;i=e}else r=pge(document),i=r?r.tagName.toLowerCase():`body`;let a=mge(r,aH,hge),o=t??0,s=n??4e3;if(o>a.length)return`offset=${o} 超出正文长度 ${a.length}(先从 offset=0 读,按 hasMore 续读)`;let c=a.slice(o,o+s);return JSON.stringify({text:c,totalChars:a.length,offset:o,limit:s,hasMore:o+c.length<a.length,container:i})},{name:`read_page`,description:`读当前页面正文纯文本(自动定位 article/main 等文章容器;排除 SDK 对话框自身与脚本样式)。回答「这个页面讲了什么/某段内容在哪」类问题用;长文按 hasMore=true 时 offset+=本次返回长度 续读。只读,大结果自动外存 vfs。`,schema:B({selector:R().optional().describe(`CSS 选择器(默认智能定位 article/main/[role=main]/.content,兜底 body)`),offset:ed().int().min(0).optional().describe(`起始字符偏移(默认 0;续读传上次 offset + 返回 text 长度)`),limit:ed().int().min(200).max(2e4).optional().describe(`本次返回字符上限(默认 4000,上限 20000)`)})})],W4=`display.position.visibility.opacity.color.background-color.background-image.font-size.font-weight.line-height.text-align.z-index.overflow.width.height.margin.padding.border.border-radius.box-shadow.transform.transition.animation.cursor.pointer-events.flex-direction.gap.max-width.min-height`.split(`.`),G4=new WeakMap,K4=!1;function q4(){if(K4)return;let e=globalThis.EventTarget;if(!e?.prototype?.addEventListener)return;K4=!0;let t=e.prototype.addEventListener,n=e.prototype.removeEventListener;e.prototype.addEventListener=function(e,...n){try{let t=G4.get(this);t||(t=new Map,G4.set(this,t)),t.set(String(e),(t.get(String(e))??0)+1)}catch{}return t.call(this,e,...n)},e.prototype.removeEventListener=function(e,...t){try{let t=G4.get(this);if(t){let n=(t.get(String(e))??1)-1;n<=0?t.delete(String(e)):t.set(String(e),n)}}catch{}return n.call(this,e,...t)}}function J4(e){return[...G4.get(e)?.entries()??[]].filter(([,e])=>e>0).map(([e])=>e)}function Y4(e,t=12){let n=[],r=e,i=0;for(;r&&r.tagName&&i<t;){let e=r.tagName.toLowerCase(),t=r.id;if(t){n.unshift(`${e}#${t}`);break}if(typeof r.getAttribute==`function`){let t=(r.getAttribute(`class`)||``).split(/\s+/).filter(Boolean)[0];t&&/^[A-Za-z][\w-]*$/.test(t)&&(e+=`.${t}`)}let a=r.parentElement;if(a){let t=Array.from(a.children).filter(e=>e.tagName===r.tagName);t.length>1&&(e+=`:nth-of-type(${t.indexOf(r)+1})`)}n.unshift(e),r=a,i++}return n.join(` > `)}function X4(e,t,n={}){if(!e)return{hits:[],total:0,truncated:!1};let r=Math.max(1,Math.min(n.limit??10,20)),i=n.mode??`selector`,a=[];if(i===`selector`)try{a=Array.from(e.querySelectorAll(t))}catch{return{hits:[],total:0,truncated:!1}}else{a=Array.from(e.querySelectorAll(`*`)).filter(e=>{let n=e.tagName.toLowerCase();if(n===`script`||n===`style`||n===`noscript`)return!1;let r=(e.textContent||``).trim();return r.length>0&&r.includes(t)});let n=a.slice(0,100),r=new Set(n);a=n.filter(e=>{for(let t of r)if(t!==e&&e.contains(t))return!1;return!0})}let o=Math.min(a.length,r);return{hits:a.slice(0,o).map(e=>{let n=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();if(i===`text`&&!n){let r=(e.textContent||``).trim(),i=r.indexOf(t);n=r.slice(Math.max(0,i-20),i+t.length+40)}return{selector:Y4(e),tag:e.tagName.toLowerCase(),text:n.slice(0,120)}}),total:a.length,truncated:a.length>o}}var gge=[`content`,`display`,`width`,`height`,`background-color`,`position`];function Z4(e,t={}){if(!e)return null;let n={selector:Y4(e),tag:e.tagName.toLowerCase(),attrs:{}};for(let t of Array.from(e.attributes))!(R4.includes(t.name)||t.name.startsWith(`data-`))||z4.test(t.name)||B4.test(t.name)||(n.attrs[t.name]=t.value);let r=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();r&&(n.text=r.slice(0,400));let i=String(e.innerText??e.textContent??``).trim();if(i&&(n.textAll=i.slice(0,1e3)),(t.includeRect??!0)&&typeof e.getBoundingClientRect==`function`){let t=e.getBoundingClientRect();n.rect={x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}}if(t.includeHtml){let r=Math.min(t.htmlLimit??1500,4e3),i=e.outerHTML??``;n.html=i.length>r?i.slice(0,r)+`…(截断 ${i.length-r} 字符)`:i}let a=t.getComputedStyle??globalThis.window?.getComputedStyle?.bind(globalThis.window),o=n=>{let r={};if(typeof a!=`function`)return r;try{let i=a(e,n??null);for(let e of n?gge:t.styles??W4){let t=typeof i.getPropertyValue==`function`?i.getPropertyValue(e):i[e];t&&(r[e]=String(t).slice(0,200))}}catch{}return r};if((t.styles===void 0||t.styles.length>0)&&(n.styles=o()),t.pseudo&&(n.pseudoStyles={before:o(`::before`),after:o(`::after`)}),t.includeEvents!==!1){let t=Array.from(e.attributes).filter(e=>/^on\w+$/i.test(e.name)).map(e=>({type:e.name.toLowerCase().slice(2),snippet:e.value.slice(0,100)})),r=e.__vueParentComponent?.vnode?.props;n.events={inline:t,vue:r?Object.keys(r).filter(e=>/^on[A-Z]/.test(e)).map(e=>e.slice(2).toLowerCase()):[],captured:J4(e)}}return n}var Q4=IF(({query:e,mode:t,limit:n,root:r})=>{q4();let i=r?document.querySelector(r):document;if(r&&!i)return`未找到 root 元素:selector="${r}"`;let a=X4(i,e,{mode:t,limit:n});return a.total?JSON.stringify({...a,note:a.truncated?`共 ${a.total} 处命中,仅返回前 ${a.hits.length} 处`:void 0},null,2):t===`text`?`未找到包含文本「${e}」的元素`:`selector "${e}" 未匹配到元素`},{name:`dom_search`,description:`搜索页面元素:CSS 选择器或可见文本两种模式,返回命中元素的 CSS 路径 + 文本片段(≤20 处)。定位元素/查渲染结果用;找到 selector 后可用 dom_info 看详情或 get_dom 看结构。`,schema:B({query:R().describe(`selector 模式 = CSS 选择器(如 ".banner .title");text 模式 = 文本关键词`),mode:jd([`selector`,`text`]).optional().describe(`搜索模式(默认 selector;text = 文本包含匹配)`),limit:ed().int().min(1).max(20).optional().describe(`返回上限(默认 10)`),root:R().optional().describe(`限定搜索范围的容器选择器(默认整页)`)})}),$4=IF(({selector:e,styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o})=>{q4();let s=document.querySelector(e);if(!s)return`未找到匹配元素:selector="${e}"(可先用 dom_search 定位)`;let c=Z4(s,{styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o});return c?JSON.stringify(c,null,2):`selector="${e}" 读取失败`},{name:`dom_info`,description:`读单个元素完整信息:内容(直接文本/全文本/HTML 片段)+ 计算样式(默认排障高频预设,可指定属性列表)+ 几何位置 + 事件绑定(inline on*/Vue props/addEventListener 记录;记录器仅覆盖 SDK 加载后注册的监听)。验证样式落地/排查交互绑定用。`,schema:B({selector:R().describe(`CSS 选择器(取首个匹配;可先用 dom_search 定位)`),styles:z(R()).optional().describe(`计算样式属性列表(不传 = 常用预设 ~30 项)`),includeHtml:od().optional().describe(`是否含 outerHTML 片段(默认 false,大 HTML 省 token)`),htmlLimit:ed().int().min(100).max(4e3).optional().describe(`HTML 片段上限字符(默认 1500)`),includeEvents:od().optional().describe(`是否含事件绑定(默认 true)`),includeRect:od().optional().describe(`是否含几何位置(默认 true)`),pseudo:od().optional().describe(`是否含 ::before/::after 伪元素摘要(默认 false)`)})}),_ge=`dom-inspect`;function e3(e={}){return{name:_ge,description:`页面 DOM 深度检视工具(dom_search 搜索元素 / dom_info 读内容·计算样式·事件绑定·几何)。定位元素、验证样式落地、排查交互绑定时加载`,getContent:()=>[`# DOM 检视工具用法`,`## read_page({ selector?, offset?, limit? })—— 读正文首选`,`- 返回页面正文纯文本(JSON:text/totalChars/offset/hasMore/container),自动定位 article/main/[role=main]/.content 容器并排除本对话框自身与 script/style`,`- 长文分页:默认每次 4000 字符;hasMore=true 时下一次调用传 offset=上次 offset+本次 text 长度 续读`,`- 回答「这个页面讲了什么/某段在哪」类问题用 read_page,不要用 get_dom 逐层翻结构(爆 token)`,`## dom_search({ query, mode?, limit?, root? })`,`- mode="selector"(默认):query 为 CSS 选择器;mode="text":文本关键词包含匹配(跳过 script/style)`,`- 返回命中列表:CSS 路径(selector)+ 文本片段;超 limit 标注总数`,`## dom_info({ selector, styles?, includeHtml?, pseudo?, ... })`,`- selector 取首个匹配(先用 dom_search 定位更稳)`,`- styles 不传 = 排障高频预设(display/position/color/background/font/z-index/transform 等约 30 项);传数组 = 只取指定属性`,`- includeHtml: true 附 outerHTML 片段(默认省);pseudo: true 附 ::before/::after 摘要`,`- events 三源:inline on* 属性 / Vue vnode props(onXxx)/ addEventListener 记录器(⚠ 仅记录本 SDK 加载之后注册的监听,更早的挂载捕不到)`,`- rect:视口坐标 + 宽高(验证可见性/布局)`,...e.withScreenshot?[`## take_screenshot({ selector?, fullPage? })—— 视觉验证`,`- 截图「看」页面:selector 截指定元素区域 / fullPage 截整页 / 都不传截当前视口;截图经压缩投递(多模态直看图,纯文本模型自动走识图转述)`,`- 布局/样式/渲染效果类问题优先截图(视觉真值),结构/属性类用 dom_info;截图失败(CSP/跨域图)会回灌原因与替代建议`]:[],...e.withDomEdit?[`## dom_edit({ patches, dryRun? })—— 修改页面元素(宿主开启才有)`,`- patches 批量原子(任一失败整批拒绝):set_text/set_html(内容)、set_attr/remove_attr、add_class/remove_class、set_style、insert(新建元素 anchor+position: before/after/prepend/append/replace)、remove、move(层级调整)、highlight(高亮+滚动)`,`- 写纪律:selector 必须唯一命中(多匹配被拒,用 dom_search 拿精确路径);先读后写(get_dom/dom_info 看现状);拿不准先 dryRun 预检`,`- 改前自动快照:dom_restore 回滚最近一批(可连续回退);改动为会话临时态(刷新即失);数据驱动页面改数据(write)不要改 DOM`]:[],`## 排障套路`,...e.withScreenshot?[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. 视觉验证 take_screenshot / 结构验证 dom_info(styles) → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]:[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. dom_info(styles:["display","background-color","pointer-events"]) 验证样式/点击性 → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]].join(`
3145
+ `).trim()}function hge(e){try{return e.querySelector?.(fge)!=null||e.querySelector?.(`.chat-dialog, .chat-mask, .debug-drawer, .skill-mask, .skill-panel, .chat-selection-menu`)!=null}catch{return!0}}var U4=[H4,IF(({selector:e,offset:t,limit:n})=>{if(typeof document>`u`)return`ERROR: read_page 仅在浏览器环境可用(当前运行在 node/服务端,无 DOM)。请基于用户消息中的引用原文回答。`;let r,i;if(e){if(r=document.querySelector(e),!r)return`未找到匹配元素:selector="${e}"`;i=e}else r=pge(document),i=r?r.tagName.toLowerCase():`body`;let a=mge(r,aH,hge),o=t??0,s=n??4e3;if(o>a.length)return`offset=${o} 超出正文长度 ${a.length}(先从 offset=0 读,按 hasMore 续读)`;let c=a.slice(o,o+s);return JSON.stringify({text:c,totalChars:a.length,offset:o,limit:s,hasMore:o+c.length<a.length,container:i})},{name:`read_page`,description:`读当前页面正文纯文本(自动定位 article/main 等文章容器;排除 SDK 对话框自身与脚本样式)。回答「这个页面讲了什么/某段内容在哪」类问题用;长文按 hasMore=true 时 offset+=本次返回长度 续读。只读,大结果自动外存 vfs。`,schema:B({selector:R().optional().describe(`CSS 选择器(默认智能定位 article/main/[role=main]/.content,兜底 body)`),offset:ed().int().min(0).optional().describe(`起始字符偏移(默认 0;续读传上次 offset + 返回 text 长度)`),limit:ed().int().min(200).max(2e4).optional().describe(`本次返回字符上限(默认 4000,上限 20000)`)})})],W4=`display.position.visibility.opacity.color.background-color.background-image.font-size.font-weight.line-height.text-align.z-index.overflow.width.height.margin.padding.border.border-radius.box-shadow.transform.transition.animation.cursor.pointer-events.flex-direction.gap.max-width.min-height`.split(`.`),G4=new WeakMap,K4=!1;function q4(){if(K4)return;let e=globalThis.EventTarget;if(!e?.prototype?.addEventListener)return;K4=!0;let t=e.prototype.addEventListener,n=e.prototype.removeEventListener;e.prototype.addEventListener=function(e,...n){try{let t=G4.get(this);t||(t=new Map,G4.set(this,t)),t.set(String(e),(t.get(String(e))??0)+1)}catch{}return t.call(this,e,...n)},e.prototype.removeEventListener=function(e,...t){try{let t=G4.get(this);if(t){let n=(t.get(String(e))??1)-1;n<=0?t.delete(String(e)):t.set(String(e),n)}}catch{}return n.call(this,e,...t)}}function J4(e){return[...G4.get(e)?.entries()??[]].filter(([,e])=>e>0).map(([e])=>e)}function Y4(e,t=12){let n=[],r=e,i=0;for(;r&&r.tagName&&i<t;){let e=r.tagName.toLowerCase(),t=r.id;if(t){n.unshift(`${e}#${t}`);break}if(typeof r.getAttribute==`function`){let t=(r.getAttribute(`class`)||``).split(/\s+/).filter(Boolean)[0];t&&/^[A-Za-z][\w-]*$/.test(t)&&(e+=`.${t}`)}let a=r.parentElement;if(a){let t=Array.from(a.children).filter(e=>e.tagName===r.tagName);t.length>1&&(e+=`:nth-of-type(${t.indexOf(r)+1})`)}n.unshift(e),r=a,i++}return n.join(` > `)}function X4(e,t,n={}){if(!e)return{hits:[],total:0,truncated:!1};let r=Math.max(1,Math.min(n.limit??10,20)),i=n.mode??`selector`,a=[];if(i===`selector`)try{a=Array.from(e.querySelectorAll(t))}catch{return{hits:[],total:0,truncated:!1}}else{a=Array.from(e.querySelectorAll(`*`)).filter(e=>{let n=e.tagName.toLowerCase();if(n===`script`||n===`style`||n===`noscript`)return!1;let r=(e.textContent||``).trim();return r.length>0&&r.includes(t)});let n=a.slice(0,100),r=new Set(n);a=n.filter(e=>{for(let t of r)if(t!==e&&e.contains(t))return!1;return!0})}let o=Math.min(a.length,r);return{hits:a.slice(0,o).map(e=>{let n=(typeof e.textContent==`string`&&e.textContent?e.textContent:Array.from(e.childNodes??[]).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``)).replace(/\s+/g,` `).trim(),r=n.slice(0,120);if(i!==`selector`&&t){let e=n.indexOf(String(t));e>=0&&(r=(e>100?`…`:``)+n.slice(Math.max(0,e-100),e+120)+(e+120<n.length?`…`:``))}return{selector:Y4(e),tag:e.tagName.toLowerCase(),text:r}}),total:a.length,truncated:a.length>o}}var gge=[`content`,`display`,`width`,`height`,`background-color`,`position`];function Z4(e,t={}){if(!e)return null;let n={selector:Y4(e),tag:e.tagName.toLowerCase(),attrs:{}};for(let t of Array.from(e.attributes))!(R4.includes(t.name)||t.name.startsWith(`data-`))||z4.test(t.name)||B4.test(t.name)||(n.attrs[t.name]=t.value);let r=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();r&&(n.text=r.slice(0,400));let i=String(e.innerText??e.textContent??``).trim();if(i&&(n.textAll=i.slice(0,1e3)),(t.includeRect??!0)&&typeof e.getBoundingClientRect==`function`){let t=e.getBoundingClientRect();n.rect={x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}}if(t.includeHtml){let r=Math.min(t.htmlLimit??1500,4e3),i=e.outerHTML??``;n.html=i.length>r?i.slice(0,r)+`…(截断 ${i.length-r} 字符)`:i}let a=t.getComputedStyle??globalThis.window?.getComputedStyle?.bind(globalThis.window),o=n=>{let r={};if(typeof a!=`function`)return r;try{let i=a(e,n??null);for(let e of n?gge:t.styles??W4){let t=typeof i.getPropertyValue==`function`?i.getPropertyValue(e):i[e];t&&(r[e]=String(t).slice(0,200))}}catch{}return r};if((t.styles===void 0||t.styles.length>0)&&(n.styles=o()),t.pseudo&&(n.pseudoStyles={before:o(`::before`),after:o(`::after`)}),t.includeEvents!==!1){let t=Array.from(e.attributes).filter(e=>/^on\w+$/i.test(e.name)).map(e=>({type:e.name.toLowerCase().slice(2),snippet:e.value.slice(0,100)})),r=e.__vueParentComponent?.vnode?.props;n.events={inline:t,vue:r?Object.keys(r).filter(e=>/^on[A-Z]/.test(e)).map(e=>e.slice(2).toLowerCase()):[],captured:J4(e)}}return n}var Q4=IF(({query:e,mode:t,limit:n,root:r})=>{q4();let i=r?document.querySelector(r):document;if(r&&!i)return`未找到 root 元素:selector="${r}"`;let a=X4(i,e,{mode:t,limit:n});return a.total?JSON.stringify({...a,note:a.truncated?`共 ${a.total} 处命中,仅返回前 ${a.hits.length} 处`:void 0},null,2):t===`text`?`未找到包含文本「${e}」的元素`:`selector "${e}" 未匹配到元素`},{name:`dom_search`,description:`搜索页面元素:CSS 选择器或可见文本两种模式,返回命中元素的 CSS 路径 + 文本片段(≤20 处)。定位元素/查渲染结果用;找到 selector 后可用 dom_info 看详情或 get_dom 看结构。`,schema:B({query:R().describe(`selector 模式 = CSS 选择器(如 ".banner .title");text 模式 = 文本关键词`),mode:jd([`selector`,`text`]).optional().describe(`搜索模式(默认 selector;text = 文本包含匹配)`),limit:ed().int().min(1).max(20).optional().describe(`返回上限(默认 10)`),root:R().optional().describe(`限定搜索范围的容器选择器(默认整页)`)})}),$4=IF(({selector:e,styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o})=>{q4();let s=document.querySelector(e);if(!s)return`未找到匹配元素:selector="${e}"(可先用 dom_search 定位)`;let c=Z4(s,{styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o});return c?JSON.stringify(c,null,2):`selector="${e}" 读取失败`},{name:`dom_info`,description:`读单个元素完整信息:内容(直接文本/全文本/HTML 片段)+ 计算样式(默认排障高频预设,可指定属性列表)+ 几何位置 + 事件绑定(inline on*/Vue props/addEventListener 记录;记录器仅覆盖 SDK 加载后注册的监听)。验证样式落地/排查交互绑定用。`,schema:B({selector:R().describe(`CSS 选择器(取首个匹配;可先用 dom_search 定位)`),styles:z(R()).optional().describe(`计算样式属性列表(不传 = 常用预设 ~30 项)`),includeHtml:od().optional().describe(`是否含 outerHTML 片段(默认 false,大 HTML 省 token)`),htmlLimit:ed().int().min(100).max(4e3).optional().describe(`HTML 片段上限字符(默认 1500)`),includeEvents:od().optional().describe(`是否含事件绑定(默认 true)`),includeRect:od().optional().describe(`是否含几何位置(默认 true)`),pseudo:od().optional().describe(`是否含 ::before/::after 伪元素摘要(默认 false)`)})}),_ge=`dom-inspect`;function e3(e={}){return{name:_ge,description:`页面 DOM 深度检视工具(dom_search 搜索元素 / dom_info 读内容·计算样式·事件绑定·几何)。定位元素、验证样式落地、排查交互绑定时加载`,getContent:()=>[`# DOM 检视工具用法`,`## read_page({ selector?, offset?, limit? })—— 读正文首选`,`- 返回页面正文纯文本(JSON:text/totalChars/offset/hasMore/container),自动定位 article/main/[role=main]/.content 容器并排除本对话框自身与 script/style`,`- 长文分页:默认每次 4000 字符;hasMore=true 时下一次调用传 offset=上次 offset+本次 text 长度 续读`,`- 回答「这个页面讲了什么/某段在哪」类问题用 read_page,不要用 get_dom 逐层翻结构(爆 token)`,`## dom_search({ query, mode?, limit?, root? })`,`- mode="selector"(默认):query 为 CSS 选择器;mode="text":文本关键词包含匹配(跳过 script/style)`,`- 返回命中列表:CSS 路径(selector)+ 文本片段;超 limit 标注总数`,`## dom_info({ selector, styles?, includeHtml?, pseudo?, ... })`,`- selector 取首个匹配(先用 dom_search 定位更稳)`,`- styles 不传 = 排障高频预设(display/position/color/background/font/z-index/transform 等约 30 项);传数组 = 只取指定属性`,`- includeHtml: true 附 outerHTML 片段(默认省);pseudo: true 附 ::before/::after 摘要`,`- events 三源:inline on* 属性 / Vue vnode props(onXxx)/ addEventListener 记录器(⚠ 仅记录本 SDK 加载之后注册的监听,更早的挂载捕不到)`,`- rect:视口坐标 + 宽高(验证可见性/布局)`,...e.withScreenshot?[`## take_screenshot({ selector?, fullPage? })—— 视觉验证`,`- 截图「看」页面:selector 截指定元素区域 / fullPage 截整页 / 都不传截当前视口;截图经压缩投递(多模态直看图,纯文本模型自动走识图转述)`,`- 布局/样式/渲染效果类问题优先截图(视觉真值),结构/属性类用 dom_info;截图失败(CSP/跨域图)会回灌原因与替代建议`]:[],...e.withDomEdit?[`## dom_edit({ patches, dryRun? })—— 修改页面元素(宿主开启才有)`,`- patches 批量原子(任一失败整批拒绝):set_text/set_html(内容)、set_attr/remove_attr、add_class/remove_class、set_style、insert(新建元素 anchor+position: before/after/prepend/append/replace)、remove、move(层级调整)、highlight(高亮+滚动)`,`- 写纪律:selector 必须唯一命中(多匹配被拒,用 dom_search 拿精确路径);先读后写(get_dom/dom_info 看现状);拿不准先 dryRun 预检`,`- 改前自动快照:dom_restore 回滚最近一批(可连续回退);改动为会话临时态(刷新即失);数据驱动页面改数据(write)不要改 DOM`]:[],`## 排障套路`,...e.withScreenshot?[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. 视觉验证 take_screenshot / 结构验证 dom_info(styles) → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]:[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. dom_info(styles:["display","background-color","pointer-events"]) 验证样式/点击性 → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]].join(`
3146
3146
  `),tools:[()=>[Q4,$4]]}}var vge=`page-analysis`;function yge(e={}){return{name:vge,description:`页面内容分析策略:按问题类型选工具(引用原文/整页理解/定位/结构/视觉/页面操作),含分页探索纪律与基于页面实料的回答纪律。回答用户关于当前页面的问题时加载`,getContent:()=>[`# 页面内容分析策略`,`## 第一步:问题分型(按类型选主力工具,不要一上来读整页)`,`- **引用原文类**(用户消息带引用块):优先围绕引用原文作答;需要上下文再向外探索(所在小节 → 整页)`,`- **整页理解类**(「这页讲了什么/总结要点」):read_page 读正文,长文按 hasMore 翻页,边读边归纳不要一次读爆`,`- **定位类**(「某概念在本页哪里/那个按钮在哪」):dom_search mode:"text" 按关键词定位 → 需要细节再 read_page 带 selector 读该区域`,`- **结构/属性类**(「这个区块是什么组件/有哪些属性」):dom_info(selector) 读单元素;层级关系用 get_dom`,...e.withScreenshot?[`- **视觉类**(「看起来对不对/布局乱不乱/渲染效果」):take_screenshot 截图看视觉真值;selector 截局部、fullPage 截整页;截图是唯一能看到实际渲染效果的手段,结构推断不能代替`]:[],...e.withDomEdit?[`- **操作类**(「把这段高亮/隐藏广告/调大字体/把这个块挪过去」):dom_edit patches 批量操作;纪律 = 先 get_dom/dom_search 定位唯一 selector → 拿不准先 dryRun → 改后 dom_info/截图验证 → 不满意 dom_restore 回滚;页面是临时态,持久修改要走宿主自己的机制`]:[],`## 探索纪律`,`1. **先窄后宽**:引用/焦点 → 所在小节 → 整页;每一步只取够回答当前问题的量`,`2. **翻页不重复**:read_page 续读传 offset = 上次 offset + 返回 text 长度;不要回头重读已读区`,`3. **定位失败换路**:selector 不命中 → dom_search text 模式换关键词;还不中 → read_page 扫小节标题再回来`,...e.withVfs?[`4. **大结果在外存**:超大结果被移入 vfs 后用 vfs_read/vfs_grep 按需取,不要盲目重调`]:[],`## 回答纪律(页面问答的底线)`,`- **基于页面实料**:答案须来自你读到的页面内容(引用原文/read_page/dom 工具结果),并在回答中点明出处小节/位置`,`- **页面 ≠ 训练数据**:页面内容可能与你的先验知识不同,冲突时以页面为准;页面没写的不要编造`,`- **不确定就说不确定**:找不到的内容如实说「本页未找到」,给出已探索的范围,勿凭印象补全`,`## 输出纪律(直接说内容,不写过程)`,`- 禁**过程叙述**:「我先读一下页面」「让我确认一下」—— 工具调用用户看得见,不需要旁白`,`- 禁**元话术**:「先给结论」「依据是」「简言之」—— 第一句直接就是答案本身,不要先宣布你要说什么`,`- 禁**方法论自述**:不要解释结论是怎么来的(「这些不是页面写明的,而是从正文用词反推的」)—— 那是你的内部过程`,`- 禁**预告与套话**:「下面分三点」「综上」—— 该分点就直接分点,说完就停`,`- 出处仍要标,但用最简形式:句末括注(如「(§小节名)」「(原文)」);引原文时直接引,不写「依据是…原文两行:」这样的引导句`].join(`
3147
- `)}}var bge=e3();Ip();function xge(e){let t=e;return typeof t.tagName==`string`||typeof t.nodeType==`number`&&typeof t.nodeName==`string`}function t3(e,t=3,n=2e3,r,i){if(e==null)return e;if(typeof e==`string`)return e.length>n?e.slice(0,n)+`…(已截断)`:e;if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(typeof e==`symbol`)return e.toString();if(typeof e==`bigint`)return`${e.toString()}n`;if(typeof e!=`object`)return String(e);let a=e;if(xge(a)){let e=a;return e.tagName?`[Element: <${e.tagName.toLowerCase()}>]`:`[Node: ${e.nodeName}]`}if(r?.has(a))return`[Circular]`;let o=r??new WeakSet;if(o.add(a),Array.isArray(e)){let r=e.slice(0,100).map(e=>t3(e,t-1,n,o,i));return e.length>100&&r.push(`…(共 ${e.length} 项,已截断)`),r}if(t<0)return`(对象,已截断)`;let s={},c=Object.keys(a);for(let e=0;e<c.length;e++){let r=c[e];if(e>=50){s[`…`]=`(共 ${c.length} 键,已截断)`;break}try{let e=a[r];i?.test(r)?s[r]=`[REDACTED]`:s[r]=t3(e,t-1,n,o,i)}catch{s[r]=`(getter 抛错)`}}return s}function n3(e){let t=e??(typeof window<`u`?window:{}),n=t.navigator,r=t.location,i=t.document;return{location:{href:r?.href,origin:r?.origin,protocol:r?.protocol,host:r?.host,hostname:r?.hostname,pathname:r?.pathname,search:r?.search},navigator:{userAgent:n?.userAgent,language:n?.language,languages:n?.languages,platform:n?.platform,onLine:n?.onLine},viewport:{innerWidth:t.innerWidth,innerHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio,scrollX:t.scrollX,scrollY:t.scrollY},document:i?{title:i.title,readyState:i.readyState,characterSet:i.characterSet}:`(无 document)`}}var Sge=/^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/,r3=/token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i,i3=IF(({key:e})=>{if(e){if(Sge.test(e)||r3.test(e))return JSON.stringify({key:e,denied:!0,reason:`安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏`},null,2);let t=(typeof window<`u`?window:{})[e];return JSON.stringify({key:e,exists:t!==void 0,type:typeof t,value:t3(t,3,2e3,void 0,r3)},null,2)}return JSON.stringify(n3(),null,2)},{name:`inspect_env`,description:`读宿主页面环境信息(排查调试)。不传参返回摘要(URL/origin、浏览器/语言、viewport、title/readyState);传 key 读指定 window 属性值(如 key:"appConfig")。只读,大结果自动外存 vfs。`,schema:B({key:R().optional().describe(`要读取的 window 属性名(如 "appConfig"/"__DEBUG__");不传 = 返回环境摘要`)})}),a3=[i3];function Cge(e,t,n){let r=0;return{name:`budget`,beforeAgent:()=>{r=Date.now()},wrapModelCall:async(i,a)=>{let{tokenBudget:o,timeBudgetMs:s}=t,c=o!=null&&(e.total_tokens??0)>o,l=s!=null&&Date.now()-r>s;return c||l?(n({type:`error`,severity:`observable`,code:`BUDGET_EXCEEDED`,message:`资源预算超限:${c?`token 超限(累计 ${e.total_tokens??0} > 上限 ${o})`:`时间超限(${Date.now()-r}ms > 上限 ${s}ms)`},agent 已停止(未完成部分可用 restoreLastCheckpoint 回退)。`}),{message:new Qx({content:``}),content:``,toolCalls:[],aborted:!0}):a(i)}}}Ip();var o3=/^[a-zA-Z][a-zA-Z0-9_]*$/;function s3(e){let t=[];for(let[n,r]of Object.entries(e)){if(!o3.test(n)){console.warn(`[page-agent-sdk][actions] 动作名 "${n}" 非法(须匹配 ${o3}),已跳过`);continue}let e=r.description||`宿主动作 ${n}`;t.push(IF(async e=>{try{let t=await r.run(e||{});return t===void 0?`动作 ${n} 执行完成。`:typeof t==`string`?t:JSON.stringify(t)}catch(e){let t=e?.message||String(e);return`动作 ${n} 执行失败:${t}`}},{name:n,description:e,schema:r.params??B({})}))}return t}function c3(e){let t={};for(let[n,r]of Object.entries(e))o3.test(n)&&(t[n]={description:r.description,hasParams:!!r.params,readsHostState:r.readsHostState===!0,deferredWrite:r.deferredWrite===!0});return t}var wge=L4,Tge=U4;function Ege(e,t){return k0(e,t)}function l3(e,t,n,r,i){let a=W2(e);return[...a.dataOps?t:[],...a.fetch?n:[],...a.domInspect&&r?r:[],...a.inspectEnv&&i?i:[]]}var u3=.7,Dge=.5,d3=.85;function Oge(e,t){if(!Number.isFinite(t)||t<=0||e<=0||e<t*Dge)return``;let n=Math.max(1,Math.round(e/1e3));return e>=t*d3?`⏳ 预算告急:本任务累计约 ${n}K prompt tokens(已达 softCap 上限的 ${Math.round(d3*100)}%)。立即停止扩展性操作(新查询/重读/优化),完成手头最关键一步后基于已有工具结果给出结论,并如实汇报剩余未完成项。轮次预算吃紧时系统会另行注入轮次提示段。`:`⏳ 预算提示:本任务累计约 ${n}K prompt tokens(已过 softCap 半程)。若已接近目标请收敛并给出总结;尚未接近请向用户汇报进度与剩余计划,勿默默继续。轮次预算吃紧时系统会另行注入轮次提示段。`}function f3(e,t,n){let r=W2(e);return{name:`usageHints`,augmentPrompt:i=>{let a=[];if(r.planning&&(a.push(`【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:`),a.push(` · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。`),a.push(` · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。`),a.push(` · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。`),a.push(` · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 "components.2"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。`),e?.humanConfirm?a.push(` · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。`):a.push(` · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。`),a.push(` · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。`)),t&&(a.push(`改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。`),a.push(`读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。`),a.push(`修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。`),a.push(`修改主数据出错时可用 restore_data 回退最近一次。`),a.push(`在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type=="card" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。`),a.push(`找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。`),a.push(`需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。`),a.push(`读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。`),a.push(`【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:"set",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。`),a.push(`读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:"该子树路径"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。`),a.push(`对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/"刚才改了啥");只读查历史快照值用 history_data({id?,jsonPath?})。`)),r.subagent&&a.push(`独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。`),r.inspectEnv&&a.push(`排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:"appConfig"}) 读 window.appConfig)。改完数据看渲染、定位"为何没生效"时用它(只读,不改数据)。`),r.domInspect){let n=t&&e?.hasActions?`配合宿主 actions(save_draft/publish 等)形成"改数据→截图/get_dom 看渲染→触发动作"闭环。`:t?`改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。`:``;a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}`)}if(e?.screenshot&&a.push(`视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。`),e?.domEdit&&a.push(`修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。`),e?.viewImage&&a.push(`看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。`),e?.hasProposals&&a.push(`【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。`),r.draftWrite&&(a.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。`),a.push(`⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。`)),r.focus&&(a.push(`【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:`),a.push(` · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:"该子树路径"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。`),a.push(` · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。`),a.push(` · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。`),a.push(` · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。`),a.push(` · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。`)),e?.subagents?.length){let t=e.subagents.filter(e=>(e.temperature??0)>=u3||/规划|创意|设计|方案|brainstorm|plan/i.test(e.description)),n=e.subagents.filter(e=>(e.temperature??0)<u3&&/反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));a.push(`【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:`),t.length&&(a.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map(e=>`use_`+e.id).join(`/`)} 出 2-3 套方案(高温创意),`),a.push(e?.humanConfirm?` 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。`:` 不要自己拍板;拿到方案后以文字列出选项等用户回复(humanConfirm 未开,勿调不存在工具)。`)),n.length&&a.push(` · 严谨/易错/校验类 → 可先调 ${n.map(e=>`use_`+e.id).join(`/`)} 反思挑刺(低温审查),据反馈修订。`),a.push(` · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。`),a.push(` · 简单/明确任务(如"标题改红色")直接执行,不必走规划-反思。`)}e?.humanConfirm&&(a.push(`【人工确认·必读】以下情形必须先调 request_human_confirmation 征询用户、拿到答复后再继续,不要自行拍板:`),a.push(` 1) 用户让你「给方案/列选项/我来选/挑一个」时:把每个方案作为一个 option,调 request_human_confirmation(question=简述, options=[方案A,方案B,...], recommendation=你推荐的)。不要只回文字罗列方案让用户自己回复——要用工具把选项做成可点选按钮。`),a.push(` 2) 需求有歧义/不确定时:调工具问清楚(options 不传则用户答同意或拒绝)。`),a.push(` 3) 即将执行高风险不可逆操作(删除/覆盖/批量改动)前:调工具确认。`),a.push(` 4) 规划出多步方案需用户确认时:把整个方案(或关键分步)作为 option 调 request_human_confirmation,确认后再执行。`),a.push(`用户在选项里选了哪个,就按那个方案继续;选「拒绝」则停止并询问如何调整。`));let o=i?.loopProgress;if(o){let e=Oge(o.invokeUsage.prompt_tokens||o.invokeUsage.total_tokens,n?.promptSoftCap??1/0);e&&a.push(e);let t=Object.entries(o.writeFailures).filter(([,e])=>e>=2);if(t.length){let e=t.map(([e,t])=>`${e||`(整体)`}×${t}`).join(`、`);a.push(`⚠️ 以下路径已连续写失败:${e}。连续失败常意味着方向错了——先 read 重新核对实际值/类型,或 restore_data 回退后再改;若确需继续,换思路而非原样重试。`)}}return a.length&&a.unshift(`调用工具务必用标准 function calling(工具调用)格式发起,不要在回复正文里输出伪 XML/标签(如 deepseek 的 tool_calls 标签、invoke、function_call、tool_call 等)或 JSON 文本——那不会被识别为工具调用,会被当普通文字,工具不执行。`),a.length?`## 能力使用提示
3147
+ `)}}var bge=e3();Ip();function xge(e){let t=e;return typeof t.tagName==`string`||typeof t.nodeType==`number`&&typeof t.nodeName==`string`}function t3(e,t=3,n=2e3,r,i){if(e==null)return e;if(typeof e==`string`)return e.length>n?e.slice(0,n)+`…(已截断)`:e;if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(typeof e==`symbol`)return e.toString();if(typeof e==`bigint`)return`${e.toString()}n`;if(typeof e!=`object`)return String(e);let a=e;if(xge(a)){let e=a;return e.tagName?`[Element: <${e.tagName.toLowerCase()}>]`:`[Node: ${e.nodeName}]`}if(r?.has(a))return`[Circular]`;let o=r??new WeakSet;if(o.add(a),Array.isArray(e)){let r=e.slice(0,100).map(e=>t3(e,t-1,n,o,i));return e.length>100&&r.push(`…(共 ${e.length} 项,已截断)`),r}if(t<0)return`(对象,已截断)`;let s={},c=Object.keys(a);for(let e=0;e<c.length;e++){let r=c[e];if(e>=50){s[`…`]=`(共 ${c.length} 键,已截断)`;break}try{let e=a[r];i?.test(r)?s[r]=`[REDACTED]`:s[r]=t3(e,t-1,n,o,i)}catch{s[r]=`(getter 抛错)`}}return s}function n3(e){let t=e??(typeof window<`u`?window:{}),n=t.navigator,r=t.location,i=t.document;return{location:{href:r?.href,origin:r?.origin,protocol:r?.protocol,host:r?.host,hostname:r?.hostname,pathname:r?.pathname,search:r?.search},navigator:{userAgent:n?.userAgent,language:n?.language,languages:n?.languages,platform:n?.platform,onLine:n?.onLine},viewport:{innerWidth:t.innerWidth,innerHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio,scrollX:t.scrollX,scrollY:t.scrollY},document:i?{title:i.title,readyState:i.readyState,characterSet:i.characterSet}:`(无 document)`}}var Sge=/^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/,r3=/token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i,i3=IF(({key:e})=>{if(e){if(Sge.test(e)||r3.test(e))return JSON.stringify({key:e,denied:!0,reason:`安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏`},null,2);let t=(typeof window<`u`?window:{})[e];return JSON.stringify({key:e,exists:t!==void 0,type:typeof t,value:t3(t,3,2e3,void 0,r3)},null,2)}return JSON.stringify(n3(),null,2)},{name:`inspect_env`,description:`读宿主页面环境信息(排查调试)。不传参返回摘要(URL/origin、浏览器/语言、viewport、title/readyState);传 key 读指定 window 属性值(如 key:"appConfig")。只读,大结果自动外存 vfs。`,schema:B({key:R().optional().describe(`要读取的 window 属性名(如 "appConfig"/"__DEBUG__");不传 = 返回环境摘要`)})}),a3=[i3];function Cge(e,t,n){let r=0;return{name:`budget`,beforeAgent:()=>{r=Date.now()},wrapModelCall:async(i,a)=>{let{tokenBudget:o,timeBudgetMs:s}=t,c=o!=null&&(e.total_tokens??0)>o,l=s!=null&&Date.now()-r>s;return c||l?(n({type:`error`,severity:`observable`,code:`BUDGET_EXCEEDED`,message:`资源预算超限:${c?`token 超限(累计 ${e.total_tokens??0} > 上限 ${o})`:`时间超限(${Date.now()-r}ms > 上限 ${s}ms)`},agent 已停止(未完成部分可用 restoreLastCheckpoint 回退)。`}),{message:new Qx({content:``}),content:``,toolCalls:[],aborted:!0}):a(i)}}}Ip();var o3=/^[a-zA-Z][a-zA-Z0-9_]*$/;function s3(e){let t=[];for(let[n,r]of Object.entries(e)){if(!o3.test(n)){console.warn(`[page-agent-sdk][actions] 动作名 "${n}" 非法(须匹配 ${o3}),已跳过`);continue}let e=r.description||`宿主动作 ${n}`;t.push(IF(async e=>{try{let t=await r.run(e||{});return t===void 0?`动作 ${n} 执行完成。`:typeof t==`string`?t:JSON.stringify(t)}catch(e){let t=e?.message||String(e);return`动作 ${n} 执行失败:${t}`}},{name:n,description:e,schema:r.params??B({})}))}return t}function c3(e){let t={};for(let[n,r]of Object.entries(e))o3.test(n)&&(t[n]={description:r.description,hasParams:!!r.params,readsHostState:r.readsHostState===!0,deferredWrite:r.deferredWrite===!0});return t}var wge=L4,Tge=U4;function Ege(e,t){return k0(e,t)}function l3(e,t,n,r,i){let a=W2(e);return[...a.dataOps?t:[],...a.fetch?n:[],...a.domInspect&&r?r:[],...a.inspectEnv&&i?i:[]]}var u3=.7,Dge=.5,d3=.85;function Oge(e,t){if(!Number.isFinite(t)||t<=0||e<=0||e<t*Dge)return``;let n=Math.max(1,Math.round(e/1e3));return e>=t*d3?`⏳ 预算告急:本任务累计约 ${n}K prompt tokens(已达 softCap 上限的 ${Math.round(d3*100)}%)。立即停止扩展性操作(新查询/重读/优化),完成手头最关键一步后基于已有工具结果给出结论,并如实汇报剩余未完成项。轮次预算吃紧时系统会另行注入轮次提示段。`:`⏳ 预算提示:本任务累计约 ${n}K prompt tokens(已过 softCap 半程)。若已接近目标请收敛并给出总结;尚未接近请向用户汇报进度与剩余计划,勿默默继续。轮次预算吃紧时系统会另行注入轮次提示段。`}function f3(e,t,n){let r=W2(e);return{name:`usageHints`,augmentPrompt:i=>{let a=[];if(r.planning&&(a.push(`【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:`),a.push(` · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。`),a.push(` · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。`),a.push(` · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。`),a.push(` · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 "components.2"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。`),e?.humanConfirm?a.push(` · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。`):a.push(` · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。`),a.push(` · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。`)),t&&(a.push(`改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。`),a.push(`读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。`),a.push(`修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。`),a.push(`修改主数据出错时可用 restore_data 回退最近一次。`),a.push(`在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type=="card" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。`),a.push(`找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。`),a.push(`需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。`),a.push(`读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。`),a.push(`【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:"set",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。`),a.push(`读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:"该子树路径"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。`),a.push(`对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/"刚才改了啥");只读查历史快照值用 history_data({id?,jsonPath?})。`)),r.subagent&&a.push(`独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。`),r.inspectEnv&&a.push(`排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:"appConfig"}) 读 window.appConfig)。改完数据看渲染、定位"为何没生效"时用它(只读,不改数据)。`),r.domInspect){let n=t&&e?.hasActions?`配合宿主 actions(save_draft/publish 等)形成"改数据→截图/get_dom 看渲染→触发动作"闭环。`:t?`改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。`:``,r=e?.skills?`长文按关键词定位(找某术语/某节在哪)先 load_skill("dom-inspect") 取得 dom_search 文本检索,命中后窄读那一节 —— 勿整页翻页找。`:``;a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}${r}`)}if(e?.screenshot&&a.push(`视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。`),e?.domEdit&&a.push(`修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。`),e?.viewImage&&a.push(`看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。`),e?.hasProposals&&a.push(`【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。`),r.draftWrite&&(a.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。`),a.push(`⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。`)),r.focus&&t&&(a.push(`【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:`),a.push(` · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:"该子树路径"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。`),a.push(` · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。`),a.push(` · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。`),a.push(` · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。`),a.push(` · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。`)),e?.subagents?.length){let t=e.subagents.filter(e=>(e.temperature??0)>=u3||/规划|创意|设计|方案|brainstorm|plan/i.test(e.description)),n=e.subagents.filter(e=>(e.temperature??0)<u3&&/反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));a.push(`【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:`),t.length&&(a.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map(e=>`use_`+e.id).join(`/`)} 出 2-3 套方案(高温创意),`),a.push(e?.humanConfirm?` 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。`:` 不要自己拍板;拿到方案后以文字列出选项等用户回复(humanConfirm 未开,勿调不存在工具)。`)),n.length&&a.push(` · 严谨/易错/校验类 → 可先调 ${n.map(e=>`use_`+e.id).join(`/`)} 反思挑刺(低温审查),据反馈修订。`),a.push(` · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。`),a.push(` · 简单/明确任务(如"标题改红色")直接执行,不必走规划-反思。`)}e?.humanConfirm&&(a.push(`【人工确认·必读】以下情形必须先调 request_human_confirmation 征询用户、拿到答复后再继续,不要自行拍板:`),a.push(` 1) 用户让你「给方案/列选项/我来选/挑一个」时:把每个方案作为一个 option,调 request_human_confirmation(question=简述, options=[方案A,方案B,...], recommendation=你推荐的)。不要只回文字罗列方案让用户自己回复——要用工具把选项做成可点选按钮。`),a.push(` 2) 需求有歧义/不确定时:调工具问清楚(options 不传则用户答同意或拒绝)。`),a.push(` 3) 即将执行高风险不可逆操作(删除/覆盖/批量改动)前:调工具确认。`),a.push(` 4) 规划出多步方案需用户确认时:把整个方案(或关键分步)作为 option 调 request_human_confirmation,确认后再执行。`),a.push(`用户在选项里选了哪个,就按那个方案继续;选「拒绝」则停止并询问如何调整。`));let o=i?.loopProgress;if(o){let e=Oge(o.invokeUsage.prompt_tokens||o.invokeUsage.total_tokens,n?.promptSoftCap??1/0);e&&a.push(e);let t=Object.entries(o.writeFailures).filter(([,e])=>e>=2);if(t.length){let e=t.map(([e,t])=>`${e||`(整体)`}×${t}`).join(`、`);a.push(`⚠️ 以下路径已连续写失败:${e}。连续失败常意味着方向错了——先 read 重新核对实际值/类型,或 restore_data 回退后再改;若确需继续,换思路而非原样重试。`)}}return a.length&&a.unshift(`调用工具务必用标准 function calling(工具调用)格式发起,不要在回复正文里输出伪 XML/标签(如 deepseek 的 tool_calls 标签、invoke、function_call、tool_call 等)或 JSON 文本——那不会被识别为工具调用,会被当普通文字,工具不执行。`),a.length?`## 能力使用提示
3148
3148
  `+a.join(`
3149
3149
  `):void 0}}}function kge(e,t){let n=[`[当前页面] 用户正在浏览:`,`- 标题:${e.title}`,`- URL:${e.url}`,`用户问题通常针对此页面内容。`];return t&&n.push(`需要页面正文时用 read_page 读取纯文本(长文按 hasMore 分页续读);读结构用 get_dom。`),n.join(`
3150
3150
  `)}function Age(e){return{name:`pageContext`,augmentPrompt:()=>{let t=e.getPageInfo();if(t)return kge(t,e.canReadPage)}}}function jge(e){return{name:`resourcesPin`,augmentPrompt:()=>{let t=e.getResourcesSnapshot();if(!t.length)return;let n=[`## 受保护资源(跨压缩保留 · 精确值保护)`];for(let e of t)e.mode===`freeze`?n.push(`- ${e.path} (freeze 已冻结,不可改)`):n.push(`- ${e.path} (verbatim 原样保留)${e.handle?` ⟦res:${e.handle}⟧`:``}`);return n.push(`读到 ⟦frozen:path⟧/⟦res:handle⟧ 占位符 = 精确值在冻结区/资源池(不入消息流);需真值用 resource_get({path});freeze 字段不可写(撞 FROZEN_FIELD 即放弃);verbatim 直接写新值会 VERBATIM_MISMATCH,先 resource_update 再写回句柄;撞 RESOURCE_EVICTED/RESOURCE_NOT_FOUND 重新 read 懒注册。`),n.join(`
@@ -3158,7 +3158,7 @@ ${`- 输出形态:完整、自包含的 HTML 页面(.${r},可独立成页)`}
3158
3158
  `)+`
3159
3159
  (视觉内容如上,请结合图片回答/继续)`,t.map(e=>({dataUri:e.image.dataUri,url:e.image.url})),je);n&&e.messages.push(new Ix({content:n}))}return t(e)}}:null,Ne=!1,Pe=P.domEdit?nge({onEdit:e=>{L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`dom_edit`,ops:e.ops.join(`,`),applied:e.applied,dryRun:e.dryRun}}),!e.dryRun&&e.applied>0&&(Ne=!0)},onRestore:e=>{e.restored>0&&(Ne=!0)}}):[],Fe=[...l3(P,ve,L4,P.domInspect?[...U4,...Pe,...Ae?[Ae]:[],...P.skills?[]:[Q4,$4]]:[],a3),...ke?[ke]:[]];ke&&Ee.set(`view_image`,`builtin`),Fe.forEach(e=>Ee.set(e.name,`builtin`));let Ie=e.proposals?lge(e.proposals,{emit:e=>{try{qt(e)}catch{}},log:(e,t)=>{L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`proposal`,kind:e,...t}})}}):null,Le=[...e.tools||[],...Ie?.tools??[]];Le.forEach(e=>Ee.set(e.name,`user`));let Re=s3(e.actions??{});Re.forEach(e=>Ee.set(e.name,`action`));let ze=Ie?e.proposals?.readToolName||`read_content`:null,Be=Ie?e.proposals?.toolName||`propose_content`:null,Ve=new Set([...Object.entries(e.actions??{}).filter(([,e])=>e?.readsHostState===!0).map(([e])=>e),...ze?[ze]:[]]),He=new Set([...Object.entries(e.actions??{}).filter(([,e])=>e?.deferredWrite===!0).map(([e])=>e),...Be?[Be]:[]]),Ue=[],We=!1,Ge=e.humanConfirm!==!1&&(!e.approval||e.approval.humanConfirmTool!==!1),Ke=Ge?Jq():null;Ke&&Ee.set(Kq,`builtin`);let qe=de&&fe?[IF(async()=>{let e=fe.list();return e.length?fe.restore()?`已回退到最近一次正常状态(checkpoint #${e[e.length-1].id})。对话历史、主数据、vfs、todos 已整体还原。请基于回退后的状态重新判断并继续。`:`回退失败:无可用 checkpoint。`:`无可用 checkpoint,无法回退。`},{name:`restore_last_checkpoint`,description:`回退到最近一次正常状态(整体还原对话历史 + 主数据 + vfs + todos)。当本轮操作出错、页面被改坏、或走偏时调用,回到本轮起点重新来过。不传参数即回退最近一次。`,schema:B({}).optional()}),IF(async()=>{let e=fe.list();return e.length?`可用 checkpoint:
3160
3160
  `+e.map(e=>`#${e.id} [${e.label??`auto`}] 消息数=${e.messageCount} 时间=${new Date(e.timestamp).toLocaleTimeString()}`).join(`
3161
- `):`无可用 checkpoint。`},{name:`list_checkpoints`,description:`列出可用会话 checkpoint(回退点)。`,schema:B({}).optional()})]:[];qe.forEach(e=>Ee.set(e.name,`builtin`));let Je=P.focus,Ye=IF(async({path:e,label:t})=>{let n=xe()?.schema;return n?aG(n,e)?(O.setFocus(ee({path:e,...t?{label:t}:{}}),`agent`),`已聚焦到 ${e}${t?`(${t})`:``}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`):`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`:`聚焦失败:当前无主数据 schema,无法聚焦。`},{name:`set_focus`,description:`聚焦到指定组件子树(如 components.3)精修,替换全部已有焦点(非累积;要保留已有焦点追加用 add_focus)。聚焦后:仅可写该子树(越界 PATH_DENIED)+ 每轮只看到该组件结构。多组件页面精修其中一个时用,避免改到别处。先 read 定位 path 再聚焦;完成调 clear_focus。`,schema:B({path:R().describe(`要聚焦的组件 jsonPath,如 components.3`),label:R().optional().describe(`人类可读标签,如「导航栏」`)})}),Xe=IF(async()=>(O.clearFocus(`agent`),`已清除聚焦,恢复全量可操作范围(可读写所有组件)。`),{name:`clear_focus`,description:`清除当前聚焦,退出精修模式,恢复对全部组件的读写权限。`,schema:B({}).optional()}),Ze=IF(async({path:e,label:t})=>{let n=xe()?.schema;if(!n)return`聚焦失败:当前无主数据 schema,无法聚焦。`;if(!aG(n,e))return`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`;O.addFocus(ee({path:e,...t?{label:t}:{}}),`agent`);let r=O.getFocuses();return`已聚焦 ${e}${t?`(${t})`:``}(当前共 ${r.length} 个焦点:${r.map(e=>e.path).join(`, `)})。后续仅可写这些子树之一(越界被拒)。`},{name:`add_focus`,description:`追加聚焦一个组件子树(multi-focus,可同时聚焦多个相关组件)。校验 path 在 schema 内。聚焦后仅可写已聚焦的子树之一(越界 PATH_DENIED)。与 set_focus(替换全部)不同:本工具累积追加,不清除已有焦点。`,schema:B({path:R().describe(`要追加聚焦的组件 jsonPath,如 components.3`),label:R().optional().describe(`人类可读标签`)})}),Qe=IF(async({path:e})=>{let t=O.getFocuses().length;O.removeFocus(e,`agent`);let n=O.getFocuses();return n.length===t?`path "${e}" 不在当前焦点列表中(当前:${n.map(e=>e.path).join(`, `)||`无`})。`:n.length?`已移除焦点 ${e}(剩余 ${n.length} 个:${n.map(e=>e.path).join(`, `)})。`:`已移除焦点 ${e},聚焦已清空,恢复全量操作范围。`},{name:`remove_focus`,description:`移除单个聚焦焦点(by path),保留其他焦点。移除最后一个等价退出精修。全部退出用 clear_focus。`,schema:B({path:R().describe(`要移除的焦点 jsonPath`)})}),$e=Je?[Ye,Xe,Ze,Qe]:[];$e.forEach(e=>Ee.set(e.name,`builtin`));let et=[],tt=new Map,nt=qme({builtinTools:()=>Fe,userTools:()=>Le,actionTools:()=>Re,humanConfirmTool:()=>Ke,checkpointTools:()=>qe,focusTools:()=>$e,mcpTools:()=>Ue,loadedSkillTools:()=>et}),rt=nt(),it=P.planning,at=P.missionAnchor,ot=P.workingMemory,st=P.skills,ct=P.vfs||se;if(ct)for(let e of Fpe)Ee.set(e,`builtin`);if(it)for(let e of y.tools??[])Ee.set(e.name,`builtin`);let lt=P.summarization,ut=P.agentCompression&&!!u;e.debug&&P.agentCompression&&!u&&console.warn(`[page-agent-sdk][agentCompression] agentCompression 开启但 summaryLlm 不可用(或缺 apiKey / 模型不支持工具),压缩决策不启用,回退静态压缩`);let dt=P.memory,ft=P.subagent,pt=ft?lq():void 0,mt=e.verify?.maxAttempts??2,ht=!!(e.verify?.check||e.verify?.maxAttempts||e.verify?.adversarial),gt=e.capabilities?.verify===!1,_t=(P.verify||ht&&!gt)&&e.verify?.enabled!==!1&&mt>0,vt=P.contextInspector;ht&&!_t&&e.verify?.enabled!==!1&&console.warn(`[page-agent-sdk][verify] 检测到 verify 配置(check/maxAttempts/adversarial)但未装载(capabilities.verify:false 显式关闭 或 maxAttempts≤0)`);let yt=e.subagent,bt=yt?.allowedTools??[],xt=e.permissions?.length?Wq(e.permissions):void 0,St=e.approval?.preview===!0&&I?(e,t)=>e===`write`?I(t):null:void 0,Ct=e.approval?.previewWrite||St?(t,n)=>e.approval?.previewWrite?.(t,n)??St?.(t,n)??null:void 0,wt=e.approval&&(e.approval.tools!==void 0||e.approval.confirm)?Gq({...e.approval,timeoutMs:e.approval.timeoutMs??T,onAutoReject:E,previewWrite:Ct}):void 0,Tt=[...xt?[xt]:[],...wt?[wt]:[],...Te?[Te]:[]],Et=!ft||yt?.enabled===!1?void 0:kq({llm:yt?.llm??e.llm,allTools:()=>L.agent?.allTools??rt,allowedTools:bt.length?bt:void 0,...e.staleReadInvalidation===void 0?{}:{staleReadInvalidation:e.staleReadInvalidation},systemPrompt:yt?.systemPrompt,temperature:yt?.temperature,maxTokens:yt?.maxTokens,skills:yt?.skills,maxDepth:yt?.maxDepth,maxParallel:yt?.maxParallel,thinkingMode:yt?.thinkingMode,debug:e.debug,getFocuses:()=>O.getActiveFocuses(),getSchema:()=>xe()?.schema??null,tracker:pt,guardMiddleware:Tt.length?Tt:void 0,getVfsFiles:ct?()=>v.files:void 0,enterDataScope:ye?.enterScope?e=>ye.enterScope(e):void 0,exitDataScope:ye?.exitScope?e=>ye.exitScope(e):void 0,onUsage:e=>{r.prompt_tokens=(r.prompt_tokens??0)+(e.prompt_tokens??0),r.completion_tokens=(r.completion_tokens??0)+(e.completion_tokens??0),r.total_tokens=(r.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(r.reasoning_tokens=(r.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:yt?.timeoutMs}),Dt=oe?.map(e=>{if(!e._codeAsset)return e;let t=e._codeAsset,n=Zpe({writablePaths:t.writablePaths,codeVfsPrefix:t.codeVfsPrefix,ext:t.ext,codeField:t.codeField,craftNotes:t.craftNotes,onWarning:e=>console.warn(`[page-agent-sdk][code-asset] ${e}`),getController:()=>ye,vfsStore:v}),r=[...e.middleware??[],n];for(let e of r)e&&kW(e)&&e._setGetController(()=>ye);return{...e,middleware:r}}),Ot=se&&ft?Qpe():void 0,kt=Ot?rme({getBind:()=>xe()?.bind,writablePaths:ce,getLocked:()=>Ot.locked(),tools:rt,getCodeFieldPaths:()=>tme(xe()?.bind,ae.map(e=>({writablePaths:e._codeAsset.writablePaths,codeField:e._codeAsset.codeField})))}):void 0,At=ye?.getSummarizedPaths&&ye.clearSummarizedPaths?ame({getSummarizedPaths:()=>ye.getSummarizedPaths(),clearSummarizedPaths:()=>ye.clearSummarizedPaths()}):void 0,jt=ft&&Dt!==void 0?Mq(Dt,{llm:e.llm,thinkingModeDefault:e.subagent?.thinkingMode,staleReadInvalidation:e.staleReadInvalidation,allTools:()=>L.agent?.allTools??rt,debug:e.debug,getFocuses:()=>O.getActiveFocuses(),getSchema:()=>xe()?.schema??null,getBind:()=>xe()?.bind,tracker:pt,guardMiddleware:Tt.length?Tt:void 0,getVfsFiles:ct?()=>v.files:void 0,enterDataScope:ye?.enterScope?e=>ye.enterScope(e):void 0,exitDataScope:ye?.exitScope?e=>ye.exitScope(e):void 0,onUsage:e=>{r.prompt_tokens=(r.prompt_tokens??0)+(e.prompt_tokens??0),r.completion_tokens=(r.completion_tokens??0)+(e.completion_tokens??0),r.total_tokens=(r.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(r.reasoning_tokens=(r.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:e.subagent?.timeoutMs,...Ot?{componentLock:Ot,resolveComponents:e=>$pe(e,Ype(xe()?.bind,ce))}:{}}):void 0,Mt=jt?jt.controller:null,Nt=t=>{let n=t.thinkingMode??e.subagent?.thinkingMode,r=n?v2(t.llm??e.llm)?`instance-noop`:`applied`:`inherited`;return{...t,...n?{thinkingMode:n}:{},thinkingApplied:r}},Pt=[`read`,`fetch_document`],Ft=rt.filter(e=>Pt.includes(e.name)),It=_t?oJ({check:e.verify.check??fJ({schemas:()=>xe()?{"":xe().schema}:{},root:()=>xe()?.bind}),adversarial:e.verify?.adversarial?{llm:e.llm,tools:Ft}:void 0}):void 0,Lt=vt?EJ({contextWindow:d.contextWindow,thresholdRatio:q2(e,d.contextWindow).summaryThresholdRatio}):void 0,Rt=f3({...P,humanConfirm:Ge,screenshot:!!Ae,domEdit:P.domEdit,hasActions:!!e.actions&&Object.keys(e.actions).length>0,hasProposals:!!e.proposals,viewImage:!!ke,subagents:oe?.map(Nt)},pe&&!!te,{promptSoftCap:iq(d.contextWindow,f.promptSoftCapTokens)}),zt=P.pageContext?Age({getPageInfo:()=>typeof document<`u`&&typeof location<`u`?{title:document.title||``,url:location.href}:null,canReadPage:P.domInspect===!0}):void 0,Bt={epoch:0,notices:[],readsInvalidated:0},Vt=0,Ht={name:`hostNotice`,beforeAgent:()=>{Vt=Bt.epoch},wrapModelCall:async(e,t)=>{if(Ne){Ne=!1;let t=wU(e.messages,`agent 已通过 dom_edit 修改页面,此前读取为改前状态`,Ve);if(t.invalidatedCount>0){for(let n=0;n<t.messages.length;n++)e.messages[n]=t.messages[n];L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`dom_edit_read_invalidated`,count:t.invalidatedCount}})}}if(Bt.epoch>Vt){Vt=Bt.epoch;let t=Bt.notices[Bt.notices.length-1]??``,n=wU(e.messages,t||void 0,Ve);if(n.invalidatedCount>0){for(let t=0;t<n.messages.length;t++)e.messages[t]=n.messages[t];Bt.readsInvalidated+=n.invalidatedCount,L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_read_invalidated`,count:n.invalidatedCount,epoch:Bt.epoch,reason:t||void 0}})}}return t(e)},augmentPrompt:()=>Bt.notices.length?[`【宿主页面已变更】`,...Bt.notices.filter(Boolean).map(e=>`· ${e}`),P.domInspect===!0?`此前的页面读取/截图结果已过期,回答任何关于当前页面的问题前必须重新 read_page / get_dom 读取当前页面;不要凭此前的读取结果或记忆作答。`:`页面内容可能已变化,断言页面前先核实当前状态;不要凭此前的印象作答。`].join(`
3161
+ `):`无可用 checkpoint。`},{name:`list_checkpoints`,description:`列出可用会话 checkpoint(回退点)。`,schema:B({}).optional()})]:[];qe.forEach(e=>Ee.set(e.name,`builtin`));let Je=P.focus&&pe,Ye=IF(async({path:e,label:t})=>{let n=xe()?.schema;return n?aG(n,e)?(O.setFocus(ee({path:e,...t?{label:t}:{}}),`agent`),`已聚焦到 ${e}${t?`(${t})`:``}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`):`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`:`聚焦失败:当前无主数据 schema,无法聚焦。`},{name:`set_focus`,description:`聚焦到指定组件子树(如 components.3)精修,替换全部已有焦点(非累积;要保留已有焦点追加用 add_focus)。聚焦后:仅可写该子树(越界 PATH_DENIED)+ 每轮只看到该组件结构。多组件页面精修其中一个时用,避免改到别处。先 read 定位 path 再聚焦;完成调 clear_focus。`,schema:B({path:R().describe(`要聚焦的组件 jsonPath,如 components.3`),label:R().optional().describe(`人类可读标签,如「导航栏」`)})}),Xe=IF(async()=>(O.clearFocus(`agent`),`已清除聚焦,恢复全量可操作范围(可读写所有组件)。`),{name:`clear_focus`,description:`清除当前聚焦,退出精修模式,恢复对全部组件的读写权限。`,schema:B({}).optional()}),Ze=IF(async({path:e,label:t})=>{let n=xe()?.schema;if(!n)return`聚焦失败:当前无主数据 schema,无法聚焦。`;if(!aG(n,e))return`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`;O.addFocus(ee({path:e,...t?{label:t}:{}}),`agent`);let r=O.getFocuses();return`已聚焦 ${e}${t?`(${t})`:``}(当前共 ${r.length} 个焦点:${r.map(e=>e.path).join(`, `)})。后续仅可写这些子树之一(越界被拒)。`},{name:`add_focus`,description:`追加聚焦一个组件子树(multi-focus,可同时聚焦多个相关组件)。校验 path 在 schema 内。聚焦后仅可写已聚焦的子树之一(越界 PATH_DENIED)。与 set_focus(替换全部)不同:本工具累积追加,不清除已有焦点。`,schema:B({path:R().describe(`要追加聚焦的组件 jsonPath,如 components.3`),label:R().optional().describe(`人类可读标签`)})}),Qe=IF(async({path:e})=>{let t=O.getFocuses().length;O.removeFocus(e,`agent`);let n=O.getFocuses();return n.length===t?`path "${e}" 不在当前焦点列表中(当前:${n.map(e=>e.path).join(`, `)||`无`})。`:n.length?`已移除焦点 ${e}(剩余 ${n.length} 个:${n.map(e=>e.path).join(`, `)})。`:`已移除焦点 ${e},聚焦已清空,恢复全量操作范围。`},{name:`remove_focus`,description:`移除单个聚焦焦点(by path),保留其他焦点。移除最后一个等价退出精修。全部退出用 clear_focus。`,schema:B({path:R().describe(`要移除的焦点 jsonPath`)})}),$e=Je?[Ye,Xe,Ze,Qe]:[];$e.forEach(e=>Ee.set(e.name,`builtin`));let et=[],tt=new Map,nt=qme({builtinTools:()=>Fe,userTools:()=>Le,actionTools:()=>Re,humanConfirmTool:()=>Ke,checkpointTools:()=>qe,focusTools:()=>$e,mcpTools:()=>Ue,loadedSkillTools:()=>et}),rt=nt(),it=P.planning,at=P.missionAnchor,ot=P.workingMemory,st=P.skills,ct=P.vfs||se;if(ct)for(let e of Fpe)Ee.set(e,`builtin`);if(it)for(let e of y.tools??[])Ee.set(e.name,`builtin`);let lt=P.summarization,ut=P.agentCompression&&!!u;e.debug&&P.agentCompression&&!u&&console.warn(`[page-agent-sdk][agentCompression] agentCompression 开启但 summaryLlm 不可用(或缺 apiKey / 模型不支持工具),压缩决策不启用,回退静态压缩`);let dt=P.memory,ft=P.subagent,pt=ft?lq():void 0,mt=e.verify?.maxAttempts??2,ht=!!(e.verify?.check||e.verify?.maxAttempts||e.verify?.adversarial),gt=e.capabilities?.verify===!1,_t=(P.verify||ht&&!gt)&&e.verify?.enabled!==!1&&mt>0,vt=P.contextInspector;ht&&!_t&&e.verify?.enabled!==!1&&console.warn(`[page-agent-sdk][verify] 检测到 verify 配置(check/maxAttempts/adversarial)但未装载(capabilities.verify:false 显式关闭 或 maxAttempts≤0)`);let yt=e.subagent,bt=yt?.allowedTools??[],xt=e.permissions?.length?Wq(e.permissions):void 0,St=e.approval?.preview===!0&&I?(e,t)=>e===`write`?I(t):null:void 0,Ct=e.approval?.previewWrite||St?(t,n)=>e.approval?.previewWrite?.(t,n)??St?.(t,n)??null:void 0,wt=e.approval&&(e.approval.tools!==void 0||e.approval.confirm)?Gq({...e.approval,timeoutMs:e.approval.timeoutMs??T,onAutoReject:E,previewWrite:Ct}):void 0,Tt=[...xt?[xt]:[],...wt?[wt]:[],...Te?[Te]:[]],Et=!ft||yt?.enabled===!1?void 0:kq({llm:yt?.llm??e.llm,allTools:()=>L.agent?.allTools??rt,allowedTools:bt.length?bt:void 0,...e.staleReadInvalidation===void 0?{}:{staleReadInvalidation:e.staleReadInvalidation},systemPrompt:yt?.systemPrompt,temperature:yt?.temperature,maxTokens:yt?.maxTokens,skills:yt?.skills,maxDepth:yt?.maxDepth,maxParallel:yt?.maxParallel,thinkingMode:yt?.thinkingMode,debug:e.debug,getFocuses:()=>O.getActiveFocuses(),getSchema:()=>xe()?.schema??null,tracker:pt,guardMiddleware:Tt.length?Tt:void 0,getVfsFiles:ct?()=>v.files:void 0,enterDataScope:ye?.enterScope?e=>ye.enterScope(e):void 0,exitDataScope:ye?.exitScope?e=>ye.exitScope(e):void 0,onUsage:e=>{r.prompt_tokens=(r.prompt_tokens??0)+(e.prompt_tokens??0),r.completion_tokens=(r.completion_tokens??0)+(e.completion_tokens??0),r.total_tokens=(r.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(r.reasoning_tokens=(r.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:yt?.timeoutMs}),Dt=oe?.map(e=>{if(!e._codeAsset)return e;let t=e._codeAsset,n=Zpe({writablePaths:t.writablePaths,codeVfsPrefix:t.codeVfsPrefix,ext:t.ext,codeField:t.codeField,craftNotes:t.craftNotes,onWarning:e=>console.warn(`[page-agent-sdk][code-asset] ${e}`),getController:()=>ye,vfsStore:v}),r=[...e.middleware??[],n];for(let e of r)e&&kW(e)&&e._setGetController(()=>ye);return{...e,middleware:r}}),Ot=se&&ft?Qpe():void 0,kt=Ot?rme({getBind:()=>xe()?.bind,writablePaths:ce,getLocked:()=>Ot.locked(),tools:rt,getCodeFieldPaths:()=>tme(xe()?.bind,ae.map(e=>({writablePaths:e._codeAsset.writablePaths,codeField:e._codeAsset.codeField})))}):void 0,At=ye?.getSummarizedPaths&&ye.clearSummarizedPaths?ame({getSummarizedPaths:()=>ye.getSummarizedPaths(),clearSummarizedPaths:()=>ye.clearSummarizedPaths()}):void 0,jt=ft&&Dt!==void 0?Mq(Dt,{llm:e.llm,thinkingModeDefault:e.subagent?.thinkingMode,staleReadInvalidation:e.staleReadInvalidation,allTools:()=>L.agent?.allTools??rt,debug:e.debug,getFocuses:()=>O.getActiveFocuses(),getSchema:()=>xe()?.schema??null,getBind:()=>xe()?.bind,tracker:pt,guardMiddleware:Tt.length?Tt:void 0,getVfsFiles:ct?()=>v.files:void 0,enterDataScope:ye?.enterScope?e=>ye.enterScope(e):void 0,exitDataScope:ye?.exitScope?e=>ye.exitScope(e):void 0,onUsage:e=>{r.prompt_tokens=(r.prompt_tokens??0)+(e.prompt_tokens??0),r.completion_tokens=(r.completion_tokens??0)+(e.completion_tokens??0),r.total_tokens=(r.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(r.reasoning_tokens=(r.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:e.subagent?.timeoutMs,...Ot?{componentLock:Ot,resolveComponents:e=>$pe(e,Ype(xe()?.bind,ce))}:{}}):void 0,Mt=jt?jt.controller:null,Nt=t=>{let n=t.thinkingMode??e.subagent?.thinkingMode,r=n?v2(t.llm??e.llm)?`instance-noop`:`applied`:`inherited`;return{...t,...n?{thinkingMode:n}:{},thinkingApplied:r}},Pt=[`read`,`fetch_document`],Ft=rt.filter(e=>Pt.includes(e.name)),It=_t?oJ({check:e.verify.check??fJ({schemas:()=>xe()?{"":xe().schema}:{},root:()=>xe()?.bind}),adversarial:e.verify?.adversarial?{llm:e.llm,tools:Ft}:void 0}):void 0,Lt=vt?EJ({contextWindow:d.contextWindow,thresholdRatio:q2(e,d.contextWindow).summaryThresholdRatio}):void 0,Rt=f3({...P,humanConfirm:Ge,screenshot:!!Ae,domEdit:P.domEdit,hasActions:!!e.actions&&Object.keys(e.actions).length>0,hasProposals:!!e.proposals,viewImage:!!ke,subagents:oe?.map(Nt)},pe&&!!te,{promptSoftCap:iq(d.contextWindow,f.promptSoftCapTokens)}),zt=P.pageContext?Age({getPageInfo:()=>typeof document<`u`&&typeof location<`u`?{title:document.title||``,url:location.href}:null,canReadPage:P.domInspect===!0}):void 0,Bt={epoch:0,notices:[],readsInvalidated:0},Vt=0,Ht={name:`hostNotice`,beforeAgent:()=>{Vt=Bt.epoch},wrapModelCall:async(e,t)=>{if(Ne){Ne=!1;let t=wU(e.messages,`agent 已通过 dom_edit 修改页面,此前读取为改前状态`,Ve);if(t.invalidatedCount>0){for(let n=0;n<t.messages.length;n++)e.messages[n]=t.messages[n];L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`dom_edit_read_invalidated`,count:t.invalidatedCount}})}}if(Bt.epoch>Vt){Vt=Bt.epoch;let t=Bt.notices[Bt.notices.length-1]??``,n=wU(e.messages,t||void 0,Ve);if(n.invalidatedCount>0){for(let t=0;t<n.messages.length;t++)e.messages[t]=n.messages[t];Bt.readsInvalidated+=n.invalidatedCount,L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_read_invalidated`,count:n.invalidatedCount,epoch:Bt.epoch,reason:t||void 0}})}}return t(e)},augmentPrompt:()=>Bt.notices.length?[`【宿主页面已变更】`,...Bt.notices.filter(Boolean).map(e=>`· ${e}`),P.domInspect===!0?`此前的页面读取/截图结果已过期,回答任何关于当前页面的问题前必须重新 read_page / get_dom 读取当前页面;不要凭此前的读取结果或记忆作答。`:`页面内容可能已变化,断言页面前先核实当前状态;不要凭此前的印象作答。`].join(`
3162
3162
  `):void 0,afterAgent:()=>{Bt.notices.length=0}},Ut=Ie?{name:`proposalNotice`,augmentPrompt:()=>Ie.state.notices.length?[`【内容提案裁决结果】(以此为准,不要凭提案前状态作答)`,...Ie.state.notices].join(`
3163
3163
  `):void 0,afterAgent:()=>{Ie.state.notices.length=0}}:null,Wt=te?{name:`dataHint`,augmentPrompt:()=>G1(xe(),e.schemaHint)||void 0}:null,Gt=e.augmentSystem?{name:`augmentSystem`,augmentPrompt:t=>{try{return e.augmentSystem({state:t,data:xe()})}catch(t){e.debug&&console.log(`[page-agent-sdk][augmentSystem] 回调抛错,降级跳过:`,t.message);return}}}:null,Kt=G2(e.onEvent),qt=Kt.emit,Jt,Yt=[],Xt=e=>({name:e.name,description:e.description,content:typeof e.getContent==`function`?e.getContent():``}),Zt=e=>({name:e.name,description:e.description,getContent:()=>e.content}),Qt=e.skillStorage===!1?null:g3({...typeof e.skillStorage==`object`?e.skillStorage:{},id:e.skillStorage&&typeof e.skillStorage==`object`&&e.skillStorage.id?e.skillStorage.id:`agent::${t}`}),$t=()=>{let t=Jt?Jt.controller:null;if(t){let n=(e.skills||[]).filter(e=>!Yt.some(t=>t.name===e.name));t.set([...n,...Yt])}L.infoTick.value++},en=async()=>{if(Qt)try{let t=await Qt.list();if(t.length){Yt=t.map(Zt);let n=Jt?Jt.controller:null;if(n){let t=(e.skills||[]).filter(e=>!Yt.some(t=>t.name===e.name));n.set([...t,...Yt])}L.infoTick.value++}}catch{}},tn=lt?cq({...f,llmInvoke:c,getRegisteredData:()=>xe()?[{description:xe().description??`主数据对象`}]:[],preserveLastToolResults:m,...ut?{decideInvoke:u,getSnapshot:()=>Lt?.getSnapshot()}:{}}):void 0,nn=st?LK([...P.domInspect&&!(e.skills||[]).some(e=>e.name===`dom-inspect`)?[e3({withScreenshot:!!Ae,withDomEdit:P.domEdit,withDataOps:pe&&!!te})]:[],...P.domInspect&&!(e.skills||[]).some(e=>e.name===`page-analysis`)?[yge({withScreenshot:!!Ae,withDomEdit:P.domEdit,withVfs:ct})]:[],...e.skills||[]],{readVfs:ct?e=>v.files[e]?.content:void 0,onToolsReady:(e,t)=>{for(let n of t){let t=et.findIndex(e=>e.name===n.name);t>=0&&et.splice(t,1),et.push(n),tt.set(n.name,e),Ee.set(n.name,`skill:${e}`)}rt=nt(),L.agent&&L.agent.setTools(rt),L.infoTick.value++}}):void 0;Jt=nn;let rn=Hme([...Wt?[Wt]:[],Rt,...zt?[zt]:[],Ht,...Ut?[Ut]:[],...at?[b]:[],x,S,...it?[y]:[],...nn?[nn]:[],...ct?[Lpe(v)]:[],...tn?[tn]:[],...ot?[k]:[],...Je?[O]:[],...be?[be]:[],...dt?[A]:[],...xt?[xt]:[],...de&&N&&fe?[iJ(fe)]:[],...Ge?[D]:[],...wt?[wt]:[],...Te?[Te]:[],...It?[It]:[],...Et?[Et]:[],...jt?[jt]:[],...kt?[kt]:[],...At?[At]:[],...ye&&ft?[sme({getBind:()=>xe()?.bind,getTools:()=>L.agent?.allTools??rt})]:[],...Gt?[Gt]:[],...Lt?[Lt]:[],...Me?[Me]:[],...e.middleware||[],...he?[Cge(r,{tokenBudget:e.tokenBudget,timeBudgetMs:e.timeBudgetMs},qt)]:[],Lge(qt,_,xe,r)]),an=e.maxMemoryRounds??Pge;function on(e){return e=>{e.type!==`approval_request`&&qt(Oe(e))}}let sn=gR([]),cn=y3(),ln=new Set;function un(e){let t=new AbortController,n=()=>t.abort();return e&&(e.aborted?t.abort():e.addEventListener(`abort`,n,{once:!0})),ln.add(t),{controller:t,untrack:()=>{ln.delete(t),e?.removeEventListener(`abort`,n)}}}function dn(){for(let e of ln)e.abort();ln.clear()}let fn=gR(null),L={agentId:t,store:o,messages:_,vfsStore:v,listeners:Kt.listeners,todosMw:y,memoryMw:A,missionMw:b,workingMemoryMw:k,focusMw:O,agent:null,initDone:Promise.resolve(),sessionId:``,refCount:0,mcpClosers:[],mcpServers:[],mcpFailed:[],checkpoint:fe,dataOpsController:ye,skillsController:Jt?Jt.controller:null,infoTick:a,pendingConflict:i.pendingConflict,pendingQuote:fn,sessions:sn,refreshSessions:()=>yn.refreshSessions(),liveData:xe,usage:r,emit:qt,runSerial:cn,trackActive:un,abortAllActive:dn,unloadSkillTools(e){if(e){let t=et.length;if(et=et.filter(t=>tt.get(t.name)===e?(Ee.delete(t.name),tt.delete(t.name),!1):!0),et.length===t)return}else{if(!et.length)return;for(let e of et)Ee.delete(e.name),tt.delete(e.name);et=[]}rt=nt(),L.agent&&L.agent.setTools(rt)},applySnapshot(t){if(t.vfs&&v.hydrate&&v.hydrate(t.vfs),t.messages?.length&&(_.push(...nde(t.messages,e=>(e?L.vfsStore?.files?.[e]?.content:void 0)||void 0)),S.markResumed()),t.todos?.length&&y.reset(t.todos),t.memory&&!e.memory&&A.reset(t.memory),t.checkpoints?.length&&fe&&fe.importStack(t.checkpoints),t.usage&&Object.assign(r,t.usage),t.mission&&at&&b.setMission(t.mission),t.workingMemory&&ot&&k.restore(t.workingMemory),t.planConfirmation&&(C.lastPlanConfirmation=t.planConfirmation),Je){let n=t.focus,r=n?Array.isArray(n)?n:[n]:[];if(r.length){let t=xe()?.schema,n=t?r.filter(e=>aG(t,e.path)):[];if(n.length&&(O.setFocus(null),n.forEach(e=>O.addFocus(ee(e)))),e.debug&&n.length<r.length){let e=r.filter(e=>!n.includes(e)).map(e=>e.path);console.warn(`[page-agent-sdk][focus] 恢复的焦点部分 path 已失效(schema 变化/无 schema),剔除:`,e)}}}gn()},addSkill(e){let t=Yt.findIndex(t=>t.name===e.name);t>=0?Yt[t]=e:Yt.push(e),$t(),Qt&&Qt.put(Xt(e))},removeSkill(e){let t=Yt.findIndex(t=>t.name===e);return t<0?!1:(Yt.splice(t,1),$t(),Qt&&Qt.remove(e),!0)},listUserSkills(){return Yt.map(e=>e.name)},getUserSkill(e){let t=Yt.find(t=>t.name===e);if(t)return{name:t.name,description:t.description,content:typeof t.getContent==`function`?t.getContent():``}},afterRound(){_n(),yn.persistRuntime()},clearCodeReuse(){let e=v;e.__pgPendingRetry?.clear(),e.__pgLastCheckout?.clear()},async send(e,t){if(await L.initDone,L.refCount<=0)throw Error(`page-agent-sdk: agent 已释放(unmount),拒绝排队中的 send`);t??={},t?.mission&&at&&b.setMission(t.mission);let n=e,r=(t.images??[]).filter(e=>e&&(e.dataUri||e.vfsRef||e.url));if(r.length>4)throw Error(`[page-agent-sdk] 单轮最多 4 张图片(收到 ${r.length})`);if(r.length&&(await vn.stowImages(r),await vn.describeIfNeeded(r,n)),r.length&&!d.vision&&!r.every(e=>e.description)){let e=`当前主模型不支持图片输入(modelCaps.vision=false)。请换多模态模型(gpt-4o/claude/qwen-vl)或 LLMConfig 声明 vision:true;或配置 images.describe 绑定识图转述(集成方识图子 agent / 自有 vision API)`;throw qt({type:`error`,message:e,severity:`recoverable`,code:`IMAGE_UNSUPPORTED_MODEL`}),Error(`[page-agent-sdk] ${e}`)}v?.setProtectedRefs?.(v3(_));let a=he?t.maxAutoRetries??1:0,s=0,c=!1,l=on(t.signal);if(t.signal){let e=()=>i.resolve(`keep_external`);t.signal.aborted?e():t.signal.addEventListener(`abort`,e,{once:!0})}let u=L.sessionId;for(;;){if(!c){let e;if(t.quote?.text){let n=hH(t.quote.anchor);e={text:oH(t.quote.text),...t.quote.source?{source:t.quote.source}:{},...n?{anchor:n}:{}}}let i=e??fn.value??void 0;_.push({role:`user`,content:n,timestamp:Date.now(),...r.length?{images:r}:{},...i?{quote:i}:{}}),c=!0,!e&&fn.value&&(fn.value=null)}try{let e=await L.agent.invoke(_,t.signal,l);if(t.signal?.aborted||L.sessionId!==u||L.refCount<=0)return L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`orphan_round_dropped`,fromSession:u,aborted:!!t.signal?.aborted,sessionChanged:L.sessionId!==u}}),e;if(_.push({role:`assistant`,content:e,timestamp:Date.now()}),L.afterRound(),o)try{await o.flush()}catch(e){qt({type:`error`,message:`落盘失败(不影响本轮回复):${e instanceof Error?e.message:String(e)}`,severity:`observable`,code:`PERSIST_FLUSH_FAILED`})}return e}catch(e){if(kH(e,t.signal))throw e;let n=eH(e,`fatal`);if(UH(e)&&(n={...n,code:`MODEL_UNAVAILABLE`,message:e instanceof Error?e.message:n.message}),s<a&&fe?.canRestore()){s+=1,fe.restore(),c=!0,qt({type:`error`,message:`致命错误自动恢复(${s}/${a}):${n.message},已回退 checkpoint 重试`,severity:`observable`,code:`AUTO_RECOVER_RETRY`,context:{attempt:s,cause:n.code??n.message.slice(0,120)}});continue}throw qt({type:`error`,message:n.message,severity:n.severity,...n.code?{code:n.code}:{},...n.context===void 0?{}:{context:n.context}}),e}}},async batch(e,t,n){if(await L.initDone,!e.length)return[];if(L.refCount<=0)throw Error(`page-agent-sdk: agent 已释放(unmount),拒绝排队中的 batch`);let r=[],a=on(n);if(v?.setProtectedRefs?.(v3(_)),n){let e=()=>i.resolve(`keep_external`);n.aborted?e():n.addEventListener(`abort`,e,{once:!0})}for(let i=0;i<e.length;i++){if(n?.aborted){for(let t=i;t<e.length;t++)r.push({index:t,task:e[t],error:`aborted(外部中止)`,ok:!1});break}let s=e[i];fe&&fe.save(`batch:${i}`);let c=_.length;try{_.push({role:`user`,content:s,timestamp:Date.now()});let c=await L.agent.invoke(_,n,a);if(_.push({role:`assistant`,content:c,timestamp:Date.now()}),L.afterRound(),o)try{await o.flush()}catch(e){qt({type:`error`,message:`落盘失败(不影响本任务结果):${e instanceof Error?e.message:String(e)}`,severity:`observable`,code:`PERSIST_FLUSH_FAILED`})}r.push({index:i,task:s,reply:c,ok:!0}),t?.({done:i+1,total:e.length,task:s,ok:!0})}catch(a){if(_.length>c&&_.splice(c),kH(a,n)){r.push({index:i,task:s,error:`aborted(外部中止)`,ok:!1});for(let t=i+1;t<e.length;t++)r.push({index:t,task:e[t],error:`aborted(外部中止)`,ok:!1});break}UH(a);let o=eH(a,`fatal`);qt({type:`error`,message:`批量任务 ${i+1}/${e.length} 失败:${o.message}`,severity:`observable`,code:`BATCH_TASK_FAILED`,context:{index:i,task:s.slice(0,100)}}),r.push({index:i,task:s,error:o.message,ok:!1}),t?.({done:i+1,total:e.length,task:s,ok:!1})}}return r},switchSession:e=>yn.switchSession(e),exportSession:e=>yn.exportSession(e),importSession:e=>yn.importSession(e),resetSession:()=>yn.resetSession(),stream:async(e,t,n)=>{if(!L.agent)throw Error(`page-agent-sdk: agent 尚未初始化完成,请先 await mount()`);let r=[...e].reverse().find(e=>e.role===`user`&&e.images?.length);if(r?.images?.length&&(await vn.stowImages(r.images),await vn.describeIfNeeded(r.images,r.content),!d.vision&&!r.images.every(e=>e.description))){let e=`当前主模型不支持图片输入(modelCaps.vision=false)。请换多模态模型(gpt-4o/claude/qwen-vl)或 LLMConfig 声明 vision:true;或配置 images.describe 绑定识图转述`;throw qt({type:`error`,message:e,severity:`recoverable`,code:`IMAGE_UNSUPPORTED_MODEL`}),Error(`[page-agent-sdk] ${e}`)}v?.setProtectedRefs?.(v3(e));let a=e=>{t?.(Oe(e)),qt(Oe(e)),e.type===`subagent`&&(e.kind===`tool_call`||e.kind===`tool_result`)&&L.infoTick.value++};if(n){let e=()=>i.resolve(`keep_external`);n.aborted?e():n.addEventListener(`abort`,e,{once:!0})}let{controller:o,untrack:s}=un(n);return L.agent.stream(e,a,o.signal).finally(s)},release(){if(L.refCount--,L.refCount<=0){dn(),We=!0,o&&(v.flush?.(),o.flush(),o.dispose()),Qt&&Qt.dispose();let e=L.mcpClosers.splice(0);e.length&&Promise.allSettled(e.map(e=>e())),b3.delete(t)}},resolveConflict:i.resolve,setTools(e){Le.length=0,e.forEach(e=>{Le.push(e),Ee.set(e.name,`user`)}),rt=nt(),L.agent&&L.agent.setTools(rt),L.infoTick.value++},addTool(e){rt.some(t=>t.name===e.name)&&console.warn(`[page-agent-sdk] 工具 "${e.name}" 已存在,新工具覆盖(后注册覆盖先注册)`);for(let t=Le.length-1;t>=0;t--)Le[t].name===e.name&&Le.splice(t,1);Le.push(e),Ee.set(e.name,`user`),rt=nt(),L.agent&&L.agent.setTools(rt),L.infoTick.value++},removeTool(e){let t=Le.findIndex(t=>t.name===e);return t<0?!1:(Le.splice(t,1),Ee.delete(e),rt=nt(),L.agent&&L.agent.setTools(rt),L.infoTick.value++,!0)},setLlm(t){let n;if(v2(t))n=t;else{let e=t;if((e.provider??`openai`)===`anthropic`)throw Error(`[page-agent-sdk][setLlm] 切换到 Anthropic 需传 BaseChatModel 实例(动态 import 无法同步);请先 const { ChatAnthropic } = await import("@langchain/anthropic") 构造实例后传入`);n=rI(e)}typeof n.bindTools!=`function`&&e.debug&&console.warn(`[page-agent-sdk][setLlm] 新模型不支持 bindTools(tool calling 会失效)`),y2(n,{emit:qt}),g=t;let r=v2(t)?void 0:t;if(d=YF({model:r?.model??t.model??t.modelName,contextWindow:e.contextWindow??r?.contextWindow,maxOutputTokens:e.maxOutputTokens??r?.maxOutputTokens,vision:r?.vision??t.vision}),d.contextWindow<2e5)throw Error(`[page-agent-sdk][setLlm] 新模型上下文窗口 ${d.contextWindow} 小于最小支持 ${WF}(需 ≥200K 窗口模型)`);L.agent&&(L.agent.setLlm(n),L.agent.setModelCaps?.(d)),tn?.setContextWindow?.(d.contextWindow),Lt?.setContextWindow?.(d.contextWindow),L.infoTick.value++,e.debug&&console.log(`[page-agent-sdk][setLlm] 重解析 modelCaps + 回灌:`,d)},setMemory(e){A.reset(e),typeof e==`function`&&A.refresh(),L.infoTick.value++},refreshMemory(){return A.refresh()},setSubagents(t){if(!Mt){e.debug&&console.warn(`[page-agent-sdk][setSubagents] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}Mt.set(t),L.infoTick.value++},addSubagent(t){if(!Mt){e.debug&&console.warn(`[page-agent-sdk][addSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}Mt.add(t),L.infoTick.value++},removeSubagent(t){if(!Mt)return e.debug&&console.warn(`[page-agent-sdk][removeSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`),!1;let n=Mt.remove(t);return n&&L.infoTick.value++,n},getActiveSubagents(){return pt?.getActive()??[]},get subagentHistory(){return pt?.getHistory()??[]},getInfo(){return{id:t,sessionId:L.sessionId,model:v2(g)?g.model??g.modelName:g.model,systemPrompt:L.agent?.getEffectiveSystemPrompt?.()??F+G1(xe(),e.schemaHint),tools:(L.agent?.allTools??rt).map(e=>({name:e.name,description:e.description,schema:e.schema,source:Ee.get(e.name)||`user`})),skills:(Jt?Jt.controller.get():e.skills??[]).map(e=>({name:e.name,description:e.description})),data:xe()?{description:xe().description,schema:xe().schema}:void 0,contextPreset:e.contextPreset??`auto`,compression:{contextWindow:d.contextWindow,summaryThresholdRatio:f.summaryThresholdRatio??.5,promptSoftCap:iq(d.contextWindow,f.promptSoftCapTokens)},memory:A.get(),staleReadsInvalidated:L.agent?.getStaleReadsInvalidated?.()??0,hostReadsInvalidated:Bt.readsInvalidated,...Ie?{proposals:Ie.snapshot()}:{},...n?{hostWatch:{...n}}:{},llmRetries:L.agent?.getLlmRetries?.()??0,llmCallFailures:L.agent?.getLlmCallFailures?.()??0,gates:L.agent?.getGateStats?.(),systemSegments:L.agent?.getLastSystemSegments?.()??[],middleware:rn.map(e=>e.name),todos:(L.agent?.getState?.()?.todos??[]).map(e=>({id:e.id,content:e.content,status:e.status,...e.parentId===void 0?{}:{parentId:e.parentId},...e.deps===void 0?{}:{deps:e.deps},...e.criteria===void 0?{}:{criteria:e.criteria},...e.evidence===void 0?{}:{evidence:e.evidence}})),planPhase:y.getPlanPhase(),mission:at?b.getMission():void 0,planConfirmation:C.lastPlanConfirmation,workingMemory:ot?k.getWorkingMemory():void 0,focus:Je?O.getFocus():void 0,focuses:Je?O.getFocuses():[],actions:c3(e.actions??{}),subagent:{enabled:!!Et,maxDepth:e.subagent?.maxDepth??1,maxParallel:e.subagent?.maxParallel??4,timeoutMs:e.subagent?.timeoutMs===void 0?18e5:e.subagent.timeoutMs>0?e.subagent.timeoutMs:0,allowedTools:e.subagent?.allowedTools??[],subagents:(Mt?.get()??[]).map(Nt),active:pt?.getActive()??[],history:pt?.getHistory()??[],lockedComponents:Ot?.locked()??{}},verify:{enabled:!!It,maxAttempts:_t?mt:0,adversarial:_t&&!!e.verify?.adversarial},context:(()=>{let e=Lt?.getSnapshot();if(e){let t=L.agent?.getState?.()?.lastCompression;t&&(e.compression=t)}return e})(),mcp:{servers:L.mcpServers,...L.mcpFailed.length?{failed:L.mcpFailed}:{}},lastCompression:L.agent?.getState?.()?.lastCompression,checkpoints:fe?{enabled:!0,auto:N,list:fe.list()}:void 0}},exportDiagnostics(){let e=L.getInfo(),t={...e,tools:e.tools.map(({schema:e,...t})=>t),data:e.data?{description:e.data.description,schemaTopKeys:nG(e.data.schema)??[]}:void 0},n=L.liveData(),r=null;if(n){let e=-1,t=[];try{let r=JSON.stringify(n.bind);e=r?r.length:0,n.bind&&typeof n.bind==`object`&&!Array.isArray(n.bind)&&(t=Object.keys(n.bind))}catch{e=-1}r={description:n.description,topKeys:t,approxBytes:e}}return $0(Q0({debugLogs:L.agent?.debugLogs?.value??[],messages:L.messages,info:t,usage:{...L.usage},pendingConflict:L.pendingConflict?.value??null,sessionId:L.sessionId,dataSummary:r}))},getMission(){return at?b.getMission():void 0},setMission(t){if(!at){e.debug&&console.warn(`[page-agent-sdk][mission] capabilities.missionAnchor 关闭,setMission 忽略`);return}b.setMission(t),L.infoTick.value++},getFocus(){return Je?O.getFocus():void 0},getFocuses(){return Je?O.getFocuses():[]},setFocus(t){let n=x3(t,`setFocus`,Je,()=>xe()?.schema,e.debug);return n.ok?(O.setFocus(ee(t)),e.debug&&O.isInvokeActive()&&console.info(`[page-agent-sdk][focus] 在途流程进行中,聚焦将在下一次输入生效(当前流程不受影响)`),L.infoTick.value++,{ok:!0}):n},addFocus(t){let n=x3(t,`addFocus`,Je,()=>xe()?.schema,e.debug);return n.ok?O.getFocuses().length>=8?(e.debug&&console.warn(`[page-agent-sdk][focus] addFocus 拒绝:焦点数已达上限 8(augmentPrompt 注入每焦点子树 schema,过多致 system prompt 超预算)`),{ok:!1,error:`焦点数上限 8(避免 system prompt 撑爆)`}):(O.addFocus(ee(t)),e.debug&&O.isInvokeActive()&&console.info(`[page-agent-sdk][focus] 在途流程进行中,聚焦将在下一次输入生效(当前流程不受影响)`),L.infoTick.value++,{ok:!0}):n},removeFocus(e){Je&&(O.removeFocus(e),L.infoTick.value++)},clearFocus(){Je&&(O.clearFocus(),L.infoTick.value++)},setQuote(e,t,n){let r=oH(e??``),i=hH(n);fn.value=r?{text:r,...t?{source:t}:{},...i?{anchor:i}:{}}:null},notifyHostChange(e){let t=typeof e?.reason==`string`?e.reason.trim().slice(0,200):``;Bt.epoch+=1,t&&!Bt.notices.includes(t)?Bt.notices.push(t):t||Bt.notices.push(``),Bt.notices.length>5&&Bt.notices.splice(0,Bt.notices.length-5),L.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_change_notified`,epoch:Bt.epoch,reason:t||void 0}}),L.infoTick.value++},clearQuote(){fn.value=null},resolveProposal(e,t,n){let r=Ie?Ie.resolve(e,t,n):!1;return r&&L.infoTick.value++,r},getProposals(){return Ie?Ie.snapshot():null}};async function pn(){if(!o)return;let n=async e=>{try{return await o.load(t,e)}catch(t){qt({type:`error`,message:`会话快照读取失败,已降级空会话:${t instanceof Error?t.message:String(t)}`,severity:`observable`,code:`SESSION_RESTORE_FAILED`,context:{sessionId:e}});return}},r=async()=>{try{return await o.listSessions(t)}catch(e){return qt({type:`error`,message:`会话列表读取失败,已降级新建会话:${e instanceof Error?e.message:String(e)}`,severity:`observable`,code:`SESSION_RESTORE_FAILED`}),[]}},i=Symbol(`storage-ready-timeout`);await Promise.race([o.ready.then(()=>`ready`),new Promise(e=>setTimeout(()=>e(i),5e3))])===i&&(console.warn(`[page-agent-sdk][persist] 存储初始化 5s 未就绪(可能被其他标签页锁住),已放行;持久化暂降级内存,就绪后自动恢复`),qt({type:`error`,message:`存储初始化 5s 未就绪(IDB blocked?),已放行降级运行`,severity:`observable`,code:`STORAGE_READY_TIMEOUT`}));let a=e.session||{};if(a.id){L.sessionId=a.id;let e=await n(L.sessionId);e?(L.applySnapshot(e),qt({type:`session_restored`,sessionId:L.sessionId,rounds:e.messages?.length??0})):await o.createSession(t,a.title,L.sessionId)}else if(a.autoResume!==!1){let i=await r();if(e.debug&&console.log(`[page-agent-sdk][restore] listSessions`,t,i.length,i.map(e=>e.sessionId)),i.length){L.sessionId=i[0].sessionId;let t=await n(L.sessionId);t?(L.applySnapshot(t),qt({type:`session_restored`,sessionId:L.sessionId,rounds:t.messages?.length??0}),e.debug&&console.log(`[page-agent-sdk][restore] 恢复会话`,L.sessionId,`${t.messages?.length??0} msgs`)):e.debug&&console.log(`[page-agent-sdk][restore] 会话 meta 存在但快照为空`,L.sessionId)}else L.sessionId=await o.createSession(t,a.title),e.debug&&console.log(`[page-agent-sdk][restore] 新建会话(无历史)`,L.sessionId)}else L.sessionId=await o.createSession(t,a.title);e.memory&&yn.persistSave({memory:A.get()||(typeof e.memory==`string`?e.memory:``)}),yn.refreshSessions()}async function mn(){await en()}function hn(e){let t={};for(let n of v3(e)){let e=v.files[n];e&&(t[n]=e.content)}return t}function gn(){let e=Nge(v.files,v3(_));for(let t of e)delete v.files[t]}function _n(){let e=KK(_,an);if(!e.trimmed)return;let{older:t,summary:n}=e;if(qt({type:`context_trimmed`,dropped:t.map(e=>({round:e.round,user:e.userMsg.content,assistant:e.assistantMsgs.map(e=>e.content),steps:e.assistantMsgs.flatMap(e=>e.steps??[])})),vfsResults:hn(t.flatMap(e=>[e.userMsg,...e.assistantMsgs])),summary:n.content,reason:`max_memory_rounds`}),_.splice(e.deleteFrom,e.deleteCount,n),gn(),p&&c){let n=e.summary,{prevSeg:r}=e;(async()=>{try{let e=await c($K(t,h)),i=_.indexOf(n);if(i<0)return;_[i].content=GK(t,r,e),yn.persistRuntime()}catch{}})()}}let vn=sde({getConfig:()=>e.images,getVision:()=>d.vision===!0,emit:qt,getVfsStore:()=>L.vfsStore,noteFailure:(e,t)=>yn.notePersistFailure(e,t)}),yn=Gme({agentId:t,options:e,emit:qt,getStore:()=>o,core:L,sessionsRef:sn,sessionVars:C,messages:_,getUsage:()=>r,mw:{todosMw:y,memoryMw:A,missionMw:b,workingMemoryMw:k,focusMw:O,summarizationMw:tn,resumeNoticeMw:S,useMission:at,useWorkingMemory:ot,useFocus:Je,useAutomation:he},vfsStore:v,checkpointMgr:fe,conflictResolve:e=>i.resolve(e),abortAllActive:dn,titleLlmInvoke:l});return L.initDone=(async()=>{await pn(),await mn(),e.mcp?.length&&kpe({servers:e.mcp,emit:qt,isReleased:()=>We,core:{mcpClosers:L.mcpClosers,mcpServers:L.mcpServers,mcpFailed:L.mcpFailed,infoTick:L.infoTick},reservedNames:()=>{let e=new Set;for(let t of rt){let n=Ee.get(t.name);n&&!n.startsWith(`mcp:`)&&e.add(t.name)}return e},pushTool:(e,t)=>(Ee.set(e.name,`mcp:${t}`),Ue.push(e),!0),rebind:()=>{rt=nt(),L.agent&&L.agent.setTools(rt),L.infoTick.value++},debug:e.debug});let t=v2(e.llm)?e.llm:await oI(e.llm);y2(t,{emit:qt}),L.agent=tG({llm:t,systemPrompt:F,tools:rt,middleware:rn,maxToolRounds:e.maxToolRounds,hasSubagent:ft,pageAssertionGate:P.domInspect===!0,pageReadTools:Ve.size?Ve:void 0,deferredWriteTools:He.size?He:void 0,maxRetries:e.maxRetries,stallMs:e.streamStallMs??9e4,streamMaxMs:e.streamMaxDurationMs??18e5,toolTimeoutMs:e.toolTimeoutMs,maxParallelTools:e.maxParallelTools,contextWindow:d.contextWindow,maxOutputTokens:d.maxOutputTokens,vision:d.vision,imageContentFormat:je,maxVerifyAttempts:_t?mt:0,roundTokenBudget:e.roundTokenBudget??0,staleReadInvalidation:e.staleReadInvalidation,onLlmChange:e=>{g=e},debug:e.debug}),j.current=L.agent,jt&&jt.setReconfigureHook(()=>{L.agent&&L.agent.setTools(nt())})})(),L}function zge(e,t){let n=e.id??T2();e.id||console.warn(`[page-agent-sdk] 未传 options.id,已生成随机 id "${n}"。刷新后持久化数据无法恢复,请传稳定 id。`);let r=e.streaming??!0,i=e.ui??`default`,a=e.hostWatch===!0?{url:!0}:e.hostWatch&&typeof e.hostWatch==`object`?e.hostWatch:null,o={enabled:!1,url:!1,pushState:!1,title:!1,autoNotified:0},s=null,c,l=e.shareContext?b3.get(n):void 0;l?c=l:(c=Rge(e,n,a?o:void 0),e.shareContext&&b3.set(n,c)),c.refCount++;let u=null,d=V2(e),f=null,p=null;async function m(n){if(await c.initDone,u){u.show();return}let l=n===void 0?e.container:n,m=()=>{c.store&&(f=()=>{c.vfsStore.flush?.(),c.store.flush()},p=()=>{document.visibilityState===`hidden`&&c.store.flush()},typeof window<`u`&&window.addEventListener(`pagehide`,f),typeof document<`u`&&document.addEventListener(`visibilitychange`,p))};if((()=>{if(!a)return;s?.dispose(),s=null;let e=typeof window<`u`?window:void 0;s=ige({target:e,history:typeof history<`u`?history:e?.history,document:typeof document<`u`?document:void 0,MutationObserver:typeof MutationObserver<`u`?MutationObserver:void 0,options:a,onReport:e=>{o.autoNotified+=1,c.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_watch`,kind:e.kind,from:e.from.slice(0,120),to:e.to.slice(0,120)}}),c.notifyHostChange({reason:rge(e)})}}),s&&(o.enabled=!0,o.url=s.info.url,o.pushState=s.info.pushState,o.title=s.info.title)})(),i===!1||!t){i!==!1&&console.warn(`[page-agent-sdk/headless] 未含 UI 组件,ui 渲染降级 headless;如需 UI 请 import page-agent-sdk 主包`),m();return}let _=typeof l==`string`?document.querySelector(l):l;if(!_)throw Error(`createChatSdk: 挂载点未找到(${l})`);u=t({el:_,core:c,dialogCfg:d,i18n:e.i18n,debug:e.debug===!0,streaming:r,runSerial:c.runSerial,hide:g,unmount:h,onDialogUnmounted:()=>{u=null,c.release()}}),d.drawer===!0&&d.drawerHidden===!0&&u.hide(),m()}function h(){c.abortAllActive(),c.resolveConflict(`keep_external`),f&&typeof window<`u`&&window.removeEventListener(`pagehide`,f),p&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,p),f=null,p=null,s?.dispose(),s=null,u?u.unmount():c.release()}function g(){u?.hide()}function _(){u?.show()}return{mount:m,unmount:h,hide:g,show:_,send:(e,t)=>c.runSerial(async()=>{let{controller:n,untrack:r}=c.trackActive(t?.signal);try{return await c.send(e,{...t,signal:n.signal})}finally{r()}}),batch:(e,t,n)=>c.runSerial(async()=>{let{controller:r,untrack:i}=c.trackActive(n);try{return await c.batch(e,t,r.signal)}finally{i()}}),switchSession:(...e)=>c.runSerial(async()=>(c.abortAllActive(),c.switchSession(...e))),async exportSession(e){return c.runSerial(()=>c.exportSession(e))},async importSession(e){return c.runSerial(()=>c.importSession(e))},resetSession:()=>c.resetSession(),sessions:c.sessions,async listSessions(){return c.store?c.store.listSessions(n):[]},async deleteSession(e){if(c.store){if(e===c.sessionId){console.warn(`[page-agent-sdk] deleteSession 忽略:不能删除当前会话,请先 switchSession 切到其他会话`);return}await c.store.deleteSession(n,e),await c.refreshSessions()}},get sessionId(){return c.sessionId},stream:(e,t,n)=>c.stream(e,t,n),afterRound:c.afterRound,clearCodeReuse:()=>c.clearCodeReuse(),get debugLogs(){return c.agent.debugLogs},infoTick:c.infoTick,inspect:c.getInfo,exportDiagnostics:()=>c.exportDiagnostics(),inspectContext:()=>c.getInfo().context,getMission:c.getMission,setMission:c.setMission,getFocus:c.getFocus,getFocuses:c.getFocuses,setFocus:c.setFocus,addFocus:c.addFocus,removeFocus:c.removeFocus,clearFocus:c.clearFocus,setQuote:c.setQuote,clearQuote:c.clearQuote,notifyHostChange:c.notifyHostChange,resolveProposal:c.resolveProposal,get proposals(){return c.getProposals()},messages:c.messages,restoreLastCheckpoint:()=>c.checkpoint?.restore()??!1,listCheckpoints:()=>c.checkpoint?.list()??[],hook:e=>(c.listeners.add(e),()=>c.listeners.delete(e)),setData:e=>{if(!c.dataOpsController){console.warn(`[page-agent-sdk] setData 忽略:dataOps 已关闭(capabilities.dataOps:false)`);return}c.dataOpsController.set(e),c.infoTick.value++,c.emit({type:`data_change`,operation:`set`,value:e.bind})},getData:()=>c.liveData(),setSkills:e=>{let t=c.skillsController;if(!t){console.warn(`[page-agent-sdk] setSkills 忽略:skills 已关闭(capabilities.skills:false)`);return}t.set(e),c.unloadSkillTools?.(),c.infoTick.value++},addSkill:e=>{if(!c.skillsController){console.warn(`[page-agent-sdk] addSkill 忽略:skills 已关闭(capabilities.skills:false)`);return}c.addSkill(e),c.unloadSkillTools?.(e.name)},removeSkill:e=>{if(!c.skillsController)return console.warn(`[page-agent-sdk] removeSkill 忽略:skills 已关闭(capabilities.skills:false)`),!1;let t=c.removeSkill(e);return t&&c.unloadSkillTools?.(e),t},listUserSkills:()=>c.listUserSkills(),getUserSkill:e=>c.getUserSkill(e),invalidateSkillCache:e=>{let t=c.skillsController;if(!t){console.warn(`[page-agent-sdk] invalidateSkillCache 忽略:skills 已关闭(capabilities.skills:false)`);return}t.invalidateCache(e),c.unloadSkillTools?.(e)},exportData:()=>{let e=c.liveData()?.bind;return e==null?null:JSON.parse(JSON.stringify(e))},importData:(e,t)=>{let n=c.liveData();if(!n||!c.dataOpsController)return{ok:!1,error:`dataOps 未开启或无主数据`};let r=n.bind;if(typeof r!=`object`||!r)return{ok:!1,error:`主数据 bind 非对象,无法就地还原(集成方应用对象包裹)`};if(t?.validate!==!1){let t=n.schema.safeParse(e);if(!t.success)return{ok:!1,error:`schema 校验失败:`+(t.error?.message??`未知错误`)}}return eJ(r,e),c.dataOpsController?.markDataDirty?.(),t?.emit!==!1&&c.emit({type:`data_change`,operation:`set`,value:r}),{ok:!0}},vfsWrite:(e,t)=>{let n=typeof t==`string`?t:JSON.stringify(t);c.vfsStore.files[$1(e)]={content:n,updatedAt:Date.now()}},vfsRead:e=>c.vfsStore.files[$1(e)]?.content,createResource:(e,t)=>{let n=c.dataOpsController;if(!n?.createResource)throw Error(`[page-agent-sdk] createResource 不可用:需配 data.resources + vfsStore(capabilities.vfs 默认开)`);return n.createResource(e,t)},getResource:e=>c.dataOpsController?.getResource?.(e),updateResource:(e,t)=>{let n=c.dataOpsController;if(!n?.updateResource)throw Error(`[page-agent-sdk] updateResource 不可用:需配 data.resources + vfsStore`);n.updateResource(e,t)},deleteResource:e=>c.dataOpsController?.deleteResource?.(e)??!1,listResources:()=>c.dataOpsController?.listResources?.()??[],releaseResources:e=>{let t=c.dataOpsController;if(!(!t?.listResources||!t.deleteResource))if(e&&e.length)for(let n of e)t.deleteResource(n);else for(let e of t.listResources())t.deleteResource(e.path)},usage:c.usage,pendingConflict:c.pendingConflict,resolveConflict:e=>c.resolveConflict(e),setTools:e=>c.setTools(e),addTool:e=>c.addTool(e),removeTool:e=>c.removeTool(e),setLlm:e=>c.setLlm(e),setMemory:e=>c.setMemory(e),refreshMemory:()=>c.refreshMemory(),setSubagents:e=>c.setSubagents(e),addSubagent:e=>c.addSubagent(e),removeSubagent:e=>c.removeSubagent(e),getActiveSubagents:()=>c.getActiveSubagents(),get subagentHistory(){return c.subagentHistory}}}var S3=(e,t)=>{let{o:n,i:r,u:i}=e,a=n,o,s=(e,t)=>{let n=a,s=e,c=t||(r?!r(n,s):n!==s);return(c||i)&&(a=s,o=n),[a,c,o]};return[t?e=>s(t(a,o),e):s,e=>[a,!!e,o]]},C3=typeof window<`u`&&typeof HTMLElement<`u`&&window.document?window:{},w3=Math.max,Bge=Math.min,T3=Math.round,E3=Math.abs,D3=Math.sign,O3=C3.cancelAnimationFrame,k3=C3.requestAnimationFrame,A3=C3.setTimeout,j3=C3.clearTimeout,M3=e=>C3[e]===void 0?void 0:C3[e],Vge=M3(`MutationObserver`),N3=M3(`IntersectionObserver`),P3=M3(`ResizeObserver`),F3=M3(`ScrollTimeline`),I3=e=>e===void 0,L3=e=>e===null,R3=e=>typeof e==`number`,z3=e=>typeof e==`string`,B3=e=>typeof e==`boolean`,V3=e=>typeof e==`function`,H3=e=>Array.isArray(e),U3=e=>typeof e==`object`&&!H3(e)&&!L3(e),W3=e=>{let t=!!e&&e.length,n=R3(t)&&t>-1&&t%1==0;return H3(e)||!V3(e)&&n?t>0&&U3(e)?t-1 in e:!0:!1},G3=e=>!!e&&e.constructor===Object,K3=e=>e instanceof HTMLElement,q3=e=>e instanceof Element;function J3(e,t){if(W3(e))for(let n=0;n<e.length&&t(e[n],n,e)!==!1;n++);else e&&J3(Object.keys(e),(n=>t(e[n],n,e)));return e}var Y3=(e,t)=>e.indexOf(t)>=0,X3=(e,t)=>e.concat(t),Z3=(e,t,n)=>(!z3(t)&&W3(t)?Array.prototype.push.apply(e,t):e.push(t),e),Q3=e=>Array.from(e||[]),$3=e=>H3(e)?e:!z3(e)&&W3(e)?Q3(e):[e],e6=e=>!!e&&!e.length,t6=e=>Q3(new Set(e)),n6=(e,t,n)=>{J3(e,e=>!e||e.apply(void 0,t||[])),n||(e.length=0)},r6=`paddingTop`,i6=`paddingRight`,a6=`paddingLeft`,o6=`paddingBottom`,s6=`marginLeft`,c6=`marginRight`,l6=`marginBottom`,u6=`overflowX`,d6=`overflowY`,f6=`width`,p6=`height`,m6=`visible`,h6=`hidden`,g6=`scroll`,Hge=e=>{let t=String(e||``);return t?t[0].toUpperCase()+t.slice(1):``},_6=(e,t,n,r)=>{if(e&&t){let r=!0;return J3(n,(n=>{e[n]!==t[n]&&(r=!1)})),r}return!1},v6=(e,t)=>_6(e,t,[`w`,`h`]),y6=(e,t)=>_6(e,t,[`x`,`y`]),Uge=(e,t)=>_6(e,t,[`t`,`r`,`b`,`l`]),b6=(e,...t)=>e.bind(0,...t),x6=e=>{let t,n=e?A3:k3,r=e?j3:O3;return[i=>{r(t),t=n((()=>i()),V3(e)?e():e)},()=>r(t)]},S6=e=>{let t=V3(e)?e():e;if(R3(t)){let e=t?A3:k3,n=t?j3:O3;return r=>{let i=e((()=>r()),t);return()=>{n(i)}}}return t&&t._},C6=(e,t)=>{let{p:n,v:r,S:i,m:a}=t||{},o,s,c,l,u=function(t){s&&s(),o&&o(),l=s=o=c=void 0,e.apply(this,t)},d=e=>a&&c?a(c,e):e,f=()=>{s&&c&&u(d(c)||c)},p=function(){let e=Q3(arguments),t=S6(n);if(t){let n=typeof i==`function`?i():i,a=S6(r),p=d(e)||e,m=u.bind(0,p);s&&s(),n&&!l?(m(),l=!0,s=t((()=>l=void 0))):(s=t(m),a&&!o&&(o=a(f))),c=p}else u(e)};return p.O=f,p},w6=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),T6=e=>e?Object.keys(e):[],E6=(e,t,n,r,i,a,o)=>{let s=[t,n,r,i,a,o];return(typeof e!=`object`||L3(e))&&!V3(e)&&(e={}),J3(s,(t=>{J3(t,((n,r)=>{let i=t[r];if(e===i)return!0;let a=H3(i);if(i&&G3(i)){let t=e[r],n=t;a&&!H3(t)?n=[]:!a&&!G3(t)&&(n={}),e[r]=E6(n,i)}else e[r]=a?i.slice():i}))})),e},D6=(e,t)=>J3(E6({},e),((e,t,n)=>{e===void 0?delete n[t]:e&&G3(e)&&(n[t]=D6(e))})),O6=e=>!T6(e).length,k6=()=>{},A6=(e,t,n)=>w3(e,Bge(t,n)),j6=e=>t6((H3(e)?e:(e||``).split(` `)).filter((e=>e))),M6=(e,t)=>e&&e.getAttribute(t),N6=(e,t)=>e&&e.hasAttribute(t),P6=(e,t,n)=>{J3(j6(t),(t=>{e&&e.setAttribute(t,String(n||``))}))},F6=(e,t)=>{J3(j6(t),(t=>e&&e.removeAttribute(t)))},I6=(e,t)=>{let n=j6(M6(e,t)),r=b6(P6,e,t),i=(e,t)=>{let r=new Set(n);return J3(j6(e),(e=>{r[t](e)})),Q3(r).join(` `)};return{C:e=>r(i(e,`delete`)),$:e=>r(i(e,`add`)),H:e=>{let t=j6(e);return t.reduce(((e,t)=>e&&n.includes(t)),t.length>0)}}},L6=(e,t,n)=>(I6(e,t).C(n),b6(R6,e,t,n)),R6=(e,t,n)=>(I6(e,t).$(n),b6(L6,e,t,n)),z6=(e,t,n,r)=>(r?R6:L6)(e,t,n),B6=(e,t,n)=>I6(e,t).H(n),V6=e=>I6(e,`class`),H6=(e,t)=>{V6(e).C(t)},U6=(e,t)=>(V6(e).$(t),b6(H6,e,t)),W6=(e,t)=>{let n=t?q3(t)&&t:document;return n?Q3(n.querySelectorAll(e)):[]},Wge=(e,t)=>{let n=t?q3(t)&&t:document;return n&&n.querySelector(e)},G6=(e,t)=>q3(e)&&e.matches(t),K6=e=>G6(e,`body`),q6=e=>e?Q3(e.childNodes):[],J6=e=>e&&e.parentElement,Y6=(e,t)=>q3(e)&&e.closest(t),X6=e=>document.activeElement,Gge=(e,t,n)=>{let r=Y6(e,t),i=e&&Wge(n,r),a=Y6(i,t)===r;return r&&i?r===e||i===e||a&&Y6(Y6(e,n),t)!==r:!1},Z6=e=>{J3($3(e),(e=>{let t=J6(e);e&&t&&t.removeChild(e)}))},Q6=(e,t)=>b6(Z6,e&&t&&J3($3(t),(t=>{t&&e.appendChild(t)}))),$6,Kge=()=>$6,qge=e=>{$6=e},e8=e=>{let t=document.createElement(`div`);return P6(t,`class`,e),t},t8=e=>{let t=e8(),n=Kge(),r=e.trim();return t.innerHTML=n?n.createHTML(r):r,J3(q6(t),(e=>Z6(e)))},n8=(e,t)=>e.getPropertyValue(t)||e[t]||``,r8=e=>{let t=e||0;return isFinite(t)?t:0},i8=e=>r8(parseFloat(e||``)),a8=e=>Math.round(e*1e4)/1e4,o8=e=>`${a8(r8(e))}px`;function s8(e,t){e&&t&&J3(t,((t,n)=>{try{let r=e.style,i=L3(t)||B3(t)?``:R3(t)?o8(t):t;n.indexOf(`--`)===0?r.setProperty(n,i):r[n]=i}catch{}}))}function c8(e,t,n){let r=z3(t),i=r?``:{};if(e){let a=C3.getComputedStyle(e,n)||e.style;i=r?n8(a,t):Q3(t).reduce(((e,t)=>(e[t]=n8(a,t),e)),i)}return i}var l8=(e,t,n)=>{let r=t?`${t}-`:``,i=n?`-${n}`:``,a=`${r}top${i}`,o=`${r}right${i}`,s=`${r}bottom${i}`,c=`${r}left${i}`,l=c8(e,[a,o,s,c]);return{t:i8(l[a]),r:i8(l[o]),b:i8(l[s]),l:i8(l[c])}},u8=(e,t)=>`translate${U3(e)?`(${e.x},${e.y})`:`${t?`X`:`Y`}(${e})`}`,Jge=e=>!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length),Yge={w:0,h:0},d8=(e,t)=>t?{w:t[`${e}Width`],h:t[`${e}Height`]}:Yge,Xge=e=>d8(`inner`,e||C3),f8=b6(d8,`offset`),p8=b6(d8,`client`),m8=b6(d8,`scroll`),h8=e=>{let t=parseFloat(c8(e,f6))||0,n=parseFloat(c8(e,p6))||0;return{w:t-T3(t),h:n-T3(n)}},g8=e=>e.getBoundingClientRect(),Zge=e=>!!e&&Jge(e),_8=e=>!!(e&&(e[p6]||e[f6])),v8=(e,t)=>{let n=_8(e);return!_8(t)&&n},y8=(e,t,n,r)=>{J3(j6(t),(t=>{e&&e.removeEventListener(t,n,r)}))},b8=(e,t,n,r)=>{let i=(r&&r.D)??!0,a=r&&r.I||!1,o=r&&r.A||!1,s={passive:i,capture:a};return b6(n6,j6(t).map((t=>{let r=o?i=>{y8(e,t,r,a),n&&n(i)}:n;return e&&e.addEventListener(t,r,s),b6(y8,e,t,r,a)})))},x8=e=>e.stopPropagation(),S8=e=>e.preventDefault(),C8=e=>x8(e)||S8(e),w8=(e,t)=>{let{x:n,y:r}=R3(t)?{x:t,y:t}:t||{};R3(n)&&(e.scrollLeft=n),R3(r)&&(e.scrollTop=r)},T8=e=>({x:e.scrollLeft,y:e.scrollTop}),E8=()=>({T:{x:0,y:0},k:{x:0,y:0}}),Qge=(e,t)=>{let{T:n,k:r}=e,{w:i,h:a}=t,o=(e,t,n)=>{let r=D3(e)*n,i=D3(t)*n;if(r===i){let n=E3(e),a=E3(t);i=n>a?0:i,r=n<a?0:r}return r=r===i?0:r,[r+0,i+0]},[s,c]=o(n.x,r.x,i),[l,u]=o(n.y,r.y,a);return{T:{x:s,y:l},k:{x:c,y:u}}},D8=({T:e,k:t})=>{let n=(e,t)=>e===0&&e<=t;return{x:n(e.x,t.x),y:n(e.y,t.y)}},O8=({T:e,k:t},n)=>{let r=(e,t,n)=>A6(0,1,(e-n)/(e-t)||0);return{x:r(e.x,t.x,n.x),y:r(e.y,t.y,n.y)}},k8=e=>{e&&e.focus&&e.focus({preventScroll:!0,focusVisible:!1})},A8=(e,t)=>{J3($3(t),e)},j8=e=>{let t=new Map,n=(e,n)=>{if(e){let r=t.get(e);A8((e=>{r&&r[e?`delete`:`clear`](e)}),n)}else t.forEach((e=>{e.clear()})),t.clear()},r=(e,i)=>{if(z3(e)){let r=t.get(e)||new Set;return t.set(e,r),A8((e=>{V3(e)&&r.add(e)}),i),b6(n,e,i)}B3(i)&&i&&n();let a=T6(e),o=[];return J3(a,(t=>{let n=e[t];n&&Z3(o,r(t,n))})),b6(n6,o)};return r(e||{}),[r,n,(e,n)=>{J3(Q3(t.get(e)),(e=>{n&&!e6(n)?e.apply(0,n):e()}))}]},M8={},N8={},$ge=e=>{J3(e,(e=>J3(e,((t,n)=>{M8[n]=e[n]}))))},P8=(e,t,n)=>T6(e).map((r=>{let{static:i,instance:a}=e[r],[o,s,c]=n||[],l=n?a:i;if(l){let e=n?l(o,s,t):l(t);return(c||N8)[r]=e}})),e_e=(e,t)=>e[t],F8=e=>e_e(N8,e),t_e=`__osOptionsValidationPlugin`,I8=`data-overlayscrollbars`,L8=`os-environment`,R8=`${L8}-scrollbar-hidden`,z8=`${I8}-initialize`,B8=`noClipping`,V8=`${I8}-body`,H8=I8,n_e=`host`,U8=`${I8}-viewport`,r_e=u6,i_e=d6,a_e=`arrange`,W8=`measuring`,o_e=`scrolling`,G8=`scrollbarHidden`,s_e=`noContent`,K8=`${I8}-padding`,q8=`${I8}-content`,J8=`os-size-observer`,c_e=`${J8}-appear`,Y8=`${J8}-listener`;`${Y8}`,`${Y8}`;var l_e=`os-trinsic-observer`,u_e=`os-theme-none`,X8=`os-scrollbar`,d_e=`${X8}-rtl`,f_e=`${X8}-horizontal`,p_e=`${X8}-vertical`,Z8=`${X8}-track`,Q8=`${X8}-handle`,m_e=`${X8}-visible`,h_e=`${X8}-cornerless`,$8=`${X8}-interaction`,e5=`${X8}-unusable`,t5=`${X8}-auto-hide`,g_e=`${t5}-hidden`,n5=`${X8}-wheel`,__e=`${Z8}-interactive`,v_e=`${Q8}-interactive`,y_e=`__osSizeObserverPlugin`,b_e=(e,t)=>{let{M:n}=t,[r,i]=e(`showNativeOverlaidScrollbars`);return[r&&n.x&&n.y,i]},r5=e=>e.indexOf(m6)===0,x_e=e=>e.replace(`${m6}-`,``),i5=(e,t)=>{if(e===`auto`)return t?g6:h6;let n=e||h6;return[h6,g6,m6].includes(n)?n:h6},S_e=(e,t)=>{let{overflowX:n,overflowY:r}=c8(e,[u6,d6]);return{x:i5(n,t.x),y:i5(r,t.y)}},a5=`__osScrollbarsHidingPlugin`,C_e=`__osClickScrollPlugin`,o5=e=>JSON.stringify(e,((e,t)=>{if(V3(t))throw 0;return t})),s5=(e,t)=>e?`${t}`.split(`.`).reduce(((e,t)=>e&&w6(e,t)?e[t]:void 0),e):void 0,w_e=[0,33],c5=[33,99],l5=[222,666,!0],T_e={paddingAbsolute:!1,showNativeOverlaidScrollbars:!1,update:{elementEvents:[[`img`,`load`]],debounce:{mutation:w_e,resize:null,event:c5,env:l5},attributes:null,ignoreMutation:null,flowDirectionStyles:null},overflow:{x:`scroll`,y:`scroll`},scrollbars:{theme:`os-theme-dark`,visibility:`auto`,autoHide:`never`,autoHideDelay:1300,autoHideSuspend:!1,dragScroll:!0,clickScroll:!1,pointers:[`mouse`,`touch`,`pen`]}},u5=(e,t)=>{let n={};return J3(X3(T6(t),T6(e)),(r=>{let i=e[r],a=t[r];if(U3(i)&&U3(a))E6(n[r]={},u5(i,a)),O6(n[r])&&delete n[r];else if(w6(t,r)&&a!==i){let e=!0;if(H3(i)||H3(a))try{o5(i)===o5(a)&&(e=!1)}catch{}e&&(n[r]=a)}})),n},d5=(e,t,n)=>r=>[s5(e,r),n||s5(t,r)!==void 0],f5,E_e=()=>f5,D_e=e=>{f5=e},p5,O_e=()=>{let e=(e,t,n)=>{Q6(document.body,e),Q6(document.body,e);let r=p8(e),i=f8(e),a=h8(t);return n&&Z6(e),{x:i.h-r.h+a.h,y:i.w-r.w+a.w}},t=e=>{let t=!1,n=U6(e,R8);try{t=c8(e,`scrollbar-width`)===`none`||c8(e,`display`,`::-webkit-scrollbar`)===`none`}catch{}return n(),t},n=t8(`<div class="${L8}"><div></div><style>${`.${L8}{scroll-behavior:auto!important;position:fixed;opacity:0;visibility:hidden;overflow:scroll;height:200px;width:200px;z-index:-1}.${L8} div{width:200%;height:200%;margin:10px 0}.${R8}{scrollbar-width:none!important}.${R8}::-webkit-scrollbar,.${R8}::-webkit-scrollbar-corner{appearance:none!important;display:none!important;width:0!important;height:0!important}`}</style></div>`)[0],r=n.firstChild,i=n.lastChild,a=E_e();a&&(i.nonce=a);let[o,,s]=j8(),[c,l]=S3({o:e(n,r),i:y6},b6(e,n,r,!0)),[u]=l(),d=t(n),f={x:u.x===0,y:u.y===0},p={elements:{host:null,padding:!d,viewport:e=>d&&K6(e)&&e,content:!1},scrollbars:{slot:!0},cancel:{nativeScrollbarsOverlaid:!1,body:null}},m=E6({},T_e),h=b6(E6,{},m),g=b6(E6,{},p),_={U:u,M:f,P:d,J:!!F3,G:b6(o,`r`),K:g,Z:e=>E6(p,e)&&g(),tt:h,nt:e=>E6(m,e)&&h(),ot:E6({},p),st:E6({},m)};if(F6(n,`style`),Z6(n),b8(C3,`resize`,(()=>{s(`r`,[])})),V3(C3.matchMedia)&&!d&&(!f.x||!f.y)){let e=t=>{b8(C3.matchMedia(`(resolution: ${C3.devicePixelRatio}dppx)`),`change`,(()=>{t(),e(t)}),{A:!0})};e((()=>{let[e,t]=c();E6(_.U,e),s(`r`,[t])}))}return _},m5=()=>(p5||=O_e(),p5),k_e=(e,t,n)=>{let r=!1,i=n?new WeakMap:!1,a=()=>{r=!0},o=a=>{i&&n&&J3(n.map((t=>{let[n,r]=t||[];return[r&&n?(a||W6)(n,e):[],r]})),(n=>J3(n[0],(a=>{let o=n[1],s=i.get(a)||[];if(e.contains(a)&&o){let e=b8(a,o,(n=>{r?(e(),i.delete(a)):t(n)}));i.set(a,Z3(s,e))}else n6(s),i.delete(a)}))))};return o(),[a,o]},h5=(e,t,n,r)=>{let i=!1,{et:a,ct:o,rt:s,it:c,lt:l,ut:u}=r||{},[d,f]=k_e(e,(()=>i&&n(!0)),s),p=a||[],m=o||[],h=X3(p,m),g=(i,a)=>{if(!e6(a)){let o=l||k6,s=u||k6,d=[],p=[],h=!1,g=!1;if(J3(a,(n=>{let{attributeName:i,target:a,type:l,oldValue:u,addedNodes:f,removedNodes:_}=n,v=l===`attributes`,y=l===`childList`,b=e===a,x=v&&i,S=x&&M6(a,i||``),C=z3(S)?S:null,w=x&&u!==C,T=Y3(m,i)&&w;if(t&&(y||!b)){let t=v&&w,l=t&&c&&G6(a,c),p=(l?!o(a,i,u,C):!v||t)&&!s(n,!!l,e,r);J3(f,(e=>Z3(d,e))),J3(_,(e=>Z3(d,e))),g||=p}!t&&b&&w&&!o(a,i,u,C)&&(Z3(p,i),h||=T)})),f((e=>t6(d).reduce(((t,n)=>(Z3(t,W6(e,n)),G6(n,e)?Z3(t,n):t)),[]))),t)return!i&&g&&n(!1),[!1];if(!e6(p)||h){let e=[t6(p),h];return i||n.apply(0,e),e}}},_=new Vge(b6(g,!1));return[()=>(_.observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:h,subtree:t,childList:t,characterData:t}),i=!0,()=>{i&&=(d(),_.disconnect(),!1)}),()=>{if(i)return g(!0,_.takeRecords())}]},g5=null,_5=(e,t,n)=>{let{ft:r}=n||{},i=F8(y_e),[a]=S3({o:!1,u:!0});return()=>{let n=[],o=t8(`<div class="${J8}"><div class="${Y8}"></div></div>`)[0],s=o.firstChild,c=e=>{let n=H3(e)&&!e6(e),r=!1,i=!1;if(n){let t=e[0],[n,,o]=a(t.contentRect),s=_8(n);i=v8(n,o),r=!i&&!s}else i=e===!0;r||t({_t:!0,ft:i})};if(P3){if(!B3(g5)){let t=new P3(k6);t.observe(e,{get box(){g5=!0}}),g5||=!1,t.disconnect()}let t=C6(c,{p:0,v:0}),r=e=>t(e),i=new P3(r);if(i.observe(g5?e:s),Z3(n,[()=>{i.disconnect()},!g5&&Q6(e,o)]),g5){let t=new P3(r);t.observe(e,{box:`border-box`}),Z3(n,(()=>t.disconnect()))}}else if(i){let[t,a]=i(s,c,r);Z3(n,X3([U6(o,c_e),b8(o,`animationstart`,t),Q6(e,o)],a))}else return k6;return b6(n6,n)}},A_e=(e,t)=>{let n,r=e=>e.h===0||e.isIntersecting||e.intersectionRatio>0,i=e8(l_e),[a]=S3({o:!1}),o=(e,n)=>{if(e){let i=a(r(e)),[,o]=i;return o&&!n&&t(i)&&[i]}},s=(e,t)=>o(t.pop(),e);return[()=>{let t=[];if(N3)n=new N3(b6(s,!1),{root:e}),n.observe(i),Z3(t,(()=>{n.disconnect()}));else{let e=()=>{let e=f8(i);o(e)};Z3(t,_5(i,e)()),e()}return b6(n6,Z3(t,Q6(e,i)))},()=>n&&s(!0,n.takeRecords())]},j_e=(e,t,n,r)=>{let i,a,o,s,c,l,u,d,f=`[${H8}]`,p=`[${U8}]`,m=[`id`,`class`,`style`,`open`,`wrap`,`cols`,`rows`],{dt:h,vt:g,L:_,gt:v,ht:y,V:b,bt:x,yt:S,wt:C,St:w}=e,T=e=>c8(e,`direction`)===`rtl`,E=()=>{let e,t,n,i=C6(r,{p:()=>e,v:()=>t,S:()=>n,m(e,t){let[n]=e,[r]=t;return[X3(T6(n),T6(r)).reduce(((e,t)=>(e[t]=n[t]||r[t],e)),{})]}}),a=(r,a)=>{if(H3(a)){let[r,i,o]=a;e=r,t=i,n=o}else R3(a)?(e=a,t=!1,n=!1):(e=!1,t=!1,n=!1);i(r)};return a.O=i.O,a},D={Ot:!1,B:T(h)},O=m5(),ee=F8(a5),[k]=S3({i:v6,o:{w:0,h:0}},(()=>{let r=ee&&ee.R(e,t,D,O,n).Y,i=!(x&&b)&&B6(g,H8,B8),a=!b&&S(a_e),o=a&&T8(v),s=o&&w(),c=C(W8,i),l=a&&r&&r(),u=m8(_),d=h8(_);return l&&l(),w8(v,o),s&&s(),i&&c(),{w:u.w+d.w,h:u.h+d.h}})),A=E(),j=e=>{let t=T(h);E6(e,{Ct:d!==t}),E6(D,{B:t}),d=t},te=(e,t)=>{let[n,i]=e,a={$t:i};return E6(D,{Ot:n}),t||r(a),a},ne=({_t:e,ft:t})=>{let n=t?r:A,i={_t:e||t,ft:t};j(i),n(i,a)},re=(e,t)=>{let[,n]=k(),r={xt:n};return j(r),n&&!t&&A(r,e?o:i),r},M=(e,t,n)=>{let r={Ht:t};return j(r),t&&!n&&A(r,i),r},[ie,ae]=y?A_e(g,te):[],oe=!b&&_5(g,ne,{ft:!0}),[se,ce]=h5(g,!1,M,{ct:m,et:m}),le=b&&P3&&new P3((e=>{let t=e[e.length-1].contentRect;ne({_t:!0,ft:v8(t,u)}),u=t}));return[()=>{le&&le.observe(g);let e=oe&&oe(),t=ie&&ie(),n=se(),r=O.G((e=>{let[,t]=k();A({Et:e,xt:t,_t:x},s)}));return()=>{le&&le.disconnect(),e&&e(),t&&t(),l&&l(),n(),r()}},({Dt:e,zt:t,It:n})=>{let r={},[u]=e(`update.ignoreMutation`),[d,h]=e(`update.attributes`),[g,v]=e(`update.elementEvents`),[x,S]=e(`update.debounce`),C=v||h,w=t||n,T=e=>V3(u)&&!!u(e);if(C){c&&c(),l&&l();let[e,t]=h5(y||_,!0,re,{et:X3(m,d||[]),rt:g,it:f,ut:(e,t)=>{let{target:n,attributeName:r}=e;return(!t&&r&&!b?Gge(n,f,p):!1)||!!Y6(n,`.${X8}`)||T(e)}});l=e(),c=t}if(S&&(A.O(),H3(x)||R3(x)?(i=x,a=!1,o=c5,s=l5):G3(x)?(i=x.mutation,a=x.resize,o=x.event,s=x.env):(i=!1,a=!1,o=!1,s=!1)),w){let e=ce(),t=ae&&ae(),n=c&&c();e&&E6(r,M(e[0],e[1],w)),t&&E6(r,te(t[0],w)),n&&E6(r,re(n[0],w))}return j(r),r},D]},v5=(e,t)=>V3(t)?t.apply(0,e):t,M_e=(e,t,n,r)=>v5(e,I3(r)?n:r)||t.apply(0,e),y5=(e,t,n,r)=>{let i=v5(e,I3(r)?n:r);return!!i&&(K3(i)?i:t.apply(0,e))},N_e=(e,t)=>{let{nativeScrollbarsOverlaid:n,body:r}=t||{},{M:i,P:a,K:o}=m5(),{nativeScrollbarsOverlaid:s,body:c}=o().cancel,l=n??s,u=I3(r)?c:r,d=(i.x||i.y)&&l,f=e&&(L3(u)?!a:u);return!!d||!!f},P_e=(e,t,n,r)=>{let{K:i}=m5(),{scrollbars:a}=i(),{slot:o}=a,{dt:s,vt:c,L:l,At:u,gt:d,bt:f,V:p}=t,{scrollbars:m}=u?{}:e,{slot:h}=m||{},g=[],_=[],v=[],y=y5([s,c,l],(()=>p&&f?s:c),o,h),b=e=>{if(F3){let t=null,r=[],i=new F3({source:d,axis:e}),a=()=>{t&&t.cancel(),t=null};return{Mt:o=>{let{Tt:s}=n,c=D8(s)[e],l=e===`x`,u=[u8(0,l),u8(`calc(-100% + 100cq${l?`w`:`h`})`,l)],d=c?u:u.reverse();return r[0]===d[0]&&r[1]===d[1]?a:(r=d,a(),t=o.kt.animate({clear:[`left`],transform:d},{timeline:i}),a)}}}},x={x:b(`x`),y:b(`y`)},S=()=>{let{Rt:e,Vt:t}=n,r=(e,t)=>A6(0,1,e/(e+t)||0);return{x:r(t.x,e.x),y:r(t.y,e.y)}},C=(e,t,n)=>{let r=n?U6:H6;J3(e,(e=>{r(e.Lt,t)}))},w=(e,t)=>{J3(e,(e=>{let[n,r]=t(e);s8(n,r)}))},T=(e,t,n)=>{let r=B3(n),i=!r||n,a=!r||!n;i&&C(_,e,t),a&&C(v,e,t)},E=()=>{let e=S(),t=e=>t=>[t.Lt,{"--os-viewport-percent":a8(e)+``}];w(_,t(e.x)),w(v,t(e.y))},D=()=>{if(!F3){let{Tt:e}=n,t=O8(e,T8(d)),r=e=>t=>[t.Lt,{"--os-scroll-percent":a8(e)+``}];w(_,r(t.x)),w(v,r(t.y))}},O=()=>{let{Tt:e}=n,t=D8(e),r=e=>t=>[t.Lt,{"--os-scroll-direction":e?`0`:`1`}];w(_,r(t.x)),w(v,r(t.y)),F3&&(_.forEach(x.x.Mt),v.forEach(x.y.Mt))},ee=()=>{if(p&&!f){let{Rt:e,Tt:t}=n,r=D8(t),i=O8(t,T8(d)),a=t=>{let{Lt:n}=t,a=J6(n)===l&&n,o=(e,t,n)=>{let r=t*e;return o8(n?r:-r)};return[a,a&&{transform:u8({x:o(i.x,e.x,r.x),y:o(i.y,e.y,r.y)})}]};w(_,a),w(v,a)}},k=e=>{let t=e?`x`:`y`,n=e8(`${X8} ${e?f_e:p_e}`),i=e8(Z8),a=e8(Q8),o={Lt:n,Pt:i,kt:a},s=x[t];return Z3(e?_:v,o),Z3(g,[Q6(n,i),Q6(i,a),b6(Z6,n),s&&s.Mt(o),r(o,T,e)]),o},A=b6(k,!0),j=b6(k,!1);return A(),j(),[{Ut:E,Nt:D,qt:O,Bt:ee,Ft:T,jt:{Xt:_,Yt:A,Wt:b6(w,_)},Jt:{Xt:v,Yt:j,Wt:b6(w,v)}},()=>(Q6(y,_[0].Lt),Q6(y,v[0].Lt),b6(n6,g))]},F_e=(e,t,n,r,i)=>(a,o,s)=>{let{vt:c,L:l,V:u,gt:d,Gt:f,St:p}=t,{Lt:m,Pt:h,kt:g}=a,[_,v]=x6(333),[y,b]=x6(444),x=e=>{V3(d.scrollBy)&&d.scrollBy({behavior:`smooth`,left:e.x,top:e.y})},S=()=>{let t=`pointerup pointercancel lostpointercapture`,i=`client${s?`X`:`Y`}`,a=s?f6:p6,o=s?`left`:`top`,c=s?`w`:`h`,l=s?`x`:`y`,u=[];return b8(h,`pointerdown`,r((r=>{let m=Y6(r.target,`.${Q8}`)===g,_=m?g:h,v=e.scrollbars,S=v[m?`dragScroll`:`clickScroll`],{button:C,isPrimary:w,pointerType:T}=r,{pointers:E}=v;if(C===0&&w&&S&&(E||[]).includes(T)){n6(u),b();let e=!m&&(r.shiftKey||S===`instant`),v=b6(g8,g),C=b6(g8,h),w=(e,t)=>(e||v())[o]-(t||C())[o],T=T3(g8(d)[a])/f8(d)[c]||1,E=T8(d)[l],D=e=>{w8(d,{[l]:E+e})},O=e=>{let{Rt:t}=n,r=f8(h)[c]-f8(g)[c],i=1/T*e/r;D(i*t[l])},ee=r[i],k=v(),A=C(),j=k[a],te=w(k,A)+j/2,ne=ee-A[o]-te,re=m?0:ne,M=e=>{n6(oe),_.releasePointerCapture(e.pointerId)},ie=m||e,ae=p(),oe=[b8(f,t,M),b8(f,`selectstart`,(e=>S8(e)),{D:!1}),b8(h,t,M),ie&&b8(h,`pointermove`,(e=>O(re+e[i]-ee))),ie&&(()=>{let e=T8(d);ae();let t=T8(d),n={x:t.x-e.x,y:t.y-e.y};(E3(n.x)>3||E3(n.y)>3)&&(p(),w8(d,e),x(n),y(ae))})];if(_.setPointerCapture(r.pointerId),e)O(ne);else if(!m){let e=F8(C_e);if(e){let{Vt:t}=n,r=e(D,O,b6(w),ne,t[l],S,!!s,(e=>{e?ae():Z3(oe,ae)}));Z3(oe,r),Z3(u,b6(r,!0))}}}})))},C=!0;return b6(n6,[b8(g,`pointermove pointerleave`,r(i)),b8(m,`pointerenter`,r((()=>{o($8,!0)}))),b8(m,`pointerleave pointercancel`,r((()=>{o($8,!1)}))),b8(m,`wheel`,r((e=>{let{deltaX:t,deltaY:n,deltaMode:r}=e;C&&r===0&&J6(m)===c&&x({x:t,y:n}),C=!1,o(n5,!0),_((()=>{C=!0,o(n5)})),S8(e)})),{D:!1,I:!0}),!u&&b8(m,`mousedown`,r((()=>{let e=X6();(N6(e,U8)||N6(e,H8)||e===document.body)&&A3(b6(k8,l),25)}))),b8(m,`pointerdown`,(()=>{let e=b8(f,`click`,(e=>{t(),C8(e)}),{A:!0,I:!0,D:!1}),t=b8(f,`pointerup pointercancel`,(()=>{t(),setTimeout(e,150)}),{I:!0,D:!0})}),{I:!0,D:!0}),S(),v,b])},I_e=(e,t,n,r,i,a,o)=>{let s,c,l,u,d,f=k6,p=0,m=[`mouse`,`pen`],h=e=>t=>{n.Kt||e(t)},g=e=>m.includes(e.pointerType),[_,v]=x6(),[y,b]=x6(100),[x,S]=x6(50),[C,w]=x6((()=>p)),[T,E]=P_e(e,a,i,F_e(t,a,i,h,(e=>g(e)&&M()))),{vt:D,Qt:O,bt:ee}=a,{Ft:k,Ut:A,Nt:j,qt:te,Bt:ne}=T,re=(e,t)=>{w();let r=e=>{n.Kt||k(g_e,e)};if(e)r();else{let e=!l||!s;p>0&&!t?C(b6(r,e)):r(e)}},M=()=>{(l?!s:!u)&&(re(!0),y((()=>{re(!1)})))},ie=e=>{g(e)&&(s=!0,!n.Kt&&l&&re(!0))},ae=e=>{g(e)&&(s=!1,!n.Kt&&l&&re(!1))},oe=e=>{k(t5,e,!0),k(t5,e,!1)},se=[w,b,S,v,()=>f(),b8(D,`pointerover`,ie,{A:!0}),b8(D,`pointerenter`,ie),b8(D,`pointerleave`,ae),b8(D,`pointermove`,h((e=>{g(e)&&c&&M()}))),b8(O,`scroll`,h((e=>{_((()=>{j(),M()})),o(e),ne()})))],ce=F8(a5);return[()=>b6(n6,Z3(se,E())),({Dt:e,It:t,Zt:n,tn:a})=>{let{nn:o,sn:s,en:m,cn:g}=a||{},{Ct:_,ft:v}=n||{},{B:y}=r,{M:b,P:S}=m5(),{rn:C,j:w}=i,[T,E]=e(`showNativeOverlaidScrollbars`),[D,M]=e(`scrollbars.theme`),[ie,ae]=e(`scrollbars.visibility`),[se,le]=e(`scrollbars.autoHide`),[ue,de]=e(`scrollbars.autoHideSuspend`),[fe]=e(`scrollbars.autoHideDelay`),[N,P]=e(`scrollbars.dragScroll`),[pe,me]=e(`scrollbars.clickScroll`),[he,ge]=e(`overflow`),F=v&&!t,_e=o||s||g||_||t,ve=m||ae||ge,ye=T&&b.x&&b.y,I=!S&&!ce,be=ye||I,xe=(e,t,n)=>{let r=e.includes(g6)&&(ie===m6||ie===`auto`&&t===g6);return k(m_e,r,n),r};if(p=fe,(E||I)&&k(u_e,be),M&&(k(d),k(D,!0),d=D),(de||F)&&(oe(!ue),F&&ue&&(w.x||w.y?(f(),x((()=>{f=b8(O,g6,h(b6(oe,!0)),{A:!0})}))):oe(!0))),le&&(c=se===`move`,l=se===`leave`,u=se===`never`,re(u,!0)),P&&k(v_e,N),me&&k(__e,!!pe),ve){let e=xe(he.x,C.x,!0),t=xe(he.y,C.y,!1);k(h_e,!(e&&t))}_e&&(j(),A(),ne(),g&&te(),k(e5,!w.x,!0),k(e5,!w.y,!1),k(d_e,y&&!ee))},{},T]},L_e=e=>{let{K:t,P:n}=m5(),{elements:r}=t(),{padding:i,viewport:a,content:o}=r,s=K3(e),c=s?{}:e,{elements:l}=c,{padding:u,viewport:d,content:f}=l||{},p=s?e:c.target,m=K6(p),h=p.ownerDocument,g=h.documentElement,_=()=>h.defaultView||C3,v=b6(M_e,[p]),y=b6(y5,[p]),b=b6(e8,``),x=b6(v,b,a),S=b6(y,b,o),C=e=>{let t=f8(e),n=m8(e),r=c8(e,u6),i=c8(e,d6);return n.w-t.w>0&&!r5(r)||n.h-t.h>0&&!r5(i)},w=x(d),T=w===p,E=T&&m,D=!T&&S(f),O=!T&&w===D,ee=E?g:w,k=E?ee:p,A=!T&&y(b,i,u),j=!O&&D,te=[j,ee,A,k].map((e=>K3(e)&&!J6(e)&&e)),ne=e=>e&&Y3(te,e),re=!ne(ee)&&C(ee)?ee:p,M=E?g:ee,ie={dt:p,vt:k,L:ee,ln:A,ht:j,gt:M,Qt:E?h:ee,an:m?g:re,Gt:h,bt:m,At:s,V:T,un:_,yt:e=>B6(ee,U8,e),wt:(e,t)=>z6(ee,U8,e,t),St:()=>z6(M,U8,o_e,!0)},{dt:ae,vt:oe,ln:se,L:ce,ht:le}=ie,ue=[()=>{F6(oe,[H8,z8]),F6(ae,z8),m&&F6(g,[z8,H8])}],de=q6([le,ce,se,oe,ae].find((e=>e&&!ne(e)))),fe=E?ae:le||ce,N=b6(n6,ue);return[ie,()=>{let e=_(),t=X6(),r=e=>{Q6(J6(e),q6(e)),Z6(e)},i=e=>b8(e,`focusin focusout focus blur`,C8,{I:!0,D:!1}),a=`tabindex`,o=M6(ce,a),s=i(t);return P6(oe,H8,T?``:n_e),P6(se,K8,``),P6(ce,U8,``),P6(le,q8,``),T||(P6(ce,a,o||`-1`),m&&P6(g,V8,``)),Q6(fe,de),Q6(oe,se),Q6(se||oe,!T&&ce),Q6(ce,le),Z3(ue,[s,()=>{let e=X6(),t=ne(ce),n=t&&e===ce?ae:e,s=i(n);F6(se,K8),F6(le,q8),F6(ce,U8),m&&F6(g,V8),o?P6(ce,a,o):F6(ce,a),ne(le)&&r(le),t&&r(ce),ne(se)&&r(se),k8(n),s()}]),n&&!T&&(R6(ce,U8,G8),Z3(ue,b6(F6,ce,U8))),k8(!T&&m&&t===ae&&e.top===e?ce:t),s(),de=0,N},N]},R_e=({ht:e})=>({Zt:t,fn:n,It:r})=>{let{$t:i}=t||{},{Ot:a}=n;e&&(i||r)&&s8(e,{[p6]:a&&`100%`})},z_e=({vt:e,ln:t,L:n,V:r},i)=>{let[a,o]=S3({i:Uge,o:l8()},b6(l8,e,`padding`,``));return({Dt:e,Zt:s,fn:c,It:l})=>{let[u,d]=o(l),{P:f}=m5(),{_t:p,xt:m,Ct:h}=s||{},{B:g}=c,[_,v]=e(`paddingAbsolute`);(p||d||l||m)&&([u,d]=a(l));let y=!r&&(v||h||d);if(y){let e=!_||!t&&!f,r=u.r+u.l,a=u.t+u.b,o={[c6]:e&&!g?-r:0,[l6]:e?-a:0,[s6]:e&&g?-r:0,top:e?-u.t:0,right:e?g?-u.r:`auto`:0,left:e?g?`auto`:-u.l:0,[f6]:e&&`calc(100% + ${r}px)`},s={[r6]:e?u.t:0,[i6]:e?u.r:0,[o6]:e?u.b:0,[a6]:e?u.l:0};s8(t||n,o),s8(n,s),E6(i,{ln:u,_n:!e,F:t?s:E6({},o,s)})}return{dn:y}}},B_e=(e,t)=>{let n=m5(),{vt:r,ln:i,L:a,V:o,Qt:s,gt:c,bt:l,wt:u,un:d}=e,{P:f}=n,p=l&&o,m=b6(w3,0),h={display:()=>!1,direction:e=>e!==`ltr`,flexDirection:e=>e.endsWith(`-reverse`),writingMode:e=>e!==`horizontal-tb`},g=T6(h),_={i:v6,o:{w:0,h:0}},v={i:y6,o:{}},y=e=>{u(W8,!p&&e)},b=()=>c8(a,g),x=(e,t)=>{let n=!T6(e).length,r=t?!0:g.some((t=>{let n=e[t];return z3(n)&&h[t](n)}));if(n||!r||!Zge(a))return{T:{x:0,y:0},k:{x:1,y:1}};y(!0);let i=T8(c),o=b8(s,g6,(e=>{let t=T8(c);e.isTrusted&&t.x===i.x&&t.y===i.y&&x8(e)}),{I:!0,A:!0}),l=u(s_e,!0);w8(c,{x:0,y:0}),l();let d=T8(c),f=m8(c);w8(c,{x:f.w,y:f.h});let p=T8(c),m={x:p.x-d.x,y:p.y-d.y};w8(c,{x:-f.w,y:-f.h});let _=T8(c),v={x:_.x-d.x,y:_.y-d.y},b={x:E3(m.x)>=E3(v.x)?p.x:_.x,y:E3(m.y)>=E3(v.y)?p.y:_.y};return w8(c,i),k3((()=>o())),{T:d,k:b}},S=(e,t)=>{let n=C3.devicePixelRatio%1==0?0:1,r={w:m(e.w-t.w),h:m(e.h-t.h)};return{w:r.w>n?r.w:0,h:r.h>n?r.h:0}},C=(e,t)=>{let n=(e,t,n,r)=>{let i=e===m6?h6:x_e(e),a=r5(e),o=r5(n);return!t&&!r?h6:a&&o?m6:a?t&&r?i:t?m6:h6:t?i:o&&r?m6:h6};return{x:n(t.x,e.x,t.y,e.y),y:n(t.y,e.y,t.x,e.x)}},w=e=>{let t=e=>[m6,h6,g6].map((t=>oe(i5(t),e))),n=t(!0).concat(t()).join(` `);u(n),u(T6(e).map((t=>oe(e[t],t===`x`))).join(` `),!0)},[T,E]=S3(_,b6(h8,a)),[D,O]=S3(_,b6(m8,a)),[ee,k]=S3(_),[A]=S3(v),[j,te]=S3(_),[ne]=S3(v),[re]=S3({i:(e,t)=>_6(e,t,t6(X3(T6(e),T6(t)))),o:{}}),[M,ie]=S3({i:(e,t)=>y6(e.T,t.T)&&y6(e.k,t.k),o:E8()}),ae=F8(a5),oe=(e,t)=>`${t?r_e:i_e}${Hge(e)}`;return({Dt:o,Zt:s,fn:c,It:l},{dn:h})=>{let{_t:g,Ht:_,xt:v,Ct:oe,ft:se,Et:ce}=s||{},{X:le,Y:ue,W:de}=ae&&ae.R(e,t,c,n,o)||{},[fe,N]=b_e(o,n),[P,pe]=o(`overflow`),me=r5(P.x),he=r5(P.y),ge=g||h||v||oe||ce||N,F=E(l),_e=O(l),ve=k(l),ye=te(l);if(N&&f&&u(G8,!fe),ge){B6(r,H8,B8)&&y(!0);let e=ue&&ue(),[t]=F=T(l),[n]=_e=D(l),i=p8(a),o=p&&Xge(d()),s={w:m(n.w+t.w),h:m(n.h+t.h)},c={w:m((o?o.w:i.w+m(i.w-n.w))+t.w),h:m((o?o.h:i.h+m(i.h-n.h))+t.h)};e&&e(),ye=j(c),ve=ee(S(s,c),l)}let[I,be]=ye,[xe,Se]=ve,[Ce,we]=_e,[Te,Ee]=F,[De]=A({x:xe.w>0,y:xe.h>0}),Oe=me&&he&&(De.x||De.y)||me&&De.x&&!De.y||he&&De.y&&!De.x,ke=h||oe||ce||Ee||we||be||Se||pe||N||ge||_&&p,[Ae]=o(`update.flowDirectionStyles`),[je,Me]=re(Ae?Ae(a)||{}:b(),l),[Ne,Pe]=oe||se||Me||l?M(x(je,!!Ae),l):ie(),Fe=C(De,P);y(!1),ke&&(w(Fe),Fe=S_e(a,De),de&&le&&(le(Fe,Ce,Te),s8(a,de(Fe))));let[Ie,Le]=ne(Fe);return z6(r,H8,B8,Oe),z6(i,K8,B8,Oe),E6(t,{rn:Ie,Vt:{x:I.w,y:I.h},Rt:{x:xe.w,y:xe.h},j:De,Tt:Qge(Ne,xe)}),{en:Le,nn:be,sn:Se,cn:Pe||Se}}},V_e=e=>{let[t,n,r]=L_e(e),i={ln:{t:0,r:0,b:0,l:0},_n:!1,F:{[c6]:0,[l6]:0,[s6]:0,[r6]:0,[i6]:0,[o6]:0,[a6]:0},Vt:{x:0,y:0},Rt:{x:0,y:0},rn:{x:h6,y:h6},j:{x:!1,y:!1},Tt:E8()},{dt:a,gt:o,V:s,St:c}=t,{P:l,M:u}=m5(),d=!l&&(u.x||u.y),f=[R_e(t),z_e(t,i),B_e(t,i)];return[n,e=>{let t={},n=d&&T8(o),r=n&&c();return J3(f,(n=>{E6(t,n(e,t)||{})})),w8(o,n),r&&r(),s||w8(a,0),t},i,t,r]},H_e=(e,t,n,r)=>{let i=!1,a={Kt:!1,pn:!1},o=d5(t,{}),[s,c,l,u,d]=V_e(e),[f,p,m]=j_e(u,l,o,(e=>{y({},e)})),[h,g,,_]=I_e(e,t,a,m,l,u,r),v=e=>T6(e).some((t=>!!e[t])),y=(e,r)=>{let{Kt:o,pn:s}=a;if(s||o&&i)return!1;let{vn:l,It:u,zt:d}=e,f=l||{},h=!!u||!i,_={Dt:d5(t,f,h),vn:f,It:h},y=r||p(E6({},_,{zt:d})),b=c(E6({},_,{fn:m,Zt:y}));g(E6({},_,{Zt:y,tn:b}));let x=v(y),S=v(b),C=x||S||!O6(f)||h;return i=!0,C&&n(e,{Zt:y,tn:b}),C};return[()=>{let{an:e,gt:t,St:n}=u,r=T8(e),i=[f(),s(),h(),()=>{a.pn=!0}],o=n();return w8(t,r),o(),b6(n6,i)},y,e=>{let t=a.Kt;a.Kt=e,!e&&t!==e&&y({It:!0,zt:!0})},()=>{g({Dt:d5(t,{},!1),vn:{},It:!1})},()=>({gn:a,hn:m,bn:l}),{yn:u,wn:_},d]},b5=new WeakMap,U_e=(e,t)=>{b5.set(e,t)},W_e=e=>{b5.delete(e)},x5=e=>b5.get(e),S5=(e,t,n)=>{let{tt:r}=m5(),i=K3(e),a=i?e:e.target,o=x5(a);if(t&&!o){let o=[],s={},c=e=>{let t=D6(e),n=F8(t_e);return n?n(t,!0):t},l=E6({},r(),c(t)),[u,d,f]=j8(),[p,m,h]=j8(n),g=(e,t)=>{h(e,t),f(e,t)},[_,v,y,b,x,S,C]=H_e(e,l,(({vn:e,It:t},{Zt:n,tn:r})=>{let{_t:i,Ct:a,$t:o,xt:s,Ht:c,ft:l}=n,{nn:u,sn:d,en:f,cn:p}=r;g(`updated`,[T,{updateHints:{sizeChanged:!!i,directionChanged:!!a,heightIntrinsicChanged:!!o,overflowEdgeChanged:!!u,overflowAmountChanged:!!d,overflowStyleChanged:!!f,scrollCoordinatesChanged:!!p,contentMutation:!!s,hostMutation:!!c,appear:!!l},changedOptions:e||{},force:!!t}])}),(e=>g(`scroll`,[T,e]))),w=e=>{let{gn:t}=x(),{pn:n}=t;n||(W_e(a),n6(o),g(`destroyed`,[T,e]),d(),m())},T={options(e,t){if(e){let n=t?r():{},i=u5(l,E6(n,c(e)));O6(i)||(E6(l,i),v({vn:i}))}return E6({},l)},on:p,off:(e,t)=>{e&&t&&m(e,t)},state(){let{gn:e,hn:t,bn:n}=x(),{pn:r,Kt:i}=e,{B:a}=t,{Vt:o,Rt:s,rn:c,j:l,ln:u,_n:d,Tt:f}=n;return E6({},{overflowEdge:o,overflowAmount:s,overflowStyle:c,hasOverflow:l,scrollCoordinates:{start:f.T,end:f.k},padding:u,paddingAbsolute:d,directionRTL:a,sleeping:i,destroyed:r})},elements(){let{dt:e,vt:t,ln:n,L:r,ht:i,gt:a,Qt:o}=S.yn,{jt:s,Jt:c}=S.wn,l=e=>{let{kt:t,Pt:n,Lt:r}=e;return{scrollbar:r,track:n,handle:t}},u=e=>{let{Xt:t,Yt:n}=e;return E6({},l(t[0]),{clone:()=>{let e=l(n());return b(),e}})};return E6({},{target:e,host:t,padding:n||r,viewport:r,content:i||r,scrollOffsetElement:a,scrollEventElement:o,scrollbarHorizontal:u(s),scrollbarVertical:u(c)})},update:e=>v({It:e,zt:!0}),destroy:b6(w,!1),sleep:y,plugin:e=>s[T6(e)[0]]};return Z3(o,[C]),U_e(a,T),P8(M8,S5,[T,u,s]),N_e(S.yn.bt,!i&&e.cancel)?(w(!0),T):(Z3(o,_()),g(`initialized`,[T]),T.update(),T)}return o};S5.plugin=e=>{let t=H3(e),n=t?e:[e],r=n.map((e=>P8(e,S5)[0]));return $ge(n),t?r:r[0]},S5.valid=e=>{let t=e&&e.elements,n=V3(t)&&t();return G3(n)&&!!x5(n.target)},S5.env=()=>{let{U:e,M:t,P:n,J:r,ot:i,st:a,K:o,Z:s,tt:c,nt:l}=m5();return E6({},{scrollbarsSize:e,scrollbarsOverlaid:t,scrollbarsHiding:n,scrollTimeline:r,staticDefaultInitialization:i,staticDefaultOptions:a,getDefaultInitialization:o,setDefaultInitialization:s,getDefaultOptions:c,setDefaultOptions:l})},S5.nonce=D_e,S5.trustedTypePolicy=qge;var G_e=4e3;function C5(e={}){let{fetchResponse:t,fetchStream:n,onPersist:r,onClear:i,onQueuedCleared:a,onBeforeRegenerate:o}=e,s=aR({messages:e.messages??[],loading:!1,error:null}),c=gR(null),l=gR(!0),u=null,d=gR([]),f=gR(null);function p(){}function m(e){let t=c.value;e.deltaY<0?l.value=!1:t&&(l.value=t.scrollHeight-t.scrollTop-t.clientHeight<64)}function h(){c.value&&requestAnimationFrame(()=>{let e=c.value;!e||!l.value||(e.scrollTop=e.scrollHeight)})}function g(e,t,n,r,i){s.messages.push({role:e,content:t,timestamp:Date.now(),...n&&n.length?{focuses:n}:{},...r?.length?{images:r}:{},...i?{quote:i}:{}}),l.value=!0,h()}async function _(e){if(l.value=!0,n){let t=aR({role:`assistant`,content:``,timestamp:Date.now(),reasoning:``,reasoningTotal:0,steps:[]}),r=!1;s.messages.push(t);try{await n(s.messages.slice(0,-1),e=>{switch(e.type){case`round_start`:e.round>1&&(t.content||t.reasoning)&&(r=!0);break;case`reasoning`:r&&=(t.reasoning+=`
3164
3164
  `,!1),t.reasoningTotal+=e.delta.length,t.reasoning=(t.reasoning+e.delta).slice(-4e3);break;case`text`:r&&=(t.content+=`
@@ -7754,6 +7754,8 @@ var Qp = {
7754
7754
  " → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。",
7755
7755
  " 页面没写不构成不答的理由。",
7756
7756
  "",
7757
+ "已懂不查:已是通用知识或对话里已读过的内容,直接用 —— 不必为同一信息再读页面;",
7758
+ "只有要断言「页面上写了什么」时才需要读页核实。",
7757
7759
  "出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、",
7758
7760
  "过渡句一律不标。「没找到」的说明压成一句,不报检索过程。"
7759
7761
  ].join("\n"),
@@ -7769,6 +7771,8 @@ var Qp = {
7769
7771
  " → Give your judgment and reasoning directly; keep the notes' stance and your own view separate (\"this page's position is ...; my take is ...\").",
7770
7772
  " The page not covering it is never a reason to refuse.",
7771
7773
  "",
7774
+ "Known means no lookup: use general knowledge you already master, and anything already read in this conversation,",
7775
+ "directly — never re-read the page for information you already have; only claims about \"what the page says\" require reading to verify.",
7772
7776
  "Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,",
7773
7777
  "personal opinions, and transitions get none. Compress \"not found\" statements to one sentence; never narrate the search process."
7774
7778
  ].join("\n"),
@@ -16996,15 +17000,15 @@ function KS(e, t, n = {}) {
16996
17000
  let o = Math.min(a.length, r);
16997
17001
  return {
16998
17002
  hits: a.slice(0, o).map((e) => {
16999
- let n = Array.from(e.childNodes).filter((e) => e.nodeType === 3).map((e) => e.textContent || "").join("").trim();
17000
- if (i === "text" && !n) {
17001
- let r = (e.textContent || "").trim(), i = r.indexOf(t);
17002
- n = r.slice(Math.max(0, i - 20), i + t.length + 40);
17003
+ let n = (typeof e.textContent == "string" && e.textContent ? e.textContent : Array.from(e.childNodes ?? []).filter((e) => e.nodeType === 3).map((e) => e.textContent || "").join("")).replace(/\s+/g, " ").trim(), r = n.slice(0, 120);
17004
+ if (i !== "selector" && t) {
17005
+ let e = n.indexOf(String(t));
17006
+ e >= 0 && (r = (e > 100 ? "…" : "") + n.slice(Math.max(0, e - 100), e + 120) + (e + 120 < n.length ? "…" : ""));
17003
17007
  }
17004
17008
  return {
17005
17009
  selector: GS(e),
17006
17010
  tag: e.tagName.toLowerCase(),
17007
- text: n.slice(0, 120)
17011
+ text: r
17008
17012
  };
17009
17013
  }),
17010
17014
  total: a.length,
@@ -17375,10 +17379,10 @@ function xC(e, t, n) {
17375
17379
  augmentPrompt: (i) => {
17376
17380
  let a = [];
17377
17381
  if (r.planning && (a.push("【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:"), a.push(" · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。"), a.push(" · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。"), a.push(" · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。"), a.push(" · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 \"components.2\"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。"), e?.humanConfirm ? a.push(" · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。") : a.push(" · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。"), a.push(" · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。")), t && (a.push("改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。"), a.push("读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。"), a.push("修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。"), a.push("修改主数据出错时可用 restore_data 回退最近一次。"), a.push("在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。"), a.push("找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。"), a.push("需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。"), a.push("读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。"), a.push("【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:\"set\",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。"), a.push("读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:\"该子树路径\"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。"), a.push("对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/\"刚才改了啥\");只读查历史快照值用 history_data({id?,jsonPath?})。")), r.subagent && a.push("独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。"), r.inspectEnv && a.push("排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:\"appConfig\"}) 读 window.appConfig)。改完数据看渲染、定位\"为何没生效\"时用它(只读,不改数据)。"), r.domInspect) {
17378
- let n = t && e?.hasActions ? "配合宿主 actions(save_draft/publish 等)形成\"改数据→截图/get_dom 看渲染→触发动作\"闭环。" : t ? "改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。" : "";
17379
- a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}`);
17382
+ let n = t && e?.hasActions ? "配合宿主 actions(save_draft/publish 等)形成\"改数据→截图/get_dom 看渲染→触发动作\"闭环。" : t ? "改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。" : "", r = e?.skills ? "长文按关键词定位(找某术语/某节在哪)先 load_skill(\"dom-inspect\") 取得 dom_search 文本检索,命中后窄读那一节 —— 勿整页翻页找。" : "";
17383
+ a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}${r}`);
17380
17384
  }
17381
- if (e?.screenshot && a.push("视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。"), e?.domEdit && a.push("修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。"), e?.viewImage && a.push("看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。"), e?.hasProposals && a.push("【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。"), r.draftWrite && (a.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。"), a.push("⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。")), r.focus && (a.push("【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:"), a.push(" · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:\"该子树路径\"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。"), a.push(" · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。"), a.push(" · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。"), a.push(" · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。"), a.push(" · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。")), e?.subagents?.length) {
17385
+ if (e?.screenshot && a.push("视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。"), e?.domEdit && a.push("修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。"), e?.viewImage && a.push("看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。"), e?.hasProposals && a.push("【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。"), r.draftWrite && (a.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。"), a.push("⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。")), r.focus && t && (a.push("【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:"), a.push(" · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:\"该子树路径\"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。"), a.push(" · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。"), a.push(" · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。"), a.push(" · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。"), a.push(" · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。")), e?.subagents?.length) {
17382
17386
  let t = e.subagents.filter((e) => (e.temperature ?? 0) >= _C || /规划|创意|设计|方案|brainstorm|plan/i.test(e.description)), n = e.subagents.filter((e) => (e.temperature ?? 0) < _C && /反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));
17383
17387
  a.push("【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:"), t.length && (a.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map((e) => "use_" + e.id).join("/")} 出 2-3 套方案(高温创意),`), a.push(e?.humanConfirm ? " 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。" : " 不要自己拍板;拿到方案后以文字列出选项等用户回复(humanConfirm 未开,勿调不存在工具)。")), n.length && a.push(` · 严谨/易错/校验类 → 可先调 ${n.map((e) => "use_" + e.id).join("/")} 反思挑刺(低温审查),据反馈修订。`), a.push(" · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。"), a.push(" · 简单/明确任务(如\"标题改红色\")直接执行,不必走规划-反思。");
17384
17388
  }
@@ -17835,7 +17839,7 @@ function BC(e, n, r) {
17835
17839
  schema: t.object({}).optional()
17836
17840
  })] : [];
17837
17841
  Ye.forEach((e) => Oe.set(e.name, "builtin"));
17838
- let Xe = V.focus, Ze = s(async ({ path: e, label: t }) => {
17842
+ let Xe = V.focus && he, Ze = s(async ({ path: e, label: t }) => {
17839
17843
  let n = Ce()?.schema;
17840
17844
  return n ? Cp(n, e) ? (ne.setFocus(P({
17841
17845
  path: e,
@@ -57631,6 +57631,8 @@ var d$ = {
57631
57631
  " → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。",
57632
57632
  " 页面没写不构成不答的理由。",
57633
57633
  "",
57634
+ "已懂不查:已是通用知识或对话里已读过的内容,直接用 —— 不必为同一信息再读页面;",
57635
+ "只有要断言「页面上写了什么」时才需要读页核实。",
57634
57636
  "出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、",
57635
57637
  "过渡句一律不标。「没找到」的说明压成一句,不报检索过程。"
57636
57638
  ].join("\n"),
@@ -57646,6 +57648,8 @@ var d$ = {
57646
57648
  " → Give your judgment and reasoning directly; keep the notes' stance and your own view separate (\"this page's position is ...; my take is ...\").",
57647
57649
  " The page not covering it is never a reason to refuse.",
57648
57650
  "",
57651
+ "Known means no lookup: use general knowledge you already master, and anything already read in this conversation,",
57652
+ "directly — never re-read the page for information you already have; only claims about \"what the page says\" require reading to verify.",
57649
57653
  "Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,",
57650
57654
  "personal opinions, and transitions get none. Compress \"not found\" statements to one sentence; never narrate the search process."
57651
57655
  ].join("\n"),
@@ -74841,15 +74845,16 @@ function fFe(e, t, n = {}) {
74841
74845
  let c = Math.min(s.length, a);
74842
74846
  return {
74843
74847
  hits: s.slice(0, c).map((e) => {
74844
- let n = Array.from(e.childNodes).filter((e) => e.nodeType === 3).map((e) => e.textContent || "").join("").trim();
74845
- if (o === "text" && !n) {
74846
- let r = (e.textContent || "").trim(), i = r.indexOf(t);
74847
- n = r.slice(Math.max(0, i - 20), i + t.length + 40);
74848
+ var n;
74849
+ let r = (typeof e.textContent == "string" && e.textContent ? e.textContent : Array.from((n = e.childNodes) == null ? [] : n).filter((e) => e.nodeType === 3).map((e) => e.textContent || "").join("")).replace(/\s+/g, " ").trim(), i = r.slice(0, 120);
74850
+ if (o !== "selector" && t) {
74851
+ let e = r.indexOf(String(t));
74852
+ e >= 0 && (i = (e > 100 ? "…" : "") + r.slice(Math.max(0, e - 100), e + 120) + (e + 120 < r.length ? "…" : ""));
74848
74853
  }
74849
74854
  return {
74850
74855
  selector: P8(e),
74851
74856
  tag: e.tagName.toLowerCase(),
74852
- text: n.slice(0, 120)
74857
+ text: i
74853
74858
  };
74854
74859
  }),
74855
74860
  total: s.length,
@@ -75227,10 +75232,10 @@ function LFe(e, t, n) {
75227
75232
  var a;
75228
75233
  let o = [];
75229
75234
  if (r.planning && (o.push("【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:"), o.push(" · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。"), o.push(" · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。"), o.push(" · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。"), o.push(" · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 \"components.2\"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。"), e != null && e.humanConfirm ? o.push(" · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。") : o.push(" · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。"), o.push(" · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。")), t && (o.push("改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。"), o.push("读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。"), o.push("修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。"), o.push("修改主数据出错时可用 restore_data 回退最近一次。"), o.push("在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type==\"card\" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。"), o.push("找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。"), o.push("需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。"), o.push("读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。"), o.push("【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:\"set\",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。"), o.push("读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:\"该子树路径\"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。"), o.push("对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/\"刚才改了啥\");只读查历史快照值用 history_data({id?,jsonPath?})。")), r.subagent && o.push("独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。"), r.inspectEnv && o.push("排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:\"appConfig\"}) 读 window.appConfig)。改完数据看渲染、定位\"为何没生效\"时用它(只读,不改数据)。"), r.domInspect) {
75230
- let n = t && e != null && e.hasActions ? "配合宿主 actions(save_draft/publish 等)形成\"改数据→截图/get_dom 看渲染→触发动作\"闭环。" : t ? "改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。" : "";
75231
- o.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}`);
75235
+ let n = t && e != null && e.hasActions ? "配合宿主 actions(save_draft/publish 等)形成\"改数据→截图/get_dom 看渲染→触发动作\"闭环。" : t ? "改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。" : "", r = e != null && e.skills ? "长文按关键词定位(找某术语/某节在哪)先 load_skill(\"dom-inspect\") 取得 dom_search 文本检索,命中后窄读那一节 —— 勿整页翻页找。" : "";
75236
+ o.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}${r}`);
75232
75237
  }
75233
- if (e != null && e.screenshot && o.push("视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。"), e != null && e.domEdit && o.push("修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。"), e != null && e.viewImage && o.push("看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。"), e != null && e.hasProposals && o.push("【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。"), r.draftWrite && (o.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。"), o.push("⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。")), r.focus && (o.push("【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:"), o.push(" · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:\"该子树路径\"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。"), o.push(" · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。"), o.push(" · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。"), o.push(" · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。"), o.push(" · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。")), !(e == null || (a = e.subagents) == null) && a.length) {
75238
+ if (e != null && e.screenshot && o.push("视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。"), e != null && e.domEdit && o.push("修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。"), e != null && e.viewImage && o.push("看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。"), e != null && e.hasProposals && o.push("【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。"), r.draftWrite && (o.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。"), o.push("⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。")), r.focus && t && (o.push("【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:"), o.push(" · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:\"该子树路径\"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。"), o.push(" · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。"), o.push(" · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。"), o.push(" · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。"), o.push(" · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。")), !(e == null || (a = e.subagents) == null) && a.length) {
75234
75239
  let t = e.subagents.filter((e) => {
75235
75240
  var t;
75236
75241
  return ((t = e.temperature) == null ? 0 : t) >= NFe || /规划|创意|设计|方案|brainstorm|plan/i.test(e.description);
@@ -75750,7 +75755,7 @@ function eIe(e, t, n) {
75750
75755
  schema: B({}).optional()
75751
75756
  })] : [];
75752
75757
  Xt.forEach((e) => kt.set(e.name, "builtin"));
75753
- let Zt = pt.focus, Qt = qP(async ({ path: e, label: t }) => {
75758
+ let Zt = pt.focus && mt, Qt = qP(async ({ path: e, label: t }) => {
75754
75759
  var n;
75755
75760
  let r = (n = wt()) == null ? void 0 : n.schema;
75756
75761
  return r ? GQ(r, e) ? (Ke.setFocus(qe(j({ path: e }, t ? { label: t } : {})), "agent"), `已聚焦到 ${e}${t ? `(${t})` : ""}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`) : `PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。` : "聚焦失败:当前无主数据 schema,无法聚焦。";
@@ -48,8 +48,8 @@ self.onmessage = async (e) => {
48
48
  `)}catch{}return``}var qp={pageBuilder:{systemPrompt:`你是页面构建助手。按用户意图读写主数据(经 data 声明 + schema 校验),改完页面实时更新。`},researcher:{systemPrompt:`你是调研助手。多路调研用 spawn_agents 并行委派子 agent(各负责一个方向);单份资料用 fetch_document 抓取;最后结构化汇总,给出结论与依据。`,subagent:{maxParallel:4}},minimal:{capabilities:{planning:!1,skills:!1,vfs:!1,summarization:!1,memory:!1,subagent:!1}}};function Jp(e,t=`code`,n=!0){let r=`use_${e}`;return[`【先判意图(防长对话误路由)】先判断用户是「问」还是「要生成/改」:**提问类**(这是什么组件/怎么用/某字段什么意思/为什么这样/解释代码)→ 用 read / list_components / rag_component_docs **直接回答**,绝不委派 ${r};**生成/修改类**(做一个/生成/改成/加一个 XX 组件)才按下面纪律委派 ${r}。长对话里上文全是生成记录时尤须警惕,不要把新问题当成延续旧任务。`,`【多方案征询=先文本】用户要「出几套/两套方案我来选」「给几个选择」「先出方案看看」→ **本轮只出文本方案**(每套一两句:布局/配色/交互差异),经 request_human_confirmation 的 options 让用户点选(或等用户回复选定);**选定后才**委派 ${r} 建所选方案。禁止先并发多个子 agent 把每套方案都生成出来再让用户挑(子 agent 产物当不了选项清单,且烧 token;真 LLM 实测踩过:「出两套方案」被路由成两个 use_${e} 委派)。`,`【执行纪律(最重要)】收到代码组件任务后:**新建类直接委派**(追加组件无需通读/翻页现有数组,子 agent 自会采样一个组件看结构;**新建组件由子 agent 全权创建** —— 它自己把整个组件(含 ${t})写进数组,你不需要也不能替它创建/追加/落地代码)→ 修改类才 read 定位(by name)→ 调 ${r} 委派 → read 核对 → 回复用户。**中间绝不输出过渡性文字** —— 「我先看看…」「稍后委派」「接下来我会…」这类计划性回复等于任务没做就结束了(回复即本轮终止);所有调研和委派在本轮内连续完成,完成后才回复总结。`,`【产物形态】每个组件是完整、自包含的 HTML 页面(含 style/script,可独立成页);你只负责委派和收尾,不关心宿主如何渲染(v-html / iframe / SFC 是集成方的事)。`,`【主 agent 职责边界(硬规则)】禁止直接 read/write 代码组件的 ${t} 字段(read 只得 <code Nkb> 摘要没用;write 绕过 vfs/verify 危险)—— 生成/修改/排查代码一律经 ${r},收尾 read 核对。**委派返回即已落地**:${r} 的结论说「已创建组件 X」= 组件已在数组里,**不要再 write/append 一遍**(子 agent 已自己创建,你再写 = 造出重复组件,还得花轮次删;真 LLM 实测踩过:主 agent 把返回的 code 又追加了一次 → 索引 8/9 重复)。核对方式 = read 该数组尾部(确认新组件存在 + name 唯一),仅此而已。`,`【多组件委派(防上下文污染)】一次要多个组件:① write_todos 列出(每项 name + 要点)② **不同组件可在同一轮并行发多个 ${r} 委派**(每组件一次 ${r},task 只写该组件 name + 要点 + 主题/风格;每次委派是独立子 agent 实例,互不共享上下文);**同一组件同一时间只能有一个委派在途**,勿对同一组件同轮发两个委派 ③ 委派返回后逐个 read 核对(确认已生成 + 名称对)+ update_todo 标完成 ④ 主题/风格在每次 task 里转述(每个子 agent 全新上下文,不知其他组件)。一次 task 塞多个组件仍禁止(同一子 agent 共享上下文生成多个 → class/样式冲突污染);主 agent 自己的 write(普通组件属性)可与委派同轮发出,不必等委派返回。`,`【委派 task 规格化(收窄子 agent 决策,防开放任务致装饰穷举)】委派 ${r} 的 task 必须含:① 组件定位(by name)② 视觉风格(配色/质感/字体;**给 1-2 个具体视觉锚** —— 主色 hex **取自平台 UI/设计规范 skill 的定义值**(有规范类 skill 先 load 再引用其 hex,勿凭页面观察自造近似色;无规范才自定,如「金黄 #F7C948」)、主体占比(如「杯高约画布 60%」)或装饰密度(如「仅 2 类背景装饰」)—— 细节空间收窄,子 agent 不在装饰细节上展开推演)③ 内容(文案/数据/图)④ 交互意图(动效/状态/触发)⑤ 历史偏好(可选):聊天上下文中有与该组件相关的用户历史偏好/反馈(如「用户偏好深色系」「上轮嫌动画太快」),提炼一句附 task 末尾(新子 agent 无记忆,全靠 task);**不含技术实现**(SVG vs CSS / keyframes vs transition 归子 agent 选)。❌「生成啤酒杯动画」→ ✅「啤酒杯倒酒(beer):金黄啤酒 #F7C948 从上方倒入透明杯(杯高约画布 60%),深绿背景,液体循环下落 2s,hover 杯子放大」。规格简练(4 要素各半句),远省子 agent 思考 token。`,`【委派失败重试】${r} 返回乱码/内部标记(如 <|DSML|)/空结论或报错 = 子 agent 异常,**重新委派一次**(task 附「上次失败,这次先把代码写短些/分步」);连续两次失败才降级告知用户。**不要因此自己直接 write/edit ${t} 字段**(绕过 vfs/格式校验,且你拿不到规范全文)。`,...n?[`【设计品味引导】子 agent 内置 web-design-engineer 设计 skill(设计系统先声明/反 AI 俗套/25 风格配方/5 维自评;**挂在子 agent 侧,你自己 load 不到也不必尝试**)。委派 task 的视觉锚可直接引用配方名 —— linear / apple-hig / muji / pentagram / bloomberg-terminal / aesop 等(如「Linear 风格:暖深色+发丝线」),子 agent 会按名取配方参数照做;用户未指定风格时勿写「随便/好看就行」,给一条具体方向(流派或参考品牌),子 agent 按其 skill 流程选配方并在结论里声明设计系统与假设。`]:[],`【预算将尽暂停】组件很多、接近工具轮次上限不要硬扛:完成手头这个后报告「已生成 K/N,还剩 M 个」,等用户确认后从 todos 剩余项继续(勿重复已完成)。`].join(`
49
49
  `)}var Yp={reliableWriteRules:[`【可靠写入规则】`,`1. 改任何字段前,先用 read({ jsonPath }) 读其当前真实值,基于真实值改,不要凭记忆;`,`2. 若不确定可操作哪些字段,先 read() 不传 jsonPath 查看主数据说明 + schema 声明字段(集成方可经 sdk.setData 运行时替换 schema,以工具返回为准,勿凭旧记忆);`,`3. 不确定某字段结构时,read({ jsonPath }) 返回含格式说明,字段以返回为准;`,`4. 写入若被 schema 校验拒绝(返回结构化错误含字段名与期望类型),按错误修正后重试,不要放弃;`,`5. 优先用 write 的 patch 增量改(只发改动,如 write({ value, patch:{ op, jsonPath } })),避免整体重传大 JSON 被截断;`,`6. 写入若触发乐观锁冲突(返回 VERSION_CONFLICT 或工具挂起等用户决定):等工具返回结果后按其指示继续(保留外部值 → 重新 read 再改;已覆盖/已回退 → 基于结果重写),不要放弃任务。`].join(`
50
50
  `),reliableWriteRulesEn:[`[Reliable write rules]`,`1. Before changing any field, read its current real value with read({ jsonPath }) and edit based on that value, never from memory;`,`2. If unsure which fields are operable, call read() without jsonPath first to see the data description + schema-declared fields (the integrator can replace the schema at runtime via sdk.setData; trust the tool response over stale memory);`,`3. When unsure about a field structure, the read({ jsonPath }) response includes a format description; treat the response as the source of truth;`,`4. If a write is rejected by schema validation (the structured error names the field and expected type), fix it per the error and retry; do not give up;`,`5. Prefer incremental write patches (send only the change, e.g. write({ value, patch:{ op, jsonPath } })) over resending the whole large JSON, which risks truncation;`,`6. If a write hits an optimistic-lock conflict (VERSION_CONFLICT returned, or the tool suspends awaiting the user decision): after the tool returns, follow its instruction (keep external → re-read then edit; overwritten/restored → continue from the result); do not abandon the task.`].join(`
51
- `),answerLanes:[`【作答车道:先判问题形态,再选纪律】`,`用户的问题分三类,判错车道是最大的答非所问:`,`A. 问页面内容(「这页写了什么 / 哪里提到 / 原文是什么 / 这段在说什么」)`,` → 以页面实料为准并点明出处;页面内容与你的先验知识冲突时以页面为准;页面没写就说没写,一句话即可,不列举查过哪些节。`,`B. 问概念术语(「X 是什么 / 啥意思 / X 和 Y 什么区别」)`,` → 页面有语境就先按页面语境讲;页面没有也必须直接用自己的知识解释,`,` 开头一句「本页未提及,以下是通用解释:」即可 —— 不许把「页面上没有」当答案。`,`C. 求观点经验(「你觉得呢 / 按你的经验 / 是不是很难 / 该怎么选」)`,` → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。`,` 页面没写不构成不答的理由。`,``,`出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、`,`过渡句一律不标。「没找到」的说明压成一句,不报检索过程。`].join(`
52
- `),answerLanesEn:[`[Answer lanes: classify the question first, then pick the discipline]`,`User questions fall into three categories; picking the wrong lane is the biggest way to miss the point:`,`A. Asking about page content ("what does this page say / where is it mentioned / what is the original text / what does this passage mean")`,` → Ground answers in what the page actually says and cite where it came from; when the page conflicts with your prior knowledge, the page wins; if the page does not say it, say so in one sentence — do not enumerate which sections you searched.`,`B. Asking about a concept or term ("what is X / what does it mean / how do X and Y differ")`,` → If the page has context for it, explain in that context first; if the page does not, you MUST still explain it directly from your own knowledge,`,` opening with one line like "Not covered on this page — general explanation:" — never treat "it is not on the page" as the answer.`,`C. Asking for your opinion or experience ("what do you think / in your experience / is it hard to match / which should I choose")`,` → Give your judgment and reasoning directly; keep the notes' stance and your own view separate ("this page's position is ...; my take is ...").`,` The page not covering it is never a reason to refuse.`,``,`Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,`,`personal opinions, and transitions get none. Compress "not found" statements to one sentence; never narrate the search process.`].join(`
51
+ `),answerLanes:[`【作答车道:先判问题形态,再选纪律】`,`用户的问题分三类,判错车道是最大的答非所问:`,`A. 问页面内容(「这页写了什么 / 哪里提到 / 原文是什么 / 这段在说什么」)`,` → 以页面实料为准并点明出处;页面内容与你的先验知识冲突时以页面为准;页面没写就说没写,一句话即可,不列举查过哪些节。`,`B. 问概念术语(「X 是什么 / 啥意思 / X 和 Y 什么区别」)`,` → 页面有语境就先按页面语境讲;页面没有也必须直接用自己的知识解释,`,` 开头一句「本页未提及,以下是通用解释:」即可 —— 不许把「页面上没有」当答案。`,`C. 求观点经验(「你觉得呢 / 按你的经验 / 是不是很难 / 该怎么选」)`,` → 直接给判断和理由;笔记口径与个人观点分开说(「本页的立场是…;我的看法是…」)。`,` 页面没写不构成不答的理由。`,``,`已懂不查:已是通用知识或对话里已读过的内容,直接用 —— 不必为同一信息再读页面;`,`只有要断言「页面上写了什么」时才需要读页核实。`,`出处密度:只有「对页面内容的断言」才标出处(句末括注即可);概念解释、个人观点、`,`过渡句一律不标。「没找到」的说明压成一句,不报检索过程。`].join(`
52
+ `),answerLanesEn:[`[Answer lanes: classify the question first, then pick the discipline]`,`User questions fall into three categories; picking the wrong lane is the biggest way to miss the point:`,`A. Asking about page content ("what does this page say / where is it mentioned / what is the original text / what does this passage mean")`,` → Ground answers in what the page actually says and cite where it came from; when the page conflicts with your prior knowledge, the page wins; if the page does not say it, say so in one sentence — do not enumerate which sections you searched.`,`B. Asking about a concept or term ("what is X / what does it mean / how do X and Y differ")`,` → If the page has context for it, explain in that context first; if the page does not, you MUST still explain it directly from your own knowledge,`,` opening with one line like "Not covered on this page — general explanation:" — never treat "it is not on the page" as the answer.`,`C. Asking for your opinion or experience ("what do you think / in your experience / is it hard to match / which should I choose")`,` → Give your judgment and reasoning directly; keep the notes' stance and your own view separate ("this page's position is ...; my take is ...").`,` The page not covering it is never a reason to refuse.`,``,`Known means no lookup: use general knowledge you already master, and anything already read in this conversation,`,`directly — never re-read the page for information you already have; only claims about "what the page says" require reading to verify.`,`Citation density: only claims about page content get a citation (a short parenthetical); concept explanations,`,`personal opinions, and transitions get none. Compress "not found" statements to one sentence; never narrate the search process.`].join(`
53
53
  `),htmlPageOrchestrator:Jp(`html`),htmlPageProposeFirst:[`【新建/创意类请求】先用简短文字给出 2~3 套方案(每套一两句风格/配色/结构要点),询问用户选哪套;选定前不要委派生成代码、不要写 components。`,`【方案切换】已生成某套方案后改选另一套:不重新罗列,直接依据之前描述重新委派生成并覆盖相应组件(委派工具见编排段 use_<id>)。`].join(`
54
54
  `),htmlDirectWriteFallback:[`【纯代码组件 · 你直接写】当前未配备 html 子 agent,纯代码组件的代码字段(code,以 schema 声明为准)由你直接 write(普通字段,经 schema 校验 + 乐观锁 + 快照栈,与改其他字段无异;无 vfs 工作副本 / 无格式校验门禁)。`,`【HTML 生成规范】代码字段必须是完整、自包含的 HTML 页面(含 <style>/<script>,可独立成页):标签正确闭合、style/script 集中放置(如 <head> 内)、class 加前缀防冲突;可引外部 JS/CSS(CDN/字体)。安全底线:禁 eval/new Function、不引可疑外部脚本、不访问 document.cookie 等敏感属性。`,`【修改而非重写】改已有代码:先 read({jsonPath}) 取当前代码字段 → 基于当前值增量改(只动要改的部分,如换配色/文案/某段结构),不要整体重写整个代码字段(易丢已有内容、token 浪费)。`,`【质量自检】无格式校验门禁,写完自查标签闭合 / 结构完整;代码进 data 由集成方渲染层(v-html/iframe)呈现。如需代码资产机制(vfs 工作副本 + 格式校验 + 增量 commit),注册 createHtmlSubagent。`].join(`
55
55
  `)},Xp=15,Zp=4e3,Qp=new WeakMap;function $p(e,t){if(!e)return``;let n=t?`${t.maxKeys??``}|${t.maxChars??``}`:``;if(typeof e==`object`){let t=Qp.get(e);if(t&&t.optsKey===n)return t.hint}let r=em(e,t);return typeof e==`object`&&Qp.set(e,{optsKey:n,hint:r}),r}function em(e,t){let n=Up(e);if(n){let r=t?.maxKeys??Xp,i=t?.maxChars??Zp;if(n.split(`
@@ -2986,9 +2986,9 @@ ${`- 输出形态:完整、自包含的 HTML 页面(.${r},可独立成页)`}
2986
2986
 
2987
2987
  `).trim();t&&r.push(t)},a=e=>{for(let r of Array.from(e.children??[])){let e=r,o=String(e.tagName??``).toLowerCase();if(!(t(e)||jS.has(o))){if(!n(e)){i(e);continue}a(e)}}};return a(e),r.join(`
2988
2988
 
2989
- `).trim()}function FS(e){try{return e.querySelector?.(MS)!=null||e.querySelector?.(`.chat-dialog, .chat-mask, .debug-drawer, .skill-mask, .skill-panel, .chat-selection-menu`)!=null}catch{return!0}}var IS=[kS,(0,i.tool)(({selector:e,offset:t,limit:n})=>{if(typeof document>`u`)return`ERROR: read_page 仅在浏览器环境可用(当前运行在 node/服务端,无 DOM)。请基于用户消息中的引用原文回答。`;let r,i;if(e){if(r=document.querySelector(e),!r)return`未找到匹配元素:selector="${e}"`;i=e}else r=NS(document),i=r?r.tagName.toLowerCase():`body`;let a=PS(r,mu,FS),o=t??0,s=n??4e3;if(o>a.length)return`offset=${o} 超出正文长度 ${a.length}(先从 offset=0 读,按 hasMore 续读)`;let c=a.slice(o,o+s);return JSON.stringify({text:c,totalChars:a.length,offset:o,limit:s,hasMore:o+c.length<a.length,container:i})},{name:`read_page`,description:`读当前页面正文纯文本(自动定位 article/main 等文章容器;排除 SDK 对话框自身与脚本样式)。回答「这个页面讲了什么/某段内容在哪」类问题用;长文按 hasMore=true 时 offset+=本次返回长度 续读。只读,大结果自动外存 vfs。`,schema:t.z.object({selector:t.z.string().optional().describe(`CSS 选择器(默认智能定位 article/main/[role=main]/.content,兜底 body)`),offset:t.z.number().int().min(0).optional().describe(`起始字符偏移(默认 0;续读传上次 offset + 返回 text 长度)`),limit:t.z.number().int().min(200).max(2e4).optional().describe(`本次返回字符上限(默认 4000,上限 20000)`)})})],LS=`display.position.visibility.opacity.color.background-color.background-image.font-size.font-weight.line-height.text-align.z-index.overflow.width.height.margin.padding.border.border-radius.box-shadow.transform.transition.animation.cursor.pointer-events.flex-direction.gap.max-width.min-height`.split(`.`),RS=new WeakMap,zS=!1;function BS(){if(zS)return;let e=globalThis.EventTarget;if(!e?.prototype?.addEventListener)return;zS=!0;let t=e.prototype.addEventListener,n=e.prototype.removeEventListener;e.prototype.addEventListener=function(e,...n){try{let t=RS.get(this);t||(t=new Map,RS.set(this,t)),t.set(String(e),(t.get(String(e))??0)+1)}catch{}return t.call(this,e,...n)},e.prototype.removeEventListener=function(e,...t){try{let t=RS.get(this);if(t){let n=(t.get(String(e))??1)-1;n<=0?t.delete(String(e)):t.set(String(e),n)}}catch{}return n.call(this,e,...t)}}function VS(e){return[...RS.get(e)?.entries()??[]].filter(([,e])=>e>0).map(([e])=>e)}function HS(e,t=12){let n=[],r=e,i=0;for(;r&&r.tagName&&i<t;){let e=r.tagName.toLowerCase(),t=r.id;if(t){n.unshift(`${e}#${t}`);break}if(typeof r.getAttribute==`function`){let t=(r.getAttribute(`class`)||``).split(/\s+/).filter(Boolean)[0];t&&/^[A-Za-z][\w-]*$/.test(t)&&(e+=`.${t}`)}let a=r.parentElement;if(a){let t=Array.from(a.children).filter(e=>e.tagName===r.tagName);t.length>1&&(e+=`:nth-of-type(${t.indexOf(r)+1})`)}n.unshift(e),r=a,i++}return n.join(` > `)}function US(e,t,n={}){if(!e)return{hits:[],total:0,truncated:!1};let r=Math.max(1,Math.min(n.limit??10,20)),i=n.mode??`selector`,a=[];if(i===`selector`)try{a=Array.from(e.querySelectorAll(t))}catch{return{hits:[],total:0,truncated:!1}}else{a=Array.from(e.querySelectorAll(`*`)).filter(e=>{let n=e.tagName.toLowerCase();if(n===`script`||n===`style`||n===`noscript`)return!1;let r=(e.textContent||``).trim();return r.length>0&&r.includes(t)});let n=a.slice(0,100),r=new Set(n);a=n.filter(e=>{for(let t of r)if(t!==e&&e.contains(t))return!1;return!0})}let o=Math.min(a.length,r);return{hits:a.slice(0,o).map(e=>{let n=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();if(i===`text`&&!n){let r=(e.textContent||``).trim(),i=r.indexOf(t);n=r.slice(Math.max(0,i-20),i+t.length+40)}return{selector:HS(e),tag:e.tagName.toLowerCase(),text:n.slice(0,120)}}),total:a.length,truncated:a.length>o}}var WS=[`content`,`display`,`width`,`height`,`background-color`,`position`];function GS(e,t={}){if(!e)return null;let n={selector:HS(e),tag:e.tagName.toLowerCase(),attrs:{}};for(let t of Array.from(e.attributes))!(TS.includes(t.name)||t.name.startsWith(`data-`))||ES.test(t.name)||DS.test(t.name)||(n.attrs[t.name]=t.value);let r=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();r&&(n.text=r.slice(0,400));let i=String(e.innerText??e.textContent??``).trim();if(i&&(n.textAll=i.slice(0,1e3)),(t.includeRect??!0)&&typeof e.getBoundingClientRect==`function`){let t=e.getBoundingClientRect();n.rect={x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}}if(t.includeHtml){let r=Math.min(t.htmlLimit??1500,4e3),i=e.outerHTML??``;n.html=i.length>r?i.slice(0,r)+`…(截断 ${i.length-r} 字符)`:i}let a=t.getComputedStyle??globalThis.window?.getComputedStyle?.bind(globalThis.window),o=n=>{let r={};if(typeof a!=`function`)return r;try{let i=a(e,n??null);for(let e of n?WS:t.styles??LS){let t=typeof i.getPropertyValue==`function`?i.getPropertyValue(e):i[e];t&&(r[e]=String(t).slice(0,200))}}catch{}return r};if((t.styles===void 0||t.styles.length>0)&&(n.styles=o()),t.pseudo&&(n.pseudoStyles={before:o(`::before`),after:o(`::after`)}),t.includeEvents!==!1){let t=Array.from(e.attributes).filter(e=>/^on\w+$/i.test(e.name)).map(e=>({type:e.name.toLowerCase().slice(2),snippet:e.value.slice(0,100)})),r=e.__vueParentComponent?.vnode?.props;n.events={inline:t,vue:r?Object.keys(r).filter(e=>/^on[A-Z]/.test(e)).map(e=>e.slice(2).toLowerCase()):[],captured:VS(e)}}return n}var KS=(0,i.tool)(({query:e,mode:t,limit:n,root:r})=>{BS();let i=r?document.querySelector(r):document;if(r&&!i)return`未找到 root 元素:selector="${r}"`;let a=US(i,e,{mode:t,limit:n});return a.total?JSON.stringify({...a,note:a.truncated?`共 ${a.total} 处命中,仅返回前 ${a.hits.length} 处`:void 0},null,2):t===`text`?`未找到包含文本「${e}」的元素`:`selector "${e}" 未匹配到元素`},{name:`dom_search`,description:`搜索页面元素:CSS 选择器或可见文本两种模式,返回命中元素的 CSS 路径 + 文本片段(≤20 处)。定位元素/查渲染结果用;找到 selector 后可用 dom_info 看详情或 get_dom 看结构。`,schema:t.z.object({query:t.z.string().describe(`selector 模式 = CSS 选择器(如 ".banner .title");text 模式 = 文本关键词`),mode:t.z.enum([`selector`,`text`]).optional().describe(`搜索模式(默认 selector;text = 文本包含匹配)`),limit:t.z.number().int().min(1).max(20).optional().describe(`返回上限(默认 10)`),root:t.z.string().optional().describe(`限定搜索范围的容器选择器(默认整页)`)})}),qS=(0,i.tool)(({selector:e,styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o})=>{BS();let s=document.querySelector(e);if(!s)return`未找到匹配元素:selector="${e}"(可先用 dom_search 定位)`;let c=GS(s,{styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o});return c?JSON.stringify(c,null,2):`selector="${e}" 读取失败`},{name:`dom_info`,description:`读单个元素完整信息:内容(直接文本/全文本/HTML 片段)+ 计算样式(默认排障高频预设,可指定属性列表)+ 几何位置 + 事件绑定(inline on*/Vue props/addEventListener 记录;记录器仅覆盖 SDK 加载后注册的监听)。验证样式落地/排查交互绑定用。`,schema:t.z.object({selector:t.z.string().describe(`CSS 选择器(取首个匹配;可先用 dom_search 定位)`),styles:t.z.array(t.z.string()).optional().describe(`计算样式属性列表(不传 = 常用预设 ~30 项)`),includeHtml:t.z.boolean().optional().describe(`是否含 outerHTML 片段(默认 false,大 HTML 省 token)`),htmlLimit:t.z.number().int().min(100).max(4e3).optional().describe(`HTML 片段上限字符(默认 1500)`),includeEvents:t.z.boolean().optional().describe(`是否含事件绑定(默认 true)`),includeRect:t.z.boolean().optional().describe(`是否含几何位置(默认 true)`),pseudo:t.z.boolean().optional().describe(`是否含 ::before/::after 伪元素摘要(默认 false)`)})}),JS=`dom-inspect`;function YS(e={}){return{name:JS,description:`页面 DOM 深度检视工具(dom_search 搜索元素 / dom_info 读内容·计算样式·事件绑定·几何)。定位元素、验证样式落地、排查交互绑定时加载`,getContent:()=>[`# DOM 检视工具用法`,`## read_page({ selector?, offset?, limit? })—— 读正文首选`,`- 返回页面正文纯文本(JSON:text/totalChars/offset/hasMore/container),自动定位 article/main/[role=main]/.content 容器并排除本对话框自身与 script/style`,`- 长文分页:默认每次 4000 字符;hasMore=true 时下一次调用传 offset=上次 offset+本次 text 长度 续读`,`- 回答「这个页面讲了什么/某段在哪」类问题用 read_page,不要用 get_dom 逐层翻结构(爆 token)`,`## dom_search({ query, mode?, limit?, root? })`,`- mode="selector"(默认):query 为 CSS 选择器;mode="text":文本关键词包含匹配(跳过 script/style)`,`- 返回命中列表:CSS 路径(selector)+ 文本片段;超 limit 标注总数`,`## dom_info({ selector, styles?, includeHtml?, pseudo?, ... })`,`- selector 取首个匹配(先用 dom_search 定位更稳)`,`- styles 不传 = 排障高频预设(display/position/color/background/font/z-index/transform 等约 30 项);传数组 = 只取指定属性`,`- includeHtml: true 附 outerHTML 片段(默认省);pseudo: true 附 ::before/::after 摘要`,`- events 三源:inline on* 属性 / Vue vnode props(onXxx)/ addEventListener 记录器(⚠ 仅记录本 SDK 加载之后注册的监听,更早的挂载捕不到)`,`- rect:视口坐标 + 宽高(验证可见性/布局)`,...e.withScreenshot?[`## take_screenshot({ selector?, fullPage? })—— 视觉验证`,`- 截图「看」页面:selector 截指定元素区域 / fullPage 截整页 / 都不传截当前视口;截图经压缩投递(多模态直看图,纯文本模型自动走识图转述)`,`- 布局/样式/渲染效果类问题优先截图(视觉真值),结构/属性类用 dom_info;截图失败(CSP/跨域图)会回灌原因与替代建议`]:[],...e.withDomEdit?[`## dom_edit({ patches, dryRun? })—— 修改页面元素(宿主开启才有)`,`- patches 批量原子(任一失败整批拒绝):set_text/set_html(内容)、set_attr/remove_attr、add_class/remove_class、set_style、insert(新建元素 anchor+position: before/after/prepend/append/replace)、remove、move(层级调整)、highlight(高亮+滚动)`,`- 写纪律:selector 必须唯一命中(多匹配被拒,用 dom_search 拿精确路径);先读后写(get_dom/dom_info 看现状);拿不准先 dryRun 预检`,`- 改前自动快照:dom_restore 回滚最近一批(可连续回退);改动为会话临时态(刷新即失);数据驱动页面改数据(write)不要改 DOM`]:[],`## 排障套路`,...e.withScreenshot?[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. 视觉验证 take_screenshot / 结构验证 dom_info(styles) → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]:[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. dom_info(styles:["display","background-color","pointer-events"]) 验证样式/点击性 → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]].join(`
2989
+ `).trim()}function FS(e){try{return e.querySelector?.(MS)!=null||e.querySelector?.(`.chat-dialog, .chat-mask, .debug-drawer, .skill-mask, .skill-panel, .chat-selection-menu`)!=null}catch{return!0}}var IS=[kS,(0,i.tool)(({selector:e,offset:t,limit:n})=>{if(typeof document>`u`)return`ERROR: read_page 仅在浏览器环境可用(当前运行在 node/服务端,无 DOM)。请基于用户消息中的引用原文回答。`;let r,i;if(e){if(r=document.querySelector(e),!r)return`未找到匹配元素:selector="${e}"`;i=e}else r=NS(document),i=r?r.tagName.toLowerCase():`body`;let a=PS(r,mu,FS),o=t??0,s=n??4e3;if(o>a.length)return`offset=${o} 超出正文长度 ${a.length}(先从 offset=0 读,按 hasMore 续读)`;let c=a.slice(o,o+s);return JSON.stringify({text:c,totalChars:a.length,offset:o,limit:s,hasMore:o+c.length<a.length,container:i})},{name:`read_page`,description:`读当前页面正文纯文本(自动定位 article/main 等文章容器;排除 SDK 对话框自身与脚本样式)。回答「这个页面讲了什么/某段内容在哪」类问题用;长文按 hasMore=true 时 offset+=本次返回长度 续读。只读,大结果自动外存 vfs。`,schema:t.z.object({selector:t.z.string().optional().describe(`CSS 选择器(默认智能定位 article/main/[role=main]/.content,兜底 body)`),offset:t.z.number().int().min(0).optional().describe(`起始字符偏移(默认 0;续读传上次 offset + 返回 text 长度)`),limit:t.z.number().int().min(200).max(2e4).optional().describe(`本次返回字符上限(默认 4000,上限 20000)`)})})],LS=`display.position.visibility.opacity.color.background-color.background-image.font-size.font-weight.line-height.text-align.z-index.overflow.width.height.margin.padding.border.border-radius.box-shadow.transform.transition.animation.cursor.pointer-events.flex-direction.gap.max-width.min-height`.split(`.`),RS=new WeakMap,zS=!1;function BS(){if(zS)return;let e=globalThis.EventTarget;if(!e?.prototype?.addEventListener)return;zS=!0;let t=e.prototype.addEventListener,n=e.prototype.removeEventListener;e.prototype.addEventListener=function(e,...n){try{let t=RS.get(this);t||(t=new Map,RS.set(this,t)),t.set(String(e),(t.get(String(e))??0)+1)}catch{}return t.call(this,e,...n)},e.prototype.removeEventListener=function(e,...t){try{let t=RS.get(this);if(t){let n=(t.get(String(e))??1)-1;n<=0?t.delete(String(e)):t.set(String(e),n)}}catch{}return n.call(this,e,...t)}}function VS(e){return[...RS.get(e)?.entries()??[]].filter(([,e])=>e>0).map(([e])=>e)}function HS(e,t=12){let n=[],r=e,i=0;for(;r&&r.tagName&&i<t;){let e=r.tagName.toLowerCase(),t=r.id;if(t){n.unshift(`${e}#${t}`);break}if(typeof r.getAttribute==`function`){let t=(r.getAttribute(`class`)||``).split(/\s+/).filter(Boolean)[0];t&&/^[A-Za-z][\w-]*$/.test(t)&&(e+=`.${t}`)}let a=r.parentElement;if(a){let t=Array.from(a.children).filter(e=>e.tagName===r.tagName);t.length>1&&(e+=`:nth-of-type(${t.indexOf(r)+1})`)}n.unshift(e),r=a,i++}return n.join(` > `)}function US(e,t,n={}){if(!e)return{hits:[],total:0,truncated:!1};let r=Math.max(1,Math.min(n.limit??10,20)),i=n.mode??`selector`,a=[];if(i===`selector`)try{a=Array.from(e.querySelectorAll(t))}catch{return{hits:[],total:0,truncated:!1}}else{a=Array.from(e.querySelectorAll(`*`)).filter(e=>{let n=e.tagName.toLowerCase();if(n===`script`||n===`style`||n===`noscript`)return!1;let r=(e.textContent||``).trim();return r.length>0&&r.includes(t)});let n=a.slice(0,100),r=new Set(n);a=n.filter(e=>{for(let t of r)if(t!==e&&e.contains(t))return!1;return!0})}let o=Math.min(a.length,r);return{hits:a.slice(0,o).map(e=>{let n=(typeof e.textContent==`string`&&e.textContent?e.textContent:Array.from(e.childNodes??[]).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``)).replace(/\s+/g,` `).trim(),r=n.slice(0,120);if(i!==`selector`&&t){let e=n.indexOf(String(t));e>=0&&(r=(e>100?`…`:``)+n.slice(Math.max(0,e-100),e+120)+(e+120<n.length?`…`:``))}return{selector:HS(e),tag:e.tagName.toLowerCase(),text:r}}),total:a.length,truncated:a.length>o}}var WS=[`content`,`display`,`width`,`height`,`background-color`,`position`];function GS(e,t={}){if(!e)return null;let n={selector:HS(e),tag:e.tagName.toLowerCase(),attrs:{}};for(let t of Array.from(e.attributes))!(TS.includes(t.name)||t.name.startsWith(`data-`))||ES.test(t.name)||DS.test(t.name)||(n.attrs[t.name]=t.value);let r=Array.from(e.childNodes).filter(e=>e.nodeType===3).map(e=>e.textContent||``).join(``).trim();r&&(n.text=r.slice(0,400));let i=String(e.innerText??e.textContent??``).trim();if(i&&(n.textAll=i.slice(0,1e3)),(t.includeRect??!0)&&typeof e.getBoundingClientRect==`function`){let t=e.getBoundingClientRect();n.rect={x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}}if(t.includeHtml){let r=Math.min(t.htmlLimit??1500,4e3),i=e.outerHTML??``;n.html=i.length>r?i.slice(0,r)+`…(截断 ${i.length-r} 字符)`:i}let a=t.getComputedStyle??globalThis.window?.getComputedStyle?.bind(globalThis.window),o=n=>{let r={};if(typeof a!=`function`)return r;try{let i=a(e,n??null);for(let e of n?WS:t.styles??LS){let t=typeof i.getPropertyValue==`function`?i.getPropertyValue(e):i[e];t&&(r[e]=String(t).slice(0,200))}}catch{}return r};if((t.styles===void 0||t.styles.length>0)&&(n.styles=o()),t.pseudo&&(n.pseudoStyles={before:o(`::before`),after:o(`::after`)}),t.includeEvents!==!1){let t=Array.from(e.attributes).filter(e=>/^on\w+$/i.test(e.name)).map(e=>({type:e.name.toLowerCase().slice(2),snippet:e.value.slice(0,100)})),r=e.__vueParentComponent?.vnode?.props;n.events={inline:t,vue:r?Object.keys(r).filter(e=>/^on[A-Z]/.test(e)).map(e=>e.slice(2).toLowerCase()):[],captured:VS(e)}}return n}var KS=(0,i.tool)(({query:e,mode:t,limit:n,root:r})=>{BS();let i=r?document.querySelector(r):document;if(r&&!i)return`未找到 root 元素:selector="${r}"`;let a=US(i,e,{mode:t,limit:n});return a.total?JSON.stringify({...a,note:a.truncated?`共 ${a.total} 处命中,仅返回前 ${a.hits.length} 处`:void 0},null,2):t===`text`?`未找到包含文本「${e}」的元素`:`selector "${e}" 未匹配到元素`},{name:`dom_search`,description:`搜索页面元素:CSS 选择器或可见文本两种模式,返回命中元素的 CSS 路径 + 文本片段(≤20 处)。定位元素/查渲染结果用;找到 selector 后可用 dom_info 看详情或 get_dom 看结构。`,schema:t.z.object({query:t.z.string().describe(`selector 模式 = CSS 选择器(如 ".banner .title");text 模式 = 文本关键词`),mode:t.z.enum([`selector`,`text`]).optional().describe(`搜索模式(默认 selector;text = 文本包含匹配)`),limit:t.z.number().int().min(1).max(20).optional().describe(`返回上限(默认 10)`),root:t.z.string().optional().describe(`限定搜索范围的容器选择器(默认整页)`)})}),qS=(0,i.tool)(({selector:e,styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o})=>{BS();let s=document.querySelector(e);if(!s)return`未找到匹配元素:selector="${e}"(可先用 dom_search 定位)`;let c=GS(s,{styles:t,includeHtml:n,htmlLimit:r,includeEvents:i,includeRect:a,pseudo:o});return c?JSON.stringify(c,null,2):`selector="${e}" 读取失败`},{name:`dom_info`,description:`读单个元素完整信息:内容(直接文本/全文本/HTML 片段)+ 计算样式(默认排障高频预设,可指定属性列表)+ 几何位置 + 事件绑定(inline on*/Vue props/addEventListener 记录;记录器仅覆盖 SDK 加载后注册的监听)。验证样式落地/排查交互绑定用。`,schema:t.z.object({selector:t.z.string().describe(`CSS 选择器(取首个匹配;可先用 dom_search 定位)`),styles:t.z.array(t.z.string()).optional().describe(`计算样式属性列表(不传 = 常用预设 ~30 项)`),includeHtml:t.z.boolean().optional().describe(`是否含 outerHTML 片段(默认 false,大 HTML 省 token)`),htmlLimit:t.z.number().int().min(100).max(4e3).optional().describe(`HTML 片段上限字符(默认 1500)`),includeEvents:t.z.boolean().optional().describe(`是否含事件绑定(默认 true)`),includeRect:t.z.boolean().optional().describe(`是否含几何位置(默认 true)`),pseudo:t.z.boolean().optional().describe(`是否含 ::before/::after 伪元素摘要(默认 false)`)})}),JS=`dom-inspect`;function YS(e={}){return{name:JS,description:`页面 DOM 深度检视工具(dom_search 搜索元素 / dom_info 读内容·计算样式·事件绑定·几何)。定位元素、验证样式落地、排查交互绑定时加载`,getContent:()=>[`# DOM 检视工具用法`,`## read_page({ selector?, offset?, limit? })—— 读正文首选`,`- 返回页面正文纯文本(JSON:text/totalChars/offset/hasMore/container),自动定位 article/main/[role=main]/.content 容器并排除本对话框自身与 script/style`,`- 长文分页:默认每次 4000 字符;hasMore=true 时下一次调用传 offset=上次 offset+本次 text 长度 续读`,`- 回答「这个页面讲了什么/某段在哪」类问题用 read_page,不要用 get_dom 逐层翻结构(爆 token)`,`## dom_search({ query, mode?, limit?, root? })`,`- mode="selector"(默认):query 为 CSS 选择器;mode="text":文本关键词包含匹配(跳过 script/style)`,`- 返回命中列表:CSS 路径(selector)+ 文本片段;超 limit 标注总数`,`## dom_info({ selector, styles?, includeHtml?, pseudo?, ... })`,`- selector 取首个匹配(先用 dom_search 定位更稳)`,`- styles 不传 = 排障高频预设(display/position/color/background/font/z-index/transform 等约 30 项);传数组 = 只取指定属性`,`- includeHtml: true 附 outerHTML 片段(默认省);pseudo: true 附 ::before/::after 摘要`,`- events 三源:inline on* 属性 / Vue vnode props(onXxx)/ addEventListener 记录器(⚠ 仅记录本 SDK 加载之后注册的监听,更早的挂载捕不到)`,`- rect:视口坐标 + 宽高(验证可见性/布局)`,...e.withScreenshot?[`## take_screenshot({ selector?, fullPage? })—— 视觉验证`,`- 截图「看」页面:selector 截指定元素区域 / fullPage 截整页 / 都不传截当前视口;截图经压缩投递(多模态直看图,纯文本模型自动走识图转述)`,`- 布局/样式/渲染效果类问题优先截图(视觉真值),结构/属性类用 dom_info;截图失败(CSP/跨域图)会回灌原因与替代建议`]:[],...e.withDomEdit?[`## dom_edit({ patches, dryRun? })—— 修改页面元素(宿主开启才有)`,`- patches 批量原子(任一失败整批拒绝):set_text/set_html(内容)、set_attr/remove_attr、add_class/remove_class、set_style、insert(新建元素 anchor+position: before/after/prepend/append/replace)、remove、move(层级调整)、highlight(高亮+滚动)`,`- 写纪律:selector 必须唯一命中(多匹配被拒,用 dom_search 拿精确路径);先读后写(get_dom/dom_info 看现状);拿不准先 dryRun 预检`,`- 改前自动快照:dom_restore 回滚最近一批(可连续回退);改动为会话临时态(刷新即失);数据驱动页面改数据(write)不要改 DOM`]:[],`## 排障套路`,...e.withScreenshot?[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. 视觉验证 take_screenshot / 结构验证 dom_info(styles) → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]:[`1. dom_search(mode:"text", query:按钮文案) 定位 → 2. dom_info(styles:["display","background-color","pointer-events"]) 验证样式/点击性 → 3. `+(e.withDataOps?`不符则改数据(write 修正后再验证)`:`不符则如实报告差异(页面为真值;本页面无数据写通道,调整预期或告知用户)`)]].join(`
2990
2990
  `),tools:[()=>[KS,qS]]}}var XS=`page-analysis`;function ZS(e={}){return{name:XS,description:`页面内容分析策略:按问题类型选工具(引用原文/整页理解/定位/结构/视觉/页面操作),含分页探索纪律与基于页面实料的回答纪律。回答用户关于当前页面的问题时加载`,getContent:()=>[`# 页面内容分析策略`,`## 第一步:问题分型(按类型选主力工具,不要一上来读整页)`,`- **引用原文类**(用户消息带引用块):优先围绕引用原文作答;需要上下文再向外探索(所在小节 → 整页)`,`- **整页理解类**(「这页讲了什么/总结要点」):read_page 读正文,长文按 hasMore 翻页,边读边归纳不要一次读爆`,`- **定位类**(「某概念在本页哪里/那个按钮在哪」):dom_search mode:"text" 按关键词定位 → 需要细节再 read_page 带 selector 读该区域`,`- **结构/属性类**(「这个区块是什么组件/有哪些属性」):dom_info(selector) 读单元素;层级关系用 get_dom`,...e.withScreenshot?[`- **视觉类**(「看起来对不对/布局乱不乱/渲染效果」):take_screenshot 截图看视觉真值;selector 截局部、fullPage 截整页;截图是唯一能看到实际渲染效果的手段,结构推断不能代替`]:[],...e.withDomEdit?[`- **操作类**(「把这段高亮/隐藏广告/调大字体/把这个块挪过去」):dom_edit patches 批量操作;纪律 = 先 get_dom/dom_search 定位唯一 selector → 拿不准先 dryRun → 改后 dom_info/截图验证 → 不满意 dom_restore 回滚;页面是临时态,持久修改要走宿主自己的机制`]:[],`## 探索纪律`,`1. **先窄后宽**:引用/焦点 → 所在小节 → 整页;每一步只取够回答当前问题的量`,`2. **翻页不重复**:read_page 续读传 offset = 上次 offset + 返回 text 长度;不要回头重读已读区`,`3. **定位失败换路**:selector 不命中 → dom_search text 模式换关键词;还不中 → read_page 扫小节标题再回来`,...e.withVfs?[`4. **大结果在外存**:超大结果被移入 vfs 后用 vfs_read/vfs_grep 按需取,不要盲目重调`]:[],`## 回答纪律(页面问答的底线)`,`- **基于页面实料**:答案须来自你读到的页面内容(引用原文/read_page/dom 工具结果),并在回答中点明出处小节/位置`,`- **页面 ≠ 训练数据**:页面内容可能与你的先验知识不同,冲突时以页面为准;页面没写的不要编造`,`- **不确定就说不确定**:找不到的内容如实说「本页未找到」,给出已探索的范围,勿凭印象补全`,`## 输出纪律(直接说内容,不写过程)`,`- 禁**过程叙述**:「我先读一下页面」「让我确认一下」—— 工具调用用户看得见,不需要旁白`,`- 禁**元话术**:「先给结论」「依据是」「简言之」—— 第一句直接就是答案本身,不要先宣布你要说什么`,`- 禁**方法论自述**:不要解释结论是怎么来的(「这些不是页面写明的,而是从正文用词反推的」)—— 那是你的内部过程`,`- 禁**预告与套话**:「下面分三点」「综上」—— 该分点就直接分点,说完就停`,`- 出处仍要标,但用最简形式:句末括注(如「(§小节名)」「(原文)」);引原文时直接引,不写「依据是…原文两行:」这样的引导句`].join(`
2991
- `)}}var QS=YS();function $S(e){let t=e;return typeof t.tagName==`string`||typeof t.nodeType==`number`&&typeof t.nodeName==`string`}function eC(e,t=3,n=2e3,r,i){if(e==null)return e;if(typeof e==`string`)return e.length>n?e.slice(0,n)+`…(已截断)`:e;if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(typeof e==`symbol`)return e.toString();if(typeof e==`bigint`)return`${e.toString()}n`;if(typeof e!=`object`)return String(e);let a=e;if($S(a)){let e=a;return e.tagName?`[Element: <${e.tagName.toLowerCase()}>]`:`[Node: ${e.nodeName}]`}if(r?.has(a))return`[Circular]`;let o=r??new WeakSet;if(o.add(a),Array.isArray(e)){let r=e.slice(0,100).map(e=>eC(e,t-1,n,o,i));return e.length>100&&r.push(`…(共 ${e.length} 项,已截断)`),r}if(t<0)return`(对象,已截断)`;let s={},c=Object.keys(a);for(let e=0;e<c.length;e++){let r=c[e];if(e>=50){s[`…`]=`(共 ${c.length} 键,已截断)`;break}try{let e=a[r];i?.test(r)?s[r]=`[REDACTED]`:s[r]=eC(e,t-1,n,o,i)}catch{s[r]=`(getter 抛错)`}}return s}function tC(e){let t=e??(typeof window<`u`?window:{}),n=t.navigator,r=t.location,i=t.document;return{location:{href:r?.href,origin:r?.origin,protocol:r?.protocol,host:r?.host,hostname:r?.hostname,pathname:r?.pathname,search:r?.search},navigator:{userAgent:n?.userAgent,language:n?.language,languages:n?.languages,platform:n?.platform,onLine:n?.onLine},viewport:{innerWidth:t.innerWidth,innerHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio,scrollX:t.scrollX,scrollY:t.scrollY},document:i?{title:i.title,readyState:i.readyState,characterSet:i.characterSet}:`(无 document)`}}var nC=/^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/,rC=/token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i,iC=(0,i.tool)(({key:e})=>{if(e){if(nC.test(e)||rC.test(e))return JSON.stringify({key:e,denied:!0,reason:`安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏`},null,2);let t=(typeof window<`u`?window:{})[e];return JSON.stringify({key:e,exists:t!==void 0,type:typeof t,value:eC(t,3,2e3,void 0,rC)},null,2)}return JSON.stringify(tC(),null,2)},{name:`inspect_env`,description:`读宿主页面环境信息(排查调试)。不传参返回摘要(URL/origin、浏览器/语言、viewport、title/readyState);传 key 读指定 window 属性值(如 key:"appConfig")。只读,大结果自动外存 vfs。`,schema:t.z.object({key:t.z.string().optional().describe(`要读取的 window 属性名(如 "appConfig"/"__DEBUG__");不传 = 返回环境摘要`)})}),aC=[iC];function oC(e,t,n){let i=0;return{name:`budget`,beforeAgent:()=>{i=Date.now()},wrapModelCall:async(a,o)=>{let{tokenBudget:s,timeBudgetMs:c}=t,l=s!=null&&(e.total_tokens??0)>s,u=c!=null&&Date.now()-i>c;return l||u?(n({type:`error`,severity:`observable`,code:`BUDGET_EXCEEDED`,message:`资源预算超限:${l?`token 超限(累计 ${e.total_tokens??0} > 上限 ${s})`:`时间超限(${Date.now()-i}ms > 上限 ${c}ms)`},agent 已停止(未完成部分可用 restoreLastCheckpoint 回退)。`}),{message:new r.AIMessage({content:``}),content:``,toolCalls:[],aborted:!0}):o(a)}}}var sC=/^[a-zA-Z][a-zA-Z0-9_]*$/;function cC(e){let n=[];for(let[r,a]of Object.entries(e)){if(!sC.test(r)){console.warn(`[page-agent-sdk][actions] 动作名 "${r}" 非法(须匹配 ${sC}),已跳过`);continue}let e=a.description||`宿主动作 ${r}`;n.push((0,i.tool)(async e=>{try{let t=await a.run(e||{});return t===void 0?`动作 ${r} 执行完成。`:typeof t==`string`?t:JSON.stringify(t)}catch(e){let t=e?.message||String(e);return`动作 ${r} 执行失败:${t}`}},{name:r,description:e,schema:a.params??t.z.object({})}))}return n}function lC(e){let t={};for(let[n,r]of Object.entries(e))sC.test(n)&&(t[n]={description:r.description,hasParams:!!r.params,readsHostState:r.readsHostState===!0,deferredWrite:r.deferredWrite===!0});return t}var uC=wS,dC=IS;function fC(e,t){return ev(e,t)}function pC(e,t,n,r,i){let a=sb(e);return[...a.dataOps?t:[],...a.fetch?n:[],...a.domInspect&&r?r:[],...a.inspectEnv&&i?i:[]]}var mC=.7,hC=.5,gC=.85;function _C(e,t){if(!Number.isFinite(t)||t<=0||e<=0||e<t*hC)return``;let n=Math.max(1,Math.round(e/1e3));return e>=t*gC?`⏳ 预算告急:本任务累计约 ${n}K prompt tokens(已达 softCap 上限的 ${Math.round(gC*100)}%)。立即停止扩展性操作(新查询/重读/优化),完成手头最关键一步后基于已有工具结果给出结论,并如实汇报剩余未完成项。轮次预算吃紧时系统会另行注入轮次提示段。`:`⏳ 预算提示:本任务累计约 ${n}K prompt tokens(已过 softCap 半程)。若已接近目标请收敛并给出总结;尚未接近请向用户汇报进度与剩余计划,勿默默继续。轮次预算吃紧时系统会另行注入轮次提示段。`}function vC(e,t,n){let r=sb(e);return{name:`usageHints`,augmentPrompt:i=>{let a=[];if(r.planning&&(a.push(`【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:`),a.push(` · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。`),a.push(` · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。`),a.push(` · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。`),a.push(` · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 "components.2"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。`),e?.humanConfirm?a.push(` · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。`):a.push(` · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。`),a.push(` · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。`)),t&&(a.push(`改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。`),a.push(`读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。`),a.push(`修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。`),a.push(`修改主数据出错时可用 restore_data 回退最近一次。`),a.push(`在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type=="card" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。`),a.push(`找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。`),a.push(`需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。`),a.push(`读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。`),a.push(`【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:"set",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。`),a.push(`读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:"该子树路径"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。`),a.push(`对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/"刚才改了啥");只读查历史快照值用 history_data({id?,jsonPath?})。`)),r.subagent&&a.push(`独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。`),r.inspectEnv&&a.push(`排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:"appConfig"}) 读 window.appConfig)。改完数据看渲染、定位"为何没生效"时用它(只读,不改数据)。`),r.domInspect){let n=t&&e?.hasActions?`配合宿主 actions(save_draft/publish 等)形成"改数据→截图/get_dom 看渲染→触发动作"闭环。`:t?`改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。`:``;a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}`)}if(e?.screenshot&&a.push(`视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。`),e?.domEdit&&a.push(`修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。`),e?.viewImage&&a.push(`看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。`),e?.hasProposals&&a.push(`【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。`),r.draftWrite&&(a.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。`),a.push(`⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。`)),r.focus&&(a.push(`【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:`),a.push(` · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:"该子树路径"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。`),a.push(` · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。`),a.push(` · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。`),a.push(` · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。`),a.push(` · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。`)),e?.subagents?.length){let t=e.subagents.filter(e=>(e.temperature??0)>=mC||/规划|创意|设计|方案|brainstorm|plan/i.test(e.description)),n=e.subagents.filter(e=>(e.temperature??0)<mC&&/反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));a.push(`【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:`),t.length&&(a.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map(e=>`use_`+e.id).join(`/`)} 出 2-3 套方案(高温创意),`),a.push(e?.humanConfirm?` 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。`:` 不要自己拍板;拿到方案后以文字列出选项等用户回复(humanConfirm 未开,勿调不存在工具)。`)),n.length&&a.push(` · 严谨/易错/校验类 → 可先调 ${n.map(e=>`use_`+e.id).join(`/`)} 反思挑刺(低温审查),据反馈修订。`),a.push(` · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。`),a.push(` · 简单/明确任务(如"标题改红色")直接执行,不必走规划-反思。`)}e?.humanConfirm&&(a.push(`【人工确认·必读】以下情形必须先调 request_human_confirmation 征询用户、拿到答复后再继续,不要自行拍板:`),a.push(` 1) 用户让你「给方案/列选项/我来选/挑一个」时:把每个方案作为一个 option,调 request_human_confirmation(question=简述, options=[方案A,方案B,...], recommendation=你推荐的)。不要只回文字罗列方案让用户自己回复——要用工具把选项做成可点选按钮。`),a.push(` 2) 需求有歧义/不确定时:调工具问清楚(options 不传则用户答同意或拒绝)。`),a.push(` 3) 即将执行高风险不可逆操作(删除/覆盖/批量改动)前:调工具确认。`),a.push(` 4) 规划出多步方案需用户确认时:把整个方案(或关键分步)作为 option 调 request_human_confirmation,确认后再执行。`),a.push(`用户在选项里选了哪个,就按那个方案继续;选「拒绝」则停止并询问如何调整。`));let o=i?.loopProgress;if(o){let e=_C(o.invokeUsage.prompt_tokens||o.invokeUsage.total_tokens,n?.promptSoftCap??1/0);e&&a.push(e);let t=Object.entries(o.writeFailures).filter(([,e])=>e>=2);if(t.length){let e=t.map(([e,t])=>`${e||`(整体)`}×${t}`).join(`、`);a.push(`⚠️ 以下路径已连续写失败:${e}。连续失败常意味着方向错了——先 read 重新核对实际值/类型,或 restore_data 回退后再改;若确需继续,换思路而非原样重试。`)}}return a.length&&a.unshift(`调用工具务必用标准 function calling(工具调用)格式发起,不要在回复正文里输出伪 XML/标签(如 deepseek 的 tool_calls 标签、invoke、function_call、tool_call 等)或 JSON 文本——那不会被识别为工具调用,会被当普通文字,工具不执行。`),a.length?`## 能力使用提示
2991
+ `)}}var QS=YS();function $S(e){let t=e;return typeof t.tagName==`string`||typeof t.nodeType==`number`&&typeof t.nodeName==`string`}function eC(e,t=3,n=2e3,r,i){if(e==null)return e;if(typeof e==`string`)return e.length>n?e.slice(0,n)+`…(已截断)`:e;if(typeof e==`number`||typeof e==`boolean`)return e;if(typeof e==`function`)return`[Function: ${e.name||`anonymous`}]`;if(typeof e==`symbol`)return e.toString();if(typeof e==`bigint`)return`${e.toString()}n`;if(typeof e!=`object`)return String(e);let a=e;if($S(a)){let e=a;return e.tagName?`[Element: <${e.tagName.toLowerCase()}>]`:`[Node: ${e.nodeName}]`}if(r?.has(a))return`[Circular]`;let o=r??new WeakSet;if(o.add(a),Array.isArray(e)){let r=e.slice(0,100).map(e=>eC(e,t-1,n,o,i));return e.length>100&&r.push(`…(共 ${e.length} 项,已截断)`),r}if(t<0)return`(对象,已截断)`;let s={},c=Object.keys(a);for(let e=0;e<c.length;e++){let r=c[e];if(e>=50){s[`…`]=`(共 ${c.length} 键,已截断)`;break}try{let e=a[r];i?.test(r)?s[r]=`[REDACTED]`:s[r]=eC(e,t-1,n,o,i)}catch{s[r]=`(getter 抛错)`}}return s}function tC(e){let t=e??(typeof window<`u`?window:{}),n=t.navigator,r=t.location,i=t.document;return{location:{href:r?.href,origin:r?.origin,protocol:r?.protocol,host:r?.host,hostname:r?.hostname,pathname:r?.pathname,search:r?.search},navigator:{userAgent:n?.userAgent,language:n?.language,languages:n?.languages,platform:n?.platform,onLine:n?.onLine},viewport:{innerWidth:t.innerWidth,innerHeight:t.innerHeight,devicePixelRatio:t.devicePixelRatio,scrollX:t.scrollX,scrollY:t.scrollY},document:i?{title:i.title,readyState:i.readyState,characterSet:i.characterSet}:`(无 document)`}}var nC=/^(localStorage|sessionStorage|cookie|document|frames|frameElement|opener|parent|top|self|window|globalThis|closed|history|navigation|trustedTypes|origin|crossOriginIsolated)$/,rC=/token|secret|password|passwd|api[-_]?key|auth|cred|csrf|session|ticket/i,iC=(0,i.tool)(({key:e})=>{if(e){if(nC.test(e)||rC.test(e))return JSON.stringify({key:e,denied:!0,reason:`安全:该 key 在 denylist(localStorage/sessionStorage/cookie/document 或敏感命名 token/secret/key/auth),不读取防泄漏`},null,2);let t=(typeof window<`u`?window:{})[e];return JSON.stringify({key:e,exists:t!==void 0,type:typeof t,value:eC(t,3,2e3,void 0,rC)},null,2)}return JSON.stringify(tC(),null,2)},{name:`inspect_env`,description:`读宿主页面环境信息(排查调试)。不传参返回摘要(URL/origin、浏览器/语言、viewport、title/readyState);传 key 读指定 window 属性值(如 key:"appConfig")。只读,大结果自动外存 vfs。`,schema:t.z.object({key:t.z.string().optional().describe(`要读取的 window 属性名(如 "appConfig"/"__DEBUG__");不传 = 返回环境摘要`)})}),aC=[iC];function oC(e,t,n){let i=0;return{name:`budget`,beforeAgent:()=>{i=Date.now()},wrapModelCall:async(a,o)=>{let{tokenBudget:s,timeBudgetMs:c}=t,l=s!=null&&(e.total_tokens??0)>s,u=c!=null&&Date.now()-i>c;return l||u?(n({type:`error`,severity:`observable`,code:`BUDGET_EXCEEDED`,message:`资源预算超限:${l?`token 超限(累计 ${e.total_tokens??0} > 上限 ${s})`:`时间超限(${Date.now()-i}ms > 上限 ${c}ms)`},agent 已停止(未完成部分可用 restoreLastCheckpoint 回退)。`}),{message:new r.AIMessage({content:``}),content:``,toolCalls:[],aborted:!0}):o(a)}}}var sC=/^[a-zA-Z][a-zA-Z0-9_]*$/;function cC(e){let n=[];for(let[r,a]of Object.entries(e)){if(!sC.test(r)){console.warn(`[page-agent-sdk][actions] 动作名 "${r}" 非法(须匹配 ${sC}),已跳过`);continue}let e=a.description||`宿主动作 ${r}`;n.push((0,i.tool)(async e=>{try{let t=await a.run(e||{});return t===void 0?`动作 ${r} 执行完成。`:typeof t==`string`?t:JSON.stringify(t)}catch(e){let t=e?.message||String(e);return`动作 ${r} 执行失败:${t}`}},{name:r,description:e,schema:a.params??t.z.object({})}))}return n}function lC(e){let t={};for(let[n,r]of Object.entries(e))sC.test(n)&&(t[n]={description:r.description,hasParams:!!r.params,readsHostState:r.readsHostState===!0,deferredWrite:r.deferredWrite===!0});return t}var uC=wS,dC=IS;function fC(e,t){return ev(e,t)}function pC(e,t,n,r,i){let a=sb(e);return[...a.dataOps?t:[],...a.fetch?n:[],...a.domInspect&&r?r:[],...a.inspectEnv&&i?i:[]]}var mC=.7,hC=.5,gC=.85;function _C(e,t){if(!Number.isFinite(t)||t<=0||e<=0||e<t*hC)return``;let n=Math.max(1,Math.round(e/1e3));return e>=t*gC?`⏳ 预算告急:本任务累计约 ${n}K prompt tokens(已达 softCap 上限的 ${Math.round(gC*100)}%)。立即停止扩展性操作(新查询/重读/优化),完成手头最关键一步后基于已有工具结果给出结论,并如实汇报剩余未完成项。轮次预算吃紧时系统会另行注入轮次提示段。`:`⏳ 预算提示:本任务累计约 ${n}K prompt tokens(已过 softCap 半程)。若已接近目标请收敛并给出总结;尚未接近请向用户汇报进度与剩余计划,勿默默继续。轮次预算吃紧时系统会另行注入轮次提示段。`}function vC(e,t,n){let r=sb(e);return{name:`usageHints`,augmentPrompt:i=>{let a=[];if(r.planning&&(a.push(`【自适应规划】按任务复杂度决定是否先规划,不要对简单任务过度编排:`),a.push(` · 简单/明确任务(改单字段、调样式、查值)→ 直接 read/write 执行,不必 write_todos。`),a.push(` · 复杂任务(多步、大改、有歧义、不可逆)→ 先 write_todos 拆解,首个任务标 in_progress,逐项推进。`),a.push(` · 执行中发现步骤要改/补/细分 → 用 update_todo({id, content?, status?}) 按 id 增量改单项,不必重传整个清单。`),a.push(` · update_todo 标 completed 时附 evidence: 本次实际写入的 jsonPath(如 "components.2"),供收口对账;工作经委派子 agent 完成等无主写路径时,如实写明完成方式(勿编造路径)。`),e?.humanConfirm?a.push(` · 规划出多步方案若需用户拍板 → 先 request_human_confirmation 给方案选项,确认后再执行。`):a.push(` · 规划出多步方案若需用户拍板 → 以文字列出方案选项等用户回复,勿自行拍板。`),a.push(` · 计划修订有次数上限(maxPlanRevisions,默认 5,只计 write_todos 调用、调研轮不计):勿反复改计划而不执行,规划充分后即开始 write 落地。`)),t&&(a.push(`改主数据前先 read({jsonPath}) 读其当前真实值(返回末尾 hash=xxx 为乐观锁标识),基于真实值改,不要凭记忆。写入是否被自动校验由集成方 conflictWatchFields 声明决定:若已声明且主数据在你 read 之后被外部改过,会触发冲突——集成方若开启人工介入,工具会挂起等用户决定(保留外部/强制覆盖/回退),你应等待工具返回后按结果继续(保留外部→重新 read 再改;强制覆盖→已写入,继续;回退→已回退到历史快照,基于回退值重写);未开启人工介入时返回 VERSION_CONFLICT 不写入,重新 read 拿最新值再改。`),a.push(`读类分流:取值/结构 → read(多路径用 jsonPaths);字段约束 → schema_data;条件筛选定位 → query_data(多条一次用 queries);名字模糊找 → search_data;整体说明 → read 不传路径。`),a.push(`修改大对象/数组优先用 write 增量改({patch:{op,jsonPath,value}} 只发改动部分),避免 write({value}) 整体重传被 max_tokens 截断导致 JSON 不完整、校验失败。`),a.push(`修改主数据出错时可用 restore_data 回退最近一次。`),a.push(`在大数组里按条件筛选元素用 query_data(JSONPath,如 $.components[?(@.type=="card" && @.price<100)]),返回匹配元素的 path/index;定位后再 write({patch}) 改。`),a.push(`找名字记不清的元素用 search_data(支持 substring/regex/fuzzy 模糊搜索)。`),a.push(`需要过滤/映射/聚合/批量重写大数组时用 eval_script(沙箱脚本,入参 data);只读探查用 mode=query,批量重写用 mode=transform(返回值经校验后落地)。`),a.push(`读大数组用 read({jsonPath,offset,limit}) 分页(返回 hasMore=true 时 offset+=limit 续读);一次读多个不相关子路径用 read({jsonPaths});复杂改动先 write({...,dryRun:true}) 预检不落盘。`),a.push(`【省轮次·批量】≥2 个路径一律 read({jsonPaths:[...]}) 一次取回(路径互不相关也合批,禁止连续单路径 read);多条件筛选用 query_data({queries:[expr1,expr2,…]}) 一次取回(2-10 条);改多处用 write({patches:[{op:"set",jsonPath,value},...]}) 一次提交多改动(原子任一失败回滚),勿逐个 write 烧轮次预算。`),a.push(`读到 <subtree Nkb keys:[…] #指纹> 或 <code Nkb> 占位 = 该子树键名/体积可见但内容未见:写入前先窄读全文(read({jsonPath:"该子树路径"}),结果根豁免返全文)或 set_focus 聚焦该区域;勿凭键名印象猜路径/猜值直写(直接写占位子树会被拦下要求先窄读)。`),a.push(`对比当前与历史快照(或一段 JSON against)的差异用 diff_data({snapshotId?,against?})(返回结构化 path→from/to,verify 自纠/操作审计/"刚才改了啥");只读查历史快照值用 history_data({id?,jsonPath?})。`)),r.subagent&&a.push(`独立子任务可 spawn_agent 委派(过程隔离,不占主上下文):默认只读,需要子 agent 写数据时传 writablePaths(路径前缀白名单,越界 PATH_OUT_OF_SCOPE)。多个独立子任务可 spawn_agents 并行委派(各子互不通信,结论由你汇总;并行委派不可授写权限,写操作由你收尾执行)。`),r.inspectEnv&&a.push(`排查页面环境(当前 URL/浏览器/视口/集成方调试变量)用 inspect_env——不传参返回环境摘要(location/navigator/viewport/document),传 key 读特定 window 属性(如 inspect_env({key:"appConfig"}) 读 window.appConfig)。改完数据看渲染、定位"为何没生效"时用它(只读,不改数据)。`),r.domInspect){let n=t&&e?.hasActions?`配合宿主 actions(save_draft/publish 等)形成"改数据→截图/get_dom 看渲染→触发动作"闭环。`:t?`改完数据可用截图/get_dom 查看渲染效果(本集成未注册宿主动作)。`:``,r=e?.skills?`长文按关键词定位(找某术语/某节在哪)先 load_skill("dom-inspect") 取得 dom_search 文本检索,命中后窄读那一节 —— 勿整页翻页找。`:``;a.push(`回答用户关于当前页面/文档的问题时优先用 read_page({selector?,offset?,limit?}) 读页面正文纯文本(长文按 hasMore 分页续读;自动排除本对话框自身);需要页面结构(检查渲染是否生效/定位元素/辅助 UI 设计问答)再用 get_dom({selector?,depth?}) 读渲染后 DOM(结构化返回 tag/attrs/text/children,depth 控制深度防爆炸,只读)。${n}${r}`)}if(e?.screenshot&&a.push(`视觉验证(看布局/样式/渲染效果像不像、对不对)用 take_screenshot({selector?, fullPage?}) 截图查看:selector 截指定元素、fullPage 截整页、默认当前视口;截图自动压缩投递(多模态直看图/纯文本模型走识图转述)。优先级:视觉问题先截图,结构/属性问题用 dom_info。`),e?.domEdit&&a.push(`修改宿主页面元素(高亮/改文案/调样式/插删移元素)用 dom_edit({patches:[{op,selector,...}],dryRun?}) 批量原子操作(op:set_text/set_html/set_attr/add_class/remove_class/set_style/insert/remove/move/highlight);selector 必须唯一命中(先 get_dom/dom_search 定位);改前自动快照,dom_restore 回滚最近一批;改动为会话临时态(刷新即失)——数据驱动页面改数据(write)不要改 DOM。`),e?.viewImage&&a.push(`看「页面数据里的某张图」(轮播第 N 帧/商品图/封面,read 结果里有其 URL)用 view_image({url}) 原图直投 —— 问特定帧时勿截当前渲染帧(自动轮播可能已切帧);要看渲染后的组件(布局/叠加文案)才用 take_screenshot。`),e?.hasProposals&&a.push(`【内容修改(提案制)】修改当前内容(文章/笔记/文档)只有一条通道:①先 read_content 取真实原文与 hash;②propose_content 带 baseHash 提案 —— 优先 ops 增量操作(replace/insertAfter/insertBefore/append,find/anchor 用原文字面片段且须唯一命中,多带上下文保唯一),勿全量重发整篇(token 只花在改动上);③提案仅送达:评审面板打开、用户点「应用」才会写回 —— 提案后如实告知用户待确认,勿声称已修改;用户裁决结果会在下一轮告知你,以裁决为准作答。`),r.draftWrite&&(a.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。`),a.push(`⚠️ 大 JSON 分块构建是典型多轮工具调用(draft_write×N + draft_commit + read 确认 + 调研 read/query),默认 maxToolRounds=30(3.43 起;轮次预算吃紧时 system 会注入预算提示段,按提示优先收口);目标组件数很大时集成方仍可在 createChatSdk 显式上调 maxToolRounds(按 N+10 估算)。draft_commit 提交同样走乐观锁(改前 read 拿 hash,bind 被改过会触发冲突介入,不静默覆盖)。`)),r.focus&&t&&(a.push(`【上下文聚焦】判断任务范围,用 set_focus/add_focus/remove_focus/clear_focus 自动收敛工作范围:`),a.push(` · 局部任务(只改某一组件/区域,如「调导航栏」「改 components.3 样式」)→ 先 read 定位 jsonPath,再 set_focus({path:"该子树路径"}) 聚焦;聚焦后每轮只看该子树结构,写其他位置会被 PATH_DENIED 拒绝。`),a.push(` · 多个相关组件(如「同时改导航栏和页脚」)→ set_focus 聚焦首个后用 add_focus({path}) 追加其余;聚焦后可写任一焦点子树,越界仍被拒;移除单个用 remove_focus({path})。`),a.push(` · 全局任务(多处/整体结构,如「重排所有组件」「换主题」)→ 不要聚焦,保持全量视野直接写。`),a.push(` · 完成局部精修、要转向其他区域或做整体改动 → 调 clear_focus 退出聚焦(清空全部焦点),恢复全部读写权限。`),a.push(` · set_focus/add_focus 的 path 必须在 schema 内(类型校验);不确定路径先 read 查。`)),e?.subagents?.length){let t=e.subagents.filter(e=>(e.temperature??0)>=mC||/规划|创意|设计|方案|brainstorm|plan/i.test(e.description)),n=e.subagents.filter(e=>(e.temperature??0)<mC&&/反思|审查|挑刺|校验|review|critique|reflect/i.test(e.description));a.push(`【规划-反思-执行·路由】按任务性质选模式,不要对简单任务过度编排:`),t.length&&(a.push(` · 创作/设计/开放性需求(如"设计主题风格""换个感觉")→ 先调 ${t.map(e=>`use_`+e.id).join(`/`)} 出 2-3 套方案(高温创意),`),a.push(e?.humanConfirm?` 不要自己拍板;拿到方案后,若需用户拍板用 request_human_confirmation 弹选项。`:` 不要自己拍板;拿到方案后以文字列出选项等用户回复(humanConfirm 未开,勿调不存在工具)。`)),n.length&&a.push(` · 严谨/易错/校验类 → 可先调 ${n.map(e=>`use_`+e.id).join(`/`)} 反思挑刺(低温审查),据反馈修订。`),a.push(` · 方案定稿后,由你(主 agent)用 write 落地成 JSON(低温度执行 + schema 校验 + 写前确认)。`),a.push(` · 简单/明确任务(如"标题改红色")直接执行,不必走规划-反思。`)}e?.humanConfirm&&(a.push(`【人工确认·必读】以下情形必须先调 request_human_confirmation 征询用户、拿到答复后再继续,不要自行拍板:`),a.push(` 1) 用户让你「给方案/列选项/我来选/挑一个」时:把每个方案作为一个 option,调 request_human_confirmation(question=简述, options=[方案A,方案B,...], recommendation=你推荐的)。不要只回文字罗列方案让用户自己回复——要用工具把选项做成可点选按钮。`),a.push(` 2) 需求有歧义/不确定时:调工具问清楚(options 不传则用户答同意或拒绝)。`),a.push(` 3) 即将执行高风险不可逆操作(删除/覆盖/批量改动)前:调工具确认。`),a.push(` 4) 规划出多步方案需用户确认时:把整个方案(或关键分步)作为 option 调 request_human_confirmation,确认后再执行。`),a.push(`用户在选项里选了哪个,就按那个方案继续;选「拒绝」则停止并询问如何调整。`));let o=i?.loopProgress;if(o){let e=_C(o.invokeUsage.prompt_tokens||o.invokeUsage.total_tokens,n?.promptSoftCap??1/0);e&&a.push(e);let t=Object.entries(o.writeFailures).filter(([,e])=>e>=2);if(t.length){let e=t.map(([e,t])=>`${e||`(整体)`}×${t}`).join(`、`);a.push(`⚠️ 以下路径已连续写失败:${e}。连续失败常意味着方向错了——先 read 重新核对实际值/类型,或 restore_data 回退后再改;若确需继续,换思路而非原样重试。`)}}return a.length&&a.unshift(`调用工具务必用标准 function calling(工具调用)格式发起,不要在回复正文里输出伪 XML/标签(如 deepseek 的 tool_calls 标签、invoke、function_call、tool_call 等)或 JSON 文本——那不会被识别为工具调用,会被当普通文字,工具不执行。`),a.length?`## 能力使用提示
2992
2992
  `+a.join(`
2993
2993
  `):void 0}}}function yC(e,t){let n=[`[当前页面] 用户正在浏览:`,`- 标题:${e.title}`,`- URL:${e.url}`,`用户问题通常针对此页面内容。`];return t&&n.push(`需要页面正文时用 read_page 读取纯文本(长文按 hasMore 分页续读);读结构用 get_dom。`),n.join(`
2994
2994
  `)}function bC(e){return{name:`pageContext`,augmentPrompt:()=>{let t=e.getPageInfo();if(t)return yC(t,e.canReadPage)}}}function xC(e){return{name:`resourcesPin`,augmentPrompt:()=>{let t=e.getResourcesSnapshot();if(!t.length)return;let n=[`## 受保护资源(跨压缩保留 · 精确值保护)`];for(let e of t)e.mode===`freeze`?n.push(`- ${e.path} (freeze 已冻结,不可改)`):n.push(`- ${e.path} (verbatim 原样保留)${e.handle?` ⟦res:${e.handle}⟧`:``}`);return n.push(`读到 ⟦frozen:path⟧/⟦res:handle⟧ 占位符 = 精确值在冻结区/资源池(不入消息流);需真值用 resource_get({path});freeze 字段不可写(撞 FROZEN_FIELD 即放弃);verbatim 直接写新值会 VERBATIM_MISMATCH,先 resource_update 再写回句柄;撞 RESOURCE_EVICTED/RESOURCE_NOT_FOUND 重新 read 懒注册。`),n.join(`
@@ -3002,7 +3002,7 @@ ${`- 输出形态:完整、自包含的 HTML 页面(.${r},可独立成页)`}
3002
3002
  `)+`
3003
3003
  (视觉内容如上,请结合图片回答/继续)`,t.map(e=>({dataUri:e.image.dataUri,url:e.image.url})),Pe);n&&e.messages.push(new r.HumanMessage({content:n}))}return t(e)}}:null,Ie=!1,Le=V.domEdit?sS({onEdit:e=>{W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`dom_edit`,ops:e.ops.join(`,`),applied:e.applied,dryRun:e.dryRun}}),!e.dryRun&&e.applied>0&&(Ie=!0)},onRestore:e=>{e.restored>0&&(Ie=!0)}}):[],Re=[...pC(V,be,wS,V.domInspect?[...IS,...Le,...Ne?[Ne]:[],...V.skills?[]:[KS,qS]]:[],aC),...Me?[Me]:[]];Me&&ke.set(`view_image`,`builtin`),Re.forEach(e=>ke.set(e.name,`builtin`));let ze=e.proposals?SS(e.proposals,{emit:e=>{try{Yt(e)}catch{}},log:(e,t)=>{W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`proposal`,kind:e,...t}})}}):null,Be=[...e.tools||[],...ze?.tools??[]];Be.forEach(e=>ke.set(e.name,`user`));let Ve=cC(e.actions??{});Ve.forEach(e=>ke.set(e.name,`action`));let He=ze?e.proposals?.readToolName||`read_content`:null,Ue=ze?e.proposals?.toolName||`propose_content`:null,We=new Set([...Object.entries(e.actions??{}).filter(([,e])=>e?.readsHostState===!0).map(([e])=>e),...He?[He]:[]]),Ge=new Set([...Object.entries(e.actions??{}).filter(([,e])=>e?.deferredWrite===!0).map(([e])=>e),...Ue?[Ue]:[]]),Ke=[],qe=!1,Je=e.humanConfirm!==!1&&(!e.approval||e.approval.humanConfirmTool!==!1),Ye=Je?lg():null;Ye&&ke.set(sg,`builtin`);let Xe=fe&&pe?[(0,i.tool)(async()=>{let e=pe.list();return e.length?pe.restore()?`已回退到最近一次正常状态(checkpoint #${e[e.length-1].id})。对话历史、主数据、vfs、todos 已整体还原。请基于回退后的状态重新判断并继续。`:`回退失败:无可用 checkpoint。`:`无可用 checkpoint,无法回退。`},{name:`restore_last_checkpoint`,description:`回退到最近一次正常状态(整体还原对话历史 + 主数据 + vfs + todos)。当本轮操作出错、页面被改坏、或走偏时调用,回到本轮起点重新来过。不传参数即回退最近一次。`,schema:t.z.object({}).optional()}),(0,i.tool)(async()=>{let e=pe.list();return e.length?`可用 checkpoint:
3004
3004
  `+e.map(e=>`#${e.id} [${e.label??`auto`}] 消息数=${e.messageCount} 时间=${new Date(e.timestamp).toLocaleTimeString()}`).join(`
3005
- `):`无可用 checkpoint。`},{name:`list_checkpoints`,description:`列出可用会话 checkpoint(回退点)。`,schema:t.z.object({}).optional()})]:[];Xe.forEach(e=>ke.set(e.name,`builtin`));let Ze=V.focus,Qe=(0,i.tool)(async({path:e,label:t})=>{let n=we()?.schema;return n?bp(n,e)?(P.setFocus(re({path:e,...t?{label:t}:{}}),`agent`),`已聚焦到 ${e}${t?`(${t})`:``}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`):`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`:`聚焦失败:当前无主数据 schema,无法聚焦。`},{name:`set_focus`,description:`聚焦到指定组件子树(如 components.3)精修,替换全部已有焦点(非累积;要保留已有焦点追加用 add_focus)。聚焦后:仅可写该子树(越界 PATH_DENIED)+ 每轮只看到该组件结构。多组件页面精修其中一个时用,避免改到别处。先 read 定位 path 再聚焦;完成调 clear_focus。`,schema:t.z.object({path:t.z.string().describe(`要聚焦的组件 jsonPath,如 components.3`),label:t.z.string().optional().describe(`人类可读标签,如「导航栏」`)})}),$e=(0,i.tool)(async()=>(P.clearFocus(`agent`),`已清除聚焦,恢复全量可操作范围(可读写所有组件)。`),{name:`clear_focus`,description:`清除当前聚焦,退出精修模式,恢复对全部组件的读写权限。`,schema:t.z.object({}).optional()}),et=(0,i.tool)(async({path:e,label:t})=>{let n=we()?.schema;if(!n)return`聚焦失败:当前无主数据 schema,无法聚焦。`;if(!bp(n,e))return`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`;P.addFocus(re({path:e,...t?{label:t}:{}}),`agent`);let r=P.getFocuses();return`已聚焦 ${e}${t?`(${t})`:``}(当前共 ${r.length} 个焦点:${r.map(e=>e.path).join(`, `)})。后续仅可写这些子树之一(越界被拒)。`},{name:`add_focus`,description:`追加聚焦一个组件子树(multi-focus,可同时聚焦多个相关组件)。校验 path 在 schema 内。聚焦后仅可写已聚焦的子树之一(越界 PATH_DENIED)。与 set_focus(替换全部)不同:本工具累积追加,不清除已有焦点。`,schema:t.z.object({path:t.z.string().describe(`要追加聚焦的组件 jsonPath,如 components.3`),label:t.z.string().optional().describe(`人类可读标签`)})}),tt=(0,i.tool)(async({path:e})=>{let t=P.getFocuses().length;P.removeFocus(e,`agent`);let n=P.getFocuses();return n.length===t?`path "${e}" 不在当前焦点列表中(当前:${n.map(e=>e.path).join(`, `)||`无`})。`:n.length?`已移除焦点 ${e}(剩余 ${n.length} 个:${n.map(e=>e.path).join(`, `)})。`:`已移除焦点 ${e},聚焦已清空,恢复全量操作范围。`},{name:`remove_focus`,description:`移除单个聚焦焦点(by path),保留其他焦点。移除最后一个等价退出精修。全部退出用 clear_focus。`,schema:t.z.object({path:t.z.string().describe(`要移除的焦点 jsonPath`)})}),nt=Ze?[Qe,$e,et,tt]:[];nt.forEach(e=>ke.set(e.name,`builtin`));let U=[],rt=new Map,it=vb({builtinTools:()=>Re,userTools:()=>Be,actionTools:()=>Ve,humanConfirmTool:()=>Ye,checkpointTools:()=>Xe,focusTools:()=>nt,mcpTools:()=>Ke,loadedSkillTools:()=>U}),at=it(),ot=V.planning,st=V.missionAnchor,ct=V.workingMemory,lt=V.skills,ut=V.vfs||ue;if(ut)for(let e of p_)ke.set(e,`builtin`);if(ot)for(let e of E.tools??[])ke.set(e.name,`builtin`);let dt=V.summarization,ft=V.agentCompression&&!!p;e.debug&&V.agentCompression&&!p&&console.warn(`[page-agent-sdk][agentCompression] agentCompression 开启但 summaryLlm 不可用(或缺 apiKey / 模型不支持工具),压缩决策不启用,回退静态压缩`);let pt=V.memory,mt=V.subagent,ht=mt?wh():void 0,gt=e.verify?.maxAttempts??2,_t=!!(e.verify?.check||e.verify?.maxAttempts||e.verify?.adversarial),vt=e.capabilities?.verify===!1,yt=(V.verify||_t&&!vt)&&e.verify?.enabled!==!1&&gt>0,bt=V.contextInspector;_t&&!yt&&e.verify?.enabled!==!1&&console.warn(`[page-agent-sdk][verify] 检测到 verify 配置(check/maxAttempts/adversarial)但未装载(capabilities.verify:false 显式关闭 或 maxAttempts≤0)`);let xt=e.subagent,St=xt?.allowedTools??[],Ct=e.permissions?.length?ag(e.permissions):void 0,wt=e.approval?.preview===!0&&Se?(e,t)=>e===`write`?Se(t):null:void 0,Tt=e.approval?.previewWrite||wt?(t,n)=>e.approval?.previewWrite?.(t,n)??wt?.(t,n)??null:void 0,Et=e.approval&&(e.approval.tools!==void 0||e.approval.confirm)?og({...e.approval,timeoutMs:e.approval.timeoutMs??ee,onAutoReject:N,previewWrite:Tt}):void 0,Dt=[...Ct?[Ct]:[],...Et?[Et]:[],...Oe?[Oe]:[]],Ot=!mt||xt?.enabled===!1?void 0:Wh({llm:xt?.llm??e.llm,allTools:()=>W.agent?.allTools??at,allowedTools:St.length?St:void 0,...e.staleReadInvalidation===void 0?{}:{staleReadInvalidation:e.staleReadInvalidation},systemPrompt:xt?.systemPrompt,temperature:xt?.temperature,maxTokens:xt?.maxTokens,skills:xt?.skills,maxDepth:xt?.maxDepth,maxParallel:xt?.maxParallel,thinkingMode:xt?.thinkingMode,debug:e.debug,getFocuses:()=>P.getActiveFocuses(),getSchema:()=>we()?.schema??null,tracker:ht,guardMiddleware:Dt.length?Dt:void 0,getVfsFiles:ut?()=>T.files:void 0,enterDataScope:xe?.enterScope?e=>xe.enterScope(e):void 0,exitDataScope:xe?.exitScope?e=>xe.exitScope(e):void 0,onUsage:e=>{o.prompt_tokens=(o.prompt_tokens??0)+(e.prompt_tokens??0),o.completion_tokens=(o.completion_tokens??0)+(e.completion_tokens??0),o.total_tokens=(o.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(o.reasoning_tokens=(o.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:xt?.timeoutMs}),kt=le?.map(e=>{if(!e._codeAsset)return e;let t=e._codeAsset,n=vv({writablePaths:t.writablePaths,codeVfsPrefix:t.codeVfsPrefix,ext:t.ext,codeField:t.codeField,craftNotes:t.craftNotes,onWarning:e=>console.warn(`[page-agent-sdk][code-asset] ${e}`),getController:()=>xe,vfsStore:T}),r=[...e.middleware??[],n];for(let e of r)e&&Wf(e)&&e._setGetController(()=>xe);return{...e,middleware:r}}),At=ue&&mt?yv():void 0,jt=At?Ev({getBind:()=>we()?.bind,writablePaths:de,getLocked:()=>At.locked(),tools:at,getCodeFieldPaths:()=>wv(we()?.bind,R.map(e=>({writablePaths:e._codeAsset.writablePaths,codeField:e._codeAsset.codeField})))}):void 0,Mt=xe?.getSummarizedPaths&&xe.clearSummarizedPaths?kv({getSummarizedPaths:()=>xe.getSummarizedPaths(),clearSummarizedPaths:()=>xe.clearSummarizedPaths()}):void 0,Nt=mt&&kt!==void 0?qh(kt,{llm:e.llm,thinkingModeDefault:e.subagent?.thinkingMode,staleReadInvalidation:e.staleReadInvalidation,allTools:()=>W.agent?.allTools??at,debug:e.debug,getFocuses:()=>P.getActiveFocuses(),getSchema:()=>we()?.schema??null,getBind:()=>we()?.bind,tracker:ht,guardMiddleware:Dt.length?Dt:void 0,getVfsFiles:ut?()=>T.files:void 0,enterDataScope:xe?.enterScope?e=>xe.enterScope(e):void 0,exitDataScope:xe?.exitScope?e=>xe.exitScope(e):void 0,onUsage:e=>{o.prompt_tokens=(o.prompt_tokens??0)+(e.prompt_tokens??0),o.completion_tokens=(o.completion_tokens??0)+(e.completion_tokens??0),o.total_tokens=(o.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(o.reasoning_tokens=(o.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:e.subagent?.timeoutMs,...At?{componentLock:At,resolveComponents:e=>bv(e,mv(we()?.bind,de))}:{}}):void 0,Pt=Nt?Nt.controller:null,Ft=t=>{let n=t.thinkingMode??e.subagent?.thinkingMode,r=n?hy(t.llm??e.llm)?`instance-noop`:`applied`:`inherited`;return{...t,...n?{thinkingMode:n}:{},thinkingApplied:r}},It=[`read`,`fetch_document`],Lt=at.filter(e=>It.includes(e.name)),Rt=yt?xg({check:e.verify.check??Dg({schemas:()=>we()?{"":we().schema}:{},root:()=>we()?.bind}),adversarial:e.verify?.adversarial?{llm:e.llm,tools:Lt}:void 0}):void 0,zt=bt?Vg({contextWindow:m.contextWindow,thresholdRatio:db(e,m.contextWindow).summaryThresholdRatio}):void 0,Bt=vC({...V,humanConfirm:Je,screenshot:!!Ne,domEdit:V.domEdit,hasActions:!!e.actions&&Object.keys(e.actions).length>0,hasProposals:!!e.proposals,viewImage:!!Me,subagents:le?.map(Ft)},he&&!!I,{promptSoftCap:yh(m.contextWindow,h.promptSoftCapTokens)}),Vt=V.pageContext?bC({getPageInfo:()=>typeof document<`u`&&typeof location<`u`?{title:document.title||``,url:location.href}:null,canReadPage:V.domInspect===!0}):void 0,Ht={epoch:0,notices:[],readsInvalidated:0},Ut=0,Wt={name:`hostNotice`,beforeAgent:()=>{Ut=Ht.epoch},wrapModelCall:async(e,t)=>{if(Ie){Ie=!1;let t=Rd(e.messages,`agent 已通过 dom_edit 修改页面,此前读取为改前状态`,We);if(t.invalidatedCount>0){for(let n=0;n<t.messages.length;n++)e.messages[n]=t.messages[n];W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`dom_edit_read_invalidated`,count:t.invalidatedCount}})}}if(Ht.epoch>Ut){Ut=Ht.epoch;let t=Ht.notices[Ht.notices.length-1]??``,n=Rd(e.messages,t||void 0,We);if(n.invalidatedCount>0){for(let t=0;t<n.messages.length;t++)e.messages[t]=n.messages[t];Ht.readsInvalidated+=n.invalidatedCount,W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_read_invalidated`,count:n.invalidatedCount,epoch:Ht.epoch,reason:t||void 0}})}}return t(e)},augmentPrompt:()=>Ht.notices.length?[`【宿主页面已变更】`,...Ht.notices.filter(Boolean).map(e=>`· ${e}`),V.domInspect===!0?`此前的页面读取/截图结果已过期,回答任何关于当前页面的问题前必须重新 read_page / get_dom 读取当前页面;不要凭此前的读取结果或记忆作答。`:`页面内容可能已变化,断言页面前先核实当前状态;不要凭此前的印象作答。`].join(`
3005
+ `):`无可用 checkpoint。`},{name:`list_checkpoints`,description:`列出可用会话 checkpoint(回退点)。`,schema:t.z.object({}).optional()})]:[];Xe.forEach(e=>ke.set(e.name,`builtin`));let Ze=V.focus&&he,Qe=(0,i.tool)(async({path:e,label:t})=>{let n=we()?.schema;return n?bp(n,e)?(P.setFocus(re({path:e,...t?{label:t}:{}}),`agent`),`已聚焦到 ${e}${t?`(${t})`:``}。后续仅可写该子树(越界被拒),每轮只看到该组件结构。完成精修后调 clear_focus 退出。`):`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`:`聚焦失败:当前无主数据 schema,无法聚焦。`},{name:`set_focus`,description:`聚焦到指定组件子树(如 components.3)精修,替换全部已有焦点(非累积;要保留已有焦点追加用 add_focus)。聚焦后:仅可写该子树(越界 PATH_DENIED)+ 每轮只看到该组件结构。多组件页面精修其中一个时用,避免改到别处。先 read 定位 path 再聚焦;完成调 clear_focus。`,schema:t.z.object({path:t.z.string().describe(`要聚焦的组件 jsonPath,如 components.3`),label:t.z.string().optional().describe(`人类可读标签,如「导航栏」`)})}),$e=(0,i.tool)(async()=>(P.clearFocus(`agent`),`已清除聚焦,恢复全量可操作范围(可读写所有组件)。`),{name:`clear_focus`,description:`清除当前聚焦,退出精修模式,恢复对全部组件的读写权限。`,schema:t.z.object({}).optional()}),et=(0,i.tool)(async({path:e,label:t})=>{let n=we()?.schema;if(!n)return`聚焦失败:当前无主数据 schema,无法聚焦。`;if(!bp(n,e))return`PATH_DENIED · 聚焦失败:path "${e}" 不在 schema 内。请先用 read 查看可操作路径再聚焦。`;P.addFocus(re({path:e,...t?{label:t}:{}}),`agent`);let r=P.getFocuses();return`已聚焦 ${e}${t?`(${t})`:``}(当前共 ${r.length} 个焦点:${r.map(e=>e.path).join(`, `)})。后续仅可写这些子树之一(越界被拒)。`},{name:`add_focus`,description:`追加聚焦一个组件子树(multi-focus,可同时聚焦多个相关组件)。校验 path 在 schema 内。聚焦后仅可写已聚焦的子树之一(越界 PATH_DENIED)。与 set_focus(替换全部)不同:本工具累积追加,不清除已有焦点。`,schema:t.z.object({path:t.z.string().describe(`要追加聚焦的组件 jsonPath,如 components.3`),label:t.z.string().optional().describe(`人类可读标签`)})}),tt=(0,i.tool)(async({path:e})=>{let t=P.getFocuses().length;P.removeFocus(e,`agent`);let n=P.getFocuses();return n.length===t?`path "${e}" 不在当前焦点列表中(当前:${n.map(e=>e.path).join(`, `)||`无`})。`:n.length?`已移除焦点 ${e}(剩余 ${n.length} 个:${n.map(e=>e.path).join(`, `)})。`:`已移除焦点 ${e},聚焦已清空,恢复全量操作范围。`},{name:`remove_focus`,description:`移除单个聚焦焦点(by path),保留其他焦点。移除最后一个等价退出精修。全部退出用 clear_focus。`,schema:t.z.object({path:t.z.string().describe(`要移除的焦点 jsonPath`)})}),nt=Ze?[Qe,$e,et,tt]:[];nt.forEach(e=>ke.set(e.name,`builtin`));let U=[],rt=new Map,it=vb({builtinTools:()=>Re,userTools:()=>Be,actionTools:()=>Ve,humanConfirmTool:()=>Ye,checkpointTools:()=>Xe,focusTools:()=>nt,mcpTools:()=>Ke,loadedSkillTools:()=>U}),at=it(),ot=V.planning,st=V.missionAnchor,ct=V.workingMemory,lt=V.skills,ut=V.vfs||ue;if(ut)for(let e of p_)ke.set(e,`builtin`);if(ot)for(let e of E.tools??[])ke.set(e.name,`builtin`);let dt=V.summarization,ft=V.agentCompression&&!!p;e.debug&&V.agentCompression&&!p&&console.warn(`[page-agent-sdk][agentCompression] agentCompression 开启但 summaryLlm 不可用(或缺 apiKey / 模型不支持工具),压缩决策不启用,回退静态压缩`);let pt=V.memory,mt=V.subagent,ht=mt?wh():void 0,gt=e.verify?.maxAttempts??2,_t=!!(e.verify?.check||e.verify?.maxAttempts||e.verify?.adversarial),vt=e.capabilities?.verify===!1,yt=(V.verify||_t&&!vt)&&e.verify?.enabled!==!1&&gt>0,bt=V.contextInspector;_t&&!yt&&e.verify?.enabled!==!1&&console.warn(`[page-agent-sdk][verify] 检测到 verify 配置(check/maxAttempts/adversarial)但未装载(capabilities.verify:false 显式关闭 或 maxAttempts≤0)`);let xt=e.subagent,St=xt?.allowedTools??[],Ct=e.permissions?.length?ag(e.permissions):void 0,wt=e.approval?.preview===!0&&Se?(e,t)=>e===`write`?Se(t):null:void 0,Tt=e.approval?.previewWrite||wt?(t,n)=>e.approval?.previewWrite?.(t,n)??wt?.(t,n)??null:void 0,Et=e.approval&&(e.approval.tools!==void 0||e.approval.confirm)?og({...e.approval,timeoutMs:e.approval.timeoutMs??ee,onAutoReject:N,previewWrite:Tt}):void 0,Dt=[...Ct?[Ct]:[],...Et?[Et]:[],...Oe?[Oe]:[]],Ot=!mt||xt?.enabled===!1?void 0:Wh({llm:xt?.llm??e.llm,allTools:()=>W.agent?.allTools??at,allowedTools:St.length?St:void 0,...e.staleReadInvalidation===void 0?{}:{staleReadInvalidation:e.staleReadInvalidation},systemPrompt:xt?.systemPrompt,temperature:xt?.temperature,maxTokens:xt?.maxTokens,skills:xt?.skills,maxDepth:xt?.maxDepth,maxParallel:xt?.maxParallel,thinkingMode:xt?.thinkingMode,debug:e.debug,getFocuses:()=>P.getActiveFocuses(),getSchema:()=>we()?.schema??null,tracker:ht,guardMiddleware:Dt.length?Dt:void 0,getVfsFiles:ut?()=>T.files:void 0,enterDataScope:xe?.enterScope?e=>xe.enterScope(e):void 0,exitDataScope:xe?.exitScope?e=>xe.exitScope(e):void 0,onUsage:e=>{o.prompt_tokens=(o.prompt_tokens??0)+(e.prompt_tokens??0),o.completion_tokens=(o.completion_tokens??0)+(e.completion_tokens??0),o.total_tokens=(o.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(o.reasoning_tokens=(o.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:xt?.timeoutMs}),kt=le?.map(e=>{if(!e._codeAsset)return e;let t=e._codeAsset,n=vv({writablePaths:t.writablePaths,codeVfsPrefix:t.codeVfsPrefix,ext:t.ext,codeField:t.codeField,craftNotes:t.craftNotes,onWarning:e=>console.warn(`[page-agent-sdk][code-asset] ${e}`),getController:()=>xe,vfsStore:T}),r=[...e.middleware??[],n];for(let e of r)e&&Wf(e)&&e._setGetController(()=>xe);return{...e,middleware:r}}),At=ue&&mt?yv():void 0,jt=At?Ev({getBind:()=>we()?.bind,writablePaths:de,getLocked:()=>At.locked(),tools:at,getCodeFieldPaths:()=>wv(we()?.bind,R.map(e=>({writablePaths:e._codeAsset.writablePaths,codeField:e._codeAsset.codeField})))}):void 0,Mt=xe?.getSummarizedPaths&&xe.clearSummarizedPaths?kv({getSummarizedPaths:()=>xe.getSummarizedPaths(),clearSummarizedPaths:()=>xe.clearSummarizedPaths()}):void 0,Nt=mt&&kt!==void 0?qh(kt,{llm:e.llm,thinkingModeDefault:e.subagent?.thinkingMode,staleReadInvalidation:e.staleReadInvalidation,allTools:()=>W.agent?.allTools??at,debug:e.debug,getFocuses:()=>P.getActiveFocuses(),getSchema:()=>we()?.schema??null,getBind:()=>we()?.bind,tracker:ht,guardMiddleware:Dt.length?Dt:void 0,getVfsFiles:ut?()=>T.files:void 0,enterDataScope:xe?.enterScope?e=>xe.enterScope(e):void 0,exitDataScope:xe?.exitScope?e=>xe.exitScope(e):void 0,onUsage:e=>{o.prompt_tokens=(o.prompt_tokens??0)+(e.prompt_tokens??0),o.completion_tokens=(o.completion_tokens??0)+(e.completion_tokens??0),o.total_tokens=(o.total_tokens??0)+(e.total_tokens??0),e.reasoning_tokens&&(o.reasoning_tokens=(o.reasoning_tokens??0)+e.reasoning_tokens)},timeoutMs:e.subagent?.timeoutMs,...At?{componentLock:At,resolveComponents:e=>bv(e,mv(we()?.bind,de))}:{}}):void 0,Pt=Nt?Nt.controller:null,Ft=t=>{let n=t.thinkingMode??e.subagent?.thinkingMode,r=n?hy(t.llm??e.llm)?`instance-noop`:`applied`:`inherited`;return{...t,...n?{thinkingMode:n}:{},thinkingApplied:r}},It=[`read`,`fetch_document`],Lt=at.filter(e=>It.includes(e.name)),Rt=yt?xg({check:e.verify.check??Dg({schemas:()=>we()?{"":we().schema}:{},root:()=>we()?.bind}),adversarial:e.verify?.adversarial?{llm:e.llm,tools:Lt}:void 0}):void 0,zt=bt?Vg({contextWindow:m.contextWindow,thresholdRatio:db(e,m.contextWindow).summaryThresholdRatio}):void 0,Bt=vC({...V,humanConfirm:Je,screenshot:!!Ne,domEdit:V.domEdit,hasActions:!!e.actions&&Object.keys(e.actions).length>0,hasProposals:!!e.proposals,viewImage:!!Me,subagents:le?.map(Ft)},he&&!!I,{promptSoftCap:yh(m.contextWindow,h.promptSoftCapTokens)}),Vt=V.pageContext?bC({getPageInfo:()=>typeof document<`u`&&typeof location<`u`?{title:document.title||``,url:location.href}:null,canReadPage:V.domInspect===!0}):void 0,Ht={epoch:0,notices:[],readsInvalidated:0},Ut=0,Wt={name:`hostNotice`,beforeAgent:()=>{Ut=Ht.epoch},wrapModelCall:async(e,t)=>{if(Ie){Ie=!1;let t=Rd(e.messages,`agent 已通过 dom_edit 修改页面,此前读取为改前状态`,We);if(t.invalidatedCount>0){for(let n=0;n<t.messages.length;n++)e.messages[n]=t.messages[n];W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`dom_edit_read_invalidated`,count:t.invalidatedCount}})}}if(Ht.epoch>Ut){Ut=Ht.epoch;let t=Ht.notices[Ht.notices.length-1]??``,n=Rd(e.messages,t||void 0,We);if(n.invalidatedCount>0){for(let t=0;t<n.messages.length;t++)e.messages[t]=n.messages[t];Ht.readsInvalidated+=n.invalidatedCount,W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_read_invalidated`,count:n.invalidatedCount,epoch:Ht.epoch,reason:t||void 0}})}}return t(e)},augmentPrompt:()=>Ht.notices.length?[`【宿主页面已变更】`,...Ht.notices.filter(Boolean).map(e=>`· ${e}`),V.domInspect===!0?`此前的页面读取/截图结果已过期,回答任何关于当前页面的问题前必须重新 read_page / get_dom 读取当前页面;不要凭此前的读取结果或记忆作答。`:`页面内容可能已变化,断言页面前先核实当前状态;不要凭此前的印象作答。`].join(`
3006
3006
  `):void 0,afterAgent:()=>{Ht.notices.length=0}},Gt=ze?{name:`proposalNotice`,augmentPrompt:()=>ze.state.notices.length?[`【内容提案裁决结果】(以此为准,不要凭提案前状态作答)`,...ze.state.notices].join(`
3007
3007
  `):void 0,afterAgent:()=>{ze.state.notices.length=0}}:null,Kt=I?{name:`dataHint`,augmentPrompt:()=>n_(we(),e.schemaHint)||void 0}:null,qt=e.augmentSystem?{name:`augmentSystem`,augmentPrompt:t=>{try{return e.augmentSystem({state:t,data:we()})}catch(t){e.debug&&console.log(`[page-agent-sdk][augmentSystem] 回调抛错,降级跳过:`,t.message);return}}}:null,Jt=cb(e.onEvent),Yt=Jt.emit,Xt,Zt=[],Qt=e=>({name:e.name,description:e.description,content:typeof e.getContent==`function`?e.getContent():``}),$t=e=>({name:e.name,description:e.description,getContent:()=>e.content}),en=e.skillStorage===!1?null:EC({...typeof e.skillStorage==`object`?e.skillStorage:{},id:e.skillStorage&&typeof e.skillStorage==`object`&&e.skillStorage.id?e.skillStorage.id:`agent::${n}`}),tn=()=>{let t=Xt?Xt.controller:null;if(t){let n=(e.skills||[]).filter(e=>!Zt.some(t=>t.name===e.name));t.set([...n,...Zt])}W.infoTick.value++},nn=async()=>{if(en)try{let t=await en.list();if(t.length){Zt=t.map($t);let n=Xt?Xt.controller:null;if(n){let t=(e.skills||[]).filter(e=>!Zt.some(t=>t.name===e.name));n.set([...t,...Zt])}W.infoTick.value++}}catch{}},rn=dt?Ch({...h,llmInvoke:d,getRegisteredData:()=>we()?[{description:we().description??`主数据对象`}]:[],preserveLastToolResults:_,...ft?{decideInvoke:p,getSnapshot:()=>zt?.getSnapshot()}:{}}):void 0,an=lt?Qm([...V.domInspect&&!(e.skills||[]).some(e=>e.name===`dom-inspect`)?[YS({withScreenshot:!!Ne,withDomEdit:V.domEdit,withDataOps:he&&!!I})]:[],...V.domInspect&&!(e.skills||[]).some(e=>e.name===`page-analysis`)?[ZS({withScreenshot:!!Ne,withDomEdit:V.domEdit,withVfs:ut})]:[],...e.skills||[]],{readVfs:ut?e=>T.files[e]?.content:void 0,onToolsReady:(e,t)=>{for(let n of t){let t=U.findIndex(e=>e.name===n.name);t>=0&&U.splice(t,1),U.push(n),rt.set(n.name,e),ke.set(n.name,`skill:${e}`)}at=it(),W.agent&&W.agent.setTools(at),W.infoTick.value++}}):void 0;Xt=an;let on=pb([...Kt?[Kt]:[],Bt,...Vt?[Vt]:[],Wt,...Gt?[Gt]:[],...st?[D]:[],O,k,...ot?[E]:[],...an?[an]:[],...ut?[h_(T)]:[],...rn?[rn]:[],...ct?[ie]:[],...Ze?[P]:[],...Ce?[Ce]:[],...pt?[F]:[],...Ct?[Ct]:[],...fe&&me&&pe?[yg(pe)]:[],...Je?[ne]:[],...Et?[Et]:[],...Oe?[Oe]:[],...Rt?[Rt]:[],...Ot?[Ot]:[],...Nt?[Nt]:[],...jt?[jt]:[],...Mt?[Mt]:[],...xe&&mt?[Mv({getBind:()=>we()?.bind,getTools:()=>W.agent?.allTools??at})]:[],...qt?[qt]:[],...zt?[zt]:[],...Fe?[Fe]:[],...e.middleware||[],...H?[oC(o,{tokenBudget:e.tokenBudget,timeBudgetMs:e.timeBudgetMs},Yt)]:[],FC(Yt,S,we,o)]),sn=e.maxMemoryRounds??jC;function cn(e){return e=>{e.type!==`approval_request`&&Yt(je(e))}}let ln=G([]),un=AC(),dn=new Set;function fn(e){let t=new AbortController,n=()=>t.abort();return e&&(e.aborted?t.abort():e.addEventListener(`abort`,n,{once:!0})),dn.add(t),{controller:t,untrack:()=>{dn.delete(t),e?.removeEventListener(`abort`,n)}}}function pn(){for(let e of dn)e.abort();dn.clear()}let mn=G(null),W={agentId:n,store:l,messages:S,vfsStore:T,listeners:Jt.listeners,todosMw:E,memoryMw:F,missionMw:D,workingMemoryMw:ie,focusMw:P,agent:null,initDone:Promise.resolve(),sessionId:``,refCount:0,mcpClosers:[],mcpServers:[],mcpFailed:[],checkpoint:pe,dataOpsController:xe,skillsController:Xt?Xt.controller:null,infoTick:c,pendingConflict:s.pendingConflict,pendingQuote:mn,sessions:ln,refreshSessions:()=>xn.refreshSessions(),liveData:we,usage:o,emit:Yt,runSerial:un,trackActive:fn,abortAllActive:pn,unloadSkillTools(e){if(e){let t=U.length;if(U=U.filter(t=>rt.get(t.name)===e?(ke.delete(t.name),rt.delete(t.name),!1):!0),U.length===t)return}else{if(!U.length)return;for(let e of U)ke.delete(e.name),rt.delete(e.name);U=[]}at=it(),W.agent&&W.agent.setTools(at)},applySnapshot(t){if(t.vfs&&T.hydrate&&T.hydrate(t.vfs),t.messages?.length&&(S.push(...ou(t.messages,e=>(e?W.vfsStore?.files?.[e]?.content:void 0)||void 0)),k.markResumed()),t.todos?.length&&E.reset(t.todos),t.memory&&!e.memory&&F.reset(t.memory),t.checkpoints?.length&&pe&&pe.importStack(t.checkpoints),t.usage&&Object.assign(o,t.usage),t.mission&&st&&D.setMission(t.mission),t.workingMemory&&ct&&ie.restore(t.workingMemory),t.planConfirmation&&(A.lastPlanConfirmation=t.planConfirmation),Ze){let n=t.focus,r=n?Array.isArray(n)?n:[n]:[];if(r.length){let t=we()?.schema,n=t?r.filter(e=>bp(t,e.path)):[];if(n.length&&(P.setFocus(null),n.forEach(e=>P.addFocus(re(e)))),e.debug&&n.length<r.length){let e=r.filter(e=>!n.includes(e)).map(e=>e.path);console.warn(`[page-agent-sdk][focus] 恢复的焦点部分 path 已失效(schema 变化/无 schema),剔除:`,e)}}}vn()},addSkill(e){let t=Zt.findIndex(t=>t.name===e.name);t>=0?Zt[t]=e:Zt.push(e),tn(),en&&en.put(Qt(e))},removeSkill(e){let t=Zt.findIndex(t=>t.name===e);return t<0?!1:(Zt.splice(t,1),tn(),en&&en.remove(e),!0)},listUserSkills(){return Zt.map(e=>e.name)},getUserSkill(e){let t=Zt.find(t=>t.name===e);if(t)return{name:t.name,description:t.description,content:typeof t.getContent==`function`?t.getContent():``}},afterRound(){yn(),xn.persistRuntime()},clearCodeReuse(){let e=T;e.__pgPendingRetry?.clear(),e.__pgLastCheckout?.clear()},async send(e,t){if(await W.initDone,W.refCount<=0)throw Error(`page-agent-sdk: agent 已释放(unmount),拒绝排队中的 send`);t??={},t?.mission&&st&&D.setMission(t.mission);let n=e,r=(t.images??[]).filter(e=>e&&(e.dataUri||e.vfsRef||e.url));if(r.length>4)throw Error(`[page-agent-sdk] 单轮最多 4 张图片(收到 ${r.length})`);if(r.length&&(await bn.stowImages(r),await bn.describeIfNeeded(r,n)),r.length&&!m.vision&&!r.every(e=>e.description)){let e=`当前主模型不支持图片输入(modelCaps.vision=false)。请换多模态模型(gpt-4o/claude/qwen-vl)或 LLMConfig 声明 vision:true;或配置 images.describe 绑定识图转述(集成方识图子 agent / 自有 vision API)`;throw Yt({type:`error`,message:e,severity:`recoverable`,code:`IMAGE_UNSUPPORTED_MODEL`}),Error(`[page-agent-sdk] ${e}`)}T?.setProtectedRefs?.(OC(S));let i=H?t.maxAutoRetries??1:0,a=0,o=!1,c=cn(t.signal);if(t.signal){let e=()=>s.resolve(`keep_external`);t.signal.aborted?e():t.signal.addEventListener(`abort`,e,{once:!0})}let u=W.sessionId;for(;;){if(!o){let e;if(t.quote?.text){let n=ku(t.quote.anchor);e={text:gu(t.quote.text),...t.quote.source?{source:t.quote.source}:{},...n?{anchor:n}:{}}}let i=e??mn.value??void 0;S.push({role:`user`,content:n,timestamp:Date.now(),...r.length?{images:r}:{},...i?{quote:i}:{}}),o=!0,!e&&mn.value&&(mn.value=null)}try{let e=await W.agent.invoke(S,t.signal,c);if(t.signal?.aborted||W.sessionId!==u||W.refCount<=0)return W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`orphan_round_dropped`,fromSession:u,aborted:!!t.signal?.aborted,sessionChanged:W.sessionId!==u}}),e;if(S.push({role:`assistant`,content:e,timestamp:Date.now()}),W.afterRound(),l)try{await l.flush()}catch(e){Yt({type:`error`,message:`落盘失败(不影响本轮回复):${e instanceof Error?e.message:String(e)}`,severity:`observable`,code:`PERSIST_FLUSH_FAILED`})}return e}catch(e){if(Uu(e,t.signal))throw e;let n=ql(e,`fatal`);if(rd(e)&&(n={...n,code:`MODEL_UNAVAILABLE`,message:e instanceof Error?e.message:n.message}),a<i&&pe?.canRestore()){a+=1,pe.restore(),o=!0,Yt({type:`error`,message:`致命错误自动恢复(${a}/${i}):${n.message},已回退 checkpoint 重试`,severity:`observable`,code:`AUTO_RECOVER_RETRY`,context:{attempt:a,cause:n.code??n.message.slice(0,120)}});continue}throw Yt({type:`error`,message:n.message,severity:n.severity,...n.code?{code:n.code}:{},...n.context===void 0?{}:{context:n.context}}),e}}},async batch(e,t,n){if(await W.initDone,!e.length)return[];if(W.refCount<=0)throw Error(`page-agent-sdk: agent 已释放(unmount),拒绝排队中的 batch`);let r=[],i=cn(n);if(T?.setProtectedRefs?.(OC(S)),n){let e=()=>s.resolve(`keep_external`);n.aborted?e():n.addEventListener(`abort`,e,{once:!0})}for(let a=0;a<e.length;a++){if(n?.aborted){for(let t=a;t<e.length;t++)r.push({index:t,task:e[t],error:`aborted(外部中止)`,ok:!1});break}let o=e[a];pe&&pe.save(`batch:${a}`);let s=S.length;try{S.push({role:`user`,content:o,timestamp:Date.now()});let s=await W.agent.invoke(S,n,i);if(S.push({role:`assistant`,content:s,timestamp:Date.now()}),W.afterRound(),l)try{await l.flush()}catch(e){Yt({type:`error`,message:`落盘失败(不影响本任务结果):${e instanceof Error?e.message:String(e)}`,severity:`observable`,code:`PERSIST_FLUSH_FAILED`})}r.push({index:a,task:o,reply:s,ok:!0}),t?.({done:a+1,total:e.length,task:o,ok:!0})}catch(i){if(S.length>s&&S.splice(s),Uu(i,n)){r.push({index:a,task:o,error:`aborted(外部中止)`,ok:!1});for(let t=a+1;t<e.length;t++)r.push({index:t,task:e[t],error:`aborted(外部中止)`,ok:!1});break}rd(i);let c=ql(i,`fatal`);Yt({type:`error`,message:`批量任务 ${a+1}/${e.length} 失败:${c.message}`,severity:`observable`,code:`BATCH_TASK_FAILED`,context:{index:a,task:o.slice(0,100)}}),r.push({index:a,task:o,error:c.message,ok:!1}),t?.({done:a+1,total:e.length,task:o,ok:!1})}}return r},switchSession:e=>xn.switchSession(e),exportSession:e=>xn.exportSession(e),importSession:e=>xn.importSession(e),resetSession:()=>xn.resetSession(),stream:async(e,t,n)=>{if(!W.agent)throw Error(`page-agent-sdk: agent 尚未初始化完成,请先 await mount()`);let r=[...e].reverse().find(e=>e.role===`user`&&e.images?.length);if(r?.images?.length&&(await bn.stowImages(r.images),await bn.describeIfNeeded(r.images,r.content),!m.vision&&!r.images.every(e=>e.description))){let e=`当前主模型不支持图片输入(modelCaps.vision=false)。请换多模态模型(gpt-4o/claude/qwen-vl)或 LLMConfig 声明 vision:true;或配置 images.describe 绑定识图转述`;throw Yt({type:`error`,message:e,severity:`recoverable`,code:`IMAGE_UNSUPPORTED_MODEL`}),Error(`[page-agent-sdk] ${e}`)}T?.setProtectedRefs?.(OC(e));let i=e=>{t?.(je(e)),Yt(je(e)),e.type===`subagent`&&(e.kind===`tool_call`||e.kind===`tool_result`)&&W.infoTick.value++};if(n){let e=()=>s.resolve(`keep_external`);n.aborted?e():n.addEventListener(`abort`,e,{once:!0})}let{controller:a,untrack:o}=fn(n);return W.agent.stream(e,i,a.signal).finally(o)},release(){if(W.refCount--,W.refCount<=0){pn(),qe=!0,l&&(T.flush?.(),l.flush(),l.dispose()),en&&en.dispose();let e=W.mcpClosers.splice(0);e.length&&Promise.allSettled(e.map(e=>e())),MC.delete(n)}},resolveConflict:s.resolve,setTools(e){Be.length=0,e.forEach(e=>{Be.push(e),ke.set(e.name,`user`)}),at=it(),W.agent&&W.agent.setTools(at),W.infoTick.value++},addTool(e){at.some(t=>t.name===e.name)&&console.warn(`[page-agent-sdk] 工具 "${e.name}" 已存在,新工具覆盖(后注册覆盖先注册)`);for(let t=Be.length-1;t>=0;t--)Be[t].name===e.name&&Be.splice(t,1);Be.push(e),ke.set(e.name,`user`),at=it(),W.agent&&W.agent.setTools(at),W.infoTick.value++},removeTool(e){let t=Be.findIndex(t=>t.name===e);return t<0?!1:(Be.splice(t,1),ke.delete(e),at=it(),W.agent&&W.agent.setTools(at),W.infoTick.value++,!0)},setLlm(t){let n;if(hy(t))n=t;else{let e=t;if((e.provider??`openai`)===`anthropic`)throw Error(`[page-agent-sdk][setLlm] 切换到 Anthropic 需传 BaseChatModel 实例(动态 import 无法同步);请先 const { ChatAnthropic } = await import("@langchain/anthropic") 构造实例后传入`);n=M(e)}typeof n.bindTools!=`function`&&e.debug&&console.warn(`[page-agent-sdk][setLlm] 新模型不支持 bindTools(tool calling 会失效)`),_y(n,{emit:Yt}),b=t;let r=hy(t)?void 0:t;if(m=w({model:r?.model??t.model??t.modelName,contextWindow:e.contextWindow??r?.contextWindow,maxOutputTokens:e.maxOutputTokens??r?.maxOutputTokens,vision:r?.vision??t.vision}),m.contextWindow<2e5)throw Error(`[page-agent-sdk][setLlm] 新模型上下文窗口 ${m.contextWindow} 小于最小支持 ${y}(需 ≥200K 窗口模型)`);W.agent&&(W.agent.setLlm(n),W.agent.setModelCaps?.(m)),rn?.setContextWindow?.(m.contextWindow),zt?.setContextWindow?.(m.contextWindow),W.infoTick.value++,e.debug&&console.log(`[page-agent-sdk][setLlm] 重解析 modelCaps + 回灌:`,m)},setMemory(e){F.reset(e),typeof e==`function`&&F.refresh(),W.infoTick.value++},refreshMemory(){return F.refresh()},setSubagents(t){if(!Pt){e.debug&&console.warn(`[page-agent-sdk][setSubagents] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}Pt.set(t),W.infoTick.value++},addSubagent(t){if(!Pt){e.debug&&console.warn(`[page-agent-sdk][addSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`);return}Pt.add(t),W.infoTick.value++},removeSubagent(t){if(!Pt)return e.debug&&console.warn(`[page-agent-sdk][removeSubagent] 未配 subagents:[] 或 capabilities.subagent 关闭,忽略`),!1;let n=Pt.remove(t);return n&&W.infoTick.value++,n},getActiveSubagents(){return ht?.getActive()??[]},get subagentHistory(){return ht?.getHistory()??[]},getInfo(){return{id:n,sessionId:W.sessionId,model:hy(b)?b.model??b.modelName:b.model,systemPrompt:W.agent?.getEffectiveSystemPrompt?.()??ve+n_(we(),e.schemaHint),tools:(W.agent?.allTools??at).map(e=>({name:e.name,description:e.description,schema:e.schema,source:ke.get(e.name)||`user`})),skills:(Xt?Xt.controller.get():e.skills??[]).map(e=>({name:e.name,description:e.description})),data:we()?{description:we().description,schema:we().schema}:void 0,contextPreset:e.contextPreset??`auto`,compression:{contextWindow:m.contextWindow,summaryThresholdRatio:h.summaryThresholdRatio??.5,promptSoftCap:yh(m.contextWindow,h.promptSoftCapTokens)},memory:F.get(),staleReadsInvalidated:W.agent?.getStaleReadsInvalidated?.()??0,hostReadsInvalidated:Ht.readsInvalidated,...ze?{proposals:ze.snapshot()}:{},...a?{hostWatch:{...a}}:{},llmRetries:W.agent?.getLlmRetries?.()??0,llmCallFailures:W.agent?.getLlmCallFailures?.()??0,gates:W.agent?.getGateStats?.(),systemSegments:W.agent?.getLastSystemSegments?.()??[],middleware:on.map(e=>e.name),todos:(W.agent?.getState?.()?.todos??[]).map(e=>({id:e.id,content:e.content,status:e.status,...e.parentId===void 0?{}:{parentId:e.parentId},...e.deps===void 0?{}:{deps:e.deps},...e.criteria===void 0?{}:{criteria:e.criteria},...e.evidence===void 0?{}:{evidence:e.evidence}})),planPhase:E.getPlanPhase(),mission:st?D.getMission():void 0,planConfirmation:A.lastPlanConfirmation,workingMemory:ct?ie.getWorkingMemory():void 0,focus:Ze?P.getFocus():void 0,focuses:Ze?P.getFocuses():[],actions:lC(e.actions??{}),subagent:{enabled:!!Ot,maxDepth:e.subagent?.maxDepth??1,maxParallel:e.subagent?.maxParallel??4,timeoutMs:e.subagent?.timeoutMs===void 0?18e5:e.subagent.timeoutMs>0?e.subagent.timeoutMs:0,allowedTools:e.subagent?.allowedTools??[],subagents:(Pt?.get()??[]).map(Ft),active:ht?.getActive()??[],history:ht?.getHistory()??[],lockedComponents:At?.locked()??{}},verify:{enabled:!!Rt,maxAttempts:yt?gt:0,adversarial:yt&&!!e.verify?.adversarial},context:(()=>{let e=zt?.getSnapshot();if(e){let t=W.agent?.getState?.()?.lastCompression;t&&(e.compression=t)}return e})(),mcp:{servers:W.mcpServers,...W.mcpFailed.length?{failed:W.mcpFailed}:{}},lastCompression:W.agent?.getState?.()?.lastCompression,checkpoints:pe?{enabled:!0,auto:me,list:pe.list()}:void 0}},exportDiagnostics(){let e=W.getInfo(),t={...e,tools:e.tools.map(({schema:e,...t})=>t),data:e.data?{description:e.data.description,schemaTopKeys:_p(e.data.schema)??[]}:void 0},n=W.liveData(),r=null;if(n){let e=-1,t=[];try{let r=JSON.stringify(n.bind);e=r?r.length:0,n.bind&&typeof n.bind==`object`&&!Array.isArray(n.bind)&&(t=Object.keys(n.bind))}catch{e=-1}r={description:n.description,topKeys:t,approxBytes:e}}return zv(Rv({debugLogs:W.agent?.debugLogs?.value??[],messages:W.messages,info:t,usage:{...W.usage},pendingConflict:W.pendingConflict?.value??null,sessionId:W.sessionId,dataSummary:r}))},getMission(){return st?D.getMission():void 0},setMission(t){if(!st){e.debug&&console.warn(`[page-agent-sdk][mission] capabilities.missionAnchor 关闭,setMission 忽略`);return}D.setMission(t),W.infoTick.value++},getFocus(){return Ze?P.getFocus():void 0},getFocuses(){return Ze?P.getFocuses():[]},setFocus(t){let n=IC(t,`setFocus`,Ze,()=>we()?.schema,e.debug);return n.ok?(P.setFocus(re(t)),e.debug&&P.isInvokeActive()&&console.info(`[page-agent-sdk][focus] 在途流程进行中,聚焦将在下一次输入生效(当前流程不受影响)`),W.infoTick.value++,{ok:!0}):n},addFocus(t){let n=IC(t,`addFocus`,Ze,()=>we()?.schema,e.debug);return n.ok?P.getFocuses().length>=8?(e.debug&&console.warn(`[page-agent-sdk][focus] addFocus 拒绝:焦点数已达上限 8(augmentPrompt 注入每焦点子树 schema,过多致 system prompt 超预算)`),{ok:!1,error:`焦点数上限 8(避免 system prompt 撑爆)`}):(P.addFocus(re(t)),e.debug&&P.isInvokeActive()&&console.info(`[page-agent-sdk][focus] 在途流程进行中,聚焦将在下一次输入生效(当前流程不受影响)`),W.infoTick.value++,{ok:!0}):n},removeFocus(e){Ze&&(P.removeFocus(e),W.infoTick.value++)},clearFocus(){Ze&&(P.clearFocus(),W.infoTick.value++)},setQuote(e,t,n){let r=gu(e??``),i=ku(n);mn.value=r?{text:r,...t?{source:t}:{},...i?{anchor:i}:{}}:null},notifyHostChange(e){let t=typeof e?.reason==`string`?e.reason.trim().slice(0,200):``;Ht.epoch+=1,t&&!Ht.notices.includes(t)?Ht.notices.push(t):t||Ht.notices.push(``),Ht.notices.length>5&&Ht.notices.splice(0,Ht.notices.length-5),W.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_change_notified`,epoch:Ht.epoch,reason:t||void 0}}),W.infoTick.value++},clearQuote(){mn.value=null},resolveProposal(e,t,n){let r=ze?ze.resolve(e,t,n):!1;return r&&W.infoTick.value++,r},getProposals(){return ze?ze.snapshot():null}};async function hn(){if(!l)return;let t=async e=>{try{return await l.load(n,e)}catch(t){Yt({type:`error`,message:`会话快照读取失败,已降级空会话:${t instanceof Error?t.message:String(t)}`,severity:`observable`,code:`SESSION_RESTORE_FAILED`,context:{sessionId:e}});return}},r=async()=>{try{return await l.listSessions(n)}catch(e){return Yt({type:`error`,message:`会话列表读取失败,已降级新建会话:${e instanceof Error?e.message:String(e)}`,severity:`observable`,code:`SESSION_RESTORE_FAILED`}),[]}},i=Symbol(`storage-ready-timeout`);await Promise.race([l.ready.then(()=>`ready`),new Promise(e=>setTimeout(()=>e(i),5e3))])===i&&(console.warn(`[page-agent-sdk][persist] 存储初始化 5s 未就绪(可能被其他标签页锁住),已放行;持久化暂降级内存,就绪后自动恢复`),Yt({type:`error`,message:`存储初始化 5s 未就绪(IDB blocked?),已放行降级运行`,severity:`observable`,code:`STORAGE_READY_TIMEOUT`}));let a=e.session||{};if(a.id){W.sessionId=a.id;let e=await t(W.sessionId);e?(W.applySnapshot(e),Yt({type:`session_restored`,sessionId:W.sessionId,rounds:e.messages?.length??0})):await l.createSession(n,a.title,W.sessionId)}else if(a.autoResume!==!1){let i=await r();if(e.debug&&console.log(`[page-agent-sdk][restore] listSessions`,n,i.length,i.map(e=>e.sessionId)),i.length){W.sessionId=i[0].sessionId;let n=await t(W.sessionId);n?(W.applySnapshot(n),Yt({type:`session_restored`,sessionId:W.sessionId,rounds:n.messages?.length??0}),e.debug&&console.log(`[page-agent-sdk][restore] 恢复会话`,W.sessionId,`${n.messages?.length??0} msgs`)):e.debug&&console.log(`[page-agent-sdk][restore] 会话 meta 存在但快照为空`,W.sessionId)}else W.sessionId=await l.createSession(n,a.title),e.debug&&console.log(`[page-agent-sdk][restore] 新建会话(无历史)`,W.sessionId)}else W.sessionId=await l.createSession(n,a.title);e.memory&&xn.persistSave({memory:F.get()||(typeof e.memory==`string`?e.memory:``)}),xn.refreshSessions()}async function gn(){await nn()}function _n(e){let t={};for(let n of OC(e)){let e=T.files[n];e&&(t[n]=e.content)}return t}function vn(){let e=kC(T.files,OC(S));for(let t of e)delete T.files[t]}function yn(){let e=sh(S,sn);if(!e.trimmed)return;let{older:t,summary:n}=e;if(Yt({type:`context_trimmed`,dropped:t.map(e=>({round:e.round,user:e.userMsg.content,assistant:e.assistantMsgs.map(e=>e.content),steps:e.assistantMsgs.flatMap(e=>e.steps??[])})),vfsResults:_n(t.flatMap(e=>[e.userMsg,...e.assistantMsgs])),summary:n.content,reason:`max_memory_rounds`}),S.splice(e.deleteFrom,e.deleteCount,n),vn(),g&&d){let n=e.summary,{prevSeg:r}=e;(async()=>{try{let e=await d(mh(t,v)),i=S.indexOf(n);if(i<0)return;S[i].content=oh(t,r,e),xn.persistRuntime()}catch{}})()}}let bn=fu({getConfig:()=>e.images,getVision:()=>m.vision===!0,emit:Yt,getVfsStore:()=>W.vfsStore,noteFailure:(e,t)=>xn.notePersistFailure(e,t)}),xn=gb({agentId:n,options:e,emit:Yt,getStore:()=>l,core:W,sessionsRef:ln,sessionVars:A,messages:S,getUsage:()=>o,mw:{todosMw:E,memoryMw:F,missionMw:D,workingMemoryMw:ie,focusMw:P,summarizationMw:rn,resumeNoticeMw:k,useMission:st,useWorkingMemory:ct,useFocus:Ze,useAutomation:H},vfsStore:T,checkpointMgr:pe,conflictResolve:e=>s.resolve(e),abortAllActive:pn,titleLlmInvoke:f});return W.initDone=(async()=>{await hn(),await gn(),e.mcp?.length&&qg({servers:e.mcp,emit:Yt,isReleased:()=>qe,core:{mcpClosers:W.mcpClosers,mcpServers:W.mcpServers,mcpFailed:W.mcpFailed,infoTick:W.infoTick},reservedNames:()=>{let e=new Set;for(let t of at){let n=ke.get(t.name);n&&!n.startsWith(`mcp:`)&&e.add(t.name)}return e},pushTool:(e,t)=>(ke.set(e.name,`mcp:${t}`),Ke.push(e),!0),rebind:()=>{at=it(),W.agent&&W.agent.setTools(at),W.infoTick.value++},debug:e.debug});let t=hy(e.llm)?e.llm:await te(e.llm);_y(t,{emit:Yt}),W.agent=gp({llm:t,systemPrompt:ve,tools:at,middleware:on,maxToolRounds:e.maxToolRounds,hasSubagent:mt,pageAssertionGate:V.domInspect===!0,pageReadTools:We.size?We:void 0,deferredWriteTools:Ge.size?Ge:void 0,maxRetries:e.maxRetries,stallMs:e.streamStallMs??9e4,streamMaxMs:e.streamMaxDurationMs??18e5,toolTimeoutMs:e.toolTimeoutMs,maxParallelTools:e.maxParallelTools,contextWindow:m.contextWindow,maxOutputTokens:m.maxOutputTokens,vision:m.vision,imageContentFormat:Pe,maxVerifyAttempts:yt?gt:0,roundTokenBudget:e.roundTokenBudget??0,staleReadInvalidation:e.staleReadInvalidation,onLlmChange:e=>{b=e},debug:e.debug}),ae.current=W.agent,Nt&&Nt.setReconfigureHook(()=>{W.agent&&W.agent.setTools(it())})})(),W}function RC(e,t){let n=e.id??Oy();e.id||console.warn(`[page-agent-sdk] 未传 options.id,已生成随机 id "${n}"。刷新后持久化数据无法恢复,请传稳定 id。`);let r=e.streaming??!0,i=e.ui??`default`,a=e.hostWatch===!0?{url:!0}:e.hostWatch&&typeof e.hostWatch==`object`?e.hostWatch:null,o={enabled:!1,url:!1,pushState:!1,title:!1,autoNotified:0},s=null,c,l=e.shareContext?MC.get(n):void 0;l?c=l:(c=LC(e,n,a?o:void 0),e.shareContext&&MC.set(n,c)),c.refCount++;let u=null,d=rb(e),f=null,p=null;async function m(n){if(await c.initDone,u){u.show();return}let l=n===void 0?e.container:n,m=()=>{c.store&&(f=()=>{c.vfsStore.flush?.(),c.store.flush()},p=()=>{document.visibilityState===`hidden`&&c.store.flush()},typeof window<`u`&&window.addEventListener(`pagehide`,f),typeof document<`u`&&document.addEventListener(`visibilitychange`,p))};if((()=>{if(!a)return;s?.dispose(),s=null;let e=typeof window<`u`?window:void 0;s=dS({target:e,history:typeof history<`u`?history:e?.history,document:typeof document<`u`?document:void 0,MutationObserver:typeof MutationObserver<`u`?MutationObserver:void 0,options:a,onReport:e=>{o.autoNotified+=1,c.agent?.debugLogs?.value?.push({timestamp:Date.now(),type:`middleware`,data:{stage:`host_watch`,kind:e.kind,from:e.from.slice(0,120),to:e.to.slice(0,120)}}),c.notifyHostChange({reason:lS(e)})}}),s&&(o.enabled=!0,o.url=s.info.url,o.pushState=s.info.pushState,o.title=s.info.title)})(),i===!1||!t){i!==!1&&console.warn(`[page-agent-sdk/headless] 未含 UI 组件,ui 渲染降级 headless;如需 UI 请 import page-agent-sdk 主包`),m();return}let _=typeof l==`string`?document.querySelector(l):l;if(!_)throw Error(`createChatSdk: 挂载点未找到(${l})`);u=t({el:_,core:c,dialogCfg:d,i18n:e.i18n,debug:e.debug===!0,streaming:r,runSerial:c.runSerial,hide:g,unmount:h,onDialogUnmounted:()=>{u=null,c.release()}}),d.drawer===!0&&d.drawerHidden===!0&&u.hide(),m()}function h(){c.abortAllActive(),c.resolveConflict(`keep_external`),f&&typeof window<`u`&&window.removeEventListener(`pagehide`,f),p&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,p),f=null,p=null,s?.dispose(),s=null,u?u.unmount():c.release()}function g(){u?.hide()}function _(){u?.show()}return{mount:m,unmount:h,hide:g,show:_,send:(e,t)=>c.runSerial(async()=>{let{controller:n,untrack:r}=c.trackActive(t?.signal);try{return await c.send(e,{...t,signal:n.signal})}finally{r()}}),batch:(e,t,n)=>c.runSerial(async()=>{let{controller:r,untrack:i}=c.trackActive(n);try{return await c.batch(e,t,r.signal)}finally{i()}}),switchSession:(...e)=>c.runSerial(async()=>(c.abortAllActive(),c.switchSession(...e))),async exportSession(e){return c.runSerial(()=>c.exportSession(e))},async importSession(e){return c.runSerial(()=>c.importSession(e))},resetSession:()=>c.resetSession(),sessions:c.sessions,async listSessions(){return c.store?c.store.listSessions(n):[]},async deleteSession(e){if(c.store){if(e===c.sessionId){console.warn(`[page-agent-sdk] deleteSession 忽略:不能删除当前会话,请先 switchSession 切到其他会话`);return}await c.store.deleteSession(n,e),await c.refreshSessions()}},get sessionId(){return c.sessionId},stream:(e,t,n)=>c.stream(e,t,n),afterRound:c.afterRound,clearCodeReuse:()=>c.clearCodeReuse(),get debugLogs(){return c.agent.debugLogs},infoTick:c.infoTick,inspect:c.getInfo,exportDiagnostics:()=>c.exportDiagnostics(),inspectContext:()=>c.getInfo().context,getMission:c.getMission,setMission:c.setMission,getFocus:c.getFocus,getFocuses:c.getFocuses,setFocus:c.setFocus,addFocus:c.addFocus,removeFocus:c.removeFocus,clearFocus:c.clearFocus,setQuote:c.setQuote,clearQuote:c.clearQuote,notifyHostChange:c.notifyHostChange,resolveProposal:c.resolveProposal,get proposals(){return c.getProposals()},messages:c.messages,restoreLastCheckpoint:()=>c.checkpoint?.restore()??!1,listCheckpoints:()=>c.checkpoint?.list()??[],hook:e=>(c.listeners.add(e),()=>c.listeners.delete(e)),setData:e=>{if(!c.dataOpsController){console.warn(`[page-agent-sdk] setData 忽略:dataOps 已关闭(capabilities.dataOps:false)`);return}c.dataOpsController.set(e),c.infoTick.value++,c.emit({type:`data_change`,operation:`set`,value:e.bind})},getData:()=>c.liveData(),setSkills:e=>{let t=c.skillsController;if(!t){console.warn(`[page-agent-sdk] setSkills 忽略:skills 已关闭(capabilities.skills:false)`);return}t.set(e),c.unloadSkillTools?.(),c.infoTick.value++},addSkill:e=>{if(!c.skillsController){console.warn(`[page-agent-sdk] addSkill 忽略:skills 已关闭(capabilities.skills:false)`);return}c.addSkill(e),c.unloadSkillTools?.(e.name)},removeSkill:e=>{if(!c.skillsController)return console.warn(`[page-agent-sdk] removeSkill 忽略:skills 已关闭(capabilities.skills:false)`),!1;let t=c.removeSkill(e);return t&&c.unloadSkillTools?.(e),t},listUserSkills:()=>c.listUserSkills(),getUserSkill:e=>c.getUserSkill(e),invalidateSkillCache:e=>{let t=c.skillsController;if(!t){console.warn(`[page-agent-sdk] invalidateSkillCache 忽略:skills 已关闭(capabilities.skills:false)`);return}t.invalidateCache(e),c.unloadSkillTools?.(e)},exportData:()=>{let e=c.liveData()?.bind;return e==null?null:JSON.parse(JSON.stringify(e))},importData:(e,t)=>{let n=c.liveData();if(!n||!c.dataOpsController)return{ok:!1,error:`dataOps 未开启或无主数据`};let r=n.bind;if(typeof r!=`object`||!r)return{ok:!1,error:`主数据 bind 非对象,无法就地还原(集成方应用对象包裹)`};if(t?.validate!==!1){let t=n.schema.safeParse(e);if(!t.success)return{ok:!1,error:`schema 校验失败:`+(t.error?.message??`未知错误`)}}return hg(r,e),c.dataOpsController?.markDataDirty?.(),t?.emit!==!1&&c.emit({type:`data_change`,operation:`set`,value:r}),{ok:!0}},vfsWrite:(e,t)=>{let n=typeof t==`string`?t:JSON.stringify(t);c.vfsStore.files[u_(e)]={content:n,updatedAt:Date.now()}},vfsRead:e=>c.vfsStore.files[u_(e)]?.content,createResource:(e,t)=>{let n=c.dataOpsController;if(!n?.createResource)throw Error(`[page-agent-sdk] createResource 不可用:需配 data.resources + vfsStore(capabilities.vfs 默认开)`);return n.createResource(e,t)},getResource:e=>c.dataOpsController?.getResource?.(e),updateResource:(e,t)=>{let n=c.dataOpsController;if(!n?.updateResource)throw Error(`[page-agent-sdk] updateResource 不可用:需配 data.resources + vfsStore`);n.updateResource(e,t)},deleteResource:e=>c.dataOpsController?.deleteResource?.(e)??!1,listResources:()=>c.dataOpsController?.listResources?.()??[],releaseResources:e=>{let t=c.dataOpsController;if(!(!t?.listResources||!t.deleteResource))if(e&&e.length)for(let n of e)t.deleteResource(n);else for(let e of t.listResources())t.deleteResource(e.path)},usage:c.usage,pendingConflict:c.pendingConflict,resolveConflict:e=>c.resolveConflict(e),setTools:e=>c.setTools(e),addTool:e=>c.addTool(e),removeTool:e=>c.removeTool(e),setLlm:e=>c.setLlm(e),setMemory:e=>c.setMemory(e),refreshMemory:()=>c.refreshMemory(),setSubagents:e=>c.setSubagents(e),addSubagent:e=>c.addSubagent(e),removeSubagent:e=>c.removeSubagent(e),getActiveSubagents:()=>c.getActiveSubagents(),get subagentHistory(){return c.subagentHistory}}}var zC=(e,t)=>{let{o:n,i:r,u:i}=e,a=n,o,s=(e,t)=>{let n=a,s=e,c=t||(r?!r(n,s):n!==s);return(c||i)&&(a=s,o=n),[a,c,o]};return[t?e=>s(t(a,o),e):s,e=>[a,!!e,o]]},BC=typeof window<`u`&&typeof HTMLElement<`u`&&window.document?window:{},VC=Math.max,HC=Math.min,UC=Math.round,WC=Math.abs,GC=Math.sign,KC=BC.cancelAnimationFrame,qC=BC.requestAnimationFrame,JC=BC.setTimeout,YC=BC.clearTimeout,XC=e=>BC[e]===void 0?void 0:BC[e],ZC=XC(`MutationObserver`),QC=XC(`IntersectionObserver`),$C=XC(`ResizeObserver`),ew=XC(`ScrollTimeline`),tw=e=>e===void 0,nw=e=>e===null,rw=e=>typeof e==`number`,iw=e=>typeof e==`string`,aw=e=>typeof e==`boolean`,ow=e=>typeof e==`function`,sw=e=>Array.isArray(e),cw=e=>typeof e==`object`&&!sw(e)&&!nw(e),lw=e=>{let t=!!e&&e.length,n=rw(t)&&t>-1&&t%1==0;return sw(e)||!ow(e)&&n?t>0&&cw(e)?t-1 in e:!0:!1},uw=e=>!!e&&e.constructor===Object,dw=e=>e instanceof HTMLElement,fw=e=>e instanceof Element;function pw(e,t){if(lw(e))for(let n=0;n<e.length&&t(e[n],n,e)!==!1;n++);else e&&pw(Object.keys(e),(n=>t(e[n],n,e)));return e}var mw=(e,t)=>e.indexOf(t)>=0,hw=(e,t)=>e.concat(t),gw=(e,t,n)=>(!iw(t)&&lw(t)?Array.prototype.push.apply(e,t):e.push(t),e),_w=e=>Array.from(e||[]),vw=e=>sw(e)?e:!iw(e)&&lw(e)?_w(e):[e],yw=e=>!!e&&!e.length,bw=e=>_w(new Set(e)),xw=(e,t,n)=>{pw(e,e=>!e||e.apply(void 0,t||[])),n||(e.length=0)},Sw=`paddingTop`,Cw=`paddingRight`,ww=`paddingLeft`,Tw=`paddingBottom`,Ew=`marginLeft`,Dw=`marginRight`,Ow=`marginBottom`,kw=`overflowX`,Aw=`overflowY`,jw=`width`,Mw=`height`,Nw=`visible`,Pw=`hidden`,Fw=`scroll`,Iw=e=>{let t=String(e||``);return t?t[0].toUpperCase()+t.slice(1):``},Lw=(e,t,n,r)=>{if(e&&t){let r=!0;return pw(n,(n=>{e[n]!==t[n]&&(r=!1)})),r}return!1},Rw=(e,t)=>Lw(e,t,[`w`,`h`]),zw=(e,t)=>Lw(e,t,[`x`,`y`]),Bw=(e,t)=>Lw(e,t,[`t`,`r`,`b`,`l`]),Vw=(e,...t)=>e.bind(0,...t),Hw=e=>{let t,n=e?JC:qC,r=e?YC:KC;return[i=>{r(t),t=n((()=>i()),ow(e)?e():e)},()=>r(t)]},Uw=e=>{let t=ow(e)?e():e;if(rw(t)){let e=t?JC:qC,n=t?YC:KC;return r=>{let i=e((()=>r()),t);return()=>{n(i)}}}return t&&t._},Ww=(e,t)=>{let{p:n,v:r,S:i,m:a}=t||{},o,s,c,l,u=function(t){s&&s(),o&&o(),l=s=o=c=void 0,e.apply(this,t)},d=e=>a&&c?a(c,e):e,f=()=>{s&&c&&u(d(c)||c)},p=function(){let e=_w(arguments),t=Uw(n);if(t){let n=typeof i==`function`?i():i,a=Uw(r),p=d(e)||e,m=u.bind(0,p);s&&s(),n&&!l?(m(),l=!0,s=t((()=>l=void 0))):(s=t(m),a&&!o&&(o=a(f))),c=p}else u(e)};return p.O=f,p},Gw=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Kw=e=>e?Object.keys(e):[],qw=(e,t,n,r,i,a,o)=>{let s=[t,n,r,i,a,o];return(typeof e!=`object`||nw(e))&&!ow(e)&&(e={}),pw(s,(t=>{pw(t,((n,r)=>{let i=t[r];if(e===i)return!0;let a=sw(i);if(i&&uw(i)){let t=e[r],n=t;a&&!sw(t)?n=[]:!a&&!uw(t)&&(n={}),e[r]=qw(n,i)}else e[r]=a?i.slice():i}))})),e},Jw=(e,t)=>pw(qw({},e),((e,t,n)=>{e===void 0?delete n[t]:e&&uw(e)&&(n[t]=Jw(e))})),Yw=e=>!Kw(e).length,Xw=()=>{},Zw=(e,t,n)=>VC(e,HC(t,n)),Qw=e=>bw((sw(e)?e:(e||``).split(` `)).filter((e=>e))),$w=(e,t)=>e&&e.getAttribute(t),eT=(e,t)=>e&&e.hasAttribute(t),tT=(e,t,n)=>{pw(Qw(t),(t=>{e&&e.setAttribute(t,String(n||``))}))},nT=(e,t)=>{pw(Qw(t),(t=>e&&e.removeAttribute(t)))},rT=(e,t)=>{let n=Qw($w(e,t)),r=Vw(tT,e,t),i=(e,t)=>{let r=new Set(n);return pw(Qw(e),(e=>{r[t](e)})),_w(r).join(` `)};return{C:e=>r(i(e,`delete`)),$:e=>r(i(e,`add`)),H:e=>{let t=Qw(e);return t.reduce(((e,t)=>e&&n.includes(t)),t.length>0)}}},iT=(e,t,n)=>(rT(e,t).C(n),Vw(aT,e,t,n)),aT=(e,t,n)=>(rT(e,t).$(n),Vw(iT,e,t,n)),oT=(e,t,n,r)=>(r?aT:iT)(e,t,n),sT=(e,t,n)=>rT(e,t).H(n),cT=e=>rT(e,`class`),lT=(e,t)=>{cT(e).C(t)},uT=(e,t)=>(cT(e).$(t),Vw(lT,e,t)),dT=(e,t)=>{let n=t?fw(t)&&t:document;return n?_w(n.querySelectorAll(e)):[]},fT=(e,t)=>{let n=t?fw(t)&&t:document;return n&&n.querySelector(e)},pT=(e,t)=>fw(e)&&e.matches(t),mT=e=>pT(e,`body`),hT=e=>e?_w(e.childNodes):[],gT=e=>e&&e.parentElement,_T=(e,t)=>fw(e)&&e.closest(t),vT=e=>document.activeElement,yT=(e,t,n)=>{let r=_T(e,t),i=e&&fT(n,r),a=_T(i,t)===r;return r&&i?r===e||i===e||a&&_T(_T(e,n),t)!==r:!1},bT=e=>{pw(vw(e),(e=>{let t=gT(e);e&&t&&t.removeChild(e)}))},xT=(e,t)=>Vw(bT,e&&t&&pw(vw(t),(t=>{t&&e.appendChild(t)}))),ST,CT=()=>ST,wT=e=>{ST=e},TT=e=>{let t=document.createElement(`div`);return tT(t,`class`,e),t},ET=e=>{let t=TT(),n=CT(),r=e.trim();return t.innerHTML=n?n.createHTML(r):r,pw(hT(t),(e=>bT(e)))},DT=(e,t)=>e.getPropertyValue(t)||e[t]||``,OT=e=>{let t=e||0;return isFinite(t)?t:0},kT=e=>OT(parseFloat(e||``)),AT=e=>Math.round(e*1e4)/1e4,jT=e=>`${AT(OT(e))}px`;function MT(e,t){e&&t&&pw(t,((t,n)=>{try{let r=e.style,i=nw(t)||aw(t)?``:rw(t)?jT(t):t;n.indexOf(`--`)===0?r.setProperty(n,i):r[n]=i}catch{}}))}function NT(e,t,n){let r=iw(t),i=r?``:{};if(e){let a=BC.getComputedStyle(e,n)||e.style;i=r?DT(a,t):_w(t).reduce(((e,t)=>(e[t]=DT(a,t),e)),i)}return i}var PT=(e,t,n)=>{let r=t?`${t}-`:``,i=n?`-${n}`:``,a=`${r}top${i}`,o=`${r}right${i}`,s=`${r}bottom${i}`,c=`${r}left${i}`,l=NT(e,[a,o,s,c]);return{t:kT(l[a]),r:kT(l[o]),b:kT(l[s]),l:kT(l[c])}},FT=(e,t)=>`translate${cw(e)?`(${e.x},${e.y})`:`${t?`X`:`Y`}(${e})`}`,IT=e=>!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length),LT={w:0,h:0},RT=(e,t)=>t?{w:t[`${e}Width`],h:t[`${e}Height`]}:LT,zT=e=>RT(`inner`,e||BC),BT=Vw(RT,`offset`),VT=Vw(RT,`client`),HT=Vw(RT,`scroll`),UT=e=>{let t=parseFloat(NT(e,jw))||0,n=parseFloat(NT(e,Mw))||0;return{w:t-UC(t),h:n-UC(n)}},WT=e=>e.getBoundingClientRect(),GT=e=>!!e&&IT(e),KT=e=>!!(e&&(e[Mw]||e[jw])),qT=(e,t)=>{let n=KT(e);return!KT(t)&&n},JT=(e,t,n,r)=>{pw(Qw(t),(t=>{e&&e.removeEventListener(t,n,r)}))},YT=(e,t,n,r)=>{let i=(r&&r.D)??!0,a=r&&r.I||!1,o=r&&r.A||!1,s={passive:i,capture:a};return Vw(xw,Qw(t).map((t=>{let r=o?i=>{JT(e,t,r,a),n&&n(i)}:n;return e&&e.addEventListener(t,r,s),Vw(JT,e,t,r,a)})))},XT=e=>e.stopPropagation(),ZT=e=>e.preventDefault(),QT=e=>XT(e)||ZT(e),$T=(e,t)=>{let{x:n,y:r}=rw(t)?{x:t,y:t}:t||{};rw(n)&&(e.scrollLeft=n),rw(r)&&(e.scrollTop=r)},eE=e=>({x:e.scrollLeft,y:e.scrollTop}),tE=()=>({T:{x:0,y:0},k:{x:0,y:0}}),nE=(e,t)=>{let{T:n,k:r}=e,{w:i,h:a}=t,o=(e,t,n)=>{let r=GC(e)*n,i=GC(t)*n;if(r===i){let n=WC(e),a=WC(t);i=n>a?0:i,r=n<a?0:r}return r=r===i?0:r,[r+0,i+0]},[s,c]=o(n.x,r.x,i),[l,u]=o(n.y,r.y,a);return{T:{x:s,y:l},k:{x:c,y:u}}},rE=({T:e,k:t})=>{let n=(e,t)=>e===0&&e<=t;return{x:n(e.x,t.x),y:n(e.y,t.y)}},iE=({T:e,k:t},n)=>{let r=(e,t,n)=>Zw(0,1,(e-n)/(e-t)||0);return{x:r(e.x,t.x,n.x),y:r(e.y,t.y,n.y)}},aE=e=>{e&&e.focus&&e.focus({preventScroll:!0,focusVisible:!1})},oE=(e,t)=>{pw(vw(t),e)},sE=e=>{let t=new Map,n=(e,n)=>{if(e){let r=t.get(e);oE((e=>{r&&r[e?`delete`:`clear`](e)}),n)}else t.forEach((e=>{e.clear()})),t.clear()},r=(e,i)=>{if(iw(e)){let r=t.get(e)||new Set;return t.set(e,r),oE((e=>{ow(e)&&r.add(e)}),i),Vw(n,e,i)}aw(i)&&i&&n();let a=Kw(e),o=[];return pw(a,(t=>{let n=e[t];n&&gw(o,r(t,n))})),Vw(xw,o)};return r(e||{}),[r,n,(e,n)=>{pw(_w(t.get(e)),(e=>{n&&!yw(n)?e.apply(0,n):e()}))}]},cE={},lE={},uE=e=>{pw(e,(e=>pw(e,((t,n)=>{cE[n]=e[n]}))))},dE=(e,t,n)=>Kw(e).map((r=>{let{static:i,instance:a}=e[r],[o,s,c]=n||[],l=n?a:i;if(l){let e=n?l(o,s,t):l(t);return(c||lE)[r]=e}})),fE=(e,t)=>e[t],pE=e=>fE(lE,e),mE=`__osOptionsValidationPlugin`,hE=`data-overlayscrollbars`,gE=`os-environment`,_E=`${gE}-scrollbar-hidden`,vE=`${hE}-initialize`,yE=`noClipping`,bE=`${hE}-body`,xE=hE,SE=`host`,CE=`${hE}-viewport`,wE=kw,TE=Aw,EE=`arrange`,DE=`measuring`,OE=`scrolling`,kE=`scrollbarHidden`,AE=`noContent`,jE=`${hE}-padding`,ME=`${hE}-content`,NE=`os-size-observer`,PE=`${NE}-appear`,FE=`${NE}-listener`;`${FE}`,`${FE}`;var IE=`os-trinsic-observer`,LE=`os-theme-none`,RE=`os-scrollbar`,zE=`${RE}-rtl`,BE=`${RE}-horizontal`,VE=`${RE}-vertical`,HE=`${RE}-track`,UE=`${RE}-handle`,WE=`${RE}-visible`,GE=`${RE}-cornerless`,KE=`${RE}-interaction`,qE=`${RE}-unusable`,JE=`${RE}-auto-hide`,YE=`${JE}-hidden`,XE=`${RE}-wheel`,ZE=`${HE}-interactive`,QE=`${UE}-interactive`,$E=`__osSizeObserverPlugin`,eD=(e,t)=>{let{M:n}=t,[r,i]=e(`showNativeOverlaidScrollbars`);return[r&&n.x&&n.y,i]},tD=e=>e.indexOf(Nw)===0,nD=e=>e.replace(`${Nw}-`,``),rD=(e,t)=>{if(e===`auto`)return t?Fw:Pw;let n=e||Pw;return[Pw,Fw,Nw].includes(n)?n:Pw},iD=(e,t)=>{let{overflowX:n,overflowY:r}=NT(e,[kw,Aw]);return{x:rD(n,t.x),y:rD(r,t.y)}},aD=`__osScrollbarsHidingPlugin`,oD=`__osClickScrollPlugin`,sD=e=>JSON.stringify(e,((e,t)=>{if(ow(t))throw 0;return t})),cD=(e,t)=>e?`${t}`.split(`.`).reduce(((e,t)=>e&&Gw(e,t)?e[t]:void 0),e):void 0,lD=[0,33],uD=[33,99],dD=[222,666,!0],fD={paddingAbsolute:!1,showNativeOverlaidScrollbars:!1,update:{elementEvents:[[`img`,`load`]],debounce:{mutation:lD,resize:null,event:uD,env:dD},attributes:null,ignoreMutation:null,flowDirectionStyles:null},overflow:{x:`scroll`,y:`scroll`},scrollbars:{theme:`os-theme-dark`,visibility:`auto`,autoHide:`never`,autoHideDelay:1300,autoHideSuspend:!1,dragScroll:!0,clickScroll:!1,pointers:[`mouse`,`touch`,`pen`]}},pD=(e,t)=>{let n={};return pw(hw(Kw(t),Kw(e)),(r=>{let i=e[r],a=t[r];if(cw(i)&&cw(a))qw(n[r]={},pD(i,a)),Yw(n[r])&&delete n[r];else if(Gw(t,r)&&a!==i){let e=!0;if(sw(i)||sw(a))try{sD(i)===sD(a)&&(e=!1)}catch{}e&&(n[r]=a)}})),n},mD=(e,t,n)=>r=>[cD(e,r),n||cD(t,r)!==void 0],hD,gD=()=>hD,_D=e=>{hD=e},vD,yD=()=>{let e=(e,t,n)=>{xT(document.body,e),xT(document.body,e);let r=VT(e),i=BT(e),a=UT(t);return n&&bT(e),{x:i.h-r.h+a.h,y:i.w-r.w+a.w}},t=e=>{let t=!1,n=uT(e,_E);try{t=NT(e,`scrollbar-width`)===`none`||NT(e,`display`,`::-webkit-scrollbar`)===`none`}catch{}return n(),t},n=ET(`<div class="${gE}"><div></div><style>${`.${gE}{scroll-behavior:auto!important;position:fixed;opacity:0;visibility:hidden;overflow:scroll;height:200px;width:200px;z-index:-1}.${gE} div{width:200%;height:200%;margin:10px 0}.${_E}{scrollbar-width:none!important}.${_E}::-webkit-scrollbar,.${_E}::-webkit-scrollbar-corner{appearance:none!important;display:none!important;width:0!important;height:0!important}`}</style></div>`)[0],r=n.firstChild,i=n.lastChild,a=gD();a&&(i.nonce=a);let[o,,s]=sE(),[c,l]=zC({o:e(n,r),i:zw},Vw(e,n,r,!0)),[u]=l(),d=t(n),f={x:u.x===0,y:u.y===0},p={elements:{host:null,padding:!d,viewport:e=>d&&mT(e)&&e,content:!1},scrollbars:{slot:!0},cancel:{nativeScrollbarsOverlaid:!1,body:null}},m=qw({},fD),h=Vw(qw,{},m),g=Vw(qw,{},p),_={U:u,M:f,P:d,J:!!ew,G:Vw(o,`r`),K:g,Z:e=>qw(p,e)&&g(),tt:h,nt:e=>qw(m,e)&&h(),ot:qw({},p),st:qw({},m)};if(nT(n,`style`),bT(n),YT(BC,`resize`,(()=>{s(`r`,[])})),ow(BC.matchMedia)&&!d&&(!f.x||!f.y)){let e=t=>{YT(BC.matchMedia(`(resolution: ${BC.devicePixelRatio}dppx)`),`change`,(()=>{t(),e(t)}),{A:!0})};e((()=>{let[e,t]=c();qw(_.U,e),s(`r`,[t])}))}return _},bD=()=>(vD||=yD(),vD),xD=(e,t,n)=>{let r=!1,i=n?new WeakMap:!1,a=()=>{r=!0},o=a=>{i&&n&&pw(n.map((t=>{let[n,r]=t||[];return[r&&n?(a||dT)(n,e):[],r]})),(n=>pw(n[0],(a=>{let o=n[1],s=i.get(a)||[];if(e.contains(a)&&o){let e=YT(a,o,(n=>{r?(e(),i.delete(a)):t(n)}));i.set(a,gw(s,e))}else xw(s),i.delete(a)}))))};return o(),[a,o]},SD=(e,t,n,r)=>{let i=!1,{et:a,ct:o,rt:s,it:c,lt:l,ut:u}=r||{},[d,f]=xD(e,(()=>i&&n(!0)),s),p=a||[],m=o||[],h=hw(p,m),g=(i,a)=>{if(!yw(a)){let o=l||Xw,s=u||Xw,d=[],p=[],h=!1,g=!1;if(pw(a,(n=>{let{attributeName:i,target:a,type:l,oldValue:u,addedNodes:f,removedNodes:_}=n,v=l===`attributes`,y=l===`childList`,b=e===a,x=v&&i,S=x&&$w(a,i||``),C=iw(S)?S:null,w=x&&u!==C,T=mw(m,i)&&w;if(t&&(y||!b)){let t=v&&w,l=t&&c&&pT(a,c),p=(l?!o(a,i,u,C):!v||t)&&!s(n,!!l,e,r);pw(f,(e=>gw(d,e))),pw(_,(e=>gw(d,e))),g||=p}!t&&b&&w&&!o(a,i,u,C)&&(gw(p,i),h||=T)})),f((e=>bw(d).reduce(((t,n)=>(gw(t,dT(e,n)),pT(n,e)?gw(t,n):t)),[]))),t)return!i&&g&&n(!1),[!1];if(!yw(p)||h){let e=[bw(p),h];return i||n.apply(0,e),e}}},_=new ZC(Vw(g,!1));return[()=>(_.observe(e,{attributes:!0,attributeOldValue:!0,attributeFilter:h,subtree:t,childList:t,characterData:t}),i=!0,()=>{i&&=(d(),_.disconnect(),!1)}),()=>{if(i)return g(!0,_.takeRecords())}]},CD=null,wD=(e,t,n)=>{let{ft:r}=n||{},i=pE($E),[a]=zC({o:!1,u:!0});return()=>{let n=[],o=ET(`<div class="${NE}"><div class="${FE}"></div></div>`)[0],s=o.firstChild,c=e=>{let n=sw(e)&&!yw(e),r=!1,i=!1;if(n){let t=e[0],[n,,o]=a(t.contentRect),s=KT(n);i=qT(n,o),r=!i&&!s}else i=e===!0;r||t({_t:!0,ft:i})};if($C){if(!aw(CD)){let t=new $C(Xw);t.observe(e,{get box(){CD=!0}}),CD||=!1,t.disconnect()}let t=Ww(c,{p:0,v:0}),r=e=>t(e),i=new $C(r);if(i.observe(CD?e:s),gw(n,[()=>{i.disconnect()},!CD&&xT(e,o)]),CD){let t=new $C(r);t.observe(e,{box:`border-box`}),gw(n,(()=>t.disconnect()))}}else if(i){let[t,a]=i(s,c,r);gw(n,hw([uT(o,PE),YT(o,`animationstart`,t),xT(e,o)],a))}else return Xw;return Vw(xw,n)}},TD=(e,t)=>{let n,r=e=>e.h===0||e.isIntersecting||e.intersectionRatio>0,i=TT(IE),[a]=zC({o:!1}),o=(e,n)=>{if(e){let i=a(r(e)),[,o]=i;return o&&!n&&t(i)&&[i]}},s=(e,t)=>o(t.pop(),e);return[()=>{let t=[];if(QC)n=new QC(Vw(s,!1),{root:e}),n.observe(i),gw(t,(()=>{n.disconnect()}));else{let e=()=>{let e=BT(i);o(e)};gw(t,wD(i,e)()),e()}return Vw(xw,gw(t,xT(e,i)))},()=>n&&s(!0,n.takeRecords())]},ED=(e,t,n,r)=>{let i,a,o,s,c,l,u,d,f=`[${xE}]`,p=`[${CE}]`,m=[`id`,`class`,`style`,`open`,`wrap`,`cols`,`rows`],{dt:h,vt:g,L:_,gt:v,ht:y,V:b,bt:x,yt:S,wt:C,St:w}=e,T=e=>NT(e,`direction`)===`rtl`,E=()=>{let e,t,n,i=Ww(r,{p:()=>e,v:()=>t,S:()=>n,m(e,t){let[n]=e,[r]=t;return[hw(Kw(n),Kw(r)).reduce(((e,t)=>(e[t]=n[t]||r[t],e)),{})]}}),a=(r,a)=>{if(sw(a)){let[r,i,o]=a;e=r,t=i,n=o}else rw(a)?(e=a,t=!1,n=!1):(e=!1,t=!1,n=!1);i(r)};return a.O=i.O,a},D={Ot:!1,B:T(h)},O=bD(),k=pE(aD),[A]=zC({i:Rw,o:{w:0,h:0}},(()=>{let r=k&&k.R(e,t,D,O,n).Y,i=!(x&&b)&&sT(g,xE,yE),a=!b&&S(EE),o=a&&eE(v),s=o&&w(),c=C(DE,i),l=a&&r&&r(),u=HT(_),d=UT(_);return l&&l(),$T(v,o),s&&s(),i&&c(),{w:u.w+d.w,h:u.h+d.h}})),j=E(),M=e=>{let t=T(h);qw(e,{Ct:d!==t}),qw(D,{B:t}),d=t},ee=(e,t)=>{let[n,i]=e,a={$t:i};return qw(D,{Ot:n}),t||r(a),a},N=({_t:e,ft:t})=>{let n=t?r:j,i={_t:e||t,ft:t};M(i),n(i,a)},te=(e,t)=>{let[,n]=A(),r={xt:n};return M(r),n&&!t&&j(r,e?o:i),r},ne=(e,t,n)=>{let r={Ht:t};return M(r),t&&!n&&j(r,i),r},[P,re]=y?TD(g,ee):[],ie=!b&&wD(g,N,{ft:!0}),[F,ae]=SD(g,!1,ne,{ct:m,et:m}),I=b&&$C&&new $C((e=>{let t=e[e.length-1].contentRect;N({_t:!0,ft:qT(t,u)}),u=t}));return[()=>{I&&I.observe(g);let e=ie&&ie(),t=P&&P(),n=F(),r=O.G((e=>{let[,t]=A();j({Et:e,xt:t,_t:x},s)}));return()=>{I&&I.disconnect(),e&&e(),t&&t(),l&&l(),n(),r()}},({Dt:e,zt:t,It:n})=>{let r={},[u]=e(`update.ignoreMutation`),[d,h]=e(`update.attributes`),[g,v]=e(`update.elementEvents`),[x,S]=e(`update.debounce`),C=v||h,w=t||n,T=e=>ow(u)&&!!u(e);if(C){c&&c(),l&&l();let[e,t]=SD(y||_,!0,te,{et:hw(m,d||[]),rt:g,it:f,ut:(e,t)=>{let{target:n,attributeName:r}=e;return(!t&&r&&!b?yT(n,f,p):!1)||!!_T(n,`.${RE}`)||T(e)}});l=e(),c=t}if(S&&(j.O(),sw(x)||rw(x)?(i=x,a=!1,o=uD,s=dD):uw(x)?(i=x.mutation,a=x.resize,o=x.event,s=x.env):(i=!1,a=!1,o=!1,s=!1)),w){let e=ae(),t=re&&re(),n=c&&c();e&&qw(r,ne(e[0],e[1],w)),t&&qw(r,ee(t[0],w)),n&&qw(r,te(n[0],w))}return M(r),r},D]},DD=(e,t)=>ow(t)?t.apply(0,e):t,OD=(e,t,n,r)=>DD(e,tw(r)?n:r)||t.apply(0,e),kD=(e,t,n,r)=>{let i=DD(e,tw(r)?n:r);return!!i&&(dw(i)?i:t.apply(0,e))},AD=(e,t)=>{let{nativeScrollbarsOverlaid:n,body:r}=t||{},{M:i,P:a,K:o}=bD(),{nativeScrollbarsOverlaid:s,body:c}=o().cancel,l=n??s,u=tw(r)?c:r,d=(i.x||i.y)&&l,f=e&&(nw(u)?!a:u);return!!d||!!f},jD=(e,t,n,r)=>{let{K:i}=bD(),{scrollbars:a}=i(),{slot:o}=a,{dt:s,vt:c,L:l,At:u,gt:d,bt:f,V:p}=t,{scrollbars:m}=u?{}:e,{slot:h}=m||{},g=[],_=[],v=[],y=kD([s,c,l],(()=>p&&f?s:c),o,h),b=e=>{if(ew){let t=null,r=[],i=new ew({source:d,axis:e}),a=()=>{t&&t.cancel(),t=null};return{Mt:o=>{let{Tt:s}=n,c=rE(s)[e],l=e===`x`,u=[FT(0,l),FT(`calc(-100% + 100cq${l?`w`:`h`})`,l)],d=c?u:u.reverse();return r[0]===d[0]&&r[1]===d[1]?a:(r=d,a(),t=o.kt.animate({clear:[`left`],transform:d},{timeline:i}),a)}}}},x={x:b(`x`),y:b(`y`)},S=()=>{let{Rt:e,Vt:t}=n,r=(e,t)=>Zw(0,1,e/(e+t)||0);return{x:r(t.x,e.x),y:r(t.y,e.y)}},C=(e,t,n)=>{let r=n?uT:lT;pw(e,(e=>{r(e.Lt,t)}))},w=(e,t)=>{pw(e,(e=>{let[n,r]=t(e);MT(n,r)}))},T=(e,t,n)=>{let r=aw(n),i=!r||n,a=!r||!n;i&&C(_,e,t),a&&C(v,e,t)},E=()=>{let e=S(),t=e=>t=>[t.Lt,{"--os-viewport-percent":AT(e)+``}];w(_,t(e.x)),w(v,t(e.y))},D=()=>{if(!ew){let{Tt:e}=n,t=iE(e,eE(d)),r=e=>t=>[t.Lt,{"--os-scroll-percent":AT(e)+``}];w(_,r(t.x)),w(v,r(t.y))}},O=()=>{let{Tt:e}=n,t=rE(e),r=e=>t=>[t.Lt,{"--os-scroll-direction":e?`0`:`1`}];w(_,r(t.x)),w(v,r(t.y)),ew&&(_.forEach(x.x.Mt),v.forEach(x.y.Mt))},k=()=>{if(p&&!f){let{Rt:e,Tt:t}=n,r=rE(t),i=iE(t,eE(d)),a=t=>{let{Lt:n}=t,a=gT(n)===l&&n,o=(e,t,n)=>{let r=t*e;return jT(n?r:-r)};return[a,a&&{transform:FT({x:o(i.x,e.x,r.x),y:o(i.y,e.y,r.y)})}]};w(_,a),w(v,a)}},A=e=>{let t=e?`x`:`y`,n=TT(`${RE} ${e?BE:VE}`),i=TT(HE),a=TT(UE),o={Lt:n,Pt:i,kt:a},s=x[t];return gw(e?_:v,o),gw(g,[xT(n,i),xT(i,a),Vw(bT,n),s&&s.Mt(o),r(o,T,e)]),o},j=Vw(A,!0),M=Vw(A,!1);return j(),M(),[{Ut:E,Nt:D,qt:O,Bt:k,Ft:T,jt:{Xt:_,Yt:j,Wt:Vw(w,_)},Jt:{Xt:v,Yt:M,Wt:Vw(w,v)}},()=>(xT(y,_[0].Lt),xT(y,v[0].Lt),Vw(xw,g))]},MD=(e,t,n,r,i)=>(a,o,s)=>{let{vt:c,L:l,V:u,gt:d,Gt:f,St:p}=t,{Lt:m,Pt:h,kt:g}=a,[_,v]=Hw(333),[y,b]=Hw(444),x=e=>{ow(d.scrollBy)&&d.scrollBy({behavior:`smooth`,left:e.x,top:e.y})},S=()=>{let t=`pointerup pointercancel lostpointercapture`,i=`client${s?`X`:`Y`}`,a=s?jw:Mw,o=s?`left`:`top`,c=s?`w`:`h`,l=s?`x`:`y`,u=[];return YT(h,`pointerdown`,r((r=>{let m=_T(r.target,`.${UE}`)===g,_=m?g:h,v=e.scrollbars,S=v[m?`dragScroll`:`clickScroll`],{button:C,isPrimary:w,pointerType:T}=r,{pointers:E}=v;if(C===0&&w&&S&&(E||[]).includes(T)){xw(u),b();let e=!m&&(r.shiftKey||S===`instant`),v=Vw(WT,g),C=Vw(WT,h),w=(e,t)=>(e||v())[o]-(t||C())[o],T=UC(WT(d)[a])/BT(d)[c]||1,E=eE(d)[l],D=e=>{$T(d,{[l]:E+e})},O=e=>{let{Rt:t}=n,r=BT(h)[c]-BT(g)[c],i=1/T*e/r;D(i*t[l])},k=r[i],A=v(),j=C(),M=A[a],ee=w(A,j)+M/2,N=k-j[o]-ee,te=m?0:N,ne=e=>{xw(ie),_.releasePointerCapture(e.pointerId)},P=m||e,re=p(),ie=[YT(f,t,ne),YT(f,`selectstart`,(e=>ZT(e)),{D:!1}),YT(h,t,ne),P&&YT(h,`pointermove`,(e=>O(te+e[i]-k))),P&&(()=>{let e=eE(d);re();let t=eE(d),n={x:t.x-e.x,y:t.y-e.y};(WC(n.x)>3||WC(n.y)>3)&&(p(),$T(d,e),x(n),y(re))})];if(_.setPointerCapture(r.pointerId),e)O(N);else if(!m){let e=pE(oD);if(e){let{Vt:t}=n,r=e(D,O,Vw(w),N,t[l],S,!!s,(e=>{e?re():gw(ie,re)}));gw(ie,r),gw(u,Vw(r,!0))}}}})))},C=!0;return Vw(xw,[YT(g,`pointermove pointerleave`,r(i)),YT(m,`pointerenter`,r((()=>{o(KE,!0)}))),YT(m,`pointerleave pointercancel`,r((()=>{o(KE,!1)}))),YT(m,`wheel`,r((e=>{let{deltaX:t,deltaY:n,deltaMode:r}=e;C&&r===0&&gT(m)===c&&x({x:t,y:n}),C=!1,o(XE,!0),_((()=>{C=!0,o(XE)})),ZT(e)})),{D:!1,I:!0}),!u&&YT(m,`mousedown`,r((()=>{let e=vT();(eT(e,CE)||eT(e,xE)||e===document.body)&&JC(Vw(aE,l),25)}))),YT(m,`pointerdown`,(()=>{let e=YT(f,`click`,(e=>{t(),QT(e)}),{A:!0,I:!0,D:!1}),t=YT(f,`pointerup pointercancel`,(()=>{t(),setTimeout(e,150)}),{I:!0,D:!0})}),{I:!0,D:!0}),S(),v,b])},ND=(e,t,n,r,i,a,o)=>{let s,c,l,u,d,f=Xw,p=0,m=[`mouse`,`pen`],h=e=>t=>{n.Kt||e(t)},g=e=>m.includes(e.pointerType),[_,v]=Hw(),[y,b]=Hw(100),[x,S]=Hw(50),[C,w]=Hw((()=>p)),[T,E]=jD(e,a,i,MD(t,a,i,h,(e=>g(e)&&ne()))),{vt:D,Qt:O,bt:k}=a,{Ft:A,Ut:j,Nt:M,qt:ee,Bt:N}=T,te=(e,t)=>{w();let r=e=>{n.Kt||A(YE,e)};if(e)r();else{let e=!l||!s;p>0&&!t?C(Vw(r,e)):r(e)}},ne=()=>{(l?!s:!u)&&(te(!0),y((()=>{te(!1)})))},P=e=>{g(e)&&(s=!0,!n.Kt&&l&&te(!0))},re=e=>{g(e)&&(s=!1,!n.Kt&&l&&te(!1))},ie=e=>{A(JE,e,!0),A(JE,e,!1)},F=[w,b,S,v,()=>f(),YT(D,`pointerover`,P,{A:!0}),YT(D,`pointerenter`,P),YT(D,`pointerleave`,re),YT(D,`pointermove`,h((e=>{g(e)&&c&&ne()}))),YT(O,`scroll`,h((e=>{_((()=>{M(),ne()})),o(e),N()})))],ae=pE(aD);return[()=>Vw(xw,gw(F,E())),({Dt:e,It:t,Zt:n,tn:a})=>{let{nn:o,sn:s,en:m,cn:g}=a||{},{Ct:_,ft:v}=n||{},{B:y}=r,{M:b,P:S}=bD(),{rn:C,j:w}=i,[T,E]=e(`showNativeOverlaidScrollbars`),[D,ne]=e(`scrollbars.theme`),[P,re]=e(`scrollbars.visibility`),[F,I]=e(`scrollbars.autoHide`),[oe,se]=e(`scrollbars.autoHideSuspend`),[ce]=e(`scrollbars.autoHideDelay`),[L,R]=e(`scrollbars.dragScroll`),[le,ue]=e(`scrollbars.clickScroll`),[de,z]=e(`overflow`),B=v&&!t,fe=o||s||g||_||t,pe=m||re||z,me=T&&b.x&&b.y,V=!S&&!ae,he=me||V,ge=(e,t,n)=>{let r=e.includes(Fw)&&(P===Nw||P===`auto`&&t===Fw);return A(WE,r,n),r};if(p=ce,(E||V)&&A(LE,he),ne&&(A(d),A(D,!0),d=D),(se||B)&&(ie(!oe),B&&oe&&(w.x||w.y?(f(),x((()=>{f=YT(O,Fw,h(Vw(ie,!0)),{A:!0})}))):ie(!0))),I&&(c=F===`move`,l=F===`leave`,u=F===`never`,te(u,!0)),R&&A(QE,L),ue&&A(ZE,!!le),pe){let e=ge(de.x,C.x,!0),t=ge(de.y,C.y,!1);A(GE,!(e&&t))}fe&&(M(),j(),N(),g&&ee(),A(qE,!w.x,!0),A(qE,!w.y,!1),A(zE,y&&!k))},{},T]},PD=e=>{let{K:t,P:n}=bD(),{elements:r}=t(),{padding:i,viewport:a,content:o}=r,s=dw(e),c=s?{}:e,{elements:l}=c,{padding:u,viewport:d,content:f}=l||{},p=s?e:c.target,m=mT(p),h=p.ownerDocument,g=h.documentElement,_=()=>h.defaultView||BC,v=Vw(OD,[p]),y=Vw(kD,[p]),b=Vw(TT,``),x=Vw(v,b,a),S=Vw(y,b,o),C=e=>{let t=BT(e),n=HT(e),r=NT(e,kw),i=NT(e,Aw);return n.w-t.w>0&&!tD(r)||n.h-t.h>0&&!tD(i)},w=x(d),T=w===p,E=T&&m,D=!T&&S(f),O=!T&&w===D,k=E?g:w,A=E?k:p,j=!T&&y(b,i,u),M=!O&&D,ee=[M,k,j,A].map((e=>dw(e)&&!gT(e)&&e)),N=e=>e&&mw(ee,e),te=!N(k)&&C(k)?k:p,ne=E?g:k,P={dt:p,vt:A,L:k,ln:j,ht:M,gt:ne,Qt:E?h:k,an:m?g:te,Gt:h,bt:m,At:s,V:T,un:_,yt:e=>sT(k,CE,e),wt:(e,t)=>oT(k,CE,e,t),St:()=>oT(ne,CE,OE,!0)},{dt:re,vt:ie,ln:F,L:ae,ht:I}=P,oe=[()=>{nT(ie,[xE,vE]),nT(re,vE),m&&nT(g,[vE,xE])}],se=hT([I,ae,F,ie,re].find((e=>e&&!N(e)))),ce=E?re:I||ae,L=Vw(xw,oe);return[P,()=>{let e=_(),t=vT(),r=e=>{xT(gT(e),hT(e)),bT(e)},i=e=>YT(e,`focusin focusout focus blur`,QT,{I:!0,D:!1}),a=`tabindex`,o=$w(ae,a),s=i(t);return tT(ie,xE,T?``:SE),tT(F,jE,``),tT(ae,CE,``),tT(I,ME,``),T||(tT(ae,a,o||`-1`),m&&tT(g,bE,``)),xT(ce,se),xT(ie,F),xT(F||ie,!T&&ae),xT(ae,I),gw(oe,[s,()=>{let e=vT(),t=N(ae),n=t&&e===ae?re:e,s=i(n);nT(F,jE),nT(I,ME),nT(ae,CE),m&&nT(g,bE),o?tT(ae,a,o):nT(ae,a),N(I)&&r(I),t&&r(ae),N(F)&&r(F),aE(n),s()}]),n&&!T&&(aT(ae,CE,kE),gw(oe,Vw(nT,ae,CE))),aE(!T&&m&&t===re&&e.top===e?ae:t),s(),se=0,L},L]},FD=({ht:e})=>({Zt:t,fn:n,It:r})=>{let{$t:i}=t||{},{Ot:a}=n;e&&(i||r)&&MT(e,{[Mw]:a&&`100%`})},ID=({vt:e,ln:t,L:n,V:r},i)=>{let[a,o]=zC({i:Bw,o:PT()},Vw(PT,e,`padding`,``));return({Dt:e,Zt:s,fn:c,It:l})=>{let[u,d]=o(l),{P:f}=bD(),{_t:p,xt:m,Ct:h}=s||{},{B:g}=c,[_,v]=e(`paddingAbsolute`);(p||d||l||m)&&([u,d]=a(l));let y=!r&&(v||h||d);if(y){let e=!_||!t&&!f,r=u.r+u.l,a=u.t+u.b,o={[Dw]:e&&!g?-r:0,[Ow]:e?-a:0,[Ew]:e&&g?-r:0,top:e?-u.t:0,right:e?g?-u.r:`auto`:0,left:e?g?`auto`:-u.l:0,[jw]:e&&`calc(100% + ${r}px)`},s={[Sw]:e?u.t:0,[Cw]:e?u.r:0,[Tw]:e?u.b:0,[ww]:e?u.l:0};MT(t||n,o),MT(n,s),qw(i,{ln:u,_n:!e,F:t?s:qw({},o,s)})}return{dn:y}}},LD=(e,t)=>{let n=bD(),{vt:r,ln:i,L:a,V:o,Qt:s,gt:c,bt:l,wt:u,un:d}=e,{P:f}=n,p=l&&o,m=Vw(VC,0),h={display:()=>!1,direction:e=>e!==`ltr`,flexDirection:e=>e.endsWith(`-reverse`),writingMode:e=>e!==`horizontal-tb`},g=Kw(h),_={i:Rw,o:{w:0,h:0}},v={i:zw,o:{}},y=e=>{u(DE,!p&&e)},b=()=>NT(a,g),x=(e,t)=>{let n=!Kw(e).length,r=t?!0:g.some((t=>{let n=e[t];return iw(n)&&h[t](n)}));if(n||!r||!GT(a))return{T:{x:0,y:0},k:{x:1,y:1}};y(!0);let i=eE(c),o=YT(s,Fw,(e=>{let t=eE(c);e.isTrusted&&t.x===i.x&&t.y===i.y&&XT(e)}),{I:!0,A:!0}),l=u(AE,!0);$T(c,{x:0,y:0}),l();let d=eE(c),f=HT(c);$T(c,{x:f.w,y:f.h});let p=eE(c),m={x:p.x-d.x,y:p.y-d.y};$T(c,{x:-f.w,y:-f.h});let _=eE(c),v={x:_.x-d.x,y:_.y-d.y},b={x:WC(m.x)>=WC(v.x)?p.x:_.x,y:WC(m.y)>=WC(v.y)?p.y:_.y};return $T(c,i),qC((()=>o())),{T:d,k:b}},S=(e,t)=>{let n=BC.devicePixelRatio%1==0?0:1,r={w:m(e.w-t.w),h:m(e.h-t.h)};return{w:r.w>n?r.w:0,h:r.h>n?r.h:0}},C=(e,t)=>{let n=(e,t,n,r)=>{let i=e===Nw?Pw:nD(e),a=tD(e),o=tD(n);return!t&&!r?Pw:a&&o?Nw:a?t&&r?i:t?Nw:Pw:t?i:o&&r?Nw:Pw};return{x:n(t.x,e.x,t.y,e.y),y:n(t.y,e.y,t.x,e.x)}},w=e=>{let t=e=>[Nw,Pw,Fw].map((t=>ie(rD(t),e))),n=t(!0).concat(t()).join(` `);u(n),u(Kw(e).map((t=>ie(e[t],t===`x`))).join(` `),!0)},[T,E]=zC(_,Vw(UT,a)),[D,O]=zC(_,Vw(HT,a)),[k,A]=zC(_),[j]=zC(v),[M,ee]=zC(_),[N]=zC(v),[te]=zC({i:(e,t)=>Lw(e,t,bw(hw(Kw(e),Kw(t)))),o:{}}),[ne,P]=zC({i:(e,t)=>zw(e.T,t.T)&&zw(e.k,t.k),o:tE()}),re=pE(aD),ie=(e,t)=>`${t?wE:TE}${Iw(e)}`;return({Dt:o,Zt:s,fn:c,It:l},{dn:h})=>{let{_t:g,Ht:_,xt:v,Ct:ie,ft:F,Et:ae}=s||{},{X:I,Y:oe,W:se}=re&&re.R(e,t,c,n,o)||{},[ce,L]=eD(o,n),[R,le]=o(`overflow`),ue=tD(R.x),de=tD(R.y),z=g||h||v||ie||ae||L,B=E(l),fe=O(l),pe=A(l),me=ee(l);if(L&&f&&u(kE,!ce),z){sT(r,xE,yE)&&y(!0);let e=oe&&oe(),[t]=B=T(l),[n]=fe=D(l),i=VT(a),o=p&&zT(d()),s={w:m(n.w+t.w),h:m(n.h+t.h)},c={w:m((o?o.w:i.w+m(i.w-n.w))+t.w),h:m((o?o.h:i.h+m(i.h-n.h))+t.h)};e&&e(),me=M(c),pe=k(S(s,c),l)}let[V,he]=me,[ge,H]=pe,[_e,ve]=fe,[ye,be]=B,[xe]=j({x:ge.w>0,y:ge.h>0}),Se=ue&&de&&(xe.x||xe.y)||ue&&xe.x&&!xe.y||de&&xe.y&&!xe.x,Ce=h||ie||ae||be||ve||he||H||le||L||z||_&&p,[we]=o(`update.flowDirectionStyles`),[Te,Ee]=te(we?we(a)||{}:b(),l),[De,Oe]=ie||F||Ee||l?ne(x(Te,!!we),l):P(),ke=C(xe,R);y(!1),Ce&&(w(ke),ke=iD(a,xe),se&&I&&(I(ke,_e,ye),MT(a,se(ke))));let[Ae,je]=N(ke);return oT(r,xE,yE,Se),oT(i,jE,yE,Se),qw(t,{rn:Ae,Vt:{x:V.w,y:V.h},Rt:{x:ge.w,y:ge.h},j:xe,Tt:nE(De,ge)}),{en:je,nn:he,sn:H,cn:Oe||H}}},RD=e=>{let[t,n,r]=PD(e),i={ln:{t:0,r:0,b:0,l:0},_n:!1,F:{[Dw]:0,[Ow]:0,[Ew]:0,[Sw]:0,[Cw]:0,[Tw]:0,[ww]:0},Vt:{x:0,y:0},Rt:{x:0,y:0},rn:{x:Pw,y:Pw},j:{x:!1,y:!1},Tt:tE()},{dt:a,gt:o,V:s,St:c}=t,{P:l,M:u}=bD(),d=!l&&(u.x||u.y),f=[FD(t),ID(t,i),LD(t,i)];return[n,e=>{let t={},n=d&&eE(o),r=n&&c();return pw(f,(n=>{qw(t,n(e,t)||{})})),$T(o,n),r&&r(),s||$T(a,0),t},i,t,r]},zD=(e,t,n,r)=>{let i=!1,a={Kt:!1,pn:!1},o=mD(t,{}),[s,c,l,u,d]=RD(e),[f,p,m]=ED(u,l,o,(e=>{y({},e)})),[h,g,,_]=ND(e,t,a,m,l,u,r),v=e=>Kw(e).some((t=>!!e[t])),y=(e,r)=>{let{Kt:o,pn:s}=a;if(s||o&&i)return!1;let{vn:l,It:u,zt:d}=e,f=l||{},h=!!u||!i,_={Dt:mD(t,f,h),vn:f,It:h},y=r||p(qw({},_,{zt:d})),b=c(qw({},_,{fn:m,Zt:y}));g(qw({},_,{Zt:y,tn:b}));let x=v(y),S=v(b),C=x||S||!Yw(f)||h;return i=!0,C&&n(e,{Zt:y,tn:b}),C};return[()=>{let{an:e,gt:t,St:n}=u,r=eE(e),i=[f(),s(),h(),()=>{a.pn=!0}],o=n();return $T(t,r),o(),Vw(xw,i)},y,e=>{let t=a.Kt;a.Kt=e,!e&&t!==e&&y({It:!0,zt:!0})},()=>{g({Dt:mD(t,{},!1),vn:{},It:!1})},()=>({gn:a,hn:m,bn:l}),{yn:u,wn:_},d]},BD=new WeakMap,VD=(e,t)=>{BD.set(e,t)},HD=e=>{BD.delete(e)},UD=e=>BD.get(e),WD=(e,t,n)=>{let{tt:r}=bD(),i=dw(e),a=i?e:e.target,o=UD(a);if(t&&!o){let o=[],s={},c=e=>{let t=Jw(e),n=pE(mE);return n?n(t,!0):t},l=qw({},r(),c(t)),[u,d,f]=sE(),[p,m,h]=sE(n),g=(e,t)=>{h(e,t),f(e,t)},[_,v,y,b,x,S,C]=zD(e,l,(({vn:e,It:t},{Zt:n,tn:r})=>{let{_t:i,Ct:a,$t:o,xt:s,Ht:c,ft:l}=n,{nn:u,sn:d,en:f,cn:p}=r;g(`updated`,[T,{updateHints:{sizeChanged:!!i,directionChanged:!!a,heightIntrinsicChanged:!!o,overflowEdgeChanged:!!u,overflowAmountChanged:!!d,overflowStyleChanged:!!f,scrollCoordinatesChanged:!!p,contentMutation:!!s,hostMutation:!!c,appear:!!l},changedOptions:e||{},force:!!t}])}),(e=>g(`scroll`,[T,e]))),w=e=>{let{gn:t}=x(),{pn:n}=t;n||(HD(a),xw(o),g(`destroyed`,[T,e]),d(),m())},T={options(e,t){if(e){let n=t?r():{},i=pD(l,qw(n,c(e)));Yw(i)||(qw(l,i),v({vn:i}))}return qw({},l)},on:p,off:(e,t)=>{e&&t&&m(e,t)},state(){let{gn:e,hn:t,bn:n}=x(),{pn:r,Kt:i}=e,{B:a}=t,{Vt:o,Rt:s,rn:c,j:l,ln:u,_n:d,Tt:f}=n;return qw({},{overflowEdge:o,overflowAmount:s,overflowStyle:c,hasOverflow:l,scrollCoordinates:{start:f.T,end:f.k},padding:u,paddingAbsolute:d,directionRTL:a,sleeping:i,destroyed:r})},elements(){let{dt:e,vt:t,ln:n,L:r,ht:i,gt:a,Qt:o}=S.yn,{jt:s,Jt:c}=S.wn,l=e=>{let{kt:t,Pt:n,Lt:r}=e;return{scrollbar:r,track:n,handle:t}},u=e=>{let{Xt:t,Yt:n}=e;return qw({},l(t[0]),{clone:()=>{let e=l(n());return b(),e}})};return qw({},{target:e,host:t,padding:n||r,viewport:r,content:i||r,scrollOffsetElement:a,scrollEventElement:o,scrollbarHorizontal:u(s),scrollbarVertical:u(c)})},update:e=>v({It:e,zt:!0}),destroy:Vw(w,!1),sleep:y,plugin:e=>s[Kw(e)[0]]};return gw(o,[C]),VD(a,T),dE(cE,WD,[T,u,s]),AD(S.yn.bt,!i&&e.cancel)?(w(!0),T):(gw(o,_()),g(`initialized`,[T]),T.update(),T)}return o};WD.plugin=e=>{let t=sw(e),n=t?e:[e],r=n.map((e=>dE(e,WD)[0]));return uE(n),t?r:r[0]},WD.valid=e=>{let t=e&&e.elements,n=ow(t)&&t();return uw(n)&&!!UD(n.target)},WD.env=()=>{let{U:e,M:t,P:n,J:r,ot:i,st:a,K:o,Z:s,tt:c,nt:l}=bD();return qw({},{scrollbarsSize:e,scrollbarsOverlaid:t,scrollbarsHiding:n,scrollTimeline:r,staticDefaultInitialization:i,staticDefaultOptions:a,getDefaultInitialization:o,setDefaultInitialization:s,getDefaultOptions:c,setDefaultOptions:l})},WD.nonce=_D,WD.trustedTypePolicy=wT;var GD=4e3;function KD(e={}){let{fetchResponse:t,fetchStream:n,onPersist:r,onClear:i,onQueuedCleared:a,onBeforeRegenerate:o}=e,s=Sn({messages:e.messages??[],loading:!1,error:null}),c=G(null),l=G(!0),u=null,d=G([]),f=G(null);function p(){}function m(e){let t=c.value;e.deltaY<0?l.value=!1:t&&(l.value=t.scrollHeight-t.scrollTop-t.clientHeight<64)}function h(){c.value&&requestAnimationFrame(()=>{let e=c.value;!e||!l.value||(e.scrollTop=e.scrollHeight)})}function g(e,t,n,r,i){s.messages.push({role:e,content:t,timestamp:Date.now(),...n&&n.length?{focuses:n}:{},...r?.length?{images:r}:{},...i?{quote:i}:{}}),l.value=!0,h()}async function _(e){if(l.value=!0,n){let t=Sn({role:`assistant`,content:``,timestamp:Date.now(),reasoning:``,reasoningTotal:0,steps:[]}),r=!1;s.messages.push(t);try{await n(s.messages.slice(0,-1),e=>{switch(e.type){case`round_start`:e.round>1&&(t.content||t.reasoning)&&(r=!0);break;case`reasoning`:r&&=(t.reasoning+=`
3008
3008
  `,!1),t.reasoningTotal+=e.delta.length,t.reasoning=(t.reasoning+e.delta).slice(-4e3);break;case`text`:r&&=(t.content+=`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "page-agent-sdk",
3
- "version": "4.24.1",
3
+ "version": "4.24.3",
4
4
  "type": "module",
5
5
  "description": "AI agent SDK for web pages — embed a chat assistant that edits page data via schema-validated tools. A lighter, framework-agnostic alternative to CopilotKit/LangChain for in-page JSON-editing agents. Vue-bundled; works with DeepSeek, OpenAI, MCP.",
6
6
  "main": "./dist/page-agent-sdk.umd.cjs",