page-agent-sdk 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,7 +49,7 @@ self.onmessage = async (e) => {
49
49
  提示:改某组件深层字段前,先 schema_data({jsonPath}) 查完整约束;或 read 子路径见实际值。`}return n}return e?.description||`(用 read 查看实际形状)`}var np=/(?:改|加|删|生成|查询|分析|创建|修改|配置|实现|检查|对比|整理|转换|设计|搭建|编排|布局|调整|更新)/;function rp(e){return!e||e.trim().length<8||/^(你好|hi|hello|ok|好的|继续|嗯|谢谢|hey|哈喽|收到|明白)/i.test(e.trim())||e.length>2e3?!1:np.test(e)}function ip(e){for(let t=0;t<e.length;t++){if(e[t].role!==`user`)continue;let n=e[t].content;if(rp(n))return{goal:n.length>200?n.slice(0,200)+`…`:n,sourceMessageIdx:t,capturedAt:Date.now(),explicit:!1}}}function ap(){let e,t=!1;return{name:`mission`,beforeAgent:n=>(!e&&!t&&(e=ip(n.messages)),e?{mission:e}:{}),augmentPrompt:()=>{if(!e)return;let t=[`## 当前主线目标`,e.goal];return e.acceptanceCriteria?.length&&(t.push(`完成标准:`),e.acceptanceCriteria.forEach((e,n)=>t.push(`${n+1}. ${e}`))),t.push(`(每步操作应服务此目标;偏离时回到主线)`),t.join(`
50
50
  `)},setMission:n=>{if(Object.keys(n).length===0){e=void 0,t=!0;return}t=!1,e={goal:n.goal??e?.goal??``,acceptanceCriteria:n.acceptanceCriteria??e?.acceptanceCriteria,sourceMessageIdx:n.sourceMessageIdx??e?.sourceMessageIdx??-1,capturedAt:n.capturedAt??e?.capturedAt??Date.now(),explicit:n.explicit??!0}},getMission:()=>e,reset:()=>{e=void 0,t=!1}}}var op=/(为什么|为啥|多少|几个|能不能|可不可以|是否|有没有|怎样|咋)/,sp=/(是什么|是啥|怎么用|如何用|有哪些|什么意思|干嘛的|干什么用)/,cp=/(吗|呢)[??]?\s*$/;function lp(e){let t=(e||``).trim();return t?!!(/[??]\s*$/.test(t)||sp.test(t)||op.test(t)&&cp.test(t)):!1}var up=[`[本轮消息为咨询] 用户最新消息是提问/咨询,不是操作指令。`,`请先作答:用 read / query / search / list_components / rag 等工具查证后基于事实回答,不要凭空猜测。`,`不要执行生成/修改/删除操作 —— 除非用户在同一条消息里同时明确提出了操作要求(如「顺便把 X 改成 Y」)。`].join(`
51
51
  `);function dp(e){let t=null;return{name:`intentGuard`,augmentPrompt:n=>{for(let r=n.messages.length-1;r>=0;r--){let i=n.messages[r];if(i.role===`user`)return lp(i.content)?(e&&t!==i.content&&(t=i.content,e(i.content.slice(0,60))),up):void 0}}}}var fp=[`[本会话从历史记录恢复] 你不在场期间,宿主页面数据可能已发生变化:`,`- 页面刷新可能使数据回退到上次保存的状态(未保存的修改已不存在);用户或宿主也可能改动过数据。`,`- 历史对话与已完成的任务记录不代表当前实际数据。`,`纪律:断言「已生成/已存在/已完成」前,先用 read / list_components 等工具核实当前状态;`,`用户要求重做历史工作(如「重新生成」)时,先核实缺失了哪些部分,再补齐或重做,勿直接回复「已完成/完毕」。`].join(`
52
- `);function pp(e){let t=!1,n=!1;return{name:`resumeNotice`,markResumed:()=>{t=!0,n=!1},reset:()=>{t=!1,n=!1},isPending:()=>t,augmentPrompt:()=>{if(t)return e&&!n&&(n=!0,e()),fp},afterAgent:()=>{t=!1}}}var mp=new Set([`__proto__`,`constructor`,`prototype`]);function hp(e){return e.split(`.`).some(e=>mp.has(e))}function gp(e,t){if(!(!t||typeof t!=`object`||Array.isArray(t)))for(let n of Object.keys(t))mp.has(n)||(e[n]=t[n])}function _p(e,t){if(!t)return e;if(hp(t))return;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function vp(e,t,n){if(!t||hp(t))return;let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];(i[t]==null||typeof i[t]!=`object`)&&(i[t]={}),i=i[t]}i[r[r.length-1]]=n}function yp(e,t){if(!t||hp(t))return!1;let n=t.split(`.`),r=e;for(let e=0;e<n.length-1;e++){if(r==null)return!1;r=r[n[e]]}let i=n[n.length-1];return r==null||!(i in r)?!1:(Array.isArray(r)&&/^\d+$/.test(i)?r.splice(Number(i),1):delete r[i],!0)}function bp(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch(t){let n=xp(e);throw n?Error(`数据存在循环引用(${n});数据槽/快照不支持环形结构,请检查宿主 bind 或写入值`):t}}function xp(e){let t=new WeakSet,n=(e,r)=>{if(typeof e!=`object`||!e)return;let i=e;if(t.has(i))return r;if(t.add(i),Array.isArray(e))for(let t=0;t<e.length;t++){let i=n(e[t],`${r}[${t}]`);if(i)return i}else for(let t of Object.keys(e)){let i=n(e[t],`${r}.${t}`);if(i)return i}t.delete(i)};return n(e,`$`)}function Sp(e){if(typeof e!=`string`)return{parsed:e};let t=e.trim();if(!t)return{parsed:e};let n=t[0]===`{`||t[0]===`[`;try{return{parsed:JSON.parse(t)}}catch(t){return n?{parseError:t}:{parsed:e}}}function Cp(e,t){if(typeof e!=`object`||!e)return e;let n=new Set(t);if(Array.isArray(e))return e.map(e=>Cp(e,t));let r={};for(let t of Object.keys(e))n.has(t)&&(r[t]=e[t]);return r}function wp(e,t){if(typeof e!=`object`||!e)return e;if(t<=0)return Array.isArray(e)?`[...${e.length}]`:`{...}`;if(Array.isArray(e))return e.map(e=>wp(e,t-1));let n={};for(let r of Object.keys(e))n[r]=wp(e[r],t-1);return n}function Tp(e,t=1/0,n){let r=new WeakSet,i;try{i=JSON.stringify(e,(e,t)=>{if(!(n&&e&&n.has(e))){if(typeof t==`function`)return`[Function]`;if(typeof t==`bigint`)return t.toString();if(typeof t==`object`&&t){if(typeof HTMLElement<`u`&&t instanceof HTMLElement)return`[HTMLElement: <${t.tagName.toLowerCase()}>]`;if(typeof Node<`u`&&t instanceof Node)return`[Node: type=${t.nodeType}]`;if(r.has(t))return`[Circular]`;r.add(t)}return t}},0)}catch(e){i=`[无法序列化: ${e?.message||String(e)}]`}return i.length>t&&(i=i.slice(0,t)+`\n…[已截断,原长度 ${i.length}]`),i}function Ep(e,t=0){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Dp(e,t){return Ep(Tp(e,1/0,t)).toString(36)}function Op(e,t){let n=[],r=e=>{if(Array.isArray(e)){e.forEach(r);return}if(e&&typeof e==`object`)for(let[i,a]of Object.entries(e))t.has(i)&&n.push(`${i}=${Tp(a)}`),r(a)};return r(e),n.sort(),Ep(n.join(`\0`)).toString(36)}function kp(e,t,n,r){if(t===`set`)return n?(vp(e,n,r),null):`set 操作需要 jsonPath(整体替换请用 write({value}))`;if(t===`remove`)return n?yp(e,n)?null:`remove 路径不存在: ${n}(数组索引越界或字段缺失;请先 read 最新结构确认索引)`:`remove 操作需要 jsonPath`;if(t===`merge`){let t=n?_p(e,n):e;return typeof t!=`object`||!t||Array.isArray(t)?`merge 目标${n?`(${n})`:`(根)`}不是对象`:(gp(t,r),null)}if(t===`move`)return jp(e,n,r);let i=n?_p(e,n):e;return Array.isArray(i)?(Array.isArray(r)?i.push(...r):i.push(r),null):`append 目标${n?`(${n})`:`(根)`}不是数组`}function Ap(e,t){let n=t.split(`.`),r=e;for(let e=0;e<n.length-1;e++){if(r==null)return null;r=r[n[e]]}return[r,n[n.length-1]]}function jp(e,t,n){if(!t)return`move 操作需要 jsonPath(源数组元素路径,如 components.2)`;if(typeof n!=`string`||!n)return`move 的 value 必须是目标路径字符串(数组本身=追加,如 "sections.1.children";数组内下标=插入,如 "components.0")`;if(hp(n))return`move 目标路径 "${n}" 含非法段`;let r=Ap(e,t);if(!r||!Array.isArray(r[0]))return`move 源的父级不是数组(仅支持数组元素移动,jsonPath 应指向数组下标,如 components.2)`;let i=Number(r[1]);if(!Number.isInteger(i)||i<0||i>=r[0].length)return`move 源下标越界:${t}(父数组长度 ${r[0].length})`;let a=r[0][i];r[0].splice(i,1);let o=_p(e,n);if(Array.isArray(o))return o.push(a),null;if(o===void 0){let t=Ap(e,n);if(t&&t[0]!=null&&typeof t[0]==`object`&&!/^\d+$/.test(t[1]))return t[0][t[1]]=[a],null}let s=Ap(e,n);if(s&&Array.isArray(s[0])&&/^\d+$/.test(s[1])){let e=Math.min(Number(s[1]),s[0].length);return s[0].splice(e,0,a),null}return`move 目标 "${n}" 不是数组(目标须为数组本身(追加)或数组内某下标(插入))`}function Mp(e,t,n,r){if(t===`set`)vp(e,n,r);else if(t===`remove`)yp(e,n);else if(t===`merge`)gp(n?_p(e,n):e,r);else if(t===`move`)jp(e,n,r);else{let t=n?_p(e,n):e;Array.isArray(r)?t.push(...r):t.push(r)}}function Np(e,t){typeof e==`object`&&e&&Pp(e,t)}function Pp(e,t){if(Array.isArray(e)){e.length=0,Array.isArray(t)&&e.push(...t);return}let n=t&&typeof t==`object`&&!Array.isArray(t)?t:{};for(let t of Object.keys(e))t in n||delete e[t];for(let t of Object.keys(n))e[t]=n[t]}function Fp(e,t,n,r=``){let i=[],a=e=>typeof e==`object`&&!!e;if(!a(t))return i;if(Array.isArray(t)){let a=Array.isArray(e)?e:[],o=Array.isArray(n)?n:[],s=new Set(a.map(e=>JSON.stringify(e)));return t.forEach((e,t)=>{s.has(JSON.stringify(e))||i.push(...Fp(a[t],e,o[t],r?`${r}.${t}`:String(t)))}),i}let o=t,s=a(n)&&!Array.isArray(n)?n:null,c=a(e)&&!Array.isArray(e)?e:null;for(let e of Object.keys(o)){let t=r?`${r}.${e}`:e;e.startsWith(`__pg`)||(s&&!(e in s)?(!c||!(e in c))&&i.push(t):s&&e in s&&i.push(...Fp(c?.[e],o[e],s[e],t)))}return i}function Ip(e,t,n=``){let r=[];if(!(typeof e==`object`&&e)||!(typeof t==`object`&&t)||Array.isArray(e)!==Array.isArray(t))return e!==t&&r.push({path:n||`(root)`,from:e,to:t}),r;if(Array.isArray(e)&&Array.isArray(t)){let i=Math.max(e.length,t.length);for(let a=0;a<i;a++){let i=n?`${n}.${a}`:`${a}`;a>=e.length?r.push({path:i,from:void 0,to:t[a]}):a>=t.length?r.push({path:i,from:e[a],to:void 0}):r.push(...Ip(e[a],t[a],i))}return r}let i=e,a=t,o=new Set([...Object.keys(i),...Object.keys(a)]);for(let e of o){let t=n?`${n}.${e}`:e;e in i?e in a?r.push(...Ip(i[e],a[e],t)):r.push({path:t,from:i[e],to:void 0}):r.push({path:t,from:void 0,to:a[e]})}return r}var Lp=new Set([`write`,`draft_commit`]);function Rp(e){let t=e??{},n=new Set;if(typeof t.jsonPath==`string`&&t.jsonPath&&n.add(t.jsonPath),typeof t.path==`string`&&t.path&&n.add(t.path),t.patch&&typeof t.patch.jsonPath==`string`&&t.patch.jsonPath&&n.add(t.patch.jsonPath),Array.isArray(t.patches))for(let e of t.patches)e&&typeof e.jsonPath==`string`&&e.jsonPath&&n.add(e.jsonPath);return[...n]}function zp(e,t){return e===t||e.startsWith(t+`.`)}function Bp(e,t){if(!t||typeof t!=`object`)return!1;let n=e.lastIndexOf(`.`);if(n<0)return!1;let r=e.slice(0,n),i=e.slice(n+1);if(!/^\d+$/.test(i))return!1;let a=_p(t,r);return Array.isArray(a)&&Number(i)>=a.length}function Vp(e){let t=e.initialFocuses?[...e.initialFocuses]:[],n=()=>e.onChange?.([...t]),r=e.unfocusGuidance??`tool`,i=e=>`若你的意图是修改聚焦组件本身(如给它新增页签/子项),请改写焦点路径的子路径重试${e?`(如 ${e})`:``};`,a=r===`tool`?`需改其他组件请先 remove_focus / clear_focus 或换焦点。${i()}`:r===`ask-user`?`焦点由用户在输入框设定与移除(聚焦 chip ✕);用户要求改其他组件时,提示用户移除聚焦后重试,勿尝试写焦点外(会被拒)。${i()}`:`需改其他组件时,在收口回复中说明需先取消焦点(焦点由主会话管理),勿尝试越界写。${i()}`,o=e=>r===`tool`?`${i(e)}需操作焦点外组件请先 remove_focus / clear_focus 或换焦点后重试。`:r===`ask-user`?`${i(e)}焦点由用户在输入框管理,请提示用户移除输入框中的聚焦 chip 后重试(当前模式无 focus 工具)。`:`${i(e)}请只改焦点子树;需改其他组件时,在收口回复中说明需先取消焦点。`;return{name:`focus`,beforeAgent:()=>t.length?{focuses:[...t],focus:t[0]}:{},augmentPrompt:()=>{if(!t.length)return;let n=[`## 当前精修目标`,t.map(e=>`· ${e.path}${e.label?`(${e.label})`:``}`).join(`
52
+ `);function pp(e){let t=!1,n=!1;return{name:`resumeNotice`,markResumed:()=>{t=!0,n=!1},reset:()=>{t=!1,n=!1},isPending:()=>t,augmentPrompt:()=>{if(t)return e&&!n&&(n=!0,e()),fp},afterAgent:()=>{t=!1}}}var mp=new Set([`__proto__`,`constructor`,`prototype`]);function hp(e){return e.split(`.`).some(e=>mp.has(e))}function gp(e,t){if(!(!t||typeof t!=`object`||Array.isArray(t)))for(let n of Object.keys(t))mp.has(n)||(e[n]=t[n])}function _p(e,t){if(!t)return e;if(hp(t))return;let n=t.split(`.`),r=e;for(let e of n){if(r==null)return;r=r[e]}return r}function vp(e,t,n){if(!t||hp(t))return;let r=t.split(`.`),i=e;for(let e=0;e<r.length-1;e++){let t=r[e];(i[t]==null||typeof i[t]!=`object`)&&(i[t]={}),i=i[t]}i[r[r.length-1]]=n}function yp(e,t){if(!t||hp(t))return!1;let n=t.split(`.`),r=e;for(let e=0;e<n.length-1;e++){if(r==null)return!1;r=r[n[e]]}let i=n[n.length-1];return r==null||!(i in r)?!1:(Array.isArray(r)&&/^\d+$/.test(i)?r.splice(Number(i),1):delete r[i],!0)}function bp(e){if(e!==void 0)try{return JSON.parse(JSON.stringify(e))}catch(t){let n=xp(e);throw n?Error(`数据存在循环引用(${n});数据槽/快照不支持环形结构,请检查宿主 bind 或写入值`):t}}function xp(e){let t=new WeakSet,n=(e,r)=>{if(typeof e!=`object`||!e)return;let i=e;if(t.has(i))return r;if(t.add(i),Array.isArray(e))for(let t=0;t<e.length;t++){let i=n(e[t],`${r}[${t}]`);if(i)return i}else for(let t of Object.keys(e)){let i=n(e[t],`${r}.${t}`);if(i)return i}t.delete(i)};return n(e,`$`)}function Sp(e){if(typeof e!=`string`)return{parsed:e};let t=e.trim();if(!t)return{parsed:e};let n=t[0]===`{`||t[0]===`[`;try{return{parsed:JSON.parse(t)}}catch(t){return n?{parseError:t}:{parsed:e}}}function Cp(e,t){if(typeof e!=`object`||!e)return e;let n=new Set(t);if(Array.isArray(e))return e.map(e=>Cp(e,t));let r={};for(let t of Object.keys(e))n.has(t)&&(r[t]=e[t]);return r}function wp(e,t){if(typeof e!=`object`||!e)return e;if(t<=0)return Array.isArray(e)?`[...${e.length}]`:`{...}`;if(Array.isArray(e))return e.map(e=>wp(e,t-1));let n={};for(let r of Object.keys(e))n[r]=wp(e[r],t-1);return n}function Tp(e,t=1/0,n){let r=new WeakSet,i;try{i=JSON.stringify(e,(e,t)=>{if(!(n&&e&&n.has(e))){if(typeof t==`function`)return`[Function]`;if(typeof t==`bigint`)return t.toString();if(typeof t==`object`&&t){if(typeof HTMLElement<`u`&&t instanceof HTMLElement)return`[HTMLElement: <${t.tagName.toLowerCase()}>]`;if(typeof Node<`u`&&t instanceof Node)return`[Node: type=${t.nodeType}]`;if(r.has(t))return`[Circular]`;r.add(t)}return t}},0)}catch(e){i=`[无法序列化: ${e?.message||String(e)}]`}return i.length>t&&(i=i.slice(0,t)+`\n…[已截断,原长度 ${i.length}]`),i}function Ep(e,t=0){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Dp(e,t){return Ep(Tp(e,1/0,t)).toString(36)}function Op(e,t){let n=[],r=e=>{if(Array.isArray(e)){e.forEach(r);return}if(e&&typeof e==`object`)for(let[i,a]of Object.entries(e))t.has(i)&&n.push(`${i}=${Tp(a)}`),r(a)};return r(e),n.sort(),Ep(n.join(`\0`)).toString(36)}function kp(e,t,n,r){if(t===`set`)return n?(vp(e,n,r),null):`set 操作需要 jsonPath(整体替换请用 write({value}))`;if(t===`remove`)return n?yp(e,n)?null:`remove 路径不存在: ${n}(数组索引越界或字段缺失;请先 read 最新结构确认索引)`:`remove 操作需要 jsonPath`;if(t===`merge`){let t=n?_p(e,n):e;return typeof t!=`object`||!t||Array.isArray(t)?`merge 目标${n?`(${n})`:`(根)`}不是对象`:(gp(t,r),null)}if(t===`move`)return jp(e,n,r);let i=n?_p(e,n):e;return typeof i==`string`?typeof r==`string`?(vp(e,n,i+r),null):`append 目标(${n})是字符串,value 必须也是字符串(拼接语义)`:Array.isArray(i)?(Array.isArray(r)?i.push(...r):i.push(r),null):`append 目标${n?`(${n})`:`(根)`}不是数组(也不支持非字符串标量拼接)`}function Ap(e,t){let n=t.split(`.`),r=e;for(let e=0;e<n.length-1;e++){if(r==null)return null;r=r[n[e]]}return[r,n[n.length-1]]}function jp(e,t,n){if(!t)return`move 操作需要 jsonPath(源数组元素路径,如 components.2)`;if(typeof n!=`string`||!n)return`move 的 value 必须是目标路径字符串(数组本身=追加,如 "sections.1.children";数组内下标=插入,如 "components.0")`;if(hp(n))return`move 目标路径 "${n}" 含非法段`;let r=Ap(e,t);if(!r||!Array.isArray(r[0]))return`move 源的父级不是数组(仅支持数组元素移动,jsonPath 应指向数组下标,如 components.2)`;let i=Number(r[1]);if(!Number.isInteger(i)||i<0||i>=r[0].length)return`move 源下标越界:${t}(父数组长度 ${r[0].length})`;let a=r[0][i];r[0].splice(i,1);let o=_p(e,n);if(Array.isArray(o))return o.push(a),null;if(o===void 0){let t=Ap(e,n);if(t&&t[0]!=null&&typeof t[0]==`object`&&!/^\d+$/.test(t[1]))return t[0][t[1]]=[a],null}let s=Ap(e,n);if(s&&Array.isArray(s[0])&&/^\d+$/.test(s[1])){let e=Math.min(Number(s[1]),s[0].length);return s[0].splice(e,0,a),null}return`move 目标 "${n}" 不是数组(目标须为数组本身(追加)或数组内某下标(插入))`}function Mp(e,t,n,r){if(t===`set`)vp(e,n,r);else if(t===`remove`)yp(e,n);else if(t===`merge`)gp(n?_p(e,n):e,r);else if(t===`move`)jp(e,n,r);else{let t=n?_p(e,n):e;Array.isArray(r)?t.push(...r):t.push(r)}}function Np(e,t){typeof e==`object`&&e&&Pp(e,t)}function Pp(e,t){if(Array.isArray(e)){e.length=0,Array.isArray(t)&&e.push(...t);return}let n=t&&typeof t==`object`&&!Array.isArray(t)?t:{};for(let t of Object.keys(e))t in n||delete e[t];for(let t of Object.keys(n))e[t]=n[t]}function Fp(e,t,n,r=``){let i=[],a=e=>typeof e==`object`&&!!e;if(!a(t))return i;if(Array.isArray(t)){let a=Array.isArray(e)?e:[],o=Array.isArray(n)?n:[],s=new Set(a.map(e=>JSON.stringify(e)));return t.forEach((e,t)=>{s.has(JSON.stringify(e))||i.push(...Fp(a[t],e,o[t],r?`${r}.${t}`:String(t)))}),i}let o=t,s=a(n)&&!Array.isArray(n)?n:null,c=a(e)&&!Array.isArray(e)?e:null;for(let e of Object.keys(o)){let t=r?`${r}.${e}`:e;e.startsWith(`__pg`)||(s&&!(e in s)?(!c||!(e in c))&&i.push(t):s&&e in s&&i.push(...Fp(c?.[e],o[e],s[e],t)))}return i}function Ip(e,t,n=``){let r=[];if(!(typeof e==`object`&&e)||!(typeof t==`object`&&t)||Array.isArray(e)!==Array.isArray(t))return e!==t&&r.push({path:n||`(root)`,from:e,to:t}),r;if(Array.isArray(e)&&Array.isArray(t)){let i=Math.max(e.length,t.length);for(let a=0;a<i;a++){let i=n?`${n}.${a}`:`${a}`;a>=e.length?r.push({path:i,from:void 0,to:t[a]}):a>=t.length?r.push({path:i,from:e[a],to:void 0}):r.push(...Ip(e[a],t[a],i))}return r}let i=e,a=t,o=new Set([...Object.keys(i),...Object.keys(a)]);for(let e of o){let t=n?`${n}.${e}`:e;e in i?e in a?r.push(...Ip(i[e],a[e],t)):r.push({path:t,from:i[e],to:void 0}):r.push({path:t,from:void 0,to:a[e]})}return r}var Lp=new Set([`write`,`draft_commit`]);function Rp(e){let t=e??{},n=new Set;if(typeof t.jsonPath==`string`&&t.jsonPath&&n.add(t.jsonPath),typeof t.path==`string`&&t.path&&n.add(t.path),t.patch&&typeof t.patch.jsonPath==`string`&&t.patch.jsonPath&&n.add(t.patch.jsonPath),Array.isArray(t.patches))for(let e of t.patches)e&&typeof e.jsonPath==`string`&&e.jsonPath&&n.add(e.jsonPath);return[...n]}function zp(e,t){return e===t||e.startsWith(t+`.`)}function Bp(e,t){if(!t||typeof t!=`object`)return!1;let n=e.lastIndexOf(`.`);if(n<0)return!1;let r=e.slice(0,n),i=e.slice(n+1);if(!/^\d+$/.test(i))return!1;let a=_p(t,r);return Array.isArray(a)&&Number(i)>=a.length}function Vp(e){let t=e.initialFocuses?[...e.initialFocuses]:[],n=()=>e.onChange?.([...t]),r=e.unfocusGuidance??`tool`,i=e=>`若你的意图是修改聚焦组件本身(如给它新增页签/子项),请改写焦点路径的子路径重试${e?`(如 ${e})`:``};`,a=r===`tool`?`需改其他组件请先 remove_focus / clear_focus 或换焦点。${i()}`:r===`ask-user`?`焦点由用户在输入框设定与移除(聚焦 chip ✕);用户要求改其他组件时,提示用户移除聚焦后重试,勿尝试写焦点外(会被拒)。${i()}`:`需改其他组件时,在收口回复中说明需先取消焦点(焦点由主会话管理),勿尝试越界写。${i()}`,o=e=>r===`tool`?`${i(e)}需操作焦点外组件请先 remove_focus / clear_focus 或换焦点后重试。`:r===`ask-user`?`${i(e)}焦点由用户在输入框管理,请提示用户移除输入框中的聚焦 chip 后重试(当前模式无 focus 工具)。`:`${i(e)}请只改焦点子树;需改其他组件时,在收口回复中说明需先取消焦点。`;return{name:`focus`,beforeAgent:()=>t.length?{focuses:[...t],focus:t[0]}:{},augmentPrompt:()=>{if(!t.length)return;let n=[`## 当前精修目标`,t.map(e=>`· ${e.path}${e.label?`(${e.label})`:``}`).join(`
53
53
  `),`仅操作上述 ${t.length} 个聚焦子树${t.length>1?`之一`:``},用户未指明目标的指令默认作用于聚焦组件(「增加/修改/删除 X」类指令优先理解为对聚焦组件本身的改动 —— 如为其加页签/子项,写焦点路径的子路径;仅用户明确要求新建独立组件时才需解除焦点);不要改动其他组件;${a}`,`read 不带路径时默认只返回聚焦子树;需要全量主数据时显式列顶层键(read({jsonPaths:[...]}) )`],r=e.getSchema();if(r){let e=t.map(e=>{let t=xf(r,e.path);return t?ep(t):null}).filter(e=>!!e);e.length&&n.push(``,`## 焦点子树结构(仅此范围可操作)`,...e)}return n.join(`
54
54
  `)},wrapToolCall:async(n,r)=>{if(t.length){let i=t.map(e=>e.label?`${e.path}(${e.label})`:e.path).join(`, `),a=t.length===1?`${t[0].path}.props.xxx`:void 0,s=e=>({content:`PATH_DENIED · 聚焦越界:当前聚焦 [${i}],不可操作「${e}」。${o(a)}`,status:`error`});if(n.name===`eval_script`){if(n.args?.mode!==`transform`)return r(n);let i=Rp(n.args);if(!i.length)return s(`(整体数据)`);for(let n of i)if(!t.some(e=>zp(n,e.path))&&!Bp(n,e.getBind?.()))return s(n);return r(n)}if(Lp.has(n.name)){let r=Rp(n.args);if(!r.length)return s(`(整体数据)`);for(let n of r)if(!t.some(e=>zp(n,e.path))&&!Bp(n,e.getBind?.()))return s(n)}if(n.name===`read`){n.callConfig={...n.callConfig??{},__pgFullTextPaths:t.map(e=>e.path)};let e=n.args;if(!e?.jsonPath&&!e?.jsonPaths){let i=t.map(e=>e.path),a=await r({...n,args:{...e,jsonPaths:i}}),o=`【聚焦模式】read 未带路径 → 默认返回聚焦子树(${i.join(`, `)});需要全量主数据时显式列顶层键,如 read({jsonPaths:['<顶层键1>','<顶层键2>']})\n`;return{...a,content:o+a.content}}}}return r(n)},setFocus:e=>{t=e?[e]:[],n()},getFocus:()=>t[0],getFocuses:()=>[...t],addFocus:e=>{let r=t.findIndex(t=>t.path===e.path);r>=0?t[r]=e:t.push(e),n()},removeFocus:e=>{t=t.filter(t=>t.path!==e),n()},clearFocus:()=>{t=[],n()},reset:()=>{t=[],n()}}}function Hp(e){return e}var Up=/^https?:\/\//i;function Wp(e){return Up.test(e)||e.startsWith(`//`)?`http`:`vfs`}function Gp(e){return e.replace(/^vfs:\/\//,``).replace(/^\/+/,``).replace(/\/+/g,`/`)}var Kp=3e4;async function qp(e){let t=new AbortController,n=setTimeout(()=>t.abort(),Kp);try{return await fetch(e,{signal:t.signal})}finally{clearTimeout(n)}}async function Jp(e,t){if(Wp(e)===`http`)try{let t=await qp(e);return t.ok?{ok:!0,content:await t.text()}:{ok:!1,error:`HTTP ${t.status} ${t.statusText}(${e})`}}catch(t){if(t?.name===`AbortError`)return{ok:!1,error:`读取超时(${Kp/1e3}s):${e}`};let n=t?.message||String(t);return/Failed to fetch|NetworkError|CORS|blocked/i.test(n)?{ok:!1,error:`CORS 跨域或网络错误(${n});浏览器仅能 GET 同源或已配 CORS 的资源`}:{ok:!1,error:n}}if(!t)return{ok:!1,error:`skill 文档 ${e} 是 vfs 路径,但 vfs 未启用`};let n=t(Gp(e));return n==null?{ok:!1,error:`未找到 vfs 文档 ${e}(可用 vfs_ls 查看)`}:{ok:!0,content:n}}function Yp(e){if(e.length)return[`## 可用 Skills(渐进式披露)`,e.map(e=>`- ${e.name}: ${e.description}`).join(`
55
55
  `),`当某 skill 适用时,先调用 load_skill(name) 加载其完整指令,再按指令执行。不要凭记忆猜测 skill 内容。`].join(`
@@ -91,11 +91,11 @@ self.onmessage = async (e) => {
91
91
  `)}`:`虚拟工作区为空。`},{name:`vfs_ls`,description:`列出虚拟工作区所有文件。`,schema:t.z.object({})}),(0,r.tool)(async({pattern:t})=>{let n;try{n=ng(t)}catch(e){return $({code:`GLOB_INVALID`,message:`glob 模式无效: ${e.message}`,hint:`* 匹配非斜杠,** 匹配任意;避免未闭合的字符类`,details:{pattern:t}})}let r=Object.keys(e.files).filter(e=>n.test(e));return r.length?`匹配 ${t}:\n${r.map(e=>`- ${e}`).join(`
92
92
  `)}`:`无匹配 ${t} 的文件。`},{name:`vfs_glob`,description:`按 glob 模式匹配虚拟工作区文件名(* 匹配非斜杠,** 匹配任意)。`,schema:t.z.object({pattern:t.z.string().describe(`glob 模式,如 "**/*.md"`)})}),(0,r.tool)(async({pattern:t,path:n})=>{let r;try{r=new RegExp(t)}catch(e){return $({code:`REGEX_INVALID`,path:n,message:`正则表达式无效: ${e.message}`,hint:`检查括号/量词是否闭合;若想搜普通字符串可先转义特殊字符`,details:{pattern:t}})}let i=n?[tg(n)]:Object.keys(e.files),a=[];for(let t of i){let n=e.files[t];n&&n.content.split(`
93
93
  `).forEach((e,n)=>{r.test(e)&&a.push(`${t}:${n+1}: ${e}`)})}return a.length?`找到 ${a.length} 处:\n${a.slice(0,50).join(`
94
- `)}`:`未找到匹配 /${t}/ 的内容。`},{name:`vfs_grep`,description:`在虚拟工作区文件内容中正则搜索。`,schema:t.z.object({pattern:t.z.string().describe(`正则表达式`),path:t.z.string().optional().describe(`限定单个文件,不传则搜索全部`)})}),(0,r.tool)(async({path:t,jsonPath:n})=>{let r=tg(t),i=e.files[r];if(!i)return $({code:`NOT_FOUND`,path:t,message:`未找到文件 "${t}"`,hint:`用 vfs_ls 查看虚拟工作区文件列表`});let a;try{a=JSON.parse(i.content)}catch(e){return $({code:`VFS_JSON_INVALID`,path:t,message:`文件内容非合法 JSON: ${e.message}`,hint:`vfs_json_read 要求文件内容是合法 JSON;先 vfs_read 查看实际内容,或 vfs_write({jsonString:true}) 重写为合法 JSON`})}if(n){let e=_p(a,n);return e===void 0?$({code:`VFS_PATH_NOT_FOUND`,path:t,message:`jsonPath "${n}" 不存在`,hint:`不传 jsonPath 整体读查看结构,或核对路径段`}):`${t}#${n} (JSON):\n${JSON.stringify(e)}`}return`${t} (JSON):\n${JSON.stringify(a)}`},{name:`vfs_json_read`,description:`把虚拟工作区文件当 JSON 读取:先 parse 整文件,再按 jsonPath 取子树(省略返整体)。文件非合法 JSON 报 VFS_JSON_INVALID。适合结构化读取 vfs 内大 JSON。`,schema:t.z.object({path:t.z.string().describe(`文件路径(内容须为合法 JSON)`),jsonPath:t.z.string().optional().describe(`点分隔子路径(如 components.0.title);省略读整体`)})}),(0,r.tool)(async({path:t,patches:n})=>{let r=tg(t),i=e.files[r];if(!i)return $({code:`NOT_FOUND`,path:t,message:`未找到文件 "${t}"`,hint:`用 vfs_ls 查看虚拟工作区文件列表`});let a;try{a=JSON.parse(i.content)}catch(e){return $({code:`VFS_JSON_INVALID`,path:t,message:`文件内容非合法 JSON: ${e.message}`,hint:`vfs_json_patch 要求文件内容是合法 JSON`})}let o=bp(a),s=[];for(let e of n){let n=kp(o,e.op,e.jsonPath,e.value);if(n)return $({code:`PATCH_FAILED`,path:t,message:n,hint:`修正 patches 后重试(原文件未改动)`,details:{failedPatch:e}});s.push(e.jsonPath||`(根)`)}let c=JSON.stringify(o);return e.files[r]={content:c,updatedAt:rg()},`已对 ${t} 应用 ${n.length} 个 patch(影响 ${s.length} 处:${s.join(`, `)}),文件现 ${c.length} 字符`},{name:`vfs_json_patch`,description:`在虚拟工作区 JSON 文件内做原子 jsonPath patch(set/remove/merge/append)。先 parse → clone 上应用全部 patches → 任一失败或 JSON 非法则整体不写回(原文件不变)。`,schema:t.z.object({path:t.z.string().describe(`文件路径(内容须为合法 JSON)`),patches:t.z.array(t.z.object({op:t.z.enum([`set`,`remove`,`merge`,`append`]).describe(`操作`),jsonPath:t.z.string().describe(`点分隔路径(如 components.0.title);merge/append 目标可为根(空串)`),value:t.z.any().optional().describe(`set/merge/append 的值(remove 不需要)`)})).describe(`按顺序应用的 patch 列表(原子:任一失败整体不写回)`)})}),(0,r.tool)(async({path:t})=>{let n=tg(t);return e.files[n]?(delete e.files[n],`已删除 ${t}`):$({code:`NOT_FOUND`,path:t,message:`未找到文件 "${t}",无需删除`,hint:`用 vfs_ls 查看虚拟工作区文件列表`})},{name:`vfs_rm`,description:`删除虚拟工作区文件(清理中间产物 / drafts 下草稿,补「只进不出」的闭环)。不存在返回 NOT_FOUND。`,schema:t.z.object({path:t.z.string().describe(`要删除的文件路径`)})})]}function og(e){return{name:`vfs`,tools:ag(e),beforeAgent:()=>({files:e.files})}}var sg=`⟦frozen:`,cg=`⟦res:`,lg=`⟧`;function ug(e){return`${sg}${e}${lg}`}function dg(e){return`${cg}${e}${lg}`}function fg(e){return typeof e==`string`?e.startsWith(sg)&&e.endsWith(lg)?{type:`frozen`,path:e.slice(8,e.length-1)}:e.startsWith(cg)&&e.endsWith(lg)?{type:`res`,handle:e.slice(5,e.length-1)}:null:null}function pg(e){return String(e??``).trim().replace(/^\.+/,``)}function mg(e){let t=5381;for(let n=0;n<e.length;n++)t=(t*33^e.charCodeAt(n))>>>0;return(t>>>0).toString(16).padStart(8,`0`).slice(0,8)}function hg(e,t){return e===t?!0:e&&t&&typeof e==`object`&&typeof t==`object`?JSON.stringify(e)===JSON.stringify(t):!1}function gg(e,t){let n=pg(e);if(!n)return;let r=t.get(n);if(r)return{spec:r,relation:`exact`,protectedPath:n};let i;for(let[e,r]of t)n!==e&&(n.startsWith(e+`.`)?(!i||e.length>i.protectedPath.length)&&(i={spec:r,protectedPath:e,relation:`descendant`}):e.startsWith(n+`.`)&&(!i||e.length<i.protectedPath.length)&&(i={spec:r,protectedPath:e,relation:`ancestor`}));return i}var _g=class{vfs;constructor(e){this.vfs=e}key(e){return`resources/${e}.json`}ensure(e,t,n){let r=mg(e),i={path:e,mode:n,value:t,handle:r};return this.vfs.files[this.key(r)]={content:JSON.stringify(i),updatedAt:Date.now()},r}get(e){return this.readEntry(this.key(e))||this.readEntry(this.key(mg(e)))}readEntry(e){let t=this.vfs.files[e];if(t)try{let e=JSON.parse(t.content);return e&&typeof e.path==`string`?e:void 0}catch{return}}update(e,t){let n=this.get(e);this.ensure(e,t,n?.mode??`verbatim`)}delete(e){let t=this.get(e)?.handle??mg(e),n=this.key(t),r=!!this.vfs.files[n];return r&&delete this.vfs.files[n],r}list(){let e=[];for(let[t,n]of Object.entries(this.vfs.files))if(t.startsWith(`resources/`))try{let t=JSON.parse(n.content);t&&typeof t.path==`string`&&e.push({path:t.path,mode:t.mode,handle:t.handle,bytes:n.content.length})}catch{}return e}clear(){for(let e of Object.keys(this.vfs.files))e.startsWith(`resources/`)&&delete this.vfs.files[e]}};function vg(e){let{jp:t,resolved:n,resourcesByPath:r,resourceStore:i}=e;if(!r.size)return n;let a=!1;for(let e of r.keys())if(t===``||e===t||e.startsWith(t+`.`)){a=!0;break}if(!a)return n;let o=bp(n);for(let[e,n]of r){if(t!==``&&e!==t&&!e.startsWith(t+`.`))continue;if(e===t){if(o===void 0)continue;return n.mode===`freeze`?ug(e):i?dg(i.ensure(e,o,`verbatim`)):o}let r=t===``?e:e.slice(t.length+1),a=_p(o,r);a!==void 0&&(n.mode===`freeze`?vp(o,r,ug(e)):i&&vp(o,r,dg(i.ensure(e,a,`verbatim`))))}return o}function yg(e,t,n,r){if(!r)return{code:`RESOURCE_NOT_FOUND`,message:`句柄 "${e}" 无法展开(资源池未启用)`,hint:`verbatim 保护需启用 vfs(capabilities.vfs 默认开);集成方经 createChatSdk 配 data.resources 时自动提供 vfsStore`};let i=r.get(e);return i?n===void 0?{code:`RESOURCE_NOT_FOUND`,message:`字段 "${t}" 在 bind 中已不存在,无法展开句柄 "${e}"`,hint:`该字段可能已被删除或 restore 到不含此字段的快照;重新 read 确认当前结构`}:hg(i.value,n)?{value:i.value}:(r.update(t,n),{value:n}):n===void 0?{code:`RESOURCE_NOT_FOUND`,message:`句柄 "${e}" 不存在(字段 "${t}" 可能未注册或已被删除)`,hint:`重新 read 该字段触发懒注册`}:{code:`RESOURCE_EVICTED`,message:`字段 "${t}" 的 verbatim 资源已被淘汰(资源池 LRU)`,hint:`重新 read 该字段触发懒注册重建句柄,再写回新句柄 ⟦res:<handle>⟧`}}function bg(e,t){let n=t.getBind();for(let[r,i]of t.resourcesByPath){let a=_p(n,r),o=_p(e,r);if(o===void 0){a!==void 0&&vp(e,r,a);continue}if(i.mode===`freeze`){if(o===ug(r)){vp(e,r,a);continue}if(!hg(o,a))return{ok:!1,code:`FROZEN_FIELD`,path:r,message:`字段 "${r}" 已冻结(freeze 保护),不可修改`,hint:`该字段由系统/集成方维护,LLM 不得改动。如需展示其值用 resource_get({path}) 取真值`}}else{let n=fg(o);if(n&&n.type===`res`){let i=yg(n.handle,r,a,t.resourceStore);if(`value`in i){vp(e,r,i.value);continue}return{ok:!1,code:i.code,path:r,message:i.message,hint:i.hint}}if(!hg(o,a))return{ok:!1,code:`VERBATIM_MISMATCH`,path:r,message:`字段 "${r}" 为 verbatim 保护(精确原样保留),写入值与原值不符`,hint:`要改该值请先 resource_update({path, value}) 更新资源池,再写回句柄 ⟦res:<handle>⟧;或写回原值(经 resource_get 取到的值)保持不变`}}}return{ok:!0}}function xg(e,t,n){let r=t===void 0?e.message:`patches[${t}]${n?` @ "${n}"`:``}: ${e.message}`;return $({code:e.code,path:e.path,message:r,hint:e.hint,...t===void 0?{}:{details:{patchIndex:t,patchJsonPath:n??null}}})}function Sg(e){let{value:t,ctx:n}=e;if(!n||!n.resourcesByPath.size)return{ok:!0,value:t};let r=bp(t),i=bg(r,n);return i.ok?{ok:!0,value:r}:{ok:!1,error:xg(i)}}function Cg(e){let{patches:t,clone:n,ctx:r}=e;if(!r||!r.resourcesByPath.size)return{ok:!0};for(let e=0;e<t.length;e++){let n=t[e];if(n.op===`remove`){let t=gg(n.jsonPath||``,r.resourcesByPath);if(t){let r=t.spec.mode===`freeze`?`FROZEN_FIELD`:`VERBATIM_PROTECTED`,i=t.spec.mode===`freeze`?`冻结字段不可删。如需移除请联系集成方调整 data.resources 配置`:`verbatim 字段不可直接删;先 resource_delete({path}) 释放资源保护后再删`;return{ok:!1,error:$({code:r,path:t.protectedPath,message:`patches[${e}] @ "${n.jsonPath}" 命中受保护字段 "${t.protectedPath}"(${t.spec.mode}),不可删除`,hint:i,details:{patchIndex:e,patchJsonPath:n.jsonPath??``}})}}}}let i=bg(n,r);if(!i.ok){let e=wg(i.path,t);return{ok:!1,error:xg(i,e>=0?e:void 0,e>=0?t[e].jsonPath:void 0)}}return{ok:!0}}function wg(e,t){let n=pg(e);for(let e=0;e<t.length;e++){let r=pg(t[e].jsonPath||``);if(r&&(r===n||n.startsWith(r+`.`)||r.startsWith(n+`.`)))return e}return-1}function Tg(e,t){if(!e)return null;let n=(t?xf(e,t):e)?.shape;return n&&typeof n==`object`?Object.keys(n):null}var Eg=e=>e&&e.length?`(可用字段:${e.slice(0,12).join(`, `)}${e.length>12?` …`:``})`:``,Dg=e=>/[.[]/.test(e)?e.replace(/[.[][^.[]*$/,``):``;function Og(e){let{schema:t,allowKeys:n,value:r,bindRef:i}=e,a=[];if(n){if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,error:Rl(``,[{path:[],code:`invalid_type`,message:`整体 set 需为 JSON 对象(当前为 ${Array.isArray(r)?`array`:r===null?`null`:typeof r})`,expected:`object`}]),notices:a};let e=i&&typeof i==`object`&&!Array.isArray(i)?i:{},n=r,o={};for(let r of Object.keys(n)){if(r.startsWith(`__pg`))continue;let i=n[r],s=Tf(t,r,i);if(!s.ok){if(s.resolution===`missing`){if(r in e)continue;return{ok:!1,error:$({code:`SCHEMA_STRIP`,message:`字段 ${r} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试${Eg(Tg(t,``))}`,path:r,details:{stripped:[r]}}),notices:a}}return{ok:!1,error:Rl(r,s.issues??[]),notices:a}}s.resolution===`open`&&a.push(`${r}=开放节点放行`);let c=Fp(e[r],i,s.data,r);if(c.length)return{ok:!1,error:$({code:`SCHEMA_STRIP`,message:`字段 ${c.join(`, `)} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试${Eg(Tg(t,Dg(String(c[0]))))}`,path:c[0],details:{stripped:c}}),notices:a};o[r]=s.data}return Ef(t)&&a.push(`根级 refine/superRefine 不再在 write 时执行(走 capabilities.verify)`),{ok:!0,assembly:o,wholeParsed:null,notices:a}}let o=t.safeParse(r);if(!o.success)return{ok:!1,error:Rl(``,o.error.issues),notices:a};let s=Fp(i,r,o.data);return s.length?{ok:!1,error:$({code:`SCHEMA_STRIP`,message:`字段 ${s.join(`, `)} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试`,path:s[0],details:{stripped:s}}),notices:a}:{ok:!0,assembly:o.data,wholeParsed:o.data,notices:a}}function kg(e){let{schema:t,bindRef:n,clone:r,patches:i,schemaErrorMode:a=`zod`,appendCaptures:o,moveCaptures:s}=e,c=[],l=t=>{let n=_p(r,t);return n===void 0?e.valueAt?.(t):n},u=(e,t)=>a===`schema_invalid`?$({code:`SCHEMA_INVALID`,message:`patches 应用后局部校验失败 @ "${e}",未写入`,hint:`确认该路径的值符合 schema;兄弟节点的既有数据不影响本次写入`,details:Ll(t)}):Rl(e,t),d=e=>$({code:`SCHEMA_STRIP`,message:`字段 ${e.join(`, `)} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试`,path:e[0],details:{stripped:e}}),f=[];Ef(t)&&c.push(`根级 refine/superRefine 不再在 write 时执行(走 capabilities.verify)`);let p=0,m=0;for(let e of i){let i=e.op??`set`,a=e.jsonPath||``;if(i===`remove`){let e=a.lastIndexOf(`.`);if(e>0&&/^\d+$/.test(a.slice(e+1))){let n=a.slice(0,e),i=wf(t,n);if(i.kind===`schemas`){let e=_p(r,n);if(Array.isArray(e))for(let t of i.schemas){let r=Df(t);if(r!==null&&e.length<r)return{ok:!1,error:u(n,[{path:[n],code:`too_small`,message:`删除后数组长度 ${e.length} 低于 schema 最小约束 ${r}`,expected:`>=${r}`}]),writeBacks:[],notices:c}}}}f.push({op:`remove`,jp:a});continue}if(i===`move`){let n=s[m++];if(n&&n.elem!==void 0){let e=n.toPath.lastIndexOf(`.`),r=e>0&&/^\d+$/.test(n.toPath.slice(e+1))?n.toPath.slice(0,e):n.toPath,i=wf(t,r);if(i.kind===`schemas`){let e=Of(i.schemas);if(e.length){let t=[],r=!1;for(let i of e){let e=i.safeParse(n.elem);if(e.success){r=!0;break}t.push(...e.error?.issues??[])}if(!r)return{ok:!1,error:u(n.toPath,t),writeBacks:[],notices:c}}}else i.kind===`open`&&c.push(`${r}=开放节点放行`)}f.push({op:`move`,jp:a,toPath:String(e.value)});continue}if(i===`append`){let e=o[p++]?.elems??[];if(!e.length){f.push({op:`appendElems`,jp:a,elems:[]});continue}let n=wf(t,a);if(n.kind===`missing`)return{ok:!1,error:d([a||`(根)`]),writeBacks:[],notices:c};if(n.kind===`open`){c.push(`${a||`(根)`}=开放节点放行`),f.push({op:`appendElems`,jp:a,elems:e});continue}let r=Of(n.schemas);if(!r.length){c.push(`${a||`(根)`}:目标非 schema 声明数组,元素未校验放行`),f.push({op:`appendElems`,jp:a,elems:e});continue}let i=[];for(let t=0;t<e.length;t++){let n=[],o,s=!1;for(let i of r){let r=i.safeParse(e[t]);if(r.success){s=!0,o=r.data;break}n.push(...r.error?.issues??[])}if(!s)return{ok:!1,error:u(`${a||`(根)`}[新增元素${t}]`,n),writeBacks:[],notices:c};let l=Fp(void 0,e[t],o,a?`${a}.${t}`:String(t));if(l.length)return{ok:!1,error:d(l),writeBacks:[],notices:c};i.push(o)}f.push({op:`appendElems`,jp:a,elems:i});continue}if(i===`merge`){let r=e.value;if(typeof r==`string`){let e=Sp(r);if(e.parseError)return{ok:!1,error:zl(`patches merge`,r,e.parseError),writeBacks:[],notices:c};r=e.parsed}if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,error:$({code:`PATCH_FAILED`,message:`merge 的 value 需为对象`,hint:`merge 合并对象键;整体替换用 set`}),writeBacks:[],notices:c};let i=[];for(let e of Object.keys(r)){if(e.startsWith(`__pg`)||mp.has(e))continue;let r=a?`${a}.${e}`:e,o=l(r),s=Tf(t,r,o);if(!s.ok){if(s.resolution===`missing`){if(_p(n,r)===void 0)return{ok:!1,error:d([r]),writeBacks:[],notices:c};i.push([e,o]);continue}return{ok:!1,error:u(r,s.issues??[]),writeBacks:[],notices:c}}s.resolution===`open`&&c.push(`${r}=开放节点放行`);let f=Fp(_p(n,r),o,s.data,r);if(f.length)return{ok:!1,error:d(f),writeBacks:[],notices:c};i.push([e,s.data])}f.push({op:`mergeKeys`,jp:a,entries:i});continue}let h=l(a),g=a.lastIndexOf(`.`);if(g>0&&/^\d+$/.test(a.slice(g+1))){let e=_p(r,a.slice(0,g));if(Array.isArray(e)){for(let t=0;t<e.length;t++)if(!(t in e))return{ok:!1,error:$({code:`PATCH_FAILED`,message:`set @ "${a}" 越界数组索引产生稀疏空洞(父数组长度 ${e.length})`,hint:`数组索引须连续(≤ 当前长度);追加请用 op:"append"`}),writeBacks:[],notices:c}}}let _=Tf(t,a,h);if(!_.ok){if(_.resolution===`missing`){if(_p(n,a)===void 0)return{ok:!1,error:d([a]),writeBacks:[],notices:c};f.push({op:`set`,jp:a,value:h});continue}return{ok:!1,error:u(a,_.issues??[]),writeBacks:[],notices:c}}_.resolution===`open`&&c.push(`${a||`(根)`}=开放节点放行`);let v=Fp(_p(n,a),h,_.data,a);if(v.length)return{ok:!1,error:d(v),writeBacks:[],notices:c};f.push({op:`set`,jp:a,value:_.data})}return{ok:!0,writeBacks:f,notices:c}}function Ag(e){let{bindRef:t,schema:n,allowKeys:r,snapshots:i,maxSnapshots:a,audit:o,dryRun:s,op:c=`set`,protectedCtx:l,snapshotLabel:u}=e,d=e.value,f=e.internalAfterWrite?bp(t):null,p=Mg(d);if(p)return{ok:!1,error:Ng(p)};if(l){let e=Sg({value:d,ctx:l});if(!e.ok)return{ok:!1,error:e.error};d=e.value}let m=Og({schema:n,allowKeys:r,value:d,bindRef:t});if(!m.ok)return{ok:!1,error:m.error};let h=m.assembly;if(s)return{ok:!0,hash:``,data:h,notices:m.notices};if(typeof t!=`object`||!t)return{ok:!1,error:$({code:`LEAF_BIND`,message:`主数据 bind 为原始类型(${t===null?`null`:typeof t}),无法就地替换外部持有的值引用`,hint:`主数据 bind 必须为对象/数组;叶子值请用对象包裹(如 {value:"x"})或集成方通过 sdk.setData 替换 bind`})};let g=bp(t),_=i.length?i[i.length-1].id+1:1;for(i.push({id:_,ts:Date.now(),op:c,value:g,...u?{label:u}:{}});i.length>a;)i.shift();return typeof h==`object`&&h&&(m.wholeParsed?Pp(t,h):gp(t,h)),o({op:c,value:h,timestamp:Date.now()}),e.onWrite?.(),e.internalAfterWrite?.(t,f),{ok:!0,hash:e.hashFn?e.hashFn():Dp(t),data:h,notices:m.notices}}function jg(e){let{bindRef:t,patches:n,schema:r,allowKeys:i,snapshots:a,maxSnapshots:o,markDataDirty:s,schemaErrorMode:c=`zod`,snapshotLabel:l,dryRun:u,protectedCtx:d}=e,f=e.internalAfterWrite?bp(t):null,p=bp(t),m=[],h=[],g=[],_=[],v=(e,t)=>{(e===`set`||e===`merge`)&&_.push({jp:t,val:_p(p,t)})};for(let e=0;e<n.length;e++){let t=n[e],a=t.jsonPath||``;if(hp(a))return{ok:!1,error:$({code:`PATH_UNSAFE`,message:`patches[${e}] jsonPath "${a}" 含非法段`,hint:`使用正常属性路径,如 components.0.text`})};if(!yf(a,r,i))return{ok:!1,error:$({code:`PATH_DENIED`,message:`patches[${e}] @ "${a}" 不在 schema 声明字段内`,hint:`仅 schema 声明的 key 可写${Eg(Tg(r,Dg(a)))}`})};let o=t.op??`set`,s;if(o!==`remove`){if(t.value===void 0||t.value===``&&o===`move`)return{ok:!1,error:$({code:`MISSING_VALUE`,message:`patches[${e}] ${o} 操作需要 value`,hint:`op 为 ${o} 时 value 必填;删除请用 op:'remove'`})};let n=Sp(t.value);if(n.parseError)return{ok:!1,error:zl(`patches[${e}]`,t.value,n.parseError)};if(s=n.parsed,o!==`move`){let t=Mg(s);if(t)return{ok:!1,error:Ng(t,`patches[${e}] @ "${a}"`)}}if(o===`move`&&typeof s==`string`&&!yf(s,r,i))return{ok:!1,error:$({code:`PATH_DENIED`,message:`patches[${e}] move 目标 "${s}" 不在 schema 声明字段内`,hint:`move 的 value(目标路径)也须在 schema 声明字段内${Eg(Tg(r,Dg(String(s))))}`})}}o===`append`&&h.push({jp:a,elems:Array.isArray(s)?[...s]:[s]}),o===`move`&&g.push({jp:a,toPath:String(s),elem:_p(p,a)});let c=kp(p,o,a,s);if(c)return{ok:!1,error:$({code:`PATCH_FAILED`,message:`patches[${e}]: ${c}`,hint:`检查 op 与目标类型:merge 需对象,append 需数组`})};v(o,a),m.push({op:o,jp:a,value:s})}if(d){let e=Cg({patches:n,clone:p,ctx:d});if(!e.ok)return{ok:!1,error:e.error}}let y=kg({schema:r,bindRef:t,clone:p,patches:n,schemaErrorMode:c,appendCaptures:h,moveCaptures:g,valueAt:e=>_.find(t=>t.jp===e)?.val});if(!y.ok)return{ok:!1,error:y.error};if(u)return{ok:!0,applied:m,clone:p,notices:y.notices};let b=a.length?a[a.length-1].id+1:1;for(a.push({id:b,ts:Date.now(),op:`edit`,value:f??bp(t),...l?{label:l}:{}});a.length>o;)a.shift();for(let e of y.writeBacks)if(e.op===`remove`)yp(t,e.jp);else if(e.op===`set`)vp(t,e.jp,e.value);else if(e.op===`move`)jp(t,e.jp,e.toPath);else if(e.op===`mergeKeys`){let n=e.jp?_p(t,e.jp):t;if(n&&typeof n==`object`&&!Array.isArray(n))for(let[t,r]of e.entries??[])n[t]=r}else if(e.op===`appendElems`){let n=e.jp?_p(t,e.jp):t;Array.isArray(n)&&e.elems?.length&&n.push(...e.elems)}return e.internalAfterWrite?.(t,f),s?.(),{ok:!0,applied:m,clone:p,notices:y.notices}}function Mg(e){let t=/^<[A-Za-z_][\w.-]*\s[\d.]+[KMG]?B>$/,n=e=>{if(typeof e==`string`)return e.includes(`<subtree `)||t.test(e)?e.slice(0,60):null;if(Array.isArray(e)){for(let t of e){let e=n(t);if(e)return e}return null}if(e&&typeof e==`object`)for(let t of Object.values(e)){let e=n(t);if(e)return e}return null};return n(e)}var Ng=(e,t)=>$({code:`PLACEHOLDER_LEAK`,path:t||void 0,message:`写入值包含摘要占位符 "${e}"(read/query 为省上下文返回的体积占位,非真实数据),已拒绝写入`,hint:`占位符子树的真实内容需先窄读获取:read({jsonPath:"<该子树路径>"}) 结果根豁免返回全文;聚焦该区域可用 set_focus。基于真实值重新构造写入内容`});function Pg(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}var Fg=3072;function Ig(e){return typeof e==`string`?e.length+2:typeof e==`number`||typeof e==`boolean`?8:4}function Lg(e,t,n,r,i){if(!t||e==null)return e;let a=new Set(n.map(e=>e.field)),o=r,s=Fg,c=i?.rootExempt??!1,l=i?.rootPath??``,u=i?.fullTextPrefixes??[],d=bp(e),f=i?.onSummarized,p=e=>u.some(t=>t&&(e===t||e.startsWith(t+`.`)||e.startsWith(t+`[`))),m=(e,t)=>{let n=`#`+String(Dp(e)).slice(0,8);if(Array.isArray(e))return`<subtree ${Pg(t)} children:${e.length} ${n}>`;let r=Object.keys(e),i=r.slice(0,6).join(`,`)+(r.length>6?`,…`:``);return`<subtree ${Pg(t)} keys:[${i}] ${n}>`},h=(e,t,n)=>{if(typeof e!=`object`||!e)return{node:e,eff:Ig(e)};if(p(t))return{node:e,eff:40};if(Array.isArray(e)){let r=2;for(let n=0;n<e.length;n++){let i=h(e[n],`${t}.${n}`,!1);e[n]=i.node,r+=i.eff}return!(n&&c)&&r>=s?(f?.(t),{node:m(e,r),eff:40}):{node:e,eff:r}}let r=2;for(let n of Object.keys(e)){let i=e[n],s=t?`${t}.${n}`:n;if(typeof i==`string`&&a.has(n)&&i.length>=o&&!p(s))e[n]=`<${n} ${Pg(i.length)}>`,f?.(s),r+=e[n].length+n.length+2;else{let t=h(i,s,!1);e[n]=t.node,r+=t.eff+n.length+2}}return!(n&&c)&&r>=s?(f?.(t),{node:m(e,r),eff:40}):{node:e,eff:r}};return h(d,l,!0).node}var Rg=0;function zg(){return Rg++,`c_`+Math.random().toString(36).slice(2,8)+Rg.toString(36)}function Bg(e,t){if(!(!e||typeof e!=`object`))for(let n of t){let t=_p(e,n);if(Array.isArray(t))for(let e of t)e&&typeof e==`object`&&!(`__pgId`in e)&&(e.__pgId=zg())}}function Vg(e){(function e(t){if(Array.isArray(t))t.forEach(e);else if(t&&typeof t==`object`)for(let n of Object.keys(t))n.startsWith(`__pg`)?delete t[n]:e(t[n])})(e)}function Hg(e,n={}){let i=n.pgIdPaths??[],a=i.length?(e,t)=>{if(t&&typeof t==`object`)for(let n of i){let r=_p(t,n),i=_p(e,n);if(!Array.isArray(r)||!Array.isArray(i))continue;let a=e=>{if(!e||typeof e!=`object`)return e;let t={...e};return delete t.__pgId,t},o=new Set;for(let e=0;e<i.length;e++){let t=i[e];if(!(!t||typeof t!=`object`||`__pgId`in t))for(let e=0;e<r.length;e++){if(o.has(e))continue;let n=r[e];if(!(!n||typeof n!=`object`||!n.__pgId)&&hg(a(n),a(t))){t.__pgId=n.__pgId,o.add(e);break}}}for(let e=0;e<r.length&&e<i.length;e++){if(o.has(e))continue;let t=r[e]?.__pgId,n=i[e];t&&n&&typeof n==`object`&&!(`__pgId`in n)&&(n.__pgId=t,o.add(e))}}Bg(e,i)}:void 0,o=i.length?Kf(e.schema,i).schema:e.schema,s=e.bind,c=e.description??`主数据对象`,l=vf(o),u=new Map,d=n.vfsStore?new _g(n.vfsStore):void 0;function f(e){if(u.clear(),e)for(let t of e){let e=pg(t.path);u.set(e,{path:e,mode:t.mode})}}f(e.resources);let p=u.size?{resourcesByPath:u,resourceStore:d,getBind:()=>s}:void 0,m=[],h=n.maxSnapshots??20,g=new Map,_=``,v=e=>e?.configurable?.__pgDataScope??_,y=e=>{let t=e?.configurable?.__pgFullTextPaths;return Array.isArray(t)?t.map(String):void 0},b=new Set,x=e=>{for(b.add(e);b.size>500;)b.delete(b.values().next().value)},S=e=>g.get(e??_),C=(e,t)=>{let n=t??_;e===void 0?g.delete(n):g.set(n,e)},w=n.conflictWatchFields??[],T=!w.includes(`*`)&&w.length?new Set(w):void 0,E=w.length>0,D=()=>T?Op(s,T):Dp(s),ee=(n.maxParallelTools??1)>1&&E,O=!1,k=[];async function te(){if(!ee)return{release:()=>{},reacquire:async()=>{}};O?await new Promise(e=>k.push(e)):O=!0;let e=!0;return{release:()=>{if(!e)return;e=!1;let t=k.shift();t?t():O=!1},reacquire:async()=>{e||=(O?await new Promise(e=>k.push(e)):O=!0,!0)}}}(n.maxParallelTools??1)>1&&!E&&console.warn(`[page-agent-sdk] maxParallelTools>1 且未声明 conflictWatchFields:并发写不互锁(后写覆盖前写,既有明文语义);声明 conflictWatchFields 后自动启用写互锁与乐观锁校验`);let A=e=>{let t=D();return C(t,e),t},j=n.largeTextThreshold??200,M=(n.largeTextPaths??[]).map(e=>{let t=e.lastIndexOf(`.`);return t>0?{arrayPath:e.slice(0,t),field:e.slice(t+1)}:null}).filter(e=>e!==null),ne=!0;function N(){ne=!0}let P={get:()=>({schema:o,bind:s,description:c}),set:e=>{o=i.length?Kf(e.schema,i).schema:e.schema,s=e.bind,c=e.description??`主数据对象`,l=vf(o),m.length=0,g.clear(),f(e.resources),d?.clear(),N()},update:e=>{s=e,m.length=0,g.clear(),N()},markDataDirty:N,consumeDataDirty:()=>{let e=ne;return ne=!1,e},enterScope:e=>{let t=_;return _=e,()=>{_=t}},exitScope:e=>{g.delete(e)},recomputeBaseline:e=>{g.set(e??``,D())},recomputeAllBaselines:()=>{let e=D();for(let t of g.keys())g.set(t,e)},hasBaselines:()=>g.size>0,getSummarizedPaths:()=>[...b],clearSummarizedPaths:()=>b.clear(),getResourcesSnapshot:()=>{let e=[];for(let[t,n]of u)if(n.mode===`verbatim`){let r=d?.get(t);e.push(r?.handle?{path:t,mode:n.mode,handle:r.handle}:{path:t,mode:n.mode})}else e.push({path:t,mode:n.mode});return e},createResource:d?(e,t)=>{let n=pg(e),r=u.get(n),i=t===void 0?_p(s,n):t;return d.ensure(n,i,r?.mode??`verbatim`)}:void 0,getResource:d?e=>{let t=d.get(e);return t?{path:t.path,mode:t.mode,value:t.value,handle:t.handle}:void 0}:void 0,updateResource:d?(e,t)=>{let n=pg(e);d.update(n,t),vp(s,n,t),N(),C(D(),``)}:void 0,deleteResource:d?e=>d.delete(e):void 0,listResources:d?()=>d.list():void 0},F=e=>{n.onAudit?.(e)};function re(e,t){let n=bp(s),r=m.length?m[m.length-1].id+1:1;for(m.push({id:r,ts:Date.now(),op:e,label:t,value:n});m.length>h;)m.shift();return r}async function ie(e,t,r,i){if(!t||t===``)return null;let a=D();if(a===t)return null;if(!n.onConflict)return $({code:`VERSION_CONFLICT`,message:`乐观锁冲突:expectedHash=${t} 但当前 hash=${a}。主数据在你 read 之后已被修改(外部代码/其他 agent/用户手动改)。`,hint:`重新 read 拿最新值与 hash,基于最新值修改后再写入。当前值:${Tp(s,400)}`});i?.release();let o=await n.onConflict({op:e,agentValue:r,currentValue:s,currentHash:a,expectedHash:t,snapshotId:0});if(o.action===`keep_external`)return`已保留外部修改(未写入)。当前值:${Tp(s,400)} (hash=${a})。请重新 read 拿最新值与 hash 再改。`;if(o.action===`restore`){if(await i?.reacquire(),!m.length)return`无历史快照可回退(本次为首次操作)。当前值:${Tp(s,400)} (hash=${a})。请重新 read 再改或选「强制覆盖」。`;let e=m[m.length-1];return Np(s,bp(e.value)),N(),C(D()),`已回退主数据到历史快照 #${e.id}[${e.op}]。当前值:${Tp(s,400)} (hash=${D()})。请基于回退后的值重写或停止。`}await i?.reacquire();let c=D();return c===a?(C(D()),null):(F({op:`conflict_recheck`,detail:`裁决基于 ${a} 恢复时 ${c}(ask 窗口新修改落地,overwrite 被拦)`,timestamp:Date.now()}),$({code:`VERSION_CONFLICT`,message:`裁决恢复点校验失败:裁决基于 hash=${a},恢复时主数据已变为 hash=${c}(裁决等待期间又有新修改落地,裁决者未见过)。`,hint:`重新 read 拿最新值与 hash,基于最新值修改后再写入(单次校验,不再二次挂起)。`}))}let ae=(e,t=!0)=>{e.writeCapable=t},I=(0,r.tool)(async()=>[`说明: ${c}`,`格式: 写入值需为 JSON,且通过声明的 schema 校验(校验失败时 write 会返回结构化错误,含具体字段与期望类型)。`].join(`
94
+ `)}`:`未找到匹配 /${t}/ 的内容。`},{name:`vfs_grep`,description:`在虚拟工作区文件内容中正则搜索。`,schema:t.z.object({pattern:t.z.string().describe(`正则表达式`),path:t.z.string().optional().describe(`限定单个文件,不传则搜索全部`)})}),(0,r.tool)(async({path:t,jsonPath:n})=>{let r=tg(t),i=e.files[r];if(!i)return $({code:`NOT_FOUND`,path:t,message:`未找到文件 "${t}"`,hint:`用 vfs_ls 查看虚拟工作区文件列表`});let a;try{a=JSON.parse(i.content)}catch(e){return $({code:`VFS_JSON_INVALID`,path:t,message:`文件内容非合法 JSON: ${e.message}`,hint:`vfs_json_read 要求文件内容是合法 JSON;先 vfs_read 查看实际内容,或 vfs_write({jsonString:true}) 重写为合法 JSON`})}if(n){let e=_p(a,n);return e===void 0?$({code:`VFS_PATH_NOT_FOUND`,path:t,message:`jsonPath "${n}" 不存在`,hint:`不传 jsonPath 整体读查看结构,或核对路径段`}):`${t}#${n} (JSON):\n${JSON.stringify(e)}`}return`${t} (JSON):\n${JSON.stringify(a)}`},{name:`vfs_json_read`,description:`把虚拟工作区文件当 JSON 读取:先 parse 整文件,再按 jsonPath 取子树(省略返整体)。文件非合法 JSON 报 VFS_JSON_INVALID。适合结构化读取 vfs 内大 JSON。`,schema:t.z.object({path:t.z.string().describe(`文件路径(内容须为合法 JSON)`),jsonPath:t.z.string().optional().describe(`点分隔子路径(如 components.0.title);省略读整体`)})}),(0,r.tool)(async({path:t,patches:n})=>{let r=tg(t),i=e.files[r];if(!i)return $({code:`NOT_FOUND`,path:t,message:`未找到文件 "${t}"`,hint:`用 vfs_ls 查看虚拟工作区文件列表`});let a;try{a=JSON.parse(i.content)}catch(e){return $({code:`VFS_JSON_INVALID`,path:t,message:`文件内容非合法 JSON: ${e.message}`,hint:`vfs_json_patch 要求文件内容是合法 JSON`})}let o=bp(a),s=[];for(let e of n){let n=kp(o,e.op,e.jsonPath,e.value);if(n)return $({code:`PATCH_FAILED`,path:t,message:n,hint:`修正 patches 后重试(原文件未改动)`,details:{failedPatch:e}});s.push(e.jsonPath||`(根)`)}let c=JSON.stringify(o);return e.files[r]={content:c,updatedAt:rg()},`已对 ${t} 应用 ${n.length} 个 patch(影响 ${s.length} 处:${s.join(`, `)}),文件现 ${c.length} 字符`},{name:`vfs_json_patch`,description:`在虚拟工作区 JSON 文件内做原子 jsonPath patch(set/remove/merge/append)。先 parse → clone 上应用全部 patches → 任一失败或 JSON 非法则整体不写回(原文件不变)。`,schema:t.z.object({path:t.z.string().describe(`文件路径(内容须为合法 JSON)`),patches:t.z.array(t.z.object({op:t.z.enum([`set`,`remove`,`merge`,`append`]).describe(`操作`),jsonPath:t.z.string().describe(`点分隔路径(如 components.0.title);merge/append 目标可为根(空串)`),value:t.z.any().optional().describe(`set/merge/append 的值(remove 不需要)`)})).describe(`按顺序应用的 patch 列表(原子:任一失败整体不写回)`)})}),(0,r.tool)(async({path:t})=>{let n=tg(t);return e.files[n]?(delete e.files[n],`已删除 ${t}`):$({code:`NOT_FOUND`,path:t,message:`未找到文件 "${t}",无需删除`,hint:`用 vfs_ls 查看虚拟工作区文件列表`})},{name:`vfs_rm`,description:`删除虚拟工作区文件(清理中间产物 / drafts 下草稿,补「只进不出」的闭环)。不存在返回 NOT_FOUND。`,schema:t.z.object({path:t.z.string().describe(`要删除的文件路径`)})})]}function og(e){return{name:`vfs`,tools:ag(e),beforeAgent:()=>({files:e.files})}}var sg=`⟦frozen:`,cg=`⟦res:`,lg=`⟧`;function ug(e){return`${sg}${e}${lg}`}function dg(e){return`${cg}${e}${lg}`}function fg(e){return typeof e==`string`?e.startsWith(sg)&&e.endsWith(lg)?{type:`frozen`,path:e.slice(8,e.length-1)}:e.startsWith(cg)&&e.endsWith(lg)?{type:`res`,handle:e.slice(5,e.length-1)}:null:null}function pg(e){return String(e??``).trim().replace(/^\.+/,``)}function mg(e){let t=5381;for(let n=0;n<e.length;n++)t=(t*33^e.charCodeAt(n))>>>0;return(t>>>0).toString(16).padStart(8,`0`).slice(0,8)}function hg(e,t){return e===t?!0:e&&t&&typeof e==`object`&&typeof t==`object`?JSON.stringify(e)===JSON.stringify(t):!1}function gg(e,t){let n=pg(e);if(!n)return;let r=t.get(n);if(r)return{spec:r,relation:`exact`,protectedPath:n};let i;for(let[e,r]of t)n!==e&&(n.startsWith(e+`.`)?(!i||e.length>i.protectedPath.length)&&(i={spec:r,protectedPath:e,relation:`descendant`}):e.startsWith(n+`.`)&&(!i||e.length<i.protectedPath.length)&&(i={spec:r,protectedPath:e,relation:`ancestor`}));return i}var _g=class{vfs;constructor(e){this.vfs=e}key(e){return`resources/${e}.json`}ensure(e,t,n){let r=mg(e),i={path:e,mode:n,value:t,handle:r};return this.vfs.files[this.key(r)]={content:JSON.stringify(i),updatedAt:Date.now()},r}get(e){return this.readEntry(this.key(e))||this.readEntry(this.key(mg(e)))}readEntry(e){let t=this.vfs.files[e];if(t)try{let e=JSON.parse(t.content);return e&&typeof e.path==`string`?e:void 0}catch{return}}update(e,t){let n=this.get(e);this.ensure(e,t,n?.mode??`verbatim`)}delete(e){let t=this.get(e)?.handle??mg(e),n=this.key(t),r=!!this.vfs.files[n];return r&&delete this.vfs.files[n],r}list(){let e=[];for(let[t,n]of Object.entries(this.vfs.files))if(t.startsWith(`resources/`))try{let t=JSON.parse(n.content);t&&typeof t.path==`string`&&e.push({path:t.path,mode:t.mode,handle:t.handle,bytes:n.content.length})}catch{}return e}clear(){for(let e of Object.keys(this.vfs.files))e.startsWith(`resources/`)&&delete this.vfs.files[e]}};function vg(e){let{jp:t,resolved:n,resourcesByPath:r,resourceStore:i}=e;if(!r.size)return n;let a=!1;for(let e of r.keys())if(t===``||e===t||e.startsWith(t+`.`)){a=!0;break}if(!a)return n;let o=bp(n);for(let[e,n]of r){if(t!==``&&e!==t&&!e.startsWith(t+`.`))continue;if(e===t){if(o===void 0)continue;return n.mode===`freeze`?ug(e):i?dg(i.ensure(e,o,`verbatim`)):o}let r=t===``?e:e.slice(t.length+1),a=_p(o,r);a!==void 0&&(n.mode===`freeze`?vp(o,r,ug(e)):i&&vp(o,r,dg(i.ensure(e,a,`verbatim`))))}return o}function yg(e,t,n,r){if(!r)return{code:`RESOURCE_NOT_FOUND`,message:`句柄 "${e}" 无法展开(资源池未启用)`,hint:`verbatim 保护需启用 vfs(capabilities.vfs 默认开);集成方经 createChatSdk 配 data.resources 时自动提供 vfsStore`};let i=r.get(e);return i?n===void 0?{code:`RESOURCE_NOT_FOUND`,message:`字段 "${t}" 在 bind 中已不存在,无法展开句柄 "${e}"`,hint:`该字段可能已被删除或 restore 到不含此字段的快照;重新 read 确认当前结构`}:hg(i.value,n)?{value:i.value}:(r.update(t,n),{value:n}):n===void 0?{code:`RESOURCE_NOT_FOUND`,message:`句柄 "${e}" 不存在(字段 "${t}" 可能未注册或已被删除)`,hint:`重新 read 该字段触发懒注册`}:{code:`RESOURCE_EVICTED`,message:`字段 "${t}" 的 verbatim 资源已被淘汰(资源池 LRU)`,hint:`重新 read 该字段触发懒注册重建句柄,再写回新句柄 ⟦res:<handle>⟧`}}function bg(e,t,n){let r=t.getBind();for(let[i,a]of t.resourcesByPath){let o=_p(r,i),s=_p(e,i);if(s===void 0){if(o===void 0)continue;let t=i.split(`.`);if(_p(e,t.length>1?t.slice(0,-1).join(`.`):``)!==void 0){vp(e,i,o);continue}if(!(e&&typeof e==`object`&&t[0]in e)){if(n)continue;vp(e,i,o);continue}return{ok:!1,code:a.mode===`freeze`?`FROZEN_FIELD`:`VERBATIM_PROTECTED`,path:i,message:`整体替换会移除受保护字段 "${i}"(${a.mode}),已拒绝`,hint:a.mode===`freeze`?`含冻结字段的容器不可整体清空/替换:保留包含该字段的元素(补齐其必填字段,如 type),或逐个 remove 其余元素;彻底移除该字段需集成方调整 data.resources`:`含 verbatim 字段的容器不可整体清空/替换:保留包含该字段的元素,或先 resource_delete({path}) 释放保护后再整体替换`}}if(a.mode===`freeze`){if(s===ug(i)){vp(e,i,o);continue}if(!hg(s,o))return{ok:!1,code:`FROZEN_FIELD`,path:i,message:`字段 "${i}" 已冻结(freeze 保护),不可修改`,hint:`该字段由系统/集成方维护,LLM 不得改动。如需展示其值用 resource_get({path}) 取真值`}}else{let n=fg(s);if(n&&n.type===`res`){let r=yg(n.handle,i,o,t.resourceStore);if(`value`in r){vp(e,i,r.value);continue}return{ok:!1,code:r.code,path:i,message:r.message,hint:r.hint}}if(!hg(s,o))return{ok:!1,code:`VERBATIM_MISMATCH`,path:i,message:`字段 "${i}" 为 verbatim 保护(精确原样保留),写入值与原值不符`,hint:`要改该值请先 resource_update({path, value}) 更新资源池,再写回句柄 ⟦res:<handle>⟧;或写回原值(经 resource_get 取到的值)保持不变`}}}return{ok:!0}}function xg(e,t,n){let r=t===void 0?e.message:`patches[${t}]${n?` @ "${n}"`:``}: ${e.message}`;return $({code:e.code,path:e.path,message:r,hint:e.hint,...t===void 0?{}:{details:{patchIndex:t,patchJsonPath:n??null}}})}function Sg(e){let{value:t,ctx:n,mergeMode:r}=e;if(!n||!n.resourcesByPath.size)return{ok:!0,value:t};let i=bp(t),a=bg(i,n,r);return a.ok?{ok:!0,value:i}:{ok:!1,error:xg(a)}}function Cg(e){let{patches:t,clone:n,ctx:r}=e;if(!r||!r.resourcesByPath.size)return{ok:!0};for(let e=0;e<t.length;e++){let n=t[e];if(n.op===`remove`){let t=gg(n.jsonPath||``,r.resourcesByPath);if(t){let r=t.spec.mode===`freeze`?`FROZEN_FIELD`:`VERBATIM_PROTECTED`,i=t.spec.mode===`freeze`?`冻结字段不可删。如需移除请联系集成方调整 data.resources 配置`:`verbatim 字段不可直接删;先 resource_delete({path}) 释放资源保护后再删`;return{ok:!1,error:$({code:r,path:t.protectedPath,message:`patches[${e}] @ "${n.jsonPath}" 命中受保护字段 "${t.protectedPath}"(${t.spec.mode}),不可删除`,hint:i,details:{patchIndex:e,patchJsonPath:n.jsonPath??``}})}}}}let i=bg(n,r);if(!i.ok){let e=wg(i.path,t);return{ok:!1,error:xg(i,e>=0?e:void 0,e>=0?t[e].jsonPath:void 0)}}return{ok:!0}}function wg(e,t){let n=pg(e);for(let e=0;e<t.length;e++){let r=pg(t[e].jsonPath||``);if(r&&(r===n||n.startsWith(r+`.`)||r.startsWith(n+`.`)))return e}return-1}function Tg(e,t){if(!e)return null;let n=(t?xf(e,t):e)?.shape;return n&&typeof n==`object`?Object.keys(n):null}var Eg=e=>e&&e.length?`(可用字段:${e.slice(0,12).join(`, `)}${e.length>12?` …`:``})`:``,Dg=e=>/[.[]/.test(e)?e.replace(/[.[][^.[]*$/,``):``;function Og(e){let{schema:t,allowKeys:n,value:r,bindRef:i}=e,a=[];if(n){if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,error:Rl(``,[{path:[],code:`invalid_type`,message:`整体 set 需为 JSON 对象(当前为 ${Array.isArray(r)?`array`:r===null?`null`:typeof r})`,expected:`object`}]),notices:a};let e=i&&typeof i==`object`&&!Array.isArray(i)?i:{},n=r,o={};for(let r of Object.keys(n)){if(r.startsWith(`__pg`))continue;let i=n[r],s=Tf(t,r,i);if(!s.ok){if(s.resolution===`missing`){if(r in e)continue;return{ok:!1,error:$({code:`SCHEMA_STRIP`,message:`字段 ${r} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试${Eg(Tg(t,``))}`,path:r,details:{stripped:[r]}}),notices:a}}return{ok:!1,error:Rl(r,s.issues??[]),notices:a}}s.resolution===`open`&&a.push(`${r}=开放节点放行`);let c=Fp(e[r],i,s.data,r);if(c.length)return{ok:!1,error:$({code:`SCHEMA_STRIP`,message:`字段 ${c.join(`, `)} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试${Eg(Tg(t,Dg(String(c[0]))))}`,path:c[0],details:{stripped:c}}),notices:a};o[r]=s.data}return Ef(t)&&a.push(`根级 refine/superRefine 不再在 write 时执行(走 capabilities.verify)`),{ok:!0,assembly:o,wholeParsed:null,notices:a}}let o=t.safeParse(r);if(!o.success)return{ok:!1,error:Rl(``,o.error.issues),notices:a};let s=Fp(i,r,o.data);return s.length?{ok:!1,error:$({code:`SCHEMA_STRIP`,message:`字段 ${s.join(`, `)} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试`,path:s[0],details:{stripped:s}}),notices:a}:{ok:!0,assembly:o.data,wholeParsed:o.data,notices:a}}function kg(e){let{schema:t,bindRef:n,clone:r,patches:i,schemaErrorMode:a=`zod`,appendCaptures:o,moveCaptures:s}=e,c=[],l=t=>{let n=_p(r,t);return n===void 0?e.valueAt?.(t):n},u=(e,t)=>a===`schema_invalid`?$({code:`SCHEMA_INVALID`,message:`patches 应用后局部校验失败 @ "${e}",未写入`,hint:`确认该路径的值符合 schema;兄弟节点的既有数据不影响本次写入`,details:Ll(t)}):Rl(e,t),d=e=>$({code:`SCHEMA_STRIP`,message:`字段 ${e.join(`, `)} 不在 schema 声明内,写入被拒绝(防静默丢失)`,hint:`该数据结构不支持这些字段;请只用 schema 声明的字段,或在 data.schema 中声明后重试`,path:e[0],details:{stripped:e}}),f=[];Ef(t)&&c.push(`根级 refine/superRefine 不再在 write 时执行(走 capabilities.verify)`);let p=0,m=0;for(let e of i){let i=e.op??`set`,a=e.jsonPath||``;if(i===`remove`){let e=a.lastIndexOf(`.`);if(e>0&&/^\d+$/.test(a.slice(e+1))){let n=a.slice(0,e),i=wf(t,n);if(i.kind===`schemas`){let e=_p(r,n);if(Array.isArray(e))for(let t of i.schemas){let r=Df(t);if(r!==null&&e.length<r)return{ok:!1,error:u(n,[{path:[n],code:`too_small`,message:`删除后数组长度 ${e.length} 低于 schema 最小约束 ${r}`,expected:`>=${r}`}]),writeBacks:[],notices:c}}}}f.push({op:`remove`,jp:a});continue}if(i===`move`){let n=s[m++];if(n&&n.elem!==void 0){let e=n.toPath.lastIndexOf(`.`),r=e>0&&/^\d+$/.test(n.toPath.slice(e+1))?n.toPath.slice(0,e):n.toPath,i=wf(t,r);if(i.kind===`schemas`){let e=Of(i.schemas);if(e.length){let t=[],r=!1;for(let i of e){let e=i.safeParse(n.elem);if(e.success){r=!0;break}t.push(...e.error?.issues??[])}if(!r)return{ok:!1,error:u(n.toPath,t),writeBacks:[],notices:c}}}else i.kind===`open`&&c.push(`${r}=开放节点放行`)}f.push({op:`move`,jp:a,toPath:String(e.value)});continue}if(i===`append`){let e=o[p++]?.elems??[],r=_p(n,a);if(typeof r==`string`&&typeof e[0]==`string`){let n=e[0],i=wf(t,a);if(i.kind===`missing`)return{ok:!1,error:d([a]),writeBacks:[],notices:c};let o=r+n;if(i.kind!==`open`){let e=i.schemas.map(e=>e.safeParse(o)).find(e=>!e.success);if(e)return{ok:!1,error:u(a,e.error?.issues??[]),writeBacks:[],notices:c}}f.push({op:`appendStr`,jp:a,str:n});continue}if(!e.length){f.push({op:`appendElems`,jp:a,elems:[]});continue}let i=wf(t,a);if(i.kind===`missing`)return{ok:!1,error:d([a||`(根)`]),writeBacks:[],notices:c};if(i.kind===`open`){c.push(`${a||`(根)`}=开放节点放行`),f.push({op:`appendElems`,jp:a,elems:e});continue}let s=Of(i.schemas);if(!s.length){c.push(`${a||`(根)`}:目标非 schema 声明数组,元素未校验放行`),f.push({op:`appendElems`,jp:a,elems:e});continue}let l=[];for(let t=0;t<e.length;t++){let n=[],r,i=!1;for(let a of s){let o=a.safeParse(e[t]);if(o.success){i=!0,r=o.data;break}n.push(...o.error?.issues??[])}if(!i)return{ok:!1,error:u(`${a||`(根)`}[新增元素${t}]`,n),writeBacks:[],notices:c};let o=Fp(void 0,e[t],r,a?`${a}.${t}`:String(t));if(o.length)return{ok:!1,error:d(o),writeBacks:[],notices:c};l.push(r)}f.push({op:`appendElems`,jp:a,elems:l});continue}if(i===`merge`){let r=e.value;if(typeof r==`string`){let e=Sp(r);if(e.parseError)return{ok:!1,error:zl(`patches merge`,r,e.parseError),writeBacks:[],notices:c};r=e.parsed}if(typeof r!=`object`||!r||Array.isArray(r))return{ok:!1,error:$({code:`PATCH_FAILED`,message:`merge 的 value 需为对象`,hint:`merge 合并对象键;整体替换用 set`}),writeBacks:[],notices:c};let i=[];for(let e of Object.keys(r)){if(e.startsWith(`__pg`)||mp.has(e))continue;let r=a?`${a}.${e}`:e,o=l(r),s=Tf(t,r,o);if(!s.ok){if(s.resolution===`missing`){if(_p(n,r)===void 0)return{ok:!1,error:d([r]),writeBacks:[],notices:c};i.push([e,o]);continue}return{ok:!1,error:u(r,s.issues??[]),writeBacks:[],notices:c}}s.resolution===`open`&&c.push(`${r}=开放节点放行`);let f=Fp(_p(n,r),o,s.data,r);if(f.length)return{ok:!1,error:d(f),writeBacks:[],notices:c};i.push([e,s.data])}f.push({op:`mergeKeys`,jp:a,entries:i});continue}let h=l(a),g=a.lastIndexOf(`.`);if(g>0&&/^\d+$/.test(a.slice(g+1))){let e=_p(r,a.slice(0,g));if(Array.isArray(e)){for(let t=0;t<e.length;t++)if(!(t in e))return{ok:!1,error:$({code:`PATCH_FAILED`,message:`set @ "${a}" 越界数组索引产生稀疏空洞(父数组长度 ${e.length})`,hint:`数组索引须连续(≤ 当前长度);追加请用 op:"append"`}),writeBacks:[],notices:c}}}let _=Tf(t,a,h);if(!_.ok){if(_.resolution===`missing`){if(_p(n,a)===void 0)return{ok:!1,error:d([a]),writeBacks:[],notices:c};f.push({op:`set`,jp:a,value:h});continue}return{ok:!1,error:u(a,_.issues??[]),writeBacks:[],notices:c}}_.resolution===`open`&&c.push(`${a||`(根)`}=开放节点放行`);let v=Fp(_p(n,a),h,_.data,a);if(v.length)return{ok:!1,error:d(v),writeBacks:[],notices:c};f.push({op:`set`,jp:a,value:_.data})}return{ok:!0,writeBacks:f,notices:c}}function Ag(e){let{bindRef:t,schema:n,allowKeys:r,snapshots:i,maxSnapshots:a,audit:o,dryRun:s,op:c=`set`,protectedCtx:l,snapshotLabel:u}=e,d=e.value,f=e.internalAfterWrite?bp(t):null,p=Mg(d);if(p)return{ok:!1,error:Ng(p)};if(l){let e=Sg({value:d,ctx:l,mergeMode:!!r});if(!e.ok)return{ok:!1,error:e.error};d=e.value}let m=Og({schema:n,allowKeys:r,value:d,bindRef:t});if(!m.ok)return{ok:!1,error:m.error};let h=m.assembly;if(s)return{ok:!0,hash:``,data:h,notices:m.notices};if(typeof t!=`object`||!t)return{ok:!1,error:$({code:`LEAF_BIND`,message:`主数据 bind 为原始类型(${t===null?`null`:typeof t}),无法就地替换外部持有的值引用`,hint:`主数据 bind 必须为对象/数组;叶子值请用对象包裹(如 {value:"x"})或集成方通过 sdk.setData 替换 bind`})};let g=bp(t),_=i.length?i[i.length-1].id+1:1;for(i.push({id:_,ts:Date.now(),op:c,value:g,...u?{label:u}:{}});i.length>a;)i.shift();return typeof h==`object`&&h&&(m.wholeParsed?Pp(t,h):gp(t,h)),o({op:c,value:h,timestamp:Date.now()}),e.onWrite?.(),e.internalAfterWrite?.(t,f),{ok:!0,hash:e.hashFn?e.hashFn():Dp(t),data:h,notices:m.notices}}function jg(e){let{bindRef:t,patches:n,schema:r,allowKeys:i,snapshots:a,maxSnapshots:o,markDataDirty:s,schemaErrorMode:c=`zod`,snapshotLabel:l,dryRun:u,protectedCtx:d}=e,f=e.internalAfterWrite?bp(t):null,p=bp(t),m=[],h=[],g=[],_=[],v=(e,t)=>{(e===`set`||e===`merge`)&&_.push({jp:t,val:_p(p,t)})};for(let e=0;e<n.length;e++){let t=n[e],a=t.jsonPath||``;if(hp(a))return{ok:!1,error:$({code:`PATH_UNSAFE`,message:`patches[${e}] jsonPath "${a}" 含非法段`,hint:`使用正常属性路径,如 components.0.text`})};if(!yf(a,r,i))return{ok:!1,error:$({code:`PATH_DENIED`,message:`patches[${e}] @ "${a}" 不在 schema 声明字段内`,hint:`仅 schema 声明的 key 可写${Eg(Tg(r,Dg(a)))}`})};let o=t.op??`set`,s;if(o!==`remove`){if(t.value===void 0||t.value===``&&o===`move`)return{ok:!1,error:$({code:`MISSING_VALUE`,message:`patches[${e}] ${o} 操作需要 value`,hint:`op 为 ${o} 时 value 必填;删除请用 op:'remove'`})};let n=Sp(t.value);if(n.parseError)return{ok:!1,error:zl(`patches[${e}]`,t.value,n.parseError)};if(s=n.parsed,o!==`move`){let t=Mg(s);if(t)return{ok:!1,error:Ng(t,`patches[${e}] @ "${a}"`)}}if(o===`move`&&typeof s==`string`&&!yf(s,r,i))return{ok:!1,error:$({code:`PATH_DENIED`,message:`patches[${e}] move 目标 "${s}" 不在 schema 声明字段内`,hint:`move 的 value(目标路径)也须在 schema 声明字段内${Eg(Tg(r,Dg(String(s))))}`})}}o===`append`&&h.push({jp:a,elems:Array.isArray(s)?[...s]:[s]}),o===`move`&&g.push({jp:a,toPath:String(s),elem:_p(p,a)});let c=kp(p,o,a,s);if(c)return{ok:!1,error:$({code:`PATCH_FAILED`,message:`patches[${e}]: ${c}`,hint:`检查 op 与目标类型:merge 需对象,append 需数组或字符串`})};v(o,a),m.push({op:o,jp:a,value:s})}if(d){let e=Cg({patches:n,clone:p,ctx:d});if(!e.ok)return{ok:!1,error:e.error}}let y=kg({schema:r,bindRef:t,clone:p,patches:n,schemaErrorMode:c,appendCaptures:h,moveCaptures:g,valueAt:e=>_.find(t=>t.jp===e)?.val});if(!y.ok)return{ok:!1,error:y.error};if(u)return{ok:!0,applied:m,clone:p,notices:y.notices};let b=a.length?a[a.length-1].id+1:1;for(a.push({id:b,ts:Date.now(),op:`edit`,value:f??bp(t),...l?{label:l}:{}});a.length>o;)a.shift();for(let e of y.writeBacks)if(e.op===`remove`)yp(t,e.jp);else if(e.op===`set`)vp(t,e.jp,e.value);else if(e.op===`move`)jp(t,e.jp,e.toPath);else if(e.op===`mergeKeys`){let n=e.jp?_p(t,e.jp):t;if(n&&typeof n==`object`&&!Array.isArray(n))for(let[t,r]of e.entries??[])n[t]=r}else if(e.op===`appendElems`){let n=e.jp?_p(t,e.jp):t;Array.isArray(n)&&e.elems?.length&&n.push(...e.elems)}else if(e.op===`appendStr`){let n=e.jp?_p(t,e.jp):t;typeof n==`string`&&typeof e.str==`string`&&vp(t,e.jp,n+e.str)}return e.internalAfterWrite?.(t,f),s?.(),{ok:!0,applied:m,clone:p,notices:y.notices}}function Mg(e){let t=/^<[A-Za-z_][\w.-]*\s[\d.]+[KMG]?B>$/,n=e=>{if(typeof e==`string`)return e.includes(`<subtree `)||t.test(e)?e.slice(0,60):null;if(Array.isArray(e)){for(let t of e){let e=n(t);if(e)return e}return null}if(e&&typeof e==`object`)for(let t of Object.values(e)){let e=n(t);if(e)return e}return null};return n(e)}var Ng=(e,t)=>$({code:`PLACEHOLDER_LEAK`,path:t||void 0,message:`写入值包含摘要占位符 "${e}"(read/query 为省上下文返回的体积占位,非真实数据),已拒绝写入`,hint:`占位符子树的真实内容需先窄读获取:read({jsonPath:"<该子树路径>"}) 结果根豁免返回全文;聚焦该区域可用 set_focus。基于真实值重新构造写入内容`});function Pg(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}var Fg=3072;function Ig(e){return typeof e==`string`?e.length+2:typeof e==`number`||typeof e==`boolean`?8:4}function Lg(e,t,n,r,i){if(!t||e==null)return e;let a=new Set(n.map(e=>e.field)),o=r,s=Fg,c=i?.rootExempt??!1,l=i?.rootPath??``,u=i?.fullTextPrefixes??[],d=bp(e),f=i?.onSummarized,p=e=>u.some(t=>t&&(e===t||e.startsWith(t+`.`)||e.startsWith(t+`[`))),m=(e,t)=>{let n=`#`+String(Dp(e)).slice(0,8);if(Array.isArray(e))return`<subtree ${Pg(t)} children:${e.length} ${n}>`;let r=Object.keys(e),i=r.slice(0,6).join(`,`)+(r.length>6?`,…`:``);return`<subtree ${Pg(t)} keys:[${i}] ${n}>`},h=(e,t,n)=>{if(typeof e!=`object`||!e)return{node:e,eff:Ig(e)};if(p(t))return{node:e,eff:40};if(Array.isArray(e)){let r=2;for(let n=0;n<e.length;n++){let i=h(e[n],`${t}.${n}`,!1);e[n]=i.node,r+=i.eff}return!(n&&c)&&r>=s?(f?.(t),{node:m(e,r),eff:40}):{node:e,eff:r}}let r=2;for(let n of Object.keys(e)){let i=e[n],s=t?`${t}.${n}`:n;if(typeof i==`string`&&a.has(n)&&i.length>=o&&!p(s))e[n]=`<${n} ${Pg(i.length)}>`,f?.(s),r+=e[n].length+n.length+2;else{let t=h(i,s,!1);e[n]=t.node,r+=t.eff+n.length+2}}return!(n&&c)&&r>=s?(f?.(t),{node:m(e,r),eff:40}):{node:e,eff:r}};return h(d,l,!0).node}var Rg=0;function zg(){return Rg++,`c_`+Math.random().toString(36).slice(2,8)+Rg.toString(36)}function Bg(e,t){if(!(!e||typeof e!=`object`))for(let n of t){let t=_p(e,n);if(Array.isArray(t))for(let e of t)e&&typeof e==`object`&&!(`__pgId`in e)&&(e.__pgId=zg())}}function Vg(e){(function e(t){if(Array.isArray(t))t.forEach(e);else if(t&&typeof t==`object`)for(let n of Object.keys(t))n.startsWith(`__pg`)?delete t[n]:e(t[n])})(e)}function Hg(e,n={}){let i=n.pgIdPaths??[],a=i.length?(e,t)=>{if(t&&typeof t==`object`)for(let n of i){let r=_p(t,n),i=_p(e,n);if(!Array.isArray(r)||!Array.isArray(i))continue;let a=e=>{if(!e||typeof e!=`object`)return e;let t={...e};return delete t.__pgId,t},o=new Set;for(let e=0;e<i.length;e++){let t=i[e];if(!(!t||typeof t!=`object`||`__pgId`in t))for(let e=0;e<r.length;e++){if(o.has(e))continue;let n=r[e];if(!(!n||typeof n!=`object`||!n.__pgId)&&hg(a(n),a(t))){t.__pgId=n.__pgId,o.add(e);break}}}for(let e=0;e<r.length&&e<i.length;e++){if(o.has(e))continue;let t=r[e]?.__pgId,n=i[e];t&&n&&typeof n==`object`&&!(`__pgId`in n)&&(n.__pgId=t,o.add(e))}}Bg(e,i)}:void 0,o=i.length?Kf(e.schema,i).schema:e.schema,s=e.bind,c=e.description??`主数据对象`,l=vf(o),u=new Map,d=n.vfsStore?new _g(n.vfsStore):void 0;function f(e){if(u.clear(),e)for(let t of e){let e=pg(t.path);u.set(e,{path:e,mode:t.mode})}}f(e.resources);let p=u.size?{resourcesByPath:u,resourceStore:d,getBind:()=>s}:void 0,m=[],h=n.maxSnapshots??20,g=new Map,_=``,v=e=>e?.configurable?.__pgDataScope??_,y=e=>{let t=e?.configurable?.__pgFullTextPaths;return Array.isArray(t)?t.map(String):void 0},b=new Set,x=e=>{for(b.add(e);b.size>500;)b.delete(b.values().next().value)},S=e=>g.get(e??_),C=(e,t)=>{let n=t??_;e===void 0?g.delete(n):g.set(n,e)},w=n.conflictWatchFields??[],T=!w.includes(`*`)&&w.length?new Set(w):void 0,E=w.length>0,D=()=>T?Op(s,T):Dp(s),ee=(n.maxParallelTools??1)>1&&E,O=!1,k=[];async function te(){if(!ee)return{release:()=>{},reacquire:async()=>{}};O?await new Promise(e=>k.push(e)):O=!0;let e=!0;return{release:()=>{if(!e)return;e=!1;let t=k.shift();t?t():O=!1},reacquire:async()=>{e||=(O?await new Promise(e=>k.push(e)):O=!0,!0)}}}(n.maxParallelTools??1)>1&&!E&&console.warn(`[page-agent-sdk] maxParallelTools>1 且未声明 conflictWatchFields:并发写不互锁(后写覆盖前写,既有明文语义);声明 conflictWatchFields 后自动启用写互锁与乐观锁校验`);let A=e=>{let t=D();return C(t,e),t},j=n.largeTextThreshold??200,M=(n.largeTextPaths??[]).map(e=>{let t=e.lastIndexOf(`.`);return t>0?{arrayPath:e.slice(0,t),field:e.slice(t+1)}:null}).filter(e=>e!==null),ne=!0;function N(){ne=!0}let P={get:()=>({schema:o,bind:s,description:c}),set:e=>{o=i.length?Kf(e.schema,i).schema:e.schema,s=e.bind,c=e.description??`主数据对象`,l=vf(o),m.length=0,g.clear(),f(e.resources),d?.clear(),N()},update:e=>{s=e,m.length=0,g.clear(),N()},markDataDirty:N,consumeDataDirty:()=>{let e=ne;return ne=!1,e},enterScope:e=>{let t=_;return _=e,()=>{_=t}},exitScope:e=>{g.delete(e)},recomputeBaseline:e=>{g.set(e??``,D())},recomputeAllBaselines:()=>{let e=D();for(let t of g.keys())g.set(t,e)},hasBaselines:()=>g.size>0,getSummarizedPaths:()=>[...b],clearSummarizedPaths:()=>b.clear(),getResourcesSnapshot:()=>{let e=[];for(let[t,n]of u)if(n.mode===`verbatim`){let r=d?.get(t);e.push(r?.handle?{path:t,mode:n.mode,handle:r.handle}:{path:t,mode:n.mode})}else e.push({path:t,mode:n.mode});return e},createResource:d?(e,t)=>{let n=pg(e),r=u.get(n),i=t===void 0?_p(s,n):t;return d.ensure(n,i,r?.mode??`verbatim`)}:void 0,getResource:d?e=>{let t=d.get(e);return t?{path:t.path,mode:t.mode,value:t.value,handle:t.handle}:void 0}:void 0,updateResource:d?(e,t)=>{let n=pg(e);d.update(n,t),vp(s,n,t),N(),C(D(),``)}:void 0,deleteResource:d?e=>d.delete(e):void 0,listResources:d?()=>d.list():void 0},F=e=>{n.onAudit?.(e)};function re(e,t){let n=bp(s),r=m.length?m[m.length-1].id+1:1;for(m.push({id:r,ts:Date.now(),op:e,label:t,value:n});m.length>h;)m.shift();return r}async function ie(e,t,r,i){if(!t||t===``)return null;let a=D();if(a===t)return null;if(!n.onConflict)return $({code:`VERSION_CONFLICT`,message:`乐观锁冲突:expectedHash=${t} 但当前 hash=${a}。主数据在你 read 之后已被修改(外部代码/其他 agent/用户手动改)。`,hint:`重新 read 拿最新值与 hash,基于最新值修改后再写入。当前值:${Tp(s,400)}`});i?.release();let o=await n.onConflict({op:e,agentValue:r,currentValue:s,currentHash:a,expectedHash:t,snapshotId:0});if(o.action===`keep_external`)return`已保留外部修改(未写入)。当前值:${Tp(s,400)} (hash=${a})。请重新 read 拿最新值与 hash 再改。`;if(o.action===`restore`){if(await i?.reacquire(),!m.length)return`无历史快照可回退(本次为首次操作)。当前值:${Tp(s,400)} (hash=${a})。请重新 read 再改或选「强制覆盖」。`;let e=m[m.length-1];return Np(s,bp(e.value)),N(),C(D()),`已回退主数据到历史快照 #${e.id}[${e.op}]。当前值:${Tp(s,400)} (hash=${D()})。请基于回退后的值重写或停止。`}await i?.reacquire();let c=D();return c===a?(C(D()),null):(F({op:`conflict_recheck`,detail:`裁决基于 ${a} 恢复时 ${c}(ask 窗口新修改落地,overwrite 被拦)`,timestamp:Date.now()}),$({code:`VERSION_CONFLICT`,message:`裁决恢复点校验失败:裁决基于 hash=${a},恢复时主数据已变为 hash=${c}(裁决等待期间又有新修改落地,裁决者未见过)。`,hint:`重新 read 拿最新值与 hash,基于最新值修改后再写入(单次校验,不再二次挂起)。`}))}let ae=(e,t=!0)=>{e.writeCapable=t},I=(0,r.tool)(async()=>[`说明: ${c}`,`格式: 写入值需为 JSON,且通过声明的 schema 校验(校验失败时 write 会返回结构化错误,含具体字段与期望类型)。`].join(`
95
95
  `),{name:`describe_data`,description:`获取主数据的说明与格式要求。`,schema:t.z.object({})}),oe=(0,r.tool)(async({id:e},t)=>{let n=v(t);if(!m.length)return $({code:`NO_SNAPSHOT`,message:`无快照可回退`,hint:`write 各写意图会自动存快照;或 history_data({list:true}) 查看可用快照`});let r=e===void 0?m[m.length-1]:m.find(t=>t.id===e);if(!r)return $({code:`SNAPSHOT_NOT_FOUND`,message:`未找到快照 #${e}`,hint:`用 history_data({list:true}) 查看可用快照序号`});let i=o.safeParse(r.value);return i.success?(Np(s,bp(r.value)),N(),F({op:`restore`,detail:`#${r.id}`,timestamp:Date.now()}),C(D(),n),`已回退主数据到快照 #${r.id}[${r.op}]${r.label?`(${r.label})`:``}。`):$({code:`SNAPSHOT_SCHEMA_INVALID`,message:`快照 #${r.id} 的值不符合当前 schema,无法回退`,hint:`schema 可能已变更;该快照已过期,选其他快照或重新设置`,details:Ll(i.error.issues)})},{name:`restore_data`,description:`把主数据回退到某个快照(就地还原,保留响应式)。不传 id 则回退最近一次(快速回退)。可用 history_data({list:true}) 查看快照列表。`,schema:t.z.object({id:t.z.number().int().optional().describe(`指定快照序号;不传则回退最近一次`)})});ae(oe);let se=(0,r.tool)(async({id:e,jsonPath:t,list:n})=>{if(n){if(!m.length)return`无快照。set/edit/delete 会自动存快照。`;let e=m.map(e=>{let t=JSON.stringify(e.value??``).length,n=new Date(e.ts).toLocaleTimeString(`zh-CN`,{hour12:!1});return` #${e.id} [${e.op}]${e.label?` "${e.label}"`:``} ${n} 修改前≈${t}字符`});return`主数据快照时间线(共 ${m.length} 条,默认最近一次):\n${e.join(`
96
96
  `)}\n用 history_data({id}) 查看某条快照内容;restore_data({id}) 回退;diff_data({snapshotId}) 对比差异。`}if(!m.length)return $({code:`NO_SNAPSHOT`,message:`无历史快照可查看`,hint:`set/edit/delete 会自动存快照;或 history_data({list:true}) 查看可用序号`});let r=e===void 0?m[m.length-1]:m.find(t=>t.id===e);if(!r)return $({code:`SNAPSHOT_NOT_FOUND`,message:`未找到快照 #${e}`,hint:`不传 id 查看最近一次;或 history_data({list:true}) 查看可用序号`});let i=bp(r.value),a=t||``;if(a){if(hp(a))return $({code:`PATH_UNSAFE`,message:`jsonPath "${a}" 含非法段`,hint:`使用正常属性路径`});if(!yf(a,o,l))return $({code:`PATH_DENIED`,message:`history_data @ "${a}" 不在 schema 声明字段内`,hint:`仅 schema 声明的 key 可读`});i=_p(i,a);let e=xf(o,a);e&&(i=Pf(i,e))}else l&&(i=Pf(i,o));return`快照 #${r.id}[${r.op}]${r.label?`(${r.label})`:``}${a?` @ ${a}`:``} = ${Tp(i)}`},{name:`history_data`,description:`查看主数据快照(只读不回退当前)。list:true 列时间线;传 id 看某次快照内容(默认最近),jsonPath 可只看子路径。冲突诊断/看上一版用;对比差异用 diff_data;回退用 restore_data。`,schema:t.z.object({id:t.z.number().int().optional().describe(`快照序号;不传则最近一次(list:true 时忽略)`),jsonPath:t.z.string().optional().describe(`只看快照的某子路径(相对主数据根);不传则整个快照`),list:t.z.boolean().optional().describe(`true 则列出快照时间线元信息(序号/操作/标签/时间/大小);不传则查看单条快照内容`)})}),L=(0,r.tool)(async({expr:e,limit:t},n)=>{let r=v(n);if(typeof s!=`object`||!s)return $({code:`NOT_OBJECT`,message:`主数据不是对象/数组,无法查询(当前为 ${s===void 0?`undefined`:typeof s})`,hint:`query 仅适用于对象/数组;叶子用 read 读`});let i=l?Pf(s,o):s,a;try{a=Gu(i,e)}catch(t){return $({code:`JSONPATH_SYNTAX`,message:`JSONPath 解析错误: ${t.message}`,hint:`语法子集:$ .key [n] ["key"] [*] [?(filter)] ..key ..*;filter:@.field op literal,&&/||/();对象根需先点出数组字段再过滤,如 $.components[?(@.x>1)]`,details:{expr:e}})}let c=t??50,u=a.slice(0,c),d=y(n),f=u.map(e=>`{"path":${JSON.stringify(e.path)},"index":${e.index===void 0?`null`:e.index},"value":${Tp(Lg(e.value,r===``,M,j,{rootExempt:!1,rootPath:String(e.path??``),fullTextPrefixes:d,onSummarized:x}))}}`);return`{"matched":${a.length},"returned":${u.length},"truncated":${a.length>c},"results":[${f.join(`,`)}]}`},{name:`query_data`,description:`用 JSONPath 查询主数据(只读):$ 根/.key/[n]/[*]/[?(==/!=/</<=/>/>=,&&/||)]/..key 递归。返回匹配元素 path/index/value(path 可作 write patch 的 jsonPath);大数组筛选定位用它。`,schema:t.z.object({expr:t.z.string().describe(`JSONPath 表达式,如 $.components[?(@.type=="card" && @.price<100)] 或 $..title(递归找所有 title)`),limit:t.z.number().int().min(1).max(200).optional().describe(`返回结果上限,默认 50`)})}),R=(0,r.tool)(async({query:e,mode:t,fuzzyThreshold:n,matchKey:r,limit:i})=>{if(s==null)return $({code:`EMPTY`,message:`主数据为空,无可搜索内容`});try{let a=qu(l?Pf(s,o):s,e,{mode:t,fuzzyThreshold:n,matchKey:r,limit:i??50});return Tp({matched:a.length,results:a})}catch(t){return $({code:`REGEX_INVALID`,message:`搜索错误: ${t.message}`,hint:`regex 模式下 query 须为合法正则;改 mode 为 substring/fuzzy 可避免正则语法问题`,details:{query:e}})}},{name:`search_data`,description:`主数据内文本搜索(只读)。mode:substring(默认,不区分大小写)/regex(i 标志)/fuzzy(Levenshtein ≤ fuzzyThreshold)。递归遍历叶子值返回命中 path+value(超 200 字符截断);找名字记不清的元素用它。`,schema:t.z.object({query:t.z.string().describe(`搜索词(substring/regex/fuzzy 共用)`),mode:t.z.enum([`substring`,`regex`,`fuzzy`]).optional().describe(`匹配模式,默认 substring`),fuzzyThreshold:t.z.number().int().min(0).max(5).optional().describe(`fuzzy 模式最大编辑距离,默认 2`),matchKey:t.z.boolean().optional().describe(`是否同时匹配 key 名,默认 true`),limit:t.z.number().int().min(1).max(200).optional().describe(`返回上限,默认 50`)})}),z=(0,r.tool)(async({script:e,mode:t,jsonPath:n},r)=>{let i=v(r);if(e.length>8e3)return $({code:`SCRIPT_TOO_LARGE`,message:`脚本过长(${e.length} 字符,上限 8000)`,hint:`精简脚本;复杂逻辑可分步(先 query 探查再 transform 改),或拆成多次 eval`});let c=n||``,u;if(c){if(!yf(c,o,l))return $({code:`PATH_DENIED`,message:`eval_script @ "${c}" 不在 schema 声明字段内`,hint:`仅 schema 声明的 key 可作为子树`});if(u=_p(s,c),l){let e=xf(o,c);e&&(u=Pf(u,e))}}else u=l?Pf(s,o):s;let d=bp(u),f=await Yu(d,e,c&&JSON.stringify(d).length>1e5?8e3:3e3);if(!f.ok){let t=/超时/.test(f.error||``);return $({code:t?`SCRIPT_TIMEOUT`:`SCRIPT_ERROR`,message:`脚本执行失败: ${f.error}`,hint:t?`脚本可能有死循环或过重计算;加边界检查/分批;transform 返回完整新值勿返回巨大中间结果`:`检查脚本语法与运行时错误;入参为 data(主数据深拷贝),沙箱内禁用 fetch/XHR/WebSocket`,details:{elapsedMs:f.elapsedMs,scriptLen:e.length}})}if(t===`transform`){let e=f.result;if(c){let t=await te();try{let t=jg({bindRef:s,patches:[{op:`set`,jsonPath:c,value:e}],schema:o,allowKeys:l,snapshots:m,maxSnapshots:h,markDataDirty:N,schemaErrorMode:`schema_invalid`,snapshotLabel:`eval_transform_subtree`,internalAfterWrite:a,protectedCtx:p});return t.ok?(F({op:`edit`,detail:`eval_transform_subtree @ ${c}`,timestamp:Date.now()}),C(D(),i),`已通过脚本 transform 子树 @ ${c} 更新(耗时 ${f.elapsedMs}ms)。当前值: ${Tp(s,600)}`):t.error}finally{t.release()}}if(e&&typeof e==`object`&&!Array.isArray(e)&&`patches`in e&&Array.isArray(e.patches)){if(typeof s!=`object`||!s)return $({code:`LEAF_BIND`,message:`主数据 bind 为原始类型(${s===null?`null`:typeof s}),eval transform(patches) 无法就地替换`,hint:`主数据 bind 必须为对象/数组;叶子值请用对象包裹或集成方通过 sdk.setData 替换 bind`});let t=await te();try{let t=jg({bindRef:s,patches:e.patches,schema:o,allowKeys:l,snapshots:m,maxSnapshots:h,markDataDirty:N,schemaErrorMode:`schema_invalid`,snapshotLabel:`eval_transform`,internalAfterWrite:a,protectedCtx:p});return t.ok?(F({op:`edit`,detail:`eval_transform(${t.applied.length} patches)`,timestamp:Date.now()}),C(D(),i),`已通过脚本 transform(patches) 更新主数据(${t.applied.length} 个 patch,耗时 ${f.elapsedMs}ms)。当前值: ${Tp(s,600)}`):t.error}finally{t.release()}}let t=e,n=Mg(t);if(n)return Ng(n);if(p){let e=Sg({value:t,ctx:p});if(!e.ok)return e.error;t=e.value}if(typeof s!=`object`||!s)return $({code:`LEAF_BIND`,message:`主数据 bind 为原始类型(${s===null?`null`:typeof s}),eval transform 无法就地替换外部持有的值引用`,hint:`主数据 bind 必须为对象/数组;叶子值请用对象包裹或集成方通过 sdk.setData 替换 bind`});let r=await te();try{let e=Og({schema:o,allowKeys:l,value:t,bindRef:s});return e.ok?(re(`edit`,`eval_transform`),e.wholeParsed?Pp(s,e.assembly):e.assembly!==null&&typeof e.assembly==`object`&&gp(s,e.assembly),N(),F({op:`edit`,detail:`eval_transform`,timestamp:Date.now()}),C(D(),i),`已通过脚本 transform 更新主数据(耗时 ${f.elapsedMs}ms)。当前值: ${Tp(s,600)}`):$({code:`SCHEMA_INVALID`,message:`脚本返回值校验失败,未写入(transform 模式要求返回主数据的完整新值或顶层 key 子集)`,hint:`确认脚本 return 了完整新值(非部分);或返回 {patches:[...]} 走增量模式;按 describe_data() 查看格式`,details:(e.error.match(/"details":\s*(\[[^\]]*\])/)?.[1]??``)||e.error})}finally{r.release()}}return Tp({ok:!0,result:f.result,elapsedMs:f.elapsedMs})},{name:`eval_script`,description:`在 Worker 沙箱对主数据跑自定义 JS(无 window/fetch,超时 3s)。入参 data(深拷贝),返回值即结果。mode:query 只读回给 LLM(过滤/映射/聚合)/transform 落地(返回完整新值或 {patches:[...]} 增量)。jsonPath 可只对子树执行。`,schema:t.z.object({script:t.z.string().describe(`JS 脚本体,如 data.filter(c=>c.stock>0).map(c=>c.id);入参名 data;末尾表达式或 return 即返回值`),mode:t.z.enum([`query`,`transform`]).optional().describe(`query=只读返回结果(默认),transform=校验后落地为新值`),jsonPath:t.z.string().optional().describe(`子树模式:仅对 jsonPath 指向的子树执行(降低大 JSON 成本);transform 时返回值作为该子树新值`)})});ae(z,e=>e?.mode===`transform`);let ce=(0,r.tool)(async({jsonPath:e,jsonPaths:t,fields:n,depth:r,offset:i,limit:a},u)=>{let d=v(u),f=y(u),m=D();if(t&&t.length){let e=!1,i=t.map(t=>{let i=t||``;if(!yf(i,o,l))return`- ${i||`(根)`}: [PATH_DENIED: 不在 schema 声明字段内]`;e=!0;let a=i?_p(s,i):s;if(!i&&l)a=Pf(a,o);else if(l){let e=xf(o,i);e&&(a=Pf(a,e))}let c=a;return p&&(c=vg({jp:i,resolved:c,resourcesByPath:p.resourcesByPath,resourceStore:p.resourceStore})),n&&n.length&&(c=Cp(c,n)),r!=null&&(c=wp(c,r)),c=Lg(c,d===``,M,j,{rootExempt:!0,rootPath:i,fullTextPrefixes:f,onSummarized:x}),c===void 0?`- ${i} = (undefined)`:`- ${i} = ${Tp(c)}`});return e&&C(m,d),`多路径读取(共 ${t.length} 项,hash=${m}):\n${i.join(`
97
97
  `)}`}let h=e||``;if(hp(h))return $({code:`PATH_UNSAFE`,message:`jsonPath "${h}" 含非法段(__proto__/constructor/prototype)`,hint:`使用正常属性路径,如 components.0.text(数组索引数字)`});let g=(e,t)=>Tg(o,e)??(t&&typeof t==`object`&&!Array.isArray(t)?Object.keys(t):[]);if(!yf(h,o,l)){let e=/[.[]/.test(h)?h.replace(/[.[][^.[]*$/,``):``,t=g(e,e?_p(s,e):s),n=t.length?`;父级 "${e||`(root)`}" 的可用字段:${t.slice(0,12).join(`, `)}${t.length>12?` …`:``}`:``;return $({code:`PATH_DENIED`,message:`read @ "${h}" 不在 schema 声明字段内`,hint:`主数据仅暴露 schema 声明的字段;若需操作该字段,集成方需在 schema 中声明它${n}`})}let _=h?_p(s,h):s;if(h&&_===void 0){let e=xf(o,h);if(!(e&&typeof e.isOptional==`function`&&e.isOptional())){let e=/[.[]/.test(h)?h.replace(/[.[][^.[]*$/,``):``,t=e?_p(s,e):s,n=g(e,t),r=Array.isArray(t)?`父级 "${e||`(root)`}" 是 ${t.length} 元数组,有效索引 0-${Math.max(t.length-1,0)};先 read({jsonPath:"${e}"}) 确认现状,追加元素走 write 的 append`:n.length?`父级 "${e||`(root)`}" 的可用字段:${n.slice(0,12).join(`, `)}${n.length>12?` …`:``};先 read({jsonPath:"${e}"}) 确认`:`父级 "${e||`(root)`}" 不存在或不是容器;先 read() 不传 jsonPath 查看顶层字段`;return $({code:`PATH_NOT_FOUND`,path:h,message:`路径 "${h}" 不存在`,hint:r})}}if(!h&&l)_=Pf(_,o);else if(l){let e=xf(o,h);e&&(_=Pf(_,e))}let b=_;p&&(b=vg({jp:h,resolved:b,resourcesByPath:p.resourcesByPath,resourceStore:p.resourceStore})),C(m,d),n&&n.length&&(b=Cp(b,n)),r!=null&&(b=wp(b,r)),b=Lg(b,d===``,M,j,{rootExempt:!0,rootPath:h,fullTextPrefixes:f,onSummarized:x});let S=e?``:`主数据说明: ${c}\n格式: 写入值需为 JSON,且通过声明的 schema 校验(校验失败时 write 会返回结构化错误)。字段约束(类型/min/max/enum/必填/默认)见 systemPrompt「可操作数据」段,或用 schema_data({ jsonPath }) 按需查。\n\n`,w=n&&n.length?`(字段裁剪:${n.join(`,`)})`:``,T=r==null?``:`(深度≤${r})`,E=w||T?` ${w}${T}`:``;if((i!==void 0||a!==void 0)&&Array.isArray(b)){let e=b.length,t=Math.max(0,i??0),n=Math.min(200,Math.max(1,a??50)),r=b.slice(t,t+n),o=t+n<e;return`${S}主数据${h?` @ ${h}`:``} 数组分页[offset=${t},limit=${n}]${E} = ${Tp(r)} (total=${e}, hasMore=${o}) (hash=${m})`}return b===void 0?`${S}主数据${h?` @ ${h}`:``}${E} = (undefined) (hash=${m})`:`${S}主数据${h?` @ ${h}`:``}${E} = ${Tp(b)} (hash=${m})`},{name:`read`,description:`读取主数据(高层入口,合并 describe/get)。不传 jsonPath → 返回主数据说明 + 格式提示(含字段约束);传 jsonPath → 返回该子路径当前值 + hash;传 jsonPaths → 一次读多个不相关子路径(省多轮往返)。hash 用于乐观锁(声明 conflictWatchFields 后 write 自动比对;未声明不自动校验)。fields(字段裁剪)/depth(深度截断)减体积;offset+limit 对数组目标分页(返回切片 + total/hasMore)。`,schema:t.z.object({jsonPath:t.z.string().optional().describe(`要读的子路径(相对主数据根,如 components.0.text);不传则读整个主数据并返回说明`),jsonPaths:t.z.array(t.z.string()).optional().describe(`多路径读取:一次读多个不相关子路径(与 jsonPath 互斥,优先于 jsonPath);返回各路径值,非法路径单项标错不整批失败`),fields:t.z.array(t.z.string()).optional().describe(`字段裁剪:只返回指定字段(对对象/数组元素投影),减少返回体积,如 ["id","title"]`),depth:t.z.number().int().min(0).optional().describe(`嵌套深度限制:0=只根占位,1=根+子,递归到 depth 层后用 {...}/[...] 占位截断,减少深层返回体积`),offset:t.z.number().int().min(0).optional().describe(`数组分页起始偏移(仅当读取目标是数组时生效,默认 0),配合 limit 分页读大数组`),limit:t.z.number().int().min(1).max(200).optional().describe(`数组分页每页条数(默认 50,上限 200;仅数组时生效),返回切片 + total/hasMore`)})}),B=(0,r.tool)(async({value:e,patch:t,patches:n,del:r,dryRun:c},u)=>{let d=v(u),f=`set`;r?f=`delete`:(n&&n.length||t)&&(f=`edit`);let g=t?.value===void 0?e:t.value,_=await te();try{let e=E?S(d):void 0;if(c&&e!==void 0){let t=D();if(t!==e)return $({code:`VERSION_CONFLICT`,message:`dryRun 预检发现乐观锁冲突: expectedHash=${e} 当前 hash=${t}(主数据在你 read 后被改)`,hint:`重新 read 拿最新 hash 再预检/写`})}if(f===`delete`){if(!t?.jsonPath)return $({code:`MISSING_VALUE`,message:`delete 需要 patch.jsonPath 指定要删的子路径(主数据整体不可删,用 write(value) 整体替换)`,hint:`如 patch:{jsonPath:"components.0"}, del:true`});if(hp(t.jsonPath))return $({code:`PATH_UNSAFE`,message:`jsonPath "${t.jsonPath}" 含非法段`,hint:`使用正常属性路径`});if(!yf(t.jsonPath,o,l))return $({code:`PATH_DENIED`,message:`write delete @ "${t.jsonPath}" 不在 schema 声明字段内`,hint:`仅 schema 声明的 key 可删`});if(p){let e=gg(t.jsonPath,p.resourcesByPath);if(e)return $({code:e.spec.mode===`freeze`?`FROZEN_FIELD`:`VERBATIM_PROTECTED`,message:`write delete @ "${t.jsonPath}" 命中受保护字段 "${e.protectedPath}"(${e.spec.mode}),不可删除`,hint:e.spec.mode===`freeze`?`冻结字段不可删`:`verbatim 字段不可直接删;先 resource_delete 释放`})}let n=await ie(`delete`,e,void 0,_);if(n!==null)return n;if(c){let e=bp(s);return yp(e,t.jsonPath)?`dryRun(delete): 将删除 @ ${t.jsonPath}。预览剩余:${Tp(e,600)}。未实际写入、未入快照。`:`dryRun(delete): @ ${t.jsonPath} 不存在(无需删除)。未实际写入。`}re(`delete`);let r=yp(s,t.jsonPath);return N(),F({op:`delete`,detail:t.jsonPath,timestamp:Date.now()}),a&&(a(s,null),N()),C(D(),d),r?`已删除主数据 @ ${t.jsonPath}`:`主数据 @ ${t.jsonPath} 不存在(无需删除)`}if(f===`edit`){if(typeof s!=`object`||!s)return $({code:`NOT_OBJECT`,message:`edit 仅适用于对象/数组主数据,当前是 ${s===void 0?`undefined`:typeof s}`,hint:`叶子用 write(value) 整体设置`});let r=await ie(`edit`,e,void 0,_);if(r!==null)return r;let i=n&&n.length?n:[{op:t.op??`set`,jsonPath:t.jsonPath||``,value:g}],u=jg({bindRef:s,patches:i,schema:o,allowKeys:l,snapshots:m,maxSnapshots:h,markDataDirty:N,schemaErrorMode:`zod`,dryRun:c,internalAfterWrite:a,protectedCtx:p});if(!u.ok)return u.error;if(c)return`dryRun(edit): ${u.applied.length} 个 patch 预检通过(schema 校验 OK)。预览结果:${Tp(u.clone,600)}。未实际写入、未入快照。`;F({op:`edit`,detail:`${u.applied.length} 个 patch${u.applied.length>1?`(批量)`:``}`,value:u.applied.map(e=>`${e.op}@${e.jp}`),timestamp:Date.now()});let f=A(d);return Vg(u.clone),`已 write(edit) 主数据(${u.applied.length} 个 patch)。当前值:${Tp(u.clone,600)} (新 hash=${f})`}let r=Sp(g);if(r.parseError)return zl(``,g,r.parseError);let u=await ie(`set`,e,g,_);if(u!==null)return u;let v=Ag({bindRef:s,value:r.parsed,schema:o,allowKeys:l,snapshots:m,maxSnapshots:h,audit:F,dryRun:c,onWrite:N,internalAfterWrite:a,protectedCtx:p,hashFn:D});if(!v.ok)return v.error;if(c)return`dryRun(set): schema 校验通过。预览新值:${Tp(v.data,600)}。未实际写入、未入快照。`;let y=v.hash??D();C(y,d);let b=i.length?bp(v.data):v.data;return Vg(b),`已 write(set) 主数据 = ${Tp(b,600)} (新 hash=${y})${l?`(白名单模式:仅更新 schema 声明字段,未声明字段保留)`:``}`}finally{_.release()}},{name:`write`,description:`写入主数据(高层入口,合并 set/edit/delete + 自动乐观锁 + 自动快照)。四意图:① 整体替换 write({value:整个对象});② 增量 write({patch:{op,jsonPath,value}}) op=set/remove/merge/append/move(move 的 value=目标路径字符串);③ 批量原子 write({patches:[...]})(任一失败整批回滚);④ 删子路径 write({patch:{jsonPath},del:true})。dryRun:true 预检不落盘。写入自动 schema 校验(失败不写,按错误修正重试)+ 自动快照。详细用法见系统提示「能力使用提示」。`,schema:t.z.object({value:t.z.unknown().optional().describe(`JSON 对象(推荐,如 {title:"x"})或 JSON 字符串;set 整体或单个 patch 的 set/merge/append 必填`),patch:t.z.object({op:t.z.enum([`set`,`remove`,`merge`,`append`,`move`]).optional().describe(`增量操作:set 设值/remove 删/merge 合并对象/append 追加数组/move 移动数组元素(value=目标路径字符串)。单 patch edit 缺省按 set;del 模式(write({patch:{jsonPath},del:true}))不读 op 可省略`),jsonPath:t.z.string().optional().describe(`相对主数据根的点号路径(如 components.0.text);set/remove 必填,merge/append 不填则作用于根`),value:t.z.unknown().optional().describe(`该 patch 的值(JSON 直传或 JSON 字符串);set/merge/append 必填,remove 不需。与顶层 value 二选一:优先 patch.value,未填则回退顶层 value(向后兼容)。推荐用 patch.value(自带,与 patches 元素一致,无歧义)`)}).optional().describe(`单个增量编辑(自带 value,与 patches 元素一致);传 patch(无 patches)走单 patch edit 语义`),patches:t.z.array(t.z.object({op:t.z.enum([`set`,`remove`,`merge`,`append`,`move`]),jsonPath:t.z.string().optional().describe(`相对主数据根的点号路径;set/remove 必填,merge/append 不填则作用于根`),value:t.z.unknown().optional().describe(`JSON 值(推荐直传)或 JSON 字符串;set/merge/append 必填,remove 不需`)})).optional().describe(`批量增量编辑:一次原子应用多个 patch(任一失败则整体不写入,clone 试跑全部 + schema 校验通过才落 live)。适合一次改多处,减少多轮往返`),del:t.z.boolean().optional().describe(`true 则删除 patch.jsonPath 指定的子路径`),dryRun:t.z.boolean().optional().describe(`预检模式:走完整校验链(schema + 白名单 + patch 应用到 clone)但不落盘、不入快照,返回预览。四意图(value/patch/patches/del)均支持;乐观锁冲突照常检测(返回 VERSION_CONFLICT 不挂起)`)})});ae(B);let V=(0,r.tool)(async({jsonPath:e})=>{let t=e||``,n=t?xf(o,t):o;return n?`schema${t?` @ ${t}`:``} = ${Tp(Vf(n))}`:$({code:`PATH_DENIED`,message:`schema @ "${t}" 不存在`,hint:`jsonPath 需在 schema 声明字段内(用 read() 不传 jsonPath 查看顶层字段)`})},{name:`schema_data`,description:`查看主数据(或子路径)的字段约束:类型/min/max/enum/必填/默认值/嵌套 shape。写前查约束,避免写错重试。不传 jsonPath 查根;传子路径(如 components.0)查该位置约束。`,schema:t.z.object({jsonPath:t.z.string().optional().describe(`要查约束的子路径;不传查根 schema`)})}),H=(0,r.tool)(async({snapshotId:e,against:t})=>{let n=t!=null,r,i;if(n){let e=t;if(typeof e==`string`){let t=Sp(e);t.parseError||(e=t.parsed)}r=e,i=`against`}else{if(!m.length)return $({code:`NO_SNAPSHOT`,message:`无快照可对比`,hint:`set/edit/delete 自动存快照;或传 against 一段 JSON 值直接对比`});let t=e===void 0?m[m.length-1]:m.find(t=>t.id===e);if(!t)return $({code:`SNAPSHOT_NOT_FOUND`,message:`未找到快照 #${e}`,hint:`不传 snapshotId 用最近一次;或传 against`});r=t.value,i=`快照 #${t.id}`}let a=l?Pf(s,o):s,c=Ip(r,bp(a));return c.length?`差异(当前 vs ${i},共 ${c.length} 处):\n${c.map(e=>` ${e.path}: ${Tp(e.from)} → ${Tp(e.to)}`).join(`
98
- `)}`:`无差异:当前主数据与 ${i} 完全相同。`},{name:`diff_data`,description:`对比当前主数据与某快照(默认最近)或一段 JSON(against)的差异,返回结构化 {path, from→to} 列表。供 verify 自纠/冲突诊断/操作审计("刚才改了啥")。snapshotId 指定快照;against 传一段 JSON 值(与 snapshotId 互斥,传则忽略快照)。`,schema:t.z.object({snapshotId:t.z.number().int().optional().describe(`对比的快照序号;不传则最近一次`),against:t.z.unknown().optional().describe(`对比的一段 JSON 值(与 snapshotId 互斥;传则忽略快照)`)})}),le=[];if(n.vfsStore){let e=n.vfsStore,i=e=>`drafts/${e}.json`,c=(0,r.tool)(({draftId:t,chunk:n,mode:r})=>{let a=i(t),o=e.files[a],s=r===`append`&&o,c=s?o.content+n:n;return e.files[a]={content:c,updatedAt:Date.now()},JSON.stringify({draftId:t,bytes:c.length,mode:s?`append`:`start`})},{name:`draft_write`,description:`分块写 JSON 草稿到 drafts 池(单次 write 受 max_tokens 限制装不下时用)。mode:"start" 新建/"append" 追加拼接;返回 {draftId,bytes} 看累计进度。累积完 draft_commit 提交;拼接不合法返回 JSON_INVALID 草稿保留。`,schema:t.z.object({draftId:t.z.string().describe(`草稿标识(自起,如 "page-gen-1")`),chunk:t.z.string().describe(`JSON 片段字符串(分块输出,append 拼接成完整 JSON;如 '{"components":[' / '{"type":"heading",...},' / ']}')`),mode:t.z.enum([`start`,`append`]).optional().describe(`start=新建/覆盖(默认);append=追加 chunk 到已有草稿`)})}),u=(0,r.tool)(async({draftId:t},n)=>{let r=v(n),c=i(t),u=e.files[c];if(!u)return $({code:`DRAFT_NOT_FOUND`,message:`草稿 "${t}" 不存在`,hint:`先 draft_write({draftId, chunk, mode:"start"}) 新建,再 append 累积分块`});let d;try{d=JSON.parse(u.content)}catch(e){return $({code:`JSON_INVALID`,message:`草稿 "${t}" 拼接后非合法 JSON: ${e.message}`,hint:`检查 chunk 拼接(逗号/括号/引号是否匹配,首尾是否闭合);草稿保留未删,可继续 draft_write 修正后重 commit`,details:{bytes:u.content.length,preview:u.content.slice(0,200)+(u.content.length>200?`…`:``)}})}let f=await te();try{let n=await ie(`set`,E?S(r):void 0,d,f);if(n!==null)return n;let i=Ag({bindRef:s,value:d,schema:o,allowKeys:l,snapshots:m,maxSnapshots:h,audit:F,op:`draft_commit`,onWrite:N,internalAfterWrite:a,protectedCtx:p,hashFn:D});return i.ok?(C(i.hash,r),delete e.files[c],`已 draft_commit 草稿 "${t}" → 主数据 = ${Tp(i.data,600)} (新 hash=${i.hash})${l?`(白名单模式:仅更新 schema 声明字段)`:``}。草稿已清理。`):i.error}finally{f.release()}},{name:`draft_commit`,description:`把 draft_write 累积的草稿合并 + JSON.parse + 乐观锁 + schema 校验,原子提交主数据(任一步失败不写,草稿保留可修后重试;成功清草稿 + 自动快照可回退)。仅大 JSON 从零生成用;小改用 write。`,schema:t.z.object({draftId:t.z.string().describe(`要提交的草稿标识(对应 draft_write 的 draftId)`)})});ae(u),le.push(c,u)}let U=[];if(e.resources?.length&&d){let e=(0,r.tool)(async({path:e,handle:t})=>{let n=e;if(!n&&t&&(n=d.get(t)?.path),!n)return $({code:`RESOURCE_NOT_FOUND`,message:`未提供 path 或有效 handle`,hint:`传 path(受保护字段)或 handle(占位符 ⟦res:handle⟧ 里的句柄)`});let r=pg(n);if(!u.has(r))return $({code:`RESOURCE_NOT_FOUND`,message:`"${n}" 不是受保护字段`,hint:`resource_get 仅查集成方在 data.resources 声明的路径`});let i=d.get(r);if(i)return Tp({path:i.path,mode:i.mode,value:i.value,handle:i.handle});let a=_p(s,r);if(a===void 0)return $({code:`RESOURCE_NOT_FOUND`,message:`字段 "${n}" 当前无值,无法注册`,hint:`该字段可能在 bind 中不存在;先 read 触发懒注册`});let o=u.get(r),c=d.ensure(r,a,o.mode);return Tp({path:r,mode:o.mode,value:a,handle:c})},{name:`resource_get`,description:`取受保护字段(freeze/verbatim)的真实值(占位符背后的精确值)。仅受保护路径(集成方在 data.resources 声明)。read 返回 ⟦frozen:path⟧/⟦res:handle⟧ 占位符,确需真值时用此工具。传 path 或 handle。`,schema:t.z.object({path:t.z.string().optional().describe(`受保护字段路径(data.resources 声明的)`),handle:t.z.string().optional().describe(`占位符 ⟦res:handle⟧ 里的句柄(与 path 二选一)`)})}),n=(0,r.tool)(async({path:e,value:t},n)=>{let r=v(n);if(!e)return $({code:`MISSING_VALUE`,message:`resource_update 需要 path`,hint:`传要更新的 verbatim 受保护字段路径`});let i=pg(e),a=u.get(i);if(!a)return $({code:`RESOURCE_NOT_FOUND`,message:`"${e}" 不是受保护字段`,hint:`resource_update 仅改 data.resources 声明的字段`});if(a.mode===`freeze`)return $({code:`FROZEN_FIELD`,message:`字段 "${e}" 已冻结,resource_update 也不可改`,hint:`冻结字段完全只读`});let c=xf(o,i);if(c){let n=c.safeParse(t);if(!n.success)return $({code:`SCHEMA_INVALID`,message:`resource_update 值不符合 "${e}" 的类型`,hint:`按字段类型传值`,details:Ll(n.error.issues)})}d.update(i,t),vp(s,i,t),C(D(),r),N();let l=d.get(i)?.handle;return`已更新 verbatim 资源 "${e}" = ${Tp(t,200)}(handle ${l??`(未知)`} 不变)。后续 write 该字段写回句柄 ⟦res:${l}⟧ 或新值`},{name:`resource_update`,description:`更新 verbatim 受保护字段的真实值(改精确原值,如刷新 token/hash)。仅 verbatim 可改;freeze 拒。更新后同步 bind + 标脏,后续 write 写回句柄即用新值。`,schema:t.z.object({path:t.z.string().describe(`要更新的 verbatim 受保护字段路径`),value:t.z.unknown().describe(`新值(需符合字段 schema 类型)`)})});ae(n);let i=(0,r.tool)(async()=>{let e=d.list();return e.length?Tp({resources:e}):`当前无已注册的受保护资源(read 受保护路径会懒注册)`},{name:`resource_list`,description:`列出所有已注册的受保护资源(path/mode/handle/bytes)。`,schema:t.z.object({})}),a=(0,r.tool)(async({path:e,handle:t})=>{let n=e;return!n&&t&&(n=d.get(t)?.path),n?d.delete(n)?`已释放资源 "${n}"(后续 read 该字段会重新懒注册)`:`资源 "${n}" 不存在(无需释放)`:$({code:`RESOURCE_NOT_FOUND`,message:`未提供 path 或有效 handle`,hint:`传要释放的受保护字段 path 或 handle`})},{name:`resource_delete`,description:`释放受保护资源(从资源池删除,后续 read 重新懒注册)。用于不再需要保护的字段或释放空间。`,schema:t.z.object({path:t.z.string().optional().describe(`要释放的受保护字段路径`),handle:t.z.string().optional().describe(`占位符句柄(与 path 二选一)`)})});ae(a),U.push(e,n,i,a)}let ue=[I,oe,se,L,R,z,ce,B,V,H,...le,...U];Object.defineProperty(ue,"controller",{value:P,enumerable:!1,configurable:!1,writable:!1});for(let e of ue)Object.defineProperty(e,"__dataOpsScoped",{value:!0,enumerable:!1,configurable:!1});return ue}var Ug=new Set([`area`,`base`,`br`,`col`,`embed`,`hr`,`img`,`input`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),Wg=new Set([`script`,`style`]);function Gg(e){let t=[],n=e.length;if(!e.trim())return t;let r=[0];for(let t=0;t<n;t++)e[t]===`
98
+ `)}`:`无差异:当前主数据与 ${i} 完全相同。`},{name:`diff_data`,description:`对比当前主数据与某快照(默认最近)或一段 JSON(against)的差异,返回结构化 {path, from→to} 列表。供 verify 自纠/冲突诊断/操作审计("刚才改了啥")。snapshotId 指定快照;against 传一段 JSON 值(与 snapshotId 互斥,传则忽略快照)。`,schema:t.z.object({snapshotId:t.z.number().int().optional().describe(`对比的快照序号;不传则最近一次`),against:t.z.unknown().optional().describe(`对比的一段 JSON 值(与 snapshotId 互斥;传则忽略快照)`)})}),le=[];if(n.vfsStore){let e=n.vfsStore,i=e=>`drafts/${e}.json`,c=(0,r.tool)(({draftId:t,chunk:n,mode:r})=>{let a=i(t),o=e.files[a],s=r===`append`&&o,c=s?o.content+n:n;return e.files[a]={content:c,updatedAt:Date.now()},JSON.stringify({draftId:t,bytes:c.length,mode:s?`append`:`start`})},{name:`draft_write`,description:`分块写 JSON 草稿到 drafts 池(单次 write 受 max_tokens 限制装不下时用)。mode:"start" 新建/"append" 追加拼接;返回 {draftId,bytes} 看累计进度。累积完 draft_commit 提交;拼接不合法返回 JSON_INVALID 草稿保留。`,schema:t.z.object({draftId:t.z.string().describe(`草稿标识(自起,如 "page-gen-1")`),chunk:t.z.string().describe(`JSON 片段字符串(分块输出,append 拼接成完整 JSON;如 '{"components":[' / '{"type":"heading",...},' / ']}')`),mode:t.z.enum([`start`,`append`]).optional().describe(`start=新建/覆盖(默认);append=追加 chunk 到已有草稿`)})}),u=(0,r.tool)(async({draftId:t},n)=>{let r=v(n),c=i(t),u=e.files[c];if(!u)return $({code:`DRAFT_NOT_FOUND`,message:`草稿 "${t}" 不存在`,hint:`先 draft_write({draftId, chunk, mode:"start"}) 新建,再 append 累积分块`});let d;try{d=JSON.parse(u.content)}catch(e){return $({code:`JSON_INVALID`,message:`草稿 "${t}" 拼接后非合法 JSON: ${e.message}`,hint:`检查 chunk 拼接(逗号/括号/引号是否匹配,首尾是否闭合);草稿保留未删,可继续 draft_write 修正后重 commit`,details:{bytes:u.content.length,preview:u.content.slice(0,200)+(u.content.length>200?`…`:``)}})}let f=await te();try{let n=await ie(`set`,E?S(r):void 0,d,f);if(n!==null)return n;let i=Ag({bindRef:s,value:d,schema:o,allowKeys:l,snapshots:m,maxSnapshots:h,audit:F,op:`draft_commit`,onWrite:N,internalAfterWrite:a,protectedCtx:p,hashFn:D});return i.ok?(C(i.hash,r),delete e.files[c],`已 draft_commit 草稿 "${t}" → 主数据 = ${Tp(i.data,600)} (新 hash=${i.hash})${l?`(白名单模式:仅更新 schema 声明字段)`:``}。草稿已清理。`):i.error}finally{f.release()}},{name:`draft_commit`,description:`把 draft_write 累积的草稿合并 + JSON.parse + 乐观锁 + schema 校验,原子提交主数据(任一步失败不写,草稿保留可修后重试;成功清草稿 + 自动快照可回退)。仅大 JSON 从零生成用;小改用 write。`,schema:t.z.object({draftId:t.z.string().describe(`要提交的草稿标识(对应 draft_write 的 draftId)`)})});ae(u),le.push(c,u)}let U=[];if(e.resources?.length&&d){let e=(0,r.tool)(async({path:e,handle:t})=>{let n=e;if(!n&&t&&(n=d.get(t)?.path),!n)return $({code:`RESOURCE_NOT_FOUND`,message:`未提供 path 或有效 handle`,hint:`传 path(受保护字段)或 handle(占位符 ⟦res:handle⟧ 里的句柄)`});let r=pg(n);if(!u.has(r))return $({code:`RESOURCE_NOT_FOUND`,message:`"${n}" 不是受保护字段`,hint:`resource_get 仅查集成方在 data.resources 声明的路径`});let i=d.get(r);if(i)return Tp({path:i.path,mode:i.mode,value:i.value,handle:i.handle});let a=_p(s,r);if(a===void 0)return $({code:`RESOURCE_NOT_FOUND`,message:`字段 "${n}" 当前无值,无法注册`,hint:`该字段可能在 bind 中不存在;先 read 触发懒注册`});let o=u.get(r),c=d.ensure(r,a,o.mode);return Tp({path:r,mode:o.mode,value:a,handle:c})},{name:`resource_get`,description:`取受保护字段(freeze/verbatim)的真实值(占位符背后的精确值)。仅受保护路径(集成方在 data.resources 声明)。read 返回 ⟦frozen:path⟧/⟦res:handle⟧ 占位符,确需真值时用此工具。传 path 或 handle。`,schema:t.z.object({path:t.z.string().optional().describe(`受保护字段路径(data.resources 声明的)`),handle:t.z.string().optional().describe(`占位符 ⟦res:handle⟧ 里的句柄(与 path 二选一)`)})}),n=(0,r.tool)(async({path:e,value:t},n)=>{let r=v(n);if(!e)return $({code:`MISSING_VALUE`,message:`resource_update 需要 path`,hint:`传要更新的 verbatim 受保护字段路径`});let i=pg(e),a=u.get(i);if(!a)return $({code:`RESOURCE_NOT_FOUND`,message:`"${e}" 不是受保护字段`,hint:`resource_update 仅改 data.resources 声明的字段`});if(a.mode===`freeze`)return $({code:`FROZEN_FIELD`,message:`字段 "${e}" 已冻结,resource_update 也不可改`,hint:`冻结字段完全只读`});let c=xf(o,i);if(c){let n=c.safeParse(t);if(!n.success)return $({code:`SCHEMA_INVALID`,message:`resource_update 值不符合 "${e}" 的类型`,hint:`按字段类型传值`,details:Ll(n.error.issues)})}d.update(i,t),vp(s,i,t),C(D(),r),N();let l=d.get(i)?.handle;return`已更新 verbatim 资源 "${e}" = ${Tp(t,200)}(handle ${l??`(未知)`} 不变)。后续 write 该字段写回句柄 ⟦res:${l}⟧ 或新值`},{name:`resource_update`,description:`更新 verbatim 受保护字段的真实值(改精确原值,如刷新 token/hash)。仅 verbatim 可改;freeze 拒。更新后同步 bind + 标脏,后续 write 写回句柄即用新值。`,schema:t.z.object({path:t.z.string().describe(`要更新的 verbatim 受保护字段路径`),value:t.z.unknown().describe(`新值(需符合字段 schema 类型)`)})});ae(n);let i=(0,r.tool)(async()=>{let e=d.list();if(!e.length){let e=[...p.resourcesByPath.entries()].filter(([,e])=>e.mode===`freeze`).map(([e])=>e);return e.length?`资源池为空,但集成方静态配置了 freeze 只读字段:${e.join(`、 `)}(freeze 无句柄、不可释放;resource_delete 仅对 verbatim 生效)`:`当前无已注册的受保护资源(read 受保护路径会懒注册)`}return Tp({resources:e})},{name:`resource_list`,description:`列出所有已注册的受保护资源(path/mode/handle/bytes)。`,schema:t.z.object({})}),a=(0,r.tool)(async({path:e,handle:t})=>{let n=e;return!n&&t&&(n=d.get(t)?.path),n?d.delete(n)?`已释放资源 "${n}"(后续 read 该字段会重新懒注册)`:p.resourcesByPath.get(n)?.mode===`freeze`?$({code:`FROZEN_FIELD`,message:`字段 "${n}" 为 freeze 静态保护(不在资源池、无句柄、不可释放)`,hint:`freeze 由集成方在 data.resources 静态配置,只读不可解;含冻结字段的元素无法整体删除,请保留该元素或由集成方调整 data.resources`}):`资源 "${n}" 不存在(无需释放)`:$({code:`RESOURCE_NOT_FOUND`,message:`未提供 path 或有效 handle`,hint:`传要释放的受保护字段 path 或 handle`})},{name:`resource_delete`,description:`释放受保护资源(从资源池删除,后续 read 重新懒注册)。用于不再需要保护的字段或释放空间。`,schema:t.z.object({path:t.z.string().optional().describe(`要释放的受保护字段路径`),handle:t.z.string().optional().describe(`占位符句柄(与 path 二选一)`)})});ae(a),U.push(e,n,i,a)}let ue=[I,oe,se,L,R,z,ce,B,V,H,...le,...U];Object.defineProperty(ue,"controller",{value:P,enumerable:!1,configurable:!1,writable:!1});for(let e of ue)Object.defineProperty(e,"__dataOpsScoped",{value:!0,enumerable:!1,configurable:!1});return ue}var Ug=new Set([`area`,`base`,`br`,`col`,`embed`,`hr`,`img`,`input`,`link`,`meta`,`param`,`source`,`track`,`wbr`]),Wg=new Set([`script`,`style`]);function Gg(e){let t=[],n=e.length;if(!e.trim())return t;let r=[0];for(let t=0;t<n;t++)e[t]===`
99
99
  `&&r.push(t+1);let i=e=>{let t=0,n=r.length-1;for(;t<n;){let i=t+n+1>>1;r[i]<=e?t=i:n=i-1}return t+1},a=[],o=0;for(;o<n;){let r=e.indexOf(`<`,o);if(r<0)break;if(e.startsWith(`<!--`,r)){let n=e.indexOf(`-->`,r+4);if(n<0){t.push({line:i(r),code:`UNCLOSED_COMMENT`,message:`注释 <!-- 未闭合(缺 -->)`});break}o=n+3;continue}if(e[r+1]===`!`){let t=e.indexOf(`>`,r);o=t<0?n:t+1;continue}let s=e[r+1]===`/`,c=s?r+2:r+1,l=e[c]??``;if(!/[a-zA-Z]/.test(l)){o=r+1;continue}let u=c,d=``;for(;u<n;){let t=e[u];if(d)t===d&&(d=``);else if(t===`"`||t===`'`)d=t;else if(t===`>`)break;u++}if(u>=n){t.push({line:i(r),code:`UNCLOSED_TAG`,message:`标签 ${e.slice(r,Math.min(r+20,n))} 未写完(缺 >)`});break}let f=e.slice(c,u),p=(f.match(/^[a-zA-Z][a-zA-Z0-9-]*/)??[``])[0].toLowerCase(),m=!s&&/\/\s*$/.test(f);if(o=u+1,p){if(s){let e=a.length-1;if(e>=0&&a[e].name===p)a.pop();else{let e=a.findIndex(e=>e.name===p);if(e>=0){let n=a.splice(e);for(let e of n.slice(1))t.push({line:i(e.idx),code:`UNCLOSED_TAG`,message:`<${e.name}> 未闭合(先遇到 </${p}>)`})}else t.push({line:i(r),code:`STRAY_CLOSE_TAG`,message:`</${p}> 无匹配的开标签`})}continue}if(!(Ug.has(p)||m)){if(Wg.has(p)){let n=RegExp(`</${p}\\s*>`,`i`).exec(e.slice(o));if(!n){t.push({line:i(r),code:`UNCLOSED_TAG`,message:`<${p}> 未闭合(缺 </${p}>)`});break}o+=n.index+n[0].length;continue}a.push({name:p,idx:r})}}}for(let e of a)t.push({line:i(e.idx),code:`UNCLOSED_TAG`,message:`<${e.name}> 未闭合`});return t}var Kg=`__pgTouched`,qg=`__pgFinalText`,Jg=`__pgCodeHashes`,Yg=`__pgKeepExternal`,Xg=`__pgNotes`,Zg=200;function Qg(e){let t=[];for(let n of e.split(`
100
100
  `)){let e=n.match(/^\s*[-*]?\s*\[note\]\s*(.*)$/i);e&&e[1].trim()&&t.push(`[note] `+e[1].trim())}return[...new Set(t)]}function $g(e,t){let n=Array.isArray(e[Xg])?e[Xg].filter(e=>typeof e==`string`):[];e[Xg]=[...new Set([...n,...t])].map(e=>e.length>Zg?e.slice(0,Zg)+`…`:e).slice(-5)}function e_(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return(t>>>0).toString(16)}function t_(e,t){let n=[];return r_(e,t,e=>{typeof e.name==`string`&&e.name&&n.push(e.name)}),n}function n_(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length),r=n.lastIndexOf(`.`);return(r>0?n.slice(0,r):r===0?``:n)||null}function r_(e,t,n){if(!(!e||typeof e!=`object`))for(let r of t){let t=_p(e,r);if(Array.isArray(t))for(let e=0;e<t.length;e++){let i=t[e];i&&typeof i==`object`&&typeof i.__pgId==`string`&&n(i,r,e)}}}function i_(e,t,n){let r=new Set;if(!e||typeof e!=`object`)return r;for(let i of t){let t=_p(e,i);if(Array.isArray(t))for(let e=0;e<t.length;e++){let a=t[e];if(!a||typeof a!=`object`)continue;let o=a.__pgId;if(typeof o!=`string`)continue;let s=`${i}.${e}`;for(let e of n)if(e.path===s||e.path.startsWith(s+`.`)){r.add(o);break}}}return r}function a_(e){let{writablePaths:t,codeVfsPrefix:n,ext:r,codeField:i=`code`,onWarning:a,getController:o,vfsStore:s,craftNotes:c=!0}=e,l=s,u=l.__pgLastCheckout??=new Map,d=l.__pgPendingRetry??=new Set;return{name:`code-asset-checkout-commit`,beforeAgent:e=>{let c=o()?.get?.().bind;c&&Bg(c,t);let l=0,f=0,p=new Map;if(r_(c,t,e=>{l++;let t=_p(e,i);if(typeof t==`string`){f++;let i=e.__pgId,a=e_(t);p.set(i,a);let o=`${n}${i}.${r}`,c=s.files[o],l=u.get(i);c&&typeof c.content==`string`&&c.content!==t&&l===a?d.add(o):(s.files[o]={content:t,updatedAt:Date.now()},d.delete(o)),u.set(i,a)}}),l>0&&f===0&&a){let e=``;for(let n of t){let t=_p(c,n);if(Array.isArray(t)&&t.length){e=Object.keys(t[0]??{}).join(`,`);break}}a(`codeField '${i}' 在当前 ${l} 个组件中均未命中 string 值。组件实际字段:[${e}]。若预期有代码组件请核对 codeField 路径;若当前确无代码组件可忽略。`)}return{files:s.files,[Kg]:new Set,[qg]:{text:``},[Jg]:p,[Yg]:[]}},wrapModelCall:async(e,t)=>{let n=await t(e),r=e.state[qg];return r&&!(n.toolCalls&&n.toolCalls.length)&&typeof n.content==`string`&&n.content&&(r.text=n.content),n},augmentPrompt:()=>{let e=o()?.get?.().bind,i=[],a=0;if(r_(e,t,(e,t,o)=>{a++;let l=typeof e.name==`string`&&e.name?e.name:``,u=l?`${l} [${o}]`:`(未命名 [${o}])`,d=`${n}${e.__pgId}.${r}`,f=!!s.files[d];if(i.push(`- ${u} → ${d}${f?``:`(尚未检出,先 vfs_write 创建)`}`),c){let t=Array.isArray(e[Xg])?e[Xg].filter(e=>typeof e==`string`):[];if(t.length){let e=t[t.length-1];i.push(` 📝 笔记×${t.length}(最近):${e.length>120?e.slice(0,120)+`…`:e}`)}}}),!i.length)return;let l=``;for(let n of t){let t=_p(e,n);if(Array.isArray(t)){l=`\n新建组件追加索引:write({patch:{op:'set',jsonPath:'${n}.${t.length}',value:{...}}})(当前共 ${t.length} 个,勿覆盖已有索引)`;break}}return`## 组件代码文件地图(改组件时按 name 直接改对应 vfs 文件;框架自动 checkout/commit)${c?`
101
101
  📝 笔记 = 前任维护者交接(设计决策/用户反馈/踩坑),改该组件时遵循;收口回复末行必须附一行 [note] 交接笔记(本组件本次的实现要点),框架存进组件转交下任`:``}\n${i.join(`
@@ -150,6 +150,7 @@ ${`- 输出形态:完整、自包含的 HTML 页面(.${r},可独立成页)`}
150
150
  - **机械决定一次定**:写法选择(read 回读 vs 复制、vfs 草稿 vs 直写 data、并行 vs 串行)快速选一个,**不在思考里反复权衡 token 成本**(为之纠结反更费 token)。
151
151
  - **禁止在思考里整段写出完整代码草稿**:CSS/JS/HTML 代码只写进 write / vfs_write / vfs_edit 工具调用(代码只出现一次);思考里只做高层设计(结构 / 字段 / 方案选择),不要先逐行预写一遍代码再在工具里重复一遍 —— 那会让代码 token 翻倍。
152
152
  - **终稿纪律(一次写成)**:动手前要点清单一次定稿(≤10 条:结构 + DOM 分层/z-index + 关键尺寸 + 动画时序),清单齐了**直接在工具调用里写终稿**;① 不先写一版再推翻重写第二版(整段重写 = 代码 token 翻倍,写前多花 30 秒把清单想齐);② 同一几何/层级约束(bottom 定位/遮挡/z-index)**只推演一次**,不重复推导第二遍;③ 写完发现小问题(遮挡/重叠/命名),只改那一处,不重写整段。
153
+ - **大段 code 分块写(超长代码硬约束)**:预计 code 超过 ~8K 字符时,**一次工具调用装不下会被 max_tokens 掐断** —— 必须分块:① 首块用 write 把组件连同 code 第一段写入(如 code 写到 CSS 中段即止);② 后续每段用 write({op:'append', jsonPath:'${n}.N.${t}', value:'下一段文本'}) 逐块尾接(每块 ≤4K 字符);③ 全部拼完再 validate_code。**禁止**在任何一次调用里塞完整超长代码(截断 = 静默失败重来,token 全废)。
153
154
  - **代码字符串不纠结转义**:代码字段(${t})/ content 参数就是普通字符串,直接写完整代码文本(换行、引号照常写),不要纠结「\n」转义、单双引号、字面换行会不会被拒 —— 框架自动序列化,反复权衡纯属浪费 token。
154
155
  - 一次想清楚 → 动手 → 验证 → 收口。**思考是手段不是目的,产出代码才是**。
155
156
  8. **收口格式(必守,最后一行)**:收口回复 = 简短结果总结 + **末行交接笔记** \`[note] <一句话实现要点>\` —— 关键设计决策 / 用户偏好 / 踩坑(如「[note] 液面用 height keyframes 4.2s 循环;装饰仅灯串+光斑 2 类」)。框架只识别末尾 [note] 行存进组件、自动转交下次维护该组件的子 agent;**漏写 = 下任失去交接**(真 LLM 实测漏写率 3/4,务必末行带上)。一行内,只写可复用结论。`}function R_(e,t){return`# HTML 完整页面生成规范
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "page-agent-sdk",
3
- "version": "4.1.0",
3
+ "version": "4.2.0",
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",