pi-webapp 0.1.50-alpha.2 → 0.1.50-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -5
- package/README.zh-CN.md +6 -3
- package/bin/pi-webapp.mjs +31 -7
- package/dist/extension.js +37 -36
- package/dist/hosted-recovery.js +3 -3
- package/dist/hosted-worker.js +2 -2
- package/docs/hosted-plugin-capabilities-rfc.md +43 -0
- package/package.json +7 -2
- package/web/dist/.vite/manifest.json +23 -23
- package/web/dist/assets/{app-BCc73x1M.js → app-BJZp9fzs.js} +113 -113
- package/web/dist/assets/app.css +1 -1
- package/web/dist/assets/app.js +5 -5
- package/web/dist/assets/{graphql-vEnFKzjg.js → graphql-ByZADDg2.js} +1 -1
- package/web/dist/assets/{http-CeYYFWcL.js → http-BNF1v2Jw.js} +1 -1
- package/web/dist/assets/{php-C05k039N.js → php-Dtpd38gN.js} +1 -1
- package/web/dist/assets/{plugin-BgIIxh_k.js → plugin-BoCMlbKP.js} +3 -3
- package/web/dist/assets/{plugin-DxpxZUGw.js → plugin-CnfAnxxc.js} +1 -1
- package/web/dist/assets/{plugin-DQjHRCDC.js → plugin-TlpBE8U3.js} +1 -1
- package/web/dist/assets/{rst-DSmsFEQN.js → rst-B2l40om9.js} +1 -1
- package/web/dist/assets/{ruby-Dp1X8bwl.js → ruby-DAJL-p3N.js} +1 -1
- package/web/dist/assets/{svelte-Dv-h3tqQ.js → svelte-CuOeLcsF.js} +1 -1
- package/web/dist/assets/{vue-ctM4ZqX0.js → vue-DgHuJHRN.js} +1 -1
package/dist/extension.js
CHANGED
|
@@ -1,48 +1,49 @@
|
|
|
1
|
-
(function(){try{var n=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="1d0c0dfd-8f19-462d-8d5a-7145c52e84a7",n._sentryDebugIdIdentifier="sentry-dbid-1d0c0dfd-8f19-462d-8d5a-7145c52e84a7")}catch{}})();import{delimiter as vp,dirname as bp,join as mt,resolve as yt}from"node:path";import{readFileSync as kp,realpathSync as Pi,watch as Pp}from"node:fs";import{fileURLToPath as Ip}from"node:url";import{DefaultPackageManager as ko,getAgentDir as Ae,ModelRuntime as Ep,SessionManager as Po,SettingsManager as Sp,VERSION as Ii}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as xp}from"@earendil-works/pi-ai";import{randomBytes as ts,randomUUID as Lr,timingSafeEqual as Sc}from"node:crypto";import{readFile as xc,readdir as _c}from"node:fs/promises";import{createServer as Tc}from"node:http";import{join as Ur}from"node:path";import{getAgentDir as Ac}from"@earendil-works/pi-coding-agent";import{isAbsolute as ra,relative as ia}from"node:path";var Ze={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var _i={id:Ze.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as To}from"node:child_process";import{realpath as Ao}from"node:fs/promises";import{isAbsolute as Ti,relative as Ro,sep as Co,win32 as No}from"node:path";var A=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function F(n,e,t=2*1024*1024,r={}){let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,o)=>{let a,c=To("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:n,env:{...i,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,f)=>{if(!l){if(a){o(new A("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let h=l.killed||l.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(f)?"index_locked":/already exists/i.test(f)?"branch_exists":/already checked out|used by worktree/i.test(f)?"branch_in_use":/would be overwritten|local changes/i.test(f)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(f)?"identity_missing":"git_failed";o(new A("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",h==="outcome_unknown"?503:409,h));return}let u=l.code;u==="ENOENT"?o(new A("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):u==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new A("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(f)?o(new A("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new A(l.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});c.stdin?.on("error",l=>{a=l}),r.input!==void 0&&c.stdin?.end(r.input)})}async function Ce(n){let e=await Ao(n),t;try{t=(await F(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(i){if(i instanceof A&&i.status===404)return{kind:"not-repository"};if(i instanceof A&&i.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw i}let r=Ro(t,e).split(Co).join("/");if(r===".."||r.startsWith("../")||Ti(r))throw new A("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function Fe(n){if(typeof n!="string"||!n||n.length>4096||n.includes("\0")||n.includes("\\")||Ti(n)||No.isAbsolute(n)||n.split("/").some(e=>!e||e==="."||e===".."))throw new A("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as Uo}from"node:crypto";import{lstat as Or,realpath as Li}from"node:fs/promises";import{dirname as Bi,isAbsolute as zo,relative as qo,resolve as bt}from"node:path";import{lstat as Fo}from"node:fs/promises";import{resolve as Bo}from"node:path";import{constants as et}from"node:fs";import{open as Ni,opendir as Oo,realpath as Ai,stat as Rr}from"node:fs/promises";import{isAbsolute as Oi,relative as Ho,resolve as Do,sep as Mo,win32 as jo}from"node:path";var Wo=1e3,Vo=512*1024,Hi=8*1024*1024,Ri=1e4,$o=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),z=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function Ci(n,e){let t=Ho(n,e);return t!==".."&&!t.startsWith(`..${Mo}`)&&!Oi(t)}async function Ft(n,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||Oi(e)||jo.isAbsolute(e))throw new z("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Ai(n),r=Do(t,e);if(!Ci(t,r))throw new z("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let i=await Ai(r);if(!Ci(t,i))throw new z("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return i}async function Cr(n){try{return await n()}catch(e){if(e instanceof z)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new z("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new z("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function Di(n,e){return Cr(async()=>{let t=await Ft(n,e),r=[],i=!1;for await(let s of await Oo(t)){if(r.length===Wo){i=!0;break}let o=e?`${e}/${s.name}`:s.name,a=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let c=await Rr(await Ft(n,o));a=c.isDirectory()?"directory":c.isFile()?"file":"other"}catch{}r.push({name:s.name,path:o,kind:a})}return r.sort((s,o)=>+(o.kind==="directory")-+(s.kind==="directory")||$o.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:r,truncated:i}})}function Mi(n){if(n.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(n[0]===255&&n[1]===216&&n[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(n.subarray(0,6).toString("ascii")))return"image/gif";if(n.subarray(0,4).toString("ascii")==="RIFF"&&n.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function vt(n,e){return Cr(async()=>{let t=await Ft(n,e);if(!(await Rr(t)).isFile())throw new z("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Ni(t,et.O_RDONLY|et.O_NONBLOCK|(et.O_NOFOLLOW??0));try{let i=await r.stat();if(!i.isFile())throw new z("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let s={path:e,size:i.size},o=Buffer.alloc(16);await r.read(o,0,o.length,0);let a=Mi(o),c=a?Hi:Vo;if(i.size>c)return{...s,kind:"too-large",limit:c,unit:"bytes"};let l=Buffer.alloc(Math.min(i.size+1,c+1)),p=0;for(;p<l.length;){let{bytesRead:h}=await r.read(l,p,l.length-p,p);if(!h)break;p+=h}if(p>i.size)throw new z("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let f=l.subarray(0,p);if(a)return{...s,kind:"image",mimeType:a,data:f.toString("base64")};if(f.some(h=>h===0||h<32&&![9,10,12,13,27].includes(h)))return{...s,kind:"unsupported"};let u=1;for(let h=0;h<f.length-1;h++)if(f[h]===10&&++u>Ri)return{...s,kind:"too-large",limit:Ri,unit:"lines"};try{return{...s,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(f)}}catch{return{...s,kind:"unsupported"}}}finally{await r.close()}})}async function ji(n,e){return Cr(async()=>{let t=await Ft(n,e);if(!(await Rr(t)).isFile())throw new z("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Ni(t,et.O_RDONLY|et.O_NONBLOCK|(et.O_NOFOLLOW??0));try{let i=await r.stat();if(!i.isFile())throw new z("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(i.size>Hi)throw new z("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(i.size+1),o=0;for(;o<s.length;){let{bytesRead:l}=await r.read(s,o,s.length-o,o);if(!l)break;o+=l}if(o>i.size)throw new z("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let a=s.subarray(0,o),c=Mi(a);if(!c)throw new z("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:c,bytes:a}}finally{await r.close()}})}var Lo=1e3,Wi=512*1024,Vi=1e4;function $i(n,e){return e.startsWith(n)&&e.slice(n.length)||void 0}async function tt(n){let e=await Ce(n);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,i=await F(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:t,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=i.split("\0");for(let a=0;a<o.length;a++){let c=o[a];if(c.startsWith("# branch.oid ")){let I=c.slice(13);s.head=I==="(initial)"?null:I;continue}if(c.startsWith("# branch.head ")){let I=c.slice(14);s.branch=I==="(detached)"?null:I;continue}if(c.startsWith("# branch.upstream ")){s.upstream=c.slice(18);continue}if(c.startsWith("# branch.ab ")){let I=c.match(/\+(\d+) -(\d+)/);I&&(s.ahead=Number(I[1]),s.behind=Number(I[2]));continue}let l=c[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,f=0;for(let I=0;I<p;I++)f=c.indexOf(" ",f)+1;let u=$i(r,c.slice(f)),h=l==="2"?o[++a]:void 0;if(!u)continue;if(s.entries.length===Lo){s.truncated=!0;continue}let g=c.slice(0,f).split(" "),v={path:u,index:l==="?"?"?":g[1][0],worktree:l==="?"?"?":g[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&g[2]!=="N..."},x=h===void 0?void 0:$i(r,h);x&&(v.originalPath=x),s.entries.push(v)}return s}async function Fi(n,e,t){if(Fe(e),!["staged","unstaged","untracked"].includes(t))throw new A("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await tt(n);if(r.kind!=="repository")throw new A("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i={path:e,area:t},s=r.entries.find(a=>a.path===e);if(!s)return{...i,kind:"empty"};if(s.conflict)return{...i,kind:"conflict"};if(s.submodule)return{...i,kind:"submodule"};if(t==="untracked"){if(!s.untracked)return{...i,kind:"empty"};if(!(await Fo(Bo(n,e))).isFile())return{...i,kind:"unsupported"};let a=await vt(n,e);if(a.kind==="too-large")return{...i,kind:"too-large"};if(a.kind!=="text")return{...i,kind:"binary"};if(!a.text)return{...i,kind:"empty"};let c=a.text.split(`
|
|
2
|
-
`),l=
|
|
1
|
+
(function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="21797faa-38d4-4a0e-a037-226896d3ebe4",s._sentryDebugIdIdentifier="sentry-dbid-21797faa-38d4-4a0e-a037-226896d3ebe4")}catch{}})();import{delimiter as rh,dirname as sh,join as Pt,resolve as St}from"node:path";import{readFileSync as nh,realpathSync as Br,watch as oh}from"node:fs";import{fileURLToPath as ah}from"node:url";import{DefaultPackageManager as sa,getAgentDir as we,ModelRuntime as ch,SessionManager as qr,SettingsManager as lh,VERSION as Ur}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as dh}from"@earendil-works/pi-ai";import{randomBytes as Pn,randomUUID as rr,timingSafeEqual as al}from"node:crypto";import{readFile as cl,readdir as ll}from"node:fs/promises";import{createServer as dl}from"node:http";import{join as sr}from"node:path";import{getAgentDir as pl}from"@earendil-works/pi-coding-agent";import{isAbsolute as Wa,relative as $a}from"node:path";var ot={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Jr={id:ot.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as da}from"node:child_process";import{realpath as pa}from"node:fs/promises";import{isAbsolute as Kr,relative as ua,sep as ha,win32 as fa}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function L(s,e,t=2*1024*1024,i={}){let r=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=da("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,env:{...r,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:i.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new R("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,i.write?"outcome_unknown":"git_failed"));return}n(p);return}if(i.write){let m=l.killed||l.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(u)?"index_locked":/already exists/i.test(u)?"branch_exists":/already checked out|used by worktree/i.test(u)?"branch_in_use":/would be overwritten|local changes/i.test(u)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(u)?"identity_missing":"git_failed";o(new R("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",m==="outcome_unknown"?503:409,m));return}let y=l.code;y==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):y==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new R("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new R("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new R(l.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});a.stdin?.on("error",l=>{c=l}),i.input!==void 0&&a.stdin?.end(i.input)})}async function De(s){let e=await pa(s),t;try{t=(await L(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(r){if(r instanceof R&&r.status===404)return{kind:"not-repository"};if(r instanceof R&&r.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw r}let i=ua(t,e).split(ha).join("/");if(i===".."||i.startsWith("../")||Kr(i))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function qe(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||Kr(s)||fa.isAbsolute(s)||s.split("/").some(e=>!e||e==="."||e===".."))throw new R("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as xa}from"node:crypto";import{lstat as Gi,realpath as ds}from"node:fs/promises";import{dirname as ls,isAbsolute as _a,relative as Aa,resolve as xt}from"node:path";import{lstat as Ia}from"node:fs/promises";import{resolve as Sa}from"node:path";import{constants as at}from"node:fs";import{open as Zr,opendir as ga,realpath as Xr,stat as Li}from"node:fs/promises";import{isAbsolute as es,relative as ma,resolve as wa,sep as ya,win32 as va}from"node:path";var ba=1e3,ka=512*1024,ts=8*1024*1024,Yr=1e4,Pa=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),J=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function Qr(s,e){let t=ma(s,e);return t!==".."&&!t.startsWith(`..${ya}`)&&!es(t)}async function Kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||es(e)||va.isAbsolute(e))throw new J("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Xr(s),i=wa(t,e);if(!Qr(t,i))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let r=await Xr(i);if(!Qr(t,r))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return r}async function zi(s){try{return await s()}catch(e){if(e instanceof J)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new J("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new J("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function is(s,e){return zi(async()=>{let t=await Kt(s,e),i=[],r=!1;for await(let n of await ga(t)){if(i.length===ba){r=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await Li(await Kt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}i.push({name:n.name,path:o,kind:c})}return i.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Pa.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:i,truncated:r}})}function rs(s){if(s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(s.subarray(0,6).toString("ascii")))return"image/gif";if(s.subarray(0,4).toString("ascii")==="RIFF"&&s.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Et(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n={path:e,size:r.size},o=Buffer.alloc(16);await i.read(o,0,o.length,0);let c=rs(o),a=c?ts:ka;if(r.size>a)return{...n,kind:"too-large",limit:a,unit:"bytes"};let l=Buffer.alloc(Math.min(r.size+1,a+1)),p=0;for(;p<l.length;){let{bytesRead:m}=await i.read(l,p,l.length-p,p);if(!m)break;p+=m}if(p>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let u=l.subarray(0,p);if(c)return{...n,kind:"image",mimeType:c,data:u.toString("base64")};if(u.some(m=>m===0||m<32&&![9,10,12,13,27].includes(m)))return{...n,kind:"unsupported"};let y=1;for(let m=0;m<u.length-1;m++)if(u[m]===10&&++y>Yr)return{...n,kind:"too-large",limit:Yr,unit:"lines"};try{return{...n,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(u)}}catch{return{...n,kind:"unsupported"}}}finally{await i.close()}})}async function ss(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(r.size>ts)throw new J("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(r.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await i.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=rs(c);if(!a)throw new J("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:c}}finally{await i.close()}})}var Ea=1e3,ns=512*1024,os=1e4;function as(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function ct(s){let e=await De(s);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,r=await L(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=r.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);n.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);n.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(n.ahead=Number(P[1]),n.behind=Number(P[2]));continue}let l=a[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,u=0;for(let P=0;P<p;P++)u=a.indexOf(" ",u)+1;let y=as(i,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!y)continue;if(n.entries.length===Ea){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),w={path:y,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},k=m===void 0?void 0:as(i,m);k&&(w.originalPath=k),n.entries.push(w)}return n}async function cs(s,e,t){if(qe(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await ct(s);if(i.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r={path:e,area:t},n=i.entries.find(c=>c.path===e);if(!n)return{...r,kind:"empty"};if(n.conflict)return{...r,kind:"conflict"};if(n.submodule)return{...r,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...r,kind:"empty"};if(!(await Ia(Sa(s,e))).isFile())return{...r,kind:"unsupported"};let c=await Et(s,e);if(c.kind==="too-large")return{...r,kind:"too-large"};if(c.kind!=="text")return{...r,kind:"binary"};if(!c.text)return{...r,kind:"empty"};let a=c.text.split(`
|
|
2
|
+
`),l=a.at(-1)==="";l&&a.pop();let p=`--- /dev/null
|
|
3
3
|
+++ b/${e.replace(/[\r\n]/g," ")}
|
|
4
|
-
@@ -0,0 +1,${
|
|
5
|
-
${
|
|
4
|
+
@@ -0,0 +1,${a.length} @@
|
|
5
|
+
${a.map(u=>`+${u}`).join(`
|
|
6
6
|
`)}
|
|
7
7
|
${l?"":`\
|
|
8
|
-
`}`;return Buffer.byteLength(p)>
|
|
9
|
-
`).length>
|
|
10
|
-
`).filter(Boolean).map(
|
|
11
|
-
`).filter(Boolean)){let[
|
|
12
|
-
`).length>1e4?{...
|
|
13
|
-
`).slice(1,31).map(
|
|
14
|
-
${
|
|
15
|
-
`)}`}else
|
|
16
|
-
${
|
|
8
|
+
`}`;return Buffer.byteLength(p)>ns||a.length>os?{...r,kind:"too-large"}:{...r,kind:"text",patch:p}}if(n.untracked||(t==="staged"?n.index:n.worktree)===".")return{...r,kind:"empty"};let o=t==="staged"&&n.originalPath?[e,n.originalPath]:[e];try{let c=await L(s,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],ns);return c?c.split(`
|
|
9
|
+
`).length>os?{...r,kind:"too-large"}:/^Binary files /m.test(c)?{...r,kind:"binary"}:{...r,kind:"text",patch:c}:{...r,kind:"empty"}}catch(c){if(c instanceof R&&c.status===413)return{...r,kind:"too-large"};throw c}}var qi=new Set,z=(s,e=409)=>{throw new R("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,s)};async function Ta(s){return ds(xt(s,(await L(s,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Ji(s,e,t=!1){let i=null;try{let r=await De(s);r.kind==="repository"&&(i=await Ta(r.cwd))}catch(r){if(!t)throw r}if(!i)return e();if(qi.has(i))return z("busy");qi.add(i);try{return await e()}finally{qi.delete(i)}}async function Xt(s){let e=await De(s),t={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return t;let i=await ct(e.root);if(i.kind!=="repository")return t;let[r,n,o]=await Promise.all([L(e.cwd,["ls-files","--stage","-z"]),L(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),L(e.cwd,["rev-parse","--absolute-git-dir"])]),c=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],a=(await Promise.all(c.map(async m=>{try{return await Gi(xt(o.replace(/\n$/,""),m)),m}catch(f){if(f.code==="ENOENT")return null;throw f}}))).filter(Boolean),l=await Promise.all(i.entries.map(async m=>{try{let f=await Gi(xt(e.root,m.path));return[m.path,f.size,f.mtimeMs,f.ctimeMs,f.ino,f.mode]}catch(f){if(["ENOENT","ENOTDIR"].includes(f.code??""))return[m.path,"missing"];throw f}})),p=n.split(`
|
|
10
|
+
`).filter(Boolean).map(m=>{let[f,,w]=m.split("\0");return{name:f,current:f===i.branch,occupied:!!w&&f!==i.branch}}),u=i.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||i.entries.some(m=>m.conflict)?"operation_in_progress":null,y=xa("sha256").update(JSON.stringify({head:i.head,branch:i.branch,index:r,refs:n,entries:i.entries,files:l,present:a})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:i.head,branch:i.branch,version:y,staged:i.entries.filter(m=>!m.untracked&&m.index!==".").length,dirty:i.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function Ra(s,e){qe(e);let t=ls(xt(s.cwd,e));for(;;)try{let n=await ds(t),o=Aa(s.cwd,n);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||_a(o))return z("invalid_path",403);break}catch(n){if(n.code!=="ENOENT")throw n;t=ls(t)}let i=await ct(s.cwd),r=i.kind==="repository"?i.entries.find(n=>n.path===e):void 0;if(!r||r.submodule||r.conflict)return z("invalid_path",400);try{let n=await Gi(xt(s.cwd,e));if(!n.isFile()&&!n.isSymbolicLink())return z("invalid_path",400)}catch(n){if(n.code!=="ENOENT")throw n}return r}async function ps(s,e,t){let i=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(i)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new R("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Ji(s,async()=>{let r=await De(s);if(r.kind!=="repository")return z("invalid_path",404);t(r.root);let n=await Xt(r.cwd);if(n.version!==e.expected)return z("state_changed");if(n.blocked)return z(n.blocked);let o,c;if(i==="stage"||i==="unstage"){if(typeof e.path!="string")return z("invalid_path",400);let p=await Ra(r,e.path);if(i==="stage"&&!p.untracked&&p.worktree==="."||i==="unstage"&&(p.untracked||p.index==="."))return z("state_changed");let u=[e.path];i==="unstage"&&p.originalPath&&(qe(p.originalPath),u.push(p.originalPath)),o=i==="stage"?["add","--",...u]:n.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(i==="commit"){if(r.scope)return z("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return z("invalid_message",400);if(!n.staged)return z("nothing_staged",400);c=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!n.head)return z("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return z("invalid_branch",400);try{await L(r.cwd,["check-ref-format","--branch",e.branch])}catch{return z("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return z("invalid_branch",400);let p=n.branches.find(y=>y.name===e.branch),u=i==="switch-branch"||e.checkout===!0;if(i==="create-branch"&&p)return z("branch_exists");if(i==="switch-branch"&&(!p||p.current))return z("invalid_branch",400);if(u&&r.scope)return z("root_required",400);if(u&&n.dirty)return z("dirty_worktree");if(p?.occupied)return z("branch_in_use");o=i==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:u?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let a=await Xt(r.cwd);if(a.version!==e.expected||a.blocked)return z(a.blocked??"state_changed");t(r.root),await L(r.cwd,o,2*1024*1024,{write:!0,input:c});let l=(await L(r.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:i,head:l}})}import{createHash as Ca}from"node:crypto";var _t=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,us="%H%x00%P%x00%an%x00%aI%x00%s",hs=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function fs(s){let[e,t,i]=await Promise.all([L(s,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),L(s,["rev-parse","--verify","--quiet","HEAD"]).then(c=>c.trim(),()=>null),L(s,["symbolic-ref","-q","HEAD"]).then(c=>c.trim(),()=>null)]),r=[];for(let c of e.split(`
|
|
11
|
+
`).filter(Boolean)){let[a,l,p,u,y]=c.split("\0"),m=l==="commit"?p:u==="commit"?y:void 0;if(!m||!_t.test(m))continue;let f=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";r.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:m,kind:f})}if(r.length>512)throw new R("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let n=[...new Set([...r.map(c=>c.hash),...t&&_t.test(t)?[t]:[]])].sort(),o=Ca("sha256").update(JSON.stringify({refs:r,head:t,symbolic:i})).digest("hex");return{refs:r,tips:n,head:t,snapshot:o}}function gs(s){let[e,t,i,r,n]=s;if(!e||!_t.test(e)||!t?.split(" ").filter(Boolean).every(o=>_t.test(o)))throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:i,authoredAt:r,subject:n}}async function ms(s,e={}){let t=e.limit??50;if(!Number.isInteger(t)||t<1||t>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let i=await De(s),r={kind:i.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(i.kind!=="repository")return r;let n=await fs(i.cwd),o=0;if(e.cursor!==void 0){let u;try{u=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!u||typeof u.snapshot!="string"||!/^[a-f0-9]{64}$/.test(u.snapshot)||!Number.isInteger(u.offset)||u.offset<1||u.offset>1e4)throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(u.snapshot!==n.snapshot)throw new R("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);o=u.offset}let c={...r,root:i.root,scope:i.scope,head:n.head,snapshot:n.snapshot,refs:n.refs};if(!n.tips.length)return c;let l=(await L(i.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${us}`,`--max-count=${t+1}`,`--skip=${o}`,...n.tips,"--"])).split("\0");if(l.at(-1)===""&&l.pop(),l.length%5)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let u=0;u<l.length;u+=5)p.push(gs(l.slice(u,u+5)));return c.commits=p.slice(0,t),p.length>t&&o+t<=1e4&&(c.nextCursor=Buffer.from(JSON.stringify({snapshot:n.snapshot,offset:o+t})).toString("base64url")),c}async function ws(s,e){if(typeof e!="string"||!_t.test(e))throw new R("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await De(s);if(t.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i=await fs(t.cwd);if(!i.tips.length)throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await L(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await L(t.cwd,["rev-list","--max-count=1",e,"--not",...i.tips,"--"])).trim())throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function ys(s,e,t){if(!Number.isInteger(t)||t<0||t>=Math.max(1,e.length))throw new R("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[t],s]:[s]}async function vs(s,e,t){let r=(await L(s.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${us}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(r.at(-1)===""&&r.pop(),r.length!==10)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let n=gs(r.slice(0,5)),o=ys(e,n.parents,t),c=["diff-tree","--root","-r","--no-commit-id",...hs],[a,l]=await Promise.all([L(s.cwd,[...c,"--name-status","-z",...o,"--","."]),L(s.cwd,[...c,"--numstat","-z",...o,"--","."])]),p=new Map;for(let m of l.split("\0").filter(Boolean)){let f=m.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);f&&p.set(f[3],[f[1]==="-"?null:Number(f[1]),f[2]==="-"?null:Number(f[2])])}let u=a.split("\0");if(u.at(-1)===""&&u.pop(),u.length%2)throw new R("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let y=[];for(let m=0;m<u.length&&y.length<1e3;m+=2){let f=u[m+1],[w,k]=p.get(f)??[null,null];y.push({path:f,status:u[m],additions:w,deletions:k})}return{...n,email:r[5],committer:r[6],committerEmail:r[7],committedAt:r[8],message:r[9],root:s.root,scope:s.scope,parentIndex:t,files:y,truncated:u.length>2e3}}async function bs(s,e,t=0){return vs(await ws(s,e),e,t)}async function ks(s,e,t,i=0){qe(t);let r=await ws(s,e),n=await vs(r,e,i),o=n.files.find(a=>a.path===t);if(!o)throw new R("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let c={hash:e,path:t,parentIndex:i,parentHash:n.parents[i]??null};if(o.additions===null)return{...c,kind:"binary"};try{let a=await L(r.cwd,["diff-tree","--root","-r","--no-commit-id",...hs,"--src-prefix=a/","--dst-prefix=b/","-p",...ys(e,n.parents,i),"--",t],524288);return a.split(`
|
|
12
|
+
`).length>1e4?{...c,kind:"too-large"}:a?{...c,kind:"text",patch:a}:{...c,kind:"empty"}}catch(a){if(a instanceof R&&a.status===413)return{...c,kind:"too-large"};throw a}}var Ps=["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff"];function Is(s,e,t){if(s.endsWith("/control"))return Xt(e);if(s.endsWith("/status"))return ct(e);if(s.endsWith("/history")){if(t.limit!==void 0&&typeof t.limit!="number"||t.cursor!==void 0&&typeof t.cursor!="string")throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return ms(e,{limit:t.limit,cursor:t.cursor})}if(s.endsWith("/diff")){if(typeof t.path!="string"||!["staged","unstaged","untracked"].includes(t.area))throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return cs(e,t.path,t.area)}if(typeof t.hash!="string"||t.parentIndex!==void 0&&(!Number.isInteger(t.parentIndex)||t.parentIndex<0))throw new R("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let i=t.parentIndex;if(s.endsWith("/commit-detail"))return bs(e,t.hash,i);if(s.endsWith("/commit-diff")&&typeof t.path=="string")return ks(e,t.hash,t.path,i);throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Qt=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),Da=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Ss={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},Na=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),Ha=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function Es(s){return s==="/api/message"||s==="/api/prompt-queue"||s.startsWith("/api/provider/")||s.startsWith("/api/workspace/files/")||s.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(s)}function fe(s){return s.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function Ie(s){let e={};for(let t of Na){let i=s[t];t==="toolName"?typeof i=="string"&&(Qt.has(i)||i==="custom")&&(e[t]=i):t==="failureKind"?Da.has(i)&&(e[t]=i):t==="level"?(i==="warning"||i==="error")&&(e[t]=i):t==="diagnosticSource"?(i==="tool_execution_end"||i==="message_end")&&(e[t]=i):t==="errorCode"?typeof i=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(i)&&(e[t]=i):t==="toolId"?typeof i=="string"&&/^[a-f0-9]{16}$/.test(i)&&(e[t]=i):t==="route"&&typeof i=="string"?e[t]=Ha.has(i.split("?")[0])?i.split("?")[0]:"[route]":t==="model"&&typeof i=="string"&&/^[\w.-]+\/[\w.-]+$/.test(i)?e[t]=i.split("/").map(fe).join("/"):typeof i=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(i)?i:fe(i).slice(0,t==="errorSummary"?512:1024):(typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)||i===null)&&(e[t]=i)}return e}function Ki(s){let e=s.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function lt(s,e=0){let t=s instanceof Error?s:new Error(typeof s=="string"?s:"Non-Error rejection"),i=new Error(fe(t.message));if(i.name=fe(t.name).slice(0,100),t.stack){let r=t.stack.split(`
|
|
13
|
+
`).slice(1,31).map(n=>{let o=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${fe(n.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:fe(n)});i.stack=`${i.name}: ${i.message}
|
|
14
|
+
${r.join(`
|
|
15
|
+
`)}`}else i.stack=void 0;return e<3&&t.cause!==void 0&&(i.cause=lt(t.cause,e+1)),i}function Ne(s,e){let t=new Error(e);return s instanceof Error&&(t.name=s.name,s.stack&&(t.stack=`${t.name}: ${e}
|
|
16
|
+
${s.stack.split(`
|
|
17
17
|
`).slice(1).join(`
|
|
18
|
-
`)}`)),t}function
|
|
19
|
-
`)[1]??""}:${t.stage??""}`,
|
|
20
|
-
`).map(
|
|
21
|
-
`),!0))),p?
|
|
22
|
-
`);let l=new
|
|
23
|
-
`,{mode:384}),i(),await ya(s,this.file),this.disabled=c}finally{this.changing=!1;try{await In(s,{force:!0})}finally{a&&(await a.close(),await In(o,{force:!0}))}}}};var Gt=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===t&&!r.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!t.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>t.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,r,i){if(!this.plugins.some(s=>s.metadata.id===e))throw new X("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new X("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,r,i),t||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(i=>i.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=t.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await t.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,t,r,i,s){let o=this.plugins.find(a=>a.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new X("\u7ED8\u56FE\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new X("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(t,r,i,s)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new X("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let i=t;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let o=i;i=()=>s.coordinateStart(e,o)}try{return await i()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof X)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let r=t.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":this.plugins.map(e=>e.restartBlocker?.()).find(Boolean)??null}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as ka,opendir as Pa,stat as Ia}from"node:fs/promises";import{homedir as Ea}from"node:os";import{basename as Sa,dirname as En,join as Sn,posix as xa,resolve as xn,win32 as _a}from"node:path";function _n(n){return process.platform==="win32"?_a.isAbsolute(n)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(n):xa.isAbsolute(n)}function Ta(n,e,t){if(n.length===t&&e.name.localeCompare(n[n.length-1].name)>=0)return!0;let r=0,i=n.length;for(;r<i;){let s=r+i>>>1;e.name.localeCompare(n[s].name)<0?i=s:r=s+1}return n.splice(r,0,e),n.length<=t?!1:(n.pop(),!0)}async function Tn(n){if(n!==void 0&&!_n(n))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=Ea(),t=xn(n??e),r=[];for(let c=t;;c=En(c)){let l=En(c);if(r.unshift({name:l===c?c:Sa(c),path:c,hidden:!1}),l===c)break}let i=[],s=!1,o=await Pa(t);for await(let c of o)!c.isDirectory()&&!c.isSymbolicLink()||Ta(i,{name:c.name,isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()},1001)&&(s=!0);let a=[];for(let c of i){let l=Sn(t,c.name);if(!c.isDirectory&&c.isSymbolicLink)try{if(!(await Ia(l)).isDirectory())continue}catch{continue}if(a.length===1e3){s=!0;break}a.push({name:c.name,path:l,hidden:c.name.startsWith(".")})}return{path:t,home:e,crumbs:r,entries:a,truncated:s}}async function An(n,e){if(!_n(n))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let t=Sn(xn(n),e);return await ka(t),t}import{execFile as Aa}from"node:child_process";import{accessSync as Ra,constants as Ca}from"node:fs";import{delimiter as Na,join as Oa}from"node:path";var Ha=(n,e,t)=>new Promise((r,i)=>{Aa(n,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(s,o,a)=>{s?i(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:o,stderr:a})):r({stdout:o,stderr:a})})});function Da(n){for(let e of(n??"").split(Na))if(e)for(let t of["zenity","kdialog"])try{return Ra(Oa(e,t),Ca.X_OK),!0}catch{}return!1}function Rn(n=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":n==="darwin"||n==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&Da(e.PATH)?"native":"browse"}function Jt(n){if(!(typeof n!="object"||n===null||!("code"in n)))return typeof n.code=="string"||typeof n.code=="number"?n.code:void 0}function Ma(n){return typeof n=="object"&&n!==null&&"stderr"in n&&typeof n.stderr=="string"?n.stderr:""}function Vr(n){return n.replace(/[\r\n]+$/,"")||null}async function Cn(n,e=process.platform,t=Ha){if(e==="darwin")try{let r=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],n);return Vr(r.stdout)}catch(r){if(!n.aborted&&Jt(r)===1&&/(?:User canceled|-128)/i.test(Ma(r)))return null;throw r}if(e==="linux"){try{return Vr((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],n)).stdout)}catch(r){if(n.aborted)throw r;if(Jt(r)===1)return null;if(Jt(r)!=="ENOENT")throw r}try{return Vr((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],n)).stdout)}catch(r){if(n.aborted)throw r;if(Jt(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as ja,randomUUID as Wa}from"node:crypto";import{mkdir as Va,readFile as $a,writeFile as Fa}from"node:fs/promises";import{join as Nn}from"node:path";import{getAgentDir as Ba}from"@earendil-works/pi-coding-agent";var Kt=20*1024*1024,On=20,La=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function Ua(n){let e=n.indexOf("."),t=(e<0?n:n.slice(0,e)).replace(/[. ]+$/u,"");return La.test(t)}function za(n,e){let t=0,r="";for(let i of Buffer.from(n).toString("utf8")){let s=Buffer.byteLength(i);if(t+s>e)break;r+=i,t+=s}return r}function qa(n){if(n===void 0)return"file";let t=n.slice(Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return Ua(t)&&(t=`_${t}`),t=za(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function Ga(n){return n.length>=8&&n.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":n.length>=3&&n.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":n.length>=6&&["GIF87a","GIF89a"].includes(n.toString("ascii",0,6))?"image/gif":n.length>=12&&n.toString("ascii",0,4)==="RIFF"&&n.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function Hn(n,e,t,r){if(r.byteLength===0||r.byteLength>Kt)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let i=qa(e),s=ja("sha256").update(r).digest("hex"),o=Nn(Ba(),"pi-web","attachments",s);await Va(o,{recursive:!0});let a=Nn(o,i);try{await Fa(a,r,{flag:"wx",mode:384})}catch(c){if(!(c instanceof Error&&"code"in c&&c.code==="EEXIST"))throw c}return{id:Wa(),name:i,bytes:r.byteLength,path:a,mediaType:Ga(r)??t.replace(/^image\//,"application/"),sessionId:n}}async function Dn(n){return{type:"image",data:(await $a(n.path)).toString("base64"),mimeType:n.mediaType}}import{randomBytes as Ja}from"node:crypto";function Mn(n,e,t){return n!=="openai-codex"||e!=="oauth"?t:{...t,prompt:r=>r.type==="select"&&r.options.some(i=>i.id==="browser")&&r.options.some(i=>i.id==="device_code")?Promise.resolve("browser"):t.prompt(r)}}var Xt=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,r,i,s){let o=this.getActive();if(o){if(o.providerId===e&&o.method===t&&i===void 0)return o;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let a=Ja(18).toString("base64url"),c={view:{id:a,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(a,c),r(e,t,{signal:c.controller.signal,notify:l=>{c.view={...c.view,event:l,...l.type==="auth_url"||l.type==="device_code"?{authorization:l}:{}}},prompt:l=>{if(l.type==="secret"&&i!==void 0){let p=i;return i=void 0,Promise.resolve(p)}return new Promise((p,f)=>{let{signal:u,...h}=l;c.answer=p,c.reject=f,c.view={...c.view,status:"waiting",prompt:h},u?.aborted?f(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):u?.addEventListener("abort",()=>f(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{c.view.status!=="cancelled"&&(c.view={id:a,providerId:e,method:t,status:"done"})}).catch(l=>{if(c.view.status!=="cancelled"){let p=new Error("Provider login failed");l instanceof Error&&l.stack&&(p.stack=`${p.message}
|
|
18
|
+
`)}`)),t}function Oa(s){return{...s.filename?{filename:Ki(s.filename)}:{},...s.abs_path?{abs_path:Ki(s.abs_path)}:{},...s.function?{function:fe(s.function)}:{},lineno:s.lineno,colno:s.colno,in_app:s.in_app}}function Ma(s){let e=Ie(s.contexts?.diagnostic??{}),t=xs(e);return{event_id:s.event_id,timestamp:s.timestamp,platform:s.platform,level:s.level,release:s.release,dist:s.dist,environment:fe(s.environment??"production"),...s.message?{message:fe(s.message)}:{},exception:s.exception?{values:s.exception.values?.slice(0,4).map(i=>({type:fe(i.type??"Error"),value:fe(i.value??""),...i.stacktrace?{stacktrace:{frames:i.stacktrace.frames?.slice(-30).map(Oa)}}:{},...i.mechanism?{mechanism:{type:i.mechanism.type,handled:i.mechanism.handled}}:{}}))}:void 0,tags:{side:s.tags?.side,buildId:s.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...t?{fingerprint:t}:{},contexts:{diagnostic:e},breadcrumbs:s.breadcrumbs?.slice(-100).map(i=>({timestamp:i.timestamp,category:fe(i.category??"app"),data:Ie(i.data??{})})),debug_meta:s.debug_meta?{images:s.debug_meta.images?.slice(0,10).map(i=>({type:i.type,debug_id:i.debug_id,...i.code_file?{code_file:Ki(i.code_file)}:{}}))}:void 0}}function xs(s){if(!(s.stage!=="tool"||s.originalStackAvailable!==!1||!s.toolName||!s.failureKind))return["pi-webapp-tool-result",String(s.toolName),String(s.toolId??"builtin"),String(s.failureKind),String(s.errorCode??"unknown")]}function _s(s,e){return e.attachments=[],Ma(s)}var At=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let i={timestamp:Date.now()/1e3,category:fe(e),data:Ie(t)},r=this.encoder.encode(JSON.stringify(i)).byteLength+1;for(this.items.push({item:i,size:r}),this.bytes+=r;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},Xi=class{windowAt=-1;total=0;seen=new Map;take(e,t=Date.now()){(this.windowAt<0||t-this.windowAt>=6e4)&&(this.windowAt=t,this.total=0);let i=this.seen.get(e);if(i&&t-i.at<6e4){i.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!i&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:i?.repeats??0}}},ja=new Set(["\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0","\u4F1A\u8BDD\u5DF2\u5207\u6362","Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u4F1A\u8BDD","\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A","\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88","\u5DF2\u6709\u767B\u5F55\u6B63\u5728\u8FDB\u884C","\u6A21\u578B\u4E0D\u53EF\u7528","\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6","\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55","\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279","\u8BF7\u5148\u9009\u62E9\u6A21\u578B","\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B","\u63D2\u4EF6\u672A\u542F\u7528","\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362","\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728","\u6587\u4EF6\u8D85\u8FC7 20 MB","\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927","\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A","\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548","\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F","\u4F1A\u8BDD\u4E0D\u5B58\u5728","\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664","\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664"]);function Ge(s){return s instanceof Error&&(s.name==="AbortError"||ja.has(s.message))}var Yt=class{budget=new Xi;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,i,r,n=new At){this.client=e,this.side=t,this.buildId=i,this.scopeClass=r.Scope,this.breadcrumbs=n,e.addIntegration(r.linkedErrorsIntegration({limit:4}))}setState(e){this.state=Ie(e)}capture(e,t={},i){try{if(Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let r=lt(e),n=Ie({...this.state,...t}),o=xs(n),c=o?JSON.stringify(o):`${r.name}:${r.message}:${r.stack?.split(`
|
|
19
|
+
`)[1]??""}:${t.stage??""}`,a=this.budget.take(c);if(!a)return;let l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),n.level==="warning"&&l.setLevel("warning"),o&&l.setFingerprint(o),l.setContext("diagnostic",{...n,repeats:a.repeats});for(let p of this.breadcrumbs.snapshot())l.addBreadcrumb(p,100);return l.captureException(r,i?{event_id:i}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function As(s,e){return s({...e,bufferSize:20},async({body:t})=>{let i=await fetch(e.url,{method:"POST",body:t,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:i.status,headers:{"x-sentry-rate-limits":i.headers.get("x-sentry-rate-limits"),"retry-after":i.headers.get("retry-after")}}})}var Ts={metadata:Jr,routes:Ps,coordinateStart:(s,e)=>Ji(s,e,!0),requestFailure:s=>s instanceof R?{status:s.status,body:{error:s.message,errorCode:"validation_error",reason:s.reason}}:null,async handle({path:s,body:e,snapshot:t,busyWorkspaces:i,json:r}){let n=t();if(e.sessionId!==n.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||i().some(u=>{let y=(m,f)=>{let w=$a(m,f);return w!==".."&&!w.startsWith("../")&&!w.startsWith("..\\")&&!Wa(w)};return y(p,u)||y(u,p)}),c=p=>{let u=t();if(u.sessionId!==n.sessionId||u.cwd!==n.cwd)throw new R("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(o(p))throw new R("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},a=s.endsWith("/write"),l=a?await ps(n.cwd,e,c):await Is(s,n.cwd,e);if(!a){let p=t();if(p.sessionId!==n.sessionId||p.cwd!==n.cwd){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(s.endsWith("/control")){let u=l;u.root&&o(u.root)&&(u.blocked??="agent_busy")}}r(200,l)}catch(o){if(o instanceof R||o instanceof J)r(o.status,{error:o.message,errorCode:"validation_error",...o instanceof R?{reason:o.reason}:{}});else throw Ne(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var Rs={id:ot.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u5DE5\u4F5C\u533A\u76EE\u5F55\uFF0C\u53EA\u8BFB\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\u3002",en:"Browse workspace directories and preview code, Markdown and images read-only."}};var Cs={metadata:Rs,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw"],async handle({path:s,body:e,snapshot:t,json:i,res:r}){let n=t();if(e.sessionId!==n.sessionId){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(typeof e.path!="string"||e.path.length>4096){i(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}try{if(s.endsWith("/raw")){let a=await ss(n.cwd,e.path),l=t();if(l.sessionId!==n.sessionId||l.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r.writeHead(200,{"Content-Type":a.mimeType,"Content-Length":a.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),r.end(a.bytes);return}let o=s.endsWith("/list")?await is(n.cwd,e.path):await Et(n.cwd,e.path),c=t();if(c.sessionId!==n.sessionId||c.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}i(200,o)}catch(o){if(o instanceof J)i(o.status,{error:o.message,errorCode:"validation_error"});else throw Ne(o,"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var Ds={id:ot.terminal,kind:"builtin",version:"1.0.0",name:{zh:"\u7EC8\u7AEF",en:"Terminal"},description:{zh:"\u5728\u5DE5\u4F5C\u533A\u8FD0\u884C\u4EA4\u4E92\u5F0F Shell\u3002\u505C\u7528\u4F1A\u7ED3\u675F\u6B64\u670D\u52A1\u7684\u6240\u6709\u7EC8\u7AEF\u8FDB\u7A0B\u3002",en:"Run an interactive shell in the workspace. Disabling ends all terminals on this service."}};import{accessSync as Os,constants as Yi,statSync as Ms}from"node:fs";import{createRequire as Ja}from"node:module";import{execFile as js}from"node:child_process";import{accessSync as Va,chmodSync as Fa,constants as Ba,statSync as Ua}from"node:fs";import{createRequire as La}from"node:module";import{dirname as za,join as qa}from"node:path";var Ns=La(import.meta.url);function Ga(s){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=qa(s,e,"spawn-helper"),i;try{i=Ua(t).mode}catch(r){if(r.code==="ENOENT")continue;throw r}try{Va(t,Ba.X_OK)}catch{Fa(t,i|73)}}}function Hs(...s){return Ga(za(Ns.resolve("node-pty/package.json"))),Ns("node-pty").spawn(...s)}var He=class extends Error{reason;constructor(e,t,i){super(t,{cause:i}),this.reason=e}},Ws=Ja(import.meta.url),Qi=class{pid;pty;screen;serializer;followers=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,i,r,n,o,c,a){this.sessionId=e,this.abandoned=c,this.graceMs=a;let{Terminal:l}=Ws("@xterm/headless"),{SerializeAddon:p}=Ws("@xterm/addon-serialize");this.screen=new l({cols:i,rows:r,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([y,m])=>m!==void 0&&!/^PI_WEBAPP_RESTART_/.test(y)));try{this.pty=Hs(n,o,{name:"xterm-256color",cwd:t,cols:i,rows:r,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(y){throw this.screen.dispose(),new He("terminal_runtime_unavailable","\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684 node-pty \u4F9D\u8D56",y)}this.pid=this.pty.pid,this.screen.onData(y=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(y)}),this.pty.onData(y=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(m=>{if(this.disposed){m();return}this.screen.write(y,()=>{this.broadcast({type:"output",data:y}),m()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(y=>this.pty.onExit(({exitCode:m,signal:f})=>{this.exit={type:"exit",exitCode:m,signal:f},this.pending.then(()=>{this.broadcast(this.exit),y()})})),this.scheduleExpiry()}broadcast(e){for(let t of this.followers)t(e)||this.followers.delete(t);this.followers.size||this.scheduleExpiry()}scheduleExpiry(){this.expire||this.disposed||(this.expire=setTimeout(this.abandoned,this.graceMs).unref())}async attach(e){if(await this.pending,this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u5173\u95ED");return clearTimeout(this.expire),this.expire=void 0,e({type:"snapshot",screen:this.serializer.serialize(),cols:this.screen.cols,rows:this.screen.rows})?(this.exit&&e(this.exit),this.followers.add(e)):this.scheduleExpiry(),()=>{this.followers.delete(e),this.followers.size||this.scheduleExpiry()}}write(e){if(this.exit||this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u9000\u51FA");this.pty.write(e)}resize(e,t){this.exit||this.disposed||(this.pty.resize(e,t),this.pending=this.pending.then(()=>{this.disposed||(this.screen.resize(e,t),this.broadcast({type:"resize",cols:e,rows:t}))}))}close(){return this.closing??=this.dispose()}async dispose(){if(this.disposed=!0,clearTimeout(this.expire),!this.exit){if(process.platform==="win32")await new Promise(e=>js("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(r=>js("ps",["-axo","pid=,ppid="],(n,o)=>r(n?"":o)))).trim().split(`
|
|
20
|
+
`).map(r=>r.trim().split(/\s+/).map(Number)),i=r=>t.filter(([,n])=>n===r).flatMap(([n])=>[...i(n),n]);for(let r of[...i(this.pid),this.pid])try{process.kill(r,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending,this.followers.clear(),this.screen.dispose()}},Zt=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,i,r,n){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,t);if(this.terminals.size>=32||[...this.terminals.values()].filter(l=>l.sessionId===t).length>=8)throw new He("terminal_limit","\u7EC8\u7AEF\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u7EC8\u7AEF");let o=this.options.shell??(process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh");try{if(Os(o,Yi.X_OK),!Ms(o).isFile())throw new Error("Not a shell file")}catch(l){throw new He("terminal_shell_unavailable","\u9ED8\u8BA4 shell \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u6267\u884C\uFF0C\u8BF7\u4FEE\u6B63 SHELL\uFF08Windows \u4E3A COMSPEC\uFF09\u540E\u91CD\u542F\u5E94\u7528",l)}try{if(!Ms(i).isDirectory())throw new Error("Not a directory");Os(i,Yi.R_OK|Yi.X_OK)}catch(l){throw new He("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",l)}let c=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),a=new Qi(t,i,r,n,o,c,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,a),a}get(e,t){let i=this.terminals.get(e);if(!i||i.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return i}async remove(e,t){let i=this.terminals.get(e);if(i){if(i.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await i.close(),this.terminals.get(e)===i&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var $s=(s,e)=>Number.isInteger(s)&&Number.isInteger(e)&&Number(s)>=2&&Number(s)<=500&&Number(e)>=1&&Number(e)<=300;async function Vs(s,e,t,i,r,n){let o=(l,p)=>{t.writeHead(l,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){o(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let c=s.slice(14),a=i();if(c!=="close"&&e.sessionId!==a.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((c==="create"||c==="resize")&&!$s(e.cols,e.rows)){o(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(c==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){o(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(c==="create"){r.create(e.id,e.sessionId,a.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(c==="close"){await r.remove(e.id,e.sessionId),o(200,{closed:!0});return}let l=r.get(e.id,e.sessionId);if(c==="attach"){let p=!1,u;t.once("close",()=>{p=!0,u?.(),n.delete(t)}),u=await l.attach(y=>p?!1:(t.headersSent||t.writeHead(200,{"Content-Type":"application/x-ndjson","Cache-Control":"no-store","X-Accel-Buffering":"no"}),t.writableLength>1024*1024?(t.destroy(),!1):(t.write(`${JSON.stringify(y)}
|
|
21
|
+
`),!0))),p?u():n.add(t);return}if(c==="input")l.write(e.data);else if(c==="resize")l.resize(e.cols,e.rows);else{o(404,{error:"\u672A\u77E5\u7EC8\u7AEF\u64CD\u4F5C"});return}o(200,{accepted:!0})}catch(l){t.headersSent?t.end():o(400,{error:l instanceof He?l.message:c==="create"?"\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684\u7EC8\u7AEF\u4F9D\u8D56":"\u7EC8\u7AEF\u4E0D\u53EF\u7528\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF",reason:l instanceof He?l.reason:c==="create"?"terminal_runtime_unavailable":void 0})}}function Fs(){let s=new Zt,e=new Set,t=async()=>{for(let i of e)i.end();e.clear(),await s.clear()};return{metadata:Ds,routes:["create","attach","input","resize","close"].map(i=>`/api/terminal/${i}`),handle:i=>Vs(i.path,i.body,i.res,i.snapshot,s,e),restartBlocker:()=>s.size?"\u8BF7\u5148\u5173\u95ED\u6240\u6709\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0":null,disable:t,async close(){await t(),await s.close()}}}function Bs(){return[Cs,Fs(),Ts]}import{createHash as Ka,randomUUID as Xa}from"node:crypto";import{mkdir as Ya,open as Qa,readFile as Za,rename as ec,rm as Us,writeFile as tc}from"node:fs/promises";import{dirname as ic}from"node:path";var Q=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},ei=class s{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Za(this.file,"utf8"));if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("disabled"in e)||!Array.isArray(e.disabled)||!e.disabled.every(t=>typeof t=="string"&&t.length>0&&t.length<=200))throw new Q("\u63D2\u4EF6\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u4FEE\u590D\u914D\u7F6E\u540E\u91CD\u542F",503);this.disabled=new Set(e.disabled)}catch(e){if(e.code!=="ENOENT")throw e}}enabled(e){return!this.disabled.has(e)}revision(){return Ka("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,i,r){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let n=`${this.file}.${Xa()}.tmp`,o=`${this.file}.lock`,c;try{if(i!==this.revision())throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");r();let a=new Set(this.disabled);t?a.delete(e):a.add(e),await Ya(ic(this.file),{recursive:!0});try{c=await Qa(o,"wx",384)}catch(p){throw p.code==="EEXIST"?new Q("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await c.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
|
|
22
|
+
`);let l=new s(this.file);if(await l.load(),l.revision()!==i)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await tc(n,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
|
|
23
|
+
`,{mode:384}),r(),await ec(n,this.file),this.disabled=a}finally{this.changing=!1;try{await Us(n,{force:!0})}finally{c&&(await c.close(),await Us(o,{force:!0}))}}}};var ti=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(i=>[...i.routes]),new Set(e.map(i=>i.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(i=>i.metadata.id===e)?.routes.find(i=>i.split("/").at(-1)===t&&!i.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(i=>i.metadata.id));return{plugins:e.plugins.filter(i=>!t.has(i.id)),errors:[...e.errors,...e.plugins.filter(i=>t.has(i.id)).map(i=>`Plugin ID reserved by host: ${i.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(i=>this.preferences.enabled(i.metadata.id)).map(i=>({id:i.metadata.id,client:`builtin:${i.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,i,r){if(!this.plugins.some(n=>n.metadata.id===e))throw new Q("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(n=>n>0))throw new Q("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,i,r),t||await this.plugins.find(n=>n.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(r=>r.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let i=t.metadata.id;this.running.set(i,(this.running.get(i)??0)+1);try{await t.handle(e)}finally{this.running.set(i,this.running.get(i)-1)}return!0}async runAgentAction(e,t,i,r,n){let o=this.plugins.find(c=>c.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new Q("\u7ED8\u56FE\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(t,i,r,n)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let i="@host/start";this.running.set(i,(this.running.get(i)??0)+1);let r=t;for(let n of this.plugins)if(n.coordinateStart&&this.preferences.enabled(n.metadata.id)){let o=r;r=()=>n.coordinateStart(e,o)}try{return await r()}finally{this.running.set(i,this.running.get(i)-1)}}requestFailure(e){if(e instanceof Q)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let i=t.requestFailure?.(e);if(i)return i}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":this.plugins.map(e=>e.restartBlocker?.()).find(Boolean)??null}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as rc,opendir as sc,stat as nc}from"node:fs/promises";import{homedir as oc}from"node:os";import{basename as ac,dirname as Ls,join as zs,posix as cc,resolve as qs,win32 as lc}from"node:path";function Gs(s){return process.platform==="win32"?lc.isAbsolute(s)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(s):cc.isAbsolute(s)}function dc(s,e,t){if(s.length===t&&e.name.localeCompare(s[s.length-1].name)>=0)return!0;let i=0,r=s.length;for(;i<r;){let n=i+r>>>1;e.name.localeCompare(s[n].name)<0?r=n:i=n+1}return s.splice(i,0,e),s.length<=t?!1:(s.pop(),!0)}async function Js(s){if(s!==void 0&&!Gs(s))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=oc(),t=qs(s??e),i=[];for(let a=t;;a=Ls(a)){let l=Ls(a);if(i.unshift({name:l===a?a:ac(a),path:a,hidden:!1}),l===a)break}let r=[],n=!1,o=await sc(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||dc(r,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(n=!0);let c=[];for(let a of r){let l=zs(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await nc(l)).isDirectory())continue}catch{continue}if(c.length===1e3){n=!0;break}c.push({name:a.name,path:l,hidden:a.name.startsWith(".")})}return{path:t,home:e,crumbs:i,entries:c,truncated:n}}async function Ks(s,e){if(!Gs(s))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let t=zs(qs(s),e);return await rc(t),t}import{execFile as pc}from"node:child_process";import{accessSync as uc,constants as hc}from"node:fs";import{delimiter as fc,join as gc}from"node:path";var mc=(s,e,t)=>new Promise((i,r)=>{pc(s,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(n,o,c)=>{n?r(Object.assign(new Error(n.message,{cause:n}),{code:n.code,stdout:o,stderr:c})):i({stdout:o,stderr:c})})});function wc(s){for(let e of(s??"").split(fc))if(e)for(let t of["zenity","kdialog"])try{return uc(gc(e,t),hc.X_OK),!0}catch{}return!1}function Xs(s=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":s==="darwin"||s==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&wc(e.PATH)?"native":"browse"}function ii(s){if(!(typeof s!="object"||s===null||!("code"in s)))return typeof s.code=="string"||typeof s.code=="number"?s.code:void 0}function yc(s){return typeof s=="object"&&s!==null&&"stderr"in s&&typeof s.stderr=="string"?s.stderr:""}function Zi(s){return s.replace(/[\r\n]+$/,"")||null}async function Ys(s,e=process.platform,t=mc){if(e==="darwin")try{let i=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],s);return Zi(i.stdout)}catch(i){if(!s.aborted&&ii(i)===1&&/(?:User canceled|-128)/i.test(yc(i)))return null;throw i}if(e==="linux"){try{return Zi((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],s)).stdout)}catch(i){if(s.aborted)throw i;if(ii(i)===1)return null;if(ii(i)!=="ENOENT")throw i}try{return Zi((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],s)).stdout)}catch(i){if(s.aborted)throw i;if(ii(i)===1)return null;throw i}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as vc,randomUUID as bc}from"node:crypto";import{mkdir as kc,readFile as Pc,writeFile as Ic}from"node:fs/promises";import{join as Qs}from"node:path";import{getAgentDir as Sc}from"@earendil-works/pi-coding-agent";var ri=20*1024*1024,Zs=20,Ec=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function xc(s){let e=s.indexOf("."),t=(e<0?s:s.slice(0,e)).replace(/[. ]+$/u,"");return Ec.test(t)}function _c(s,e){let t=0,i="";for(let r of Buffer.from(s).toString("utf8")){let n=Buffer.byteLength(r);if(t+n>e)break;i+=r,t+=n}return i}function Ac(s){if(s===void 0)return"file";let t=s.slice(Math.max(s.lastIndexOf("/"),s.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return xc(t)&&(t=`_${t}`),t=_c(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function Tc(s){return s.length>=8&&s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":s.length>=3&&s.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":s.length>=6&&["GIF87a","GIF89a"].includes(s.toString("ascii",0,6))?"image/gif":s.length>=12&&s.toString("ascii",0,4)==="RIFF"&&s.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function en(s,e,t,i){if(i.byteLength===0||i.byteLength>ri)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let r=Ac(e),n=vc("sha256").update(i).digest("hex"),o=Qs(Sc(),"pi-web","attachments",n);await kc(o,{recursive:!0});let c=Qs(o,r);try{await Ic(c,i,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:bc(),name:r,bytes:i.byteLength,path:c,mediaType:Tc(i)??t.replace(/^image\//,"application/"),sessionId:s}}async function tn(s){return{type:"image",data:(await Pc(s.path)).toString("base64"),mimeType:s.mediaType}}import{randomBytes as Rc}from"node:crypto";function rn(s,e,t){return s!=="openai-codex"||e!=="oauth"?t:{...t,prompt:i=>i.type==="select"&&i.options.some(r=>r.id==="browser")&&i.options.some(r=>r.id==="device_code")?Promise.resolve("browser"):t.prompt(i)}}var si=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,i,r,n){let o=this.getActive();if(o){if(o.providerId===e&&o.method===t&&r===void 0)return o;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let c=Rc(18).toString("base64url"),a={view:{id:c,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(c,a),i(e,t,{signal:a.controller.signal,notify:l=>{a.view={...a.view,event:l,...l.type==="auth_url"||l.type==="device_code"?{authorization:l}:{}}},prompt:l=>{if(l.type==="secret"&&r!==void 0){let p=r;return r=void 0,Promise.resolve(p)}return new Promise((p,u)=>{let{signal:y,...m}=l;a.answer=p,a.reject=u,a.view={...a.view,status:"waiting",prompt:m},y?.aborted?u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):y?.addEventListener("abort",()=>u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{a.view.status!=="cancelled"&&(a.view={id:c,providerId:e,method:t,status:"done"})}).catch(l=>{if(a.view.status!=="cancelled"){let p=new Error("Provider login failed");l instanceof Error&&l.stack&&(p.stack=`${p.message}
|
|
24
24
|
${l.stack.split(`
|
|
25
25
|
`).slice(1).join(`
|
|
26
|
-
`)}`);let
|
|
27
|
-
`,{mode:
|
|
28
|
-
`,{mode:
|
|
26
|
+
`)}`);let u=this.reportError(p,{...n,stage:"provider_login"});a.view={id:c,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:u}}}),{...a.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let i=this.flows.get(e);if(!i?.answer||i.view.status!=="waiting"||i.view.prompt?.type==="select"&&!i.view.prompt.options.some(n=>n.id===t))return!1;let r=i.answer;return i.answer=void 0,i.reject=void 0,i.view={...i.view,status:"running",prompt:void 0},r(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as Cc}from"node:crypto";import{readFile as Dc,rename as Nc,rm as Hc,stat as Oc,writeFile as Mc,mkdir as jc}from"node:fs/promises";import{dirname as Wc}from"node:path";var $c=["openai-completions","openai-responses","anthropic-messages"];function er(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!$c.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let t=new URL(e.baseUrl);return(t.protocol==="https:"||t.protocol==="http:")&&!!t.hostname&&!t.username&&!t.password&&!t.hash}catch{return!1}}async function sn(s,e){if(!er(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let t;try{t=await Dc(s,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let i;if(t===void 0)i={providers:{}};else{try{i=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(i.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let r={...i,providers:{...i.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await jc(Wc(s),{recursive:!0});let n=t===void 0?384:(await Oc(s)).mode&511,o=`${s}.pi-web-${Cc(6).toString("hex")}.tmp`;try{await Mc(o,`${JSON.stringify(r,null,2)}
|
|
27
|
+
`,{mode:n,flag:"wx"}),await Nc(o,s)}finally{await Hc(o,{force:!0})}}import{randomBytes as Vc}from"node:crypto";import{mkdir as Fc,readFile as Bc,rename as Uc,rm as Lc,stat as zc,writeFile as qc}from"node:fs/promises";import{dirname as Gc}from"node:path";function nn(s){if(!s||s.length>2048)return!1;try{let e=new URL(s);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function on(s){if(!s||typeof s!="object")return!1;let e=s;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&an(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&nn(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function an(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let t of[e.contextWindow,e.maxTokens])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(t=>t==="text"||t==="image")&&new Set(e.input).size===e.input.length}async function cn(s){let e;try{e=await Bc(s,"utf8")}catch(i){if(i.code!=="ENOENT")throw i}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function Jc(s,e,t){await Fc(Gc(s),{recursive:!0});let i=t===void 0?384:(await zc(s)).mode&511,r=`${s}.pi-web-${Vc(6).toString("hex")}.tmp`;try{await qc(r,`${JSON.stringify(e,null,2)}
|
|
28
|
+
`,{mode:i,flag:"wx"}),await Uc(r,s)}finally{await Lc(r,{force:!0})}}async function ln(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await cn(s),r=i.providers[e],n=new Set(r?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:r?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!r?.modelOverrides?.[o.id]}))}}async function dn(s,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r,existing:n}=await cn(s),o={...r.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!nn(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!an(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let l={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},p=t.originalId,u=p===void 0?-1:c.findIndex(y=>y.id===p);if(p===void 0&&(c.some(y=>y.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(c.some(m=>m.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let y={...c[u],...l};for(let m of["name","contextWindow","maxTokens","input"])l[m]===void 0&&delete y[m];c[u]=y}else if(p!==void 0&&i.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:y,...m}=l;a[p]={...a[p],...m};for(let f of["name","contextWindow","maxTokens","input"])l[f]===void 0&&delete a[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(l)}}else{let l=c.findIndex(p=>p.id===t.id);if(l>=0)c.splice(l,1);else if(Object.hasOwn(a,t.id))delete a[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(a).length?o.modelOverrides=a:delete o.modelOverrides,Object.keys(o).length?r.providers[e]=o:delete r.providers[e],await Jc(s,r,n)}function pn(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as un,createHash as Kc}from"node:crypto";import{fileURLToPath as Xc}from"node:url";var Tt="pi-webapp@0.1.50-alpha.4+6f276aca4a67bf831236",Se="6f276aca4a67bf831236";var Yc="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ni(s=process.env,e=console.warn){let t=i=>{let r={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Tt,buildId:Se},n=s[`PI_WEB_SENTRY_${i}_DSN`]??s.PI_WEB_SENTRY_DSN??Yc;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return r;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...r,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),r}};return{browser:t("BROWSER"),node:t("NODE")}}var xe=class{config;ready;reporter;client;salt=un(16);breadcrumbs=new At;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=ni(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Xc(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),r=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:r)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Se,integrations:[],transport:e.transport??(i=>As(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:_s,sendClientReports:!1,dataCollection:{...Ss,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Yt(this.client,"node",Se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=un(16).toString("hex");return this.early.push({error:lt(e),context:Ie(t),eventId:i}),i}catch{return}}setState(e){this.state=Ie({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return Kc("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as ul}from"@earendil-works/pi-coding-agent";function We(s,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(s.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!s.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Qc}from"node:crypto";function Rt(s){let e=[],t=s;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let r;try{r=JSON.parse(i[2])}catch{break}e.unshift({name:r,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(r)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Ct=s=>Buffer.byteLength(s.text)+s.images.reduce((e,t)=>e+t.data.length,0),ae=class extends Error{status=409},$e=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...Rt(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((r,n)=>r+Ct(n),Ct({text:e,images:t}))>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Qc(),revision:1,text:e,images:t.map(r=>({...r})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new ae("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(r=>r.id===e);if(!i||i.revision!==t)throw new ae("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new ae("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,r){let n=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(i.kind==="edit"){let o=Rt(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[i.text.trim(),c].filter(Boolean).join(`
|
|
29
29
|
|
|
30
|
-
`);if(this.validateText(c),this.entries.reduce((l,p)=>l+St(p),0)-St(s)+St({text:c,images:s.images})>64*1024*1024)throw new se("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=c,s.revision++,delete s.error,this.changed();return}await this.deliver(s,i)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,t){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var w=class extends Error{code;status;reason;constructor(e,t,r={}){super(t),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function Y(n){let e=n&&typeof n=="object"?n:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:n instanceof Error?n.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var it=n=>n.code==="ENOENT";var qn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views"];async function Fr(n,e,t,r){if(!n)throw new w("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return n.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new w("invalid_input","Expected plugin request object",{status:400});let i=t;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","cancel-initialization"].includes(String(i.operation)))throw new w("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(i.operation!=="pollMany")return n.views(i);if(!Array.isArray(i.views)||!i.views.length||i.views.length>64||i.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new w("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(i.views.map(async s=>{try{return{reply:await n.views({...s,operation:"poll",immediate:!0})}}catch(o){return{failure:Qt(o)}}}))}}if(typeof i.pluginId!="string"||i.pluginId.length>214)throw new w("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new w("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof i.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(i.operation)||i.version!==void 0&&(typeof i.version!="string"||!/^\d+\.\d+\.\d+$/.test(i.version)))throw new w("invalid_input","Invalid plugin management request",{status:400});if(i.downloadId!==void 0&&(typeof i.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(i.downloadId))||i.operation==="cancel-download"&&!i.downloadId)throw new w("invalid_input","Exact download identity required",{status:400});if(i.reopenEditors!==void 0&&typeof i.reopenEditors!="boolean")throw new w("invalid_input","Invalid editor reopen consent",{status:400});if(i.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(i.updatePolicy)||i.operation==="policy"&&(typeof i.updatePolicy!="string"||i.updatePolicy==="pinned"&&!i.version))throw new w("invalid_input","Invalid update policy or missing exact pin",{status:400});return n.manage({pluginId:i.pluginId,operation:i.operation,...typeof i.downloadId=="string"?{downloadId:i.downloadId}:{},...typeof i.updatePolicy=="string"?{updatePolicy:i.updatePolicy}:{},...typeof i.version=="string"?{version:i.version}:{},...typeof i.reopenEditors=="boolean"?{reopenEditors:i.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof i.sessionId!="string"||!i.sessionId||i.sessionId.length>200||!Number.isSafeInteger(i.generation)||Number(i.generation)<1||typeof i.action!="string"||!/^[\w.-]{1,80}$/.test(i.action))throw new w("invalid_input","Invalid plugin action request",{status:400});if(i.viewToken!==void 0&&(typeof i.viewToken!="string"||i.viewToken.length>200)||i.mountId!==void 0&&(typeof i.mountId!="string"||i.mountId.length>200))throw new w("invalid_input","Invalid view flush capability",{status:400});return n.action({sessionId:i.sessionId,pluginId:i.pluginId,generation:Number(i.generation),action:i.action,input:i.input??{},...typeof i.viewToken=="string"?{viewToken:i.viewToken}:{},...typeof i.mountId=="string"?{mountId:i.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new w("invalid_route","Unknown hosted plugin route",{status:404})}function Qt(n){let e=Y(n);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as Gn}from"node:fs/promises";import{join as Jn}from"node:path";async function Kn(n){try{let e=JSON.parse(await Gn(Jn(n,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await Gn(Jn(n,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let o of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let i={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(s=>[`/${s}`,{path:s,type:i[s.split(".").pop()]}]))}catch{return{}}}import{access as yc,readFile as Br,realpath as tr,rename as vc,rm as bc,writeFile as kc}from"node:fs/promises";import{randomUUID as Pc}from"node:crypto";import{dirname as er,join as Ee,resolve as Ic,sep as Yn}from"node:path";import{createRequire as Ec}from"node:module";var wc=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function We(n){let e=typeof n=="string"&&wc.exec(n);if(!e||e[0]!==n)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||r.some(i=>/^\d+$/.test(i)&&i.length>1&&i[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:r}}function ue(n,e){let t=We(n),r=We(e);for(let i=0;i<3;i++)if(t.core[i]!==r.core[i])return t.core[i]>r.core[i]?1:-1;if(!t.prerelease.length||!r.prerelease.length)return+!t.prerelease.length-+!r.prerelease.length;for(let i=0;i<Math.max(t.prerelease.length,r.prerelease.length);i++){let s=t.prerelease[i],o=r.prerelease[i];if(s===void 0||o===void 0)return s===void 0?-1:1;if(s===o)continue;let a=/^\d+$/.test(s),c=/^\d+$/.test(o);return a!==c?a?-1:1:a&&s.length!==o.length?s.length>o.length?1:-1:s>o?1:-1}return 0}function Xn(n){try{return We(n).prerelease.length===0}catch{return!1}}function Zt(n){try{return We(n),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(n)}catch{return!1}}var Ve=1,Qn=n=>Ee(n,"pi-web","desktop-update.json");async function nt(n,e){let t=Ec(Ee(n,"package.json"));for(let r of t.resolve.paths(e)??[]){let i=Ee(r,e);try{if(JSON.parse(await Br(Ee(i,"package.json"),"utf8")).name===e)return await tr(i)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function rr(n,e){if(ue(e?.version,e?.version),e.desktopProtocolVersion!==Ve||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await tr(Ic(er(e.launcher),"..")),r=await tr(Ee(n,"pi-web","releases")),i=er(er(t));if(await tr(e.launcher)!==Ee(t,"bin","pi-webapp.mjs")||er(i)!==r||!i.startsWith(r+Yn)||!i.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(i.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await Br(Ee(t,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==Ve)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await nt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(i+Yn))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let a=Ee(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,a,Ee(t,"dist","extension.js"),Ee(t,"web","dist","index.html")].map(c=>yc(c))),e.fallbackVersion!==void 0&&We(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:a,desktopProtocolVersion:Ve,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}async function Zn(n,e,t=e){try{let r=JSON.parse(await Br(Qn(n),"utf8"));return ue(r.version,e)<0&&r.fallbackVersion!==t?null:await rr(n,r)}catch{return null}}async function es(n,e){let t=Qn(n),r=`${t}.${Pc()}.tmp`;try{await kc(r,JSON.stringify(e),{mode:384}),await vc(r,t)}finally{await bc(r,{force:!0})}}var Cc={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function b(n,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:n.getHeader("X-Request-ID"),operationId:n.getHeader("X-Operation-ID")}),n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify(t))}function Nc(n,e){let t=n.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let r=Buffer.from(t.slice(7),"utf8");return r.length===e.length&&Sc(r,e)}async function rs(n,e=64*1024){let t=0,r=[];for await(let i of n){let s=Buffer.isBuffer(i)?i:Buffer.from(i);if(t+=s.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function Oc(n){let e=0,t=[];for await(let r of n){let i=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=i.length,e>Kt)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(i)}return Buffer.concat(t)}async function Hc(n,e=0){await new Promise((r,i)=>{n.once("error",i),n.listen(e,"127.0.0.1",()=>{n.off("error",i),r()})});let t=n.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function is(n,e,t=new Ie,r={}){t.setState({piVersion:Rc});let i=process.env.PI_WEBAPP_RESTART_TOKEN,s=i&&/^[A-Za-z0-9_-]{32}$/.test(i)?i:ts(24).toString("base64url"),o=Buffer.from(s),a=Rn(),c=new Set,l=new qt(r.pluginSettingsFile??Ur(Ac(),"pi-web","plugins.json"));try{await l.load()}catch(k){throw await t.close(),k}let p=new Gt(Pn(),l),f=async()=>await n.plugins?.()??{plugins:[],errors:[]},u=()=>({type:"plugin_state",disabled:p.plugins.filter(k=>!l.enabled(k.metadata.id)).map(k=>k.metadata.id)}),h=()=>{for(let k of c)k.write(`${JSON.stringify(u())}
|
|
31
|
-
`)},
|
|
32
|
-
`),y.on("close",()=>c.delete(y));return}if(k.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(E)){if(k.headers.origin!==void 0&&k.headers.origin!==I){b(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){b(y,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let m;try{m=await rs(k,E==="/api/plugin-action"?544*1024:64*1024)}catch(P){if(P instanceof Error&&P.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){b(y,413,{error:P.message});return}if(P instanceof SyntaxError||Be(P)){b(y,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw P}if(E==="/api/desktop/handoff"){let P=m;if(!P||typeof P.nonce!="string"||typeof P.requestId!="string"){b(y,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!n.selfUpdate?.requestLauncherHandoff){b(y,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(T||O||v.getActive()){b(y,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let _=p.restartBlocker();if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length||_){b(y,409,{error:_??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}T=!0;try{await n.selfUpdate.requestLauncherHandoff(P.nonce,P.requestId)}catch(C){throw T=!1,C}b(y,202,{accepted:!0,protocol:1,requestId:P.requestId});return}if(typeof m!="object"||m===null||!("sessionId"in m)||typeof m.sessionId!="string"){b(y,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(T&&E!=="/api/update/cancel"){b(y,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(E==="/api/plugin-management"){let P=m;if(typeof P.id!="string"||P.id.length>200||typeof P.enabled!="boolean"||typeof P.expected!="string"){b(y,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let _=()=>{if(n.snapshot().sessionId!==m.sessionId)throw new X("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length)throw new X("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(P.id,P.enabled,P.expected,_),b(y,200,p.inventory(await f()))}catch(C){if(C instanceof X)b(y,C.status,{error:C.message});else throw C}finally{h()}return}if(p.mutating&&E!=="/api/abort"){b(y,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:E,body:m,res:y,snapshot:()=>n.snapshot(),busyWorkspaces:()=>n.busyGitWorkspaces?.()??[],json:(P,_)=>b(y,P,_)}))return;if(E==="/api/plugin-interaction"){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in m)||typeof m.pluginId!="string"||m.pluginId.length>200||!("requestId"in m)||typeof m.requestId!="string"||m.requestId.length>200||!n.resolvePluginInteraction||!("value"in m)){b(y,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(n.snapshot().cwd,async()=>n.resolvePluginInteraction(m.sessionId,m.pluginId,m.requestId,m.value)),b(y,200,{accepted:!0});return}if(E==="/api/plugin-action"){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in m)||typeof m.pluginId!="string"||m.pluginId.length>200||!("action"in m)||typeof m.action!="string"||m.action.length>100){b(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(C=>C.metadata.id===m.pluginId)){let C=p.actionRoute(m.pluginId,m.action);if(!C){b(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let U="input"in m?m.input:{};if(!U||typeof U!="object"||Array.isArray(U)){b(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...U,sessionId:m.sessionId},res:y,snapshot:()=>n.snapshot(),busyWorkspaces:()=>n.busyGitWorkspaces?.()??[],json:(we,$t)=>b(y,we,we>=200&&we<300?{value:$t}:$t)});return}if(!n.invokePluginAction){b(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let _=await p.coordinateStart(n.snapshot().cwd,async()=>n.invokePluginAction(m.sessionId,m.pluginId,m.action,"input"in m?m.input:void 0));b(y,200,{value:_});return}if(E==="/api/update/channel"){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in m)||m.channel!=="stable"&&m.channel!=="alpha"){b(y,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!n.selfUpdate?.setChannel){b(y,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}b(y,200,await n.selfUpdate.setChannel(m.channel));return}if(E==="/api/update/cancel"){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!n.selfUpdate?.cancel){b(y,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await n.selfUpdate.cancel(),b(y,200,{cancelled:!0,dataPreserved:!0});return}if(E==="/api/update"){if(O){b(y,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!n.snapshot().idle){b(y,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!n.selfUpdate){b(y,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let P=p.restartBlocker();if((n.busyGitWorkspaces?.()??[]).length||P){b(y,409,{error:P??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let _=m,C="channel"in _||"version"in _||"allowDowngrade"in _;if(C&&(_.channel!=="stable"&&_.channel!=="alpha"||typeof _.version!="string"||_.allowDowngrade!==void 0&&typeof _.allowDowngrade!="boolean")){b(y,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}O=!0;let U;try{U=await n.selfUpdate.prepare(C?{channel:_.channel,version:_.version,allowDowngrade:_.allowDowngrade}:void 0);let we=p.restartBlocker();if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length||we)throw new Error(we??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");T=!0,await n.selfUpdate.requestRestart(U)}catch(we){throw T=!1,we}finally{O=!1}b(y,202,{accepted:!0,version:U.version});return}if(E==="/api/provider/custom"){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in m)||!$r(m.provider)||!n.addCustomProvider){b(y,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await n.addCustomProvider(m.sessionId,m.provider),b(y,201,{accepted:!0});return}if(E==="/api/provider/models"||E==="/api/provider/logout"){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in m)||typeof m.providerId!="string"){b(y,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(E==="/api/provider/models"){if(!("change"in m)||!Vn(m.change)||!n.updateProviderModel){b(y,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await n.updateProviderModel(m.sessionId,m.providerId,m.change)}else{if(!n.logoutProvider){b(y,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await n.logoutProvider(m.sessionId,m.providerId)}b(y,200,{accepted:!0});return}if(E.startsWith("/api/provider/login")){if(m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(E==="/api/provider/login"){if(!("providerId"in m)||typeof m.providerId!="string"||!("method"in m)||m.method!=="api_key"&&m.method!=="oauth"||!n.loginProvider||!n.providers){b(y,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await n.providers()).some(U=>U.id===m.providerId&&U.methods.includes(m.method))){b(y,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let _="initialSecret"in m?m.initialSecret:void 0;if(_!==void 0&&(m.method!=="api_key"||typeof _!="string"||!_.trim()||_.length>16384)){b(y,400,{error:"API Key \u65E0\u6548"});return}let C=v.start(m.providerId,m.method,n.loginProvider,_,te);b(y,202,{id:C.id});return}if(!("id"in m)||typeof m.id!="string"){b(y,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(E==="/api/provider/login/cancel"){b(y,v.cancel(m.id)?202:404,{accepted:!0});return}if(!("value"in m)||typeof m.value!="string"||m.value.length>16384||!v.respond(m.id,m.value)){b(y,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}b(y,202,{accepted:!0});return}if(E==="/api/attachment/remove"){if(!("id"in m)||typeof m.id!="string"||m.sessionId!==n.snapshot().sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}g.get(m.id)?.sessionId===m.sessionId&&g.delete(m.id),b(y,202,{accepted:!0});return}if(E==="/api/directory/pick"){if(a!=="native"){b(y,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let P=new AbortController;y.once("close",()=>P.abort()),b(y,200,{path:await Cn(P.signal)});return}if(E==="/api/directory/list"){if("path"in m&&(typeof m.path!="string"||m.path.length>4096)){b(y,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}b(y,200,await Tn("path"in m?m.path:void 0));return}if(E==="/api/directory/create"){if(!("path"in m)||typeof m.path!="string"||m.path.length>4096||!("name"in m)||typeof m.name!="string"||m.name.length>255){b(y,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}b(y,200,{path:await An(m.path,m.name)});return}if(E==="/api/workspace/add"){if(!("path"in m)||typeof m.path!="string"||m.path.length>4096||!("create"in m)||typeof m.create!="boolean"){b(y,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await n.addWorkspace(m.path,m.create),b(y,202,{accepted:!0});return}if(E==="/api/workspace/select"||E==="/api/workspace/remove"||E==="/api/workspace/new-session"){if(!("id"in m)||typeof m.id!="string"){b(y,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}E==="/api/workspace/select"?await n.selectWorkspace(m.id):E==="/api/workspace/new-session"?await n.newSessionInWorkspace(m.id):await n.removeWorkspace(m.id),b(y,202,{accepted:!0});return}if(E==="/api/session/select"){if(!("workspaceId"in m)||typeof m.workspaceId!="string"||!("id"in m)||typeof m.id!="string"||!("path"in m)||typeof m.path!="string"){b(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await n.selectSession(m.workspaceId,m.id,m.path),b(y,202,{accepted:!0});return}if(E==="/api/thinking-level"){if(!("level"in m)||typeof m.level!="string"){b(y,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await n.setThinkingLevel(m.sessionId,m.level)}else if(E==="/api/model"){if(!("provider"in m)||typeof m.provider!="string"||!("id"in m)||typeof m.id!="string"){b(y,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await n.setModel(m.sessionId,m.provider,m.id)}else if(E==="/api/config"){let P=m;if(!["packages","extensions","skills"].includes(P.kind)||!["global","project"].includes(P.scope)||!["add","remove"].includes(P.action)||typeof P.value!="string"||!P.value.trim()||P.value.length>2048){b(y,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(P.action==="add"&&P.kind!=="packages"&&Un(P.value)){b(y,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}b(y,200,await n.updateConfig(P));return}else if(E==="/api/prompt-queue"){let P=m,_=P.action;if(typeof P.id!="string"||P.id.length>100||!Number.isSafeInteger(P.revision)||P.revision<1||!_||typeof _!="object"||!["edit","remove","steer"].includes(_.kind)||_.kind==="edit"&&(typeof _.text!="string"||_.text.length>32e3)){b(y,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let C=n.snapshot();if(P.sessionId!==C.sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(_.kind==="steer"&&C.idle){b(y,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(_.kind==="steer"&&C.interactions?.length){b(y,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!n.updateQueuedPrompt){b(y,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(C.cwd,async()=>n.updateQueuedPrompt(m.sessionId,P.id,P.revision,_))}else if(E==="/api/message"){let P="delivery"in m?m.delivery:void 0;if(P!==void 0&&P!=="steer"&&P!=="followUp"){b(y,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let _="attachments"in m?m.attachments:[];if(!Array.isArray(_)||_.length>On||_.some(ne=>typeof ne!="string")||new Set(_).size!==_.length){b(y,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=_.map(ne=>g.get(ne));if(C.some(ne=>!ne||ne.sessionId!==m.sessionId)){b(y,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in m)||typeof m.text!="string"||!m.text.trim()&&_.length===0||m.text.length>32e3){b(y,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let U=n.snapshot();if(m.sessionId!==U.sessionId){b(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{Me(U,m.text,P)}catch(ne){b(y,409,{error:ne.message});return}let we=C,$t=[m.text.trim(),...we.map(ne=>`\u9644\u4EF6 ${JSON.stringify(ne.name)}\uFF1A${ne.path}`)].filter(Boolean).join(`
|
|
30
|
+
`);if(this.validateText(a),this.entries.reduce((l,p)=>l+Ct(p),0)-Ct(n)+Ct({text:a,images:n.images})>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");n.text=a,n.revision++,delete n.error,this.changed();return}await this.deliver(n,r)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(i=>i!==e)}catch(i){throw e.status="queued",e.revision++,e.error=i instanceof Error?i.message:"\u53D1\u9001\u5931\u8D25",i}finally{this.changed()}}schedule(e,t){let i=this.entries[0];this.pumping||!i||i.status!=="queued"||i.error||!e()||(this.pumping=!0,i.status="sending",i.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){i.status="queued",i.revision++,this.changed();return}await this.deliver(i,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var h=class extends Error{code;status;reason;constructor(e,t,i={}){super(t),this.name="HostedPluginError",this.code=e,this.status=i.status,this.reason=i.reason}};function G(s){let e=s&&typeof s=="object"?s:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:s instanceof Error?s.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Ve=s=>s.code==="ENOENT";var hn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function tr(s,e,t,i){if(!s)throw new h("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return s.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new h("invalid_input","Expected plugin request object",{status:400});let r=t;if(e==="/api/hosted-plugins/views"){if(i?.draining&&!["poll","pollMany","change","ack","close","reconcile","cancel-initialization"].includes(String(r.operation)))throw new h("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(r.operation!=="pollMany")return s.views(r);if(!Array.isArray(r.views)||!r.views.length||r.views.length>64||r.views.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.operation!=="poll"))throw new h("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(r.views.map(async n=>{try{return{reply:await s.views({...n,operation:"poll",immediate:!0})}}catch(o){return{failure:oi(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(i?.draining)throw new h("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof r.id!="string"||!/^[a-f0-9-]{36}$/.test(r.id)||r.decision!=="allow"&&r.decision!=="deny")throw new h("invalid_input","Invalid approval decision",{status:400});if(!s.decide)throw new h("hosted_unavailable","Approvals are not available in this runtime",{status:503});return s.decide(r.id,r.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(i?.draining)throw new h("host_restarting","Host is updating; secret changes are fenced",{status:409});if(r.auth!==void 0){if(!s.secretAuth)throw new h("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(r.auth==="start"&&typeof r.pluginId=="string"&&r.pluginId.length<=214&&typeof r.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(r.name))return s.secretAuth({phase:"start",pluginId:r.pluginId,name:r.name});if((r.auth==="poll"||r.auth==="cancel")&&typeof r.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(r.deviceId))return s.secretAuth({phase:r.auth,deviceId:r.deviceId});throw new h("invalid_input","Invalid sign-in request",{status:400})}if(typeof r.pluginId!="string"||r.pluginId.length>214||typeof r.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(r.name)||!(r.value===null||typeof r.value=="string"&&r.value.length>=1&&r.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(r.value)))throw new h("invalid_input","Invalid secret request",{status:400});if(!s.secret)throw new h("hosted_unavailable","Secrets are not available in this runtime",{status:503});return s.secret(r.pluginId,r.name,r.value)}if(typeof r.pluginId!="string"||r.pluginId.length>214)throw new h("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(i?.draining)throw new h("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof r.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(r.operation)||r.version!==void 0&&(typeof r.version!="string"||!/^\d+\.\d+\.\d+$/.test(r.version)))throw new h("invalid_input","Invalid plugin management request",{status:400});if(r.downloadId!==void 0&&(typeof r.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(r.downloadId))||r.operation==="cancel-download"&&!r.downloadId)throw new h("invalid_input","Exact download identity required",{status:400});if(r.reopenEditors!==void 0&&typeof r.reopenEditors!="boolean")throw new h("invalid_input","Invalid editor reopen consent",{status:400});if(r.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(r.updatePolicy)||r.operation==="policy"&&(typeof r.updatePolicy!="string"||r.updatePolicy==="pinned"&&!r.version))throw new h("invalid_input","Invalid update policy or missing exact pin",{status:400});return s.manage({pluginId:r.pluginId,operation:r.operation,...typeof r.downloadId=="string"?{downloadId:r.downloadId}:{},...typeof r.updatePolicy=="string"?{updatePolicy:r.updatePolicy}:{},...typeof r.version=="string"?{version:r.version}:{},...typeof r.reopenEditors=="boolean"?{reopenEditors:r.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof r.sessionId!="string"||!r.sessionId||r.sessionId.length>200||!Number.isSafeInteger(r.generation)||Number(r.generation)<1||typeof r.action!="string"||!/^[\w.-]{1,80}$/.test(r.action))throw new h("invalid_input","Invalid plugin action request",{status:400});if(r.viewToken!==void 0&&(typeof r.viewToken!="string"||r.viewToken.length>200)||r.mountId!==void 0&&(typeof r.mountId!="string"||r.mountId.length>200))throw new h("invalid_input","Invalid view flush capability",{status:400});return s.action({sessionId:r.sessionId,pluginId:r.pluginId,generation:Number(r.generation),action:r.action,input:r.input??{},...typeof r.viewToken=="string"?{viewToken:r.viewToken}:{},...typeof r.mountId=="string"?{mountId:r.mountId}:{}},i?.draining?{checkpointOnly:!0}:void 0)}throw new h("invalid_route","Unknown hosted plugin route",{status:404})}function oi(s){let e=G(s);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as fn}from"node:fs/promises";import{join as gn}from"node:path";async function mn(s){try{let e=JSON.parse(await fn(gn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,i=await fn(gn(s,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let n of[...Object.values(e),{assets:Array.isArray(i)?i:[]}])if(!(!n||typeof n!="object"))for(let o of[n.file,...Array.isArray(n.css)?n.css:[],...Array.isArray(n.assets)?n.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let r={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(n=>[`/${n}`,{path:n,type:r[n.split(".").pop()]}]))}catch{return{}}}import{access as el,readFile as ir,realpath as li,rename as tl,rm as il,writeFile as rl}from"node:fs/promises";import{randomUUID as sl}from"node:crypto";import{dirname as ci,join as _e,resolve as nl,sep as yn}from"node:path";import{createRequire as ol}from"node:module";var Zc=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function Fe(s){let e=typeof s=="string"&&Zc.exec(s);if(!e||e[0]!==s)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),i=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||i.some(r=>/^\d+$/.test(r)&&r.length>1&&r[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:i}}function ue(s,e){let t=Fe(s),i=Fe(e);for(let r=0;r<3;r++)if(t.core[r]!==i.core[r])return t.core[r]>i.core[r]?1:-1;if(!t.prerelease.length||!i.prerelease.length)return+!t.prerelease.length-+!i.prerelease.length;for(let r=0;r<Math.max(t.prerelease.length,i.prerelease.length);r++){let n=t.prerelease[r],o=i.prerelease[r];if(n===void 0||o===void 0)return n===void 0?-1:1;if(n===o)continue;let c=/^\d+$/.test(n),a=/^\d+$/.test(o);return c!==a?c?-1:1:c&&n.length!==o.length?n.length>o.length?1:-1:n>o?1:-1}return 0}function wn(s){try{return Fe(s).prerelease.length===0}catch{return!1}}function ai(s){try{return Fe(s),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(s)}catch{return!1}}var Be=1,vn=s=>_e(s,"pi-web","desktop-update.json");async function dt(s,e){let t=ol(_e(s,"package.json"));for(let i of t.resolve.paths(e)??[]){let r=_e(i,e);try{if(JSON.parse(await ir(_e(r,"package.json"),"utf8")).name===e)return await li(r)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function di(s,e){if(ue(e?.version,e?.version),e.desktopProtocolVersion!==Be||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await li(nl(ci(e.launcher),"..")),i=await li(_e(s,"pi-web","releases")),r=ci(ci(t));if(await li(e.launcher)!==_e(t,"bin","pi-webapp.mjs")||ci(r)!==i||!r.startsWith(i+yn)||!r.slice(i.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(r.slice(i.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let n=JSON.parse(await ir(_e(t,"package.json"),"utf8"));if(n.name!=="pi-webapp"||n.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(n.piWebappDesktopProtocol!==Be)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await dt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(r+yn))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let c=_e(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,c,_e(t,"dist","extension.js"),_e(t,"web","dist","index.html")].map(a=>el(a))),e.fallbackVersion!==void 0&&Fe(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:Be,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}async function bn(s,e,t=e){try{let i=JSON.parse(await ir(vn(s),"utf8"));return ue(i.version,e)<0&&i.fallbackVersion!==t?null:await di(s,i)}catch{return null}}async function kn(s,e){let t=vn(s),i=`${t}.${sl()}.tmp`;try{await rl(i,JSON.stringify(e),{mode:384}),await tl(i,t)}finally{await il(i,{force:!0})}}var hl={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function I(s,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:s.getHeader("X-Request-ID"),operationId:s.getHeader("X-Operation-ID")}),s.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),s.end(JSON.stringify(t))}function fl(s,e){let t=s.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let i=Buffer.from(t.slice(7),"utf8");return i.length===e.length&&al(i,e)}async function In(s,e=64*1024){let t=0,i=[];for await(let r of s){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(t+=n.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");i.push(n)}return JSON.parse(Buffer.concat(i).toString("utf8"))}async function gl(s){let e=0,t=[];for await(let i of s){let r=Buffer.isBuffer(i)?i:Buffer.from(i);if(e+=r.length,e>ri)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(r)}return Buffer.concat(t)}async function ml(s,e=0){await new Promise((i,r)=>{s.once("error",r),s.listen(e,"127.0.0.1",()=>{s.off("error",r),i()})});let t=s.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function Sn(s,e,t=new xe,i={}){t.setState({piVersion:ul});let r=process.env.PI_WEBAPP_RESTART_TOKEN,n=r&&/^[A-Za-z0-9_-]{32}$/.test(r)?r:Pn(24).toString("base64url"),o=Buffer.from(n),c=Xs(),a=new Set,l=new ei(i.pluginSettingsFile??sr(pl(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new ti(Bs(),l),u=async()=>await s.plugins?.()??{plugins:[],errors:[]},y=()=>({type:"plugin_state",disabled:p.plugins.filter(b=>!l.enabled(b.metadata.id)).map(b=>b.metadata.id)}),m=()=>{for(let b of a)b.write(`${JSON.stringify(y())}
|
|
31
|
+
`)},f=new Map,w=new si((b,v)=>t.capture(b,v)),k=b=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(b.sessionId),idle:b.idle,model:b.model,thinkingLevel:b.thinkingLevel,messageCount:b.messages.length}),P="",E=!1,_=!1,H={...hl,...await mn(e)};for(let b of await ll(sr(e,"assets")).catch(()=>[])){let v=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(b);if(!v)continue;let $={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};H[`/assets/${b}`]={path:`assets/${b}`,type:$[v[1]]}}let N=dl(async(b,v)=>{let $=Pn(18).toString("base64"),ye=pe=>typeof pe=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(pe),ve=ye(b.headers["x-request-id"])?b.headers["x-request-id"]:rr(),se={requestId:ve,operationId:ye(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",ve),se.operationId&&v.setHeader("X-Operation-ID",se.operationId);let x="/",ca=performance.now(),de=(pe,g,S)=>{let C=!Ge(pe)&&Es(x)?Ne(pe,"Agent or provider operation failed"):pe,q=t.capture(C,{...se,route:x,method:b.method,status:g,stage:"http"});I(v,g,{error:S,errorId:q,errorReported:t.enabled,errorCode:Ge(pe)?"validation_error":"unexpected_error"})};v.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...se,route:x,method:b.method,status:v.statusCode,durationMs:Math.round(performance.now()-ca)})});try{v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${$}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${t.config.browser.dsn?` ${new URL(t.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{x=new URL(b.url??"/",P).pathname}catch{I(v,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let pe=H[x];if(b.method==="GET"&&pe){try{let g=await cl(sr(e,pe.path));v.writeHead(200,{"Content-Type":pe.type,"Cache-Control":"no-store"}),v.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${$}">`):g)}catch(g){de(g,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let g=await s.hosted?.asset(x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),v.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),v.end(g.bytes)}catch{I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(b.method==="GET"&&x.startsWith("/plugins/")){try{let g=await s.pluginAsset?.(b.url??x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),v.end(g.bytes)}catch(g){de(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(v,404,{error:"\u672A\u627E\u5230"});return}if(!fl(b,o)){I(v,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(b.method==="GET"&&x==="/api/hosted-plugins"){try{I(v,200,await tr(s.hosted,x,void 0))}catch(g){let S=oi(g);I(v,S.status,S.body)}return}if(b.method==="POST"&&hn.includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){I(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let g;try{g=await In(b,2*1024*1024)}catch(S){I(v,S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{I(v,200,await tr(s.hosted,x,g,{draining:E}))}catch(S){let A=oi(S);I(v,A.status,A.body)}return}if(b.method==="GET"&&x==="/api/telemetry/config"){I(v,200,t.config.browser);return}if(b.method==="GET"&&x==="/api/update/version"){try{I(v,200,{current:await s.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Be,...s.selfUpdate?.launcherIdentity?{launcher:s.selfUpdate.launcherIdentity(),desktopHandoffProtocol:s.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){de(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{I(v,200,await s.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){de(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/image"){let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId")??"",A=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==s.snapshot().sessionId||!A||!Number.isInteger(C)||C<0||C>100){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let q=s.image?.(S,A,C);if(!q||!["image/png","image/jpeg","image/webp","image/gif"].includes(q.mimeType)){I(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":q.mimeType,"Cache-Control":"private, no-store"}),v.end(q.data);return}if(b.method==="POST"&&x==="/api/attachment"){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId"),A=g.searchParams.get("name");try{if(!S||!A||A.length>1024||S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(b.headers["content-length"]??0)>ri){I(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await en(S,A,b.headers["content-type"]??"application/octet-stream",await gl(b));if(S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}f.set(C.id,C),I(v,201,{id:C.id,name:C.name,bytes:C.bytes})}catch(C){de(C,400,C instanceof Error?C.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/session"){try{let g=s.snapshot();k(g),I(v,200,g)}catch(g){de(g,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugin-management"){try{I(v,200,p.inventory(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugins"){try{I(v,200,p.catalog(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/providers"){try{I(v,200,await s.providers?.()??[])}catch(g){de(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/models"){let g=new URL(b.url??x,P).searchParams.get("providerId")??"";try{if(!g||!s.providerModels){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(v,200,await s.providerModels(g))}catch(S){de(S,400,S instanceof Error?S.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/login/active"){I(v,200,{active:w.getActive()??null});return}if(b.method==="GET"&&x==="/api/provider/login"){let g=new URL(b.url??x,P).searchParams.get("id")??"",S=w.get(g);I(v,S?200:404,S??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(b.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{I(v,200,x==="/api/models"?await s.models():x==="/api/config"?await s.config():x==="/api/commands"?s.commands?.()??[]:await s.workspaces())}catch(g){de(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/directory/capability"){I(v,200,{kind:c});return}if(b.method==="GET"&&x==="/api/events"){let g;try{g=s.snapshot(),k(g)}catch(S){de(S,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}v.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),a.add(v),v.write(`${JSON.stringify({type:"snapshot",session:g})}
|
|
32
|
+
`),v.on("close",()=>a.delete(v));return}if(b.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){I(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let g;try{g=await In(b,x==="/api/plugin-action"?544*1024:64*1024)}catch(S){if(S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){I(v,413,{error:S.message});return}if(S instanceof SyntaxError||Ge(S)){I(v,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw S}if(x==="/api/desktop/handoff"){let S=g;if(!S||typeof S.nonce!="string"||typeof S.requestId!="string"){I(v,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!s.selfUpdate?.requestLauncherHandoff){I(v,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(E||_||w.getActive()){I(v,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let A=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||A){I(v,409,{error:A??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}E=!0;try{await s.selfUpdate.requestLauncherHandoff(S.nonce,S.requestId)}catch(C){throw E=!1,C}I(v,202,{accepted:!0,protocol:1,requestId:S.requestId});return}if(typeof g!="object"||g===null||!("sessionId"in g)||typeof g.sessionId!="string"){I(v,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(E&&x!=="/api/update/cancel"){I(v,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(x==="/api/plugin-management"){let S=g;if(typeof S.id!="string"||S.id.length>200||typeof S.enabled!="boolean"||typeof S.expected!="string"){I(v,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let A=()=>{if(s.snapshot().sessionId!==g.sessionId)throw new Q("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length)throw new Q("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(S.id,S.enabled,S.expected,A),I(v,200,p.inventory(await u()))}catch(C){if(C instanceof Q)I(v,C.status,{error:C.message});else throw C}finally{m()}return}if(p.mutating&&x!=="/api/abort"){I(v,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:x,body:g,res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(S,A)=>I(v,S,A)}))return;if(x==="/api/plugin-interaction"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("requestId"in g)||typeof g.requestId!="string"||g.requestId.length>200||!s.resolvePluginInteraction||!("value"in g)){I(v,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(s.snapshot().cwd,async()=>s.resolvePluginInteraction(g.sessionId,g.pluginId,g.requestId,g.value)),I(v,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("action"in g)||typeof g.action!="string"||g.action.length>100){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(C=>C.metadata.id===g.pluginId)){let C=p.actionRoute(g.pluginId,g.action);if(!C){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let q="input"in g?g.input:{};if(!q||typeof q!="object"||Array.isArray(q)){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...q,sessionId:g.sessionId},res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(be,Jt)=>I(v,be,be>=200&&be<300?{value:Jt}:Jt)});return}if(!s.invokePluginAction){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let A=await p.coordinateStart(s.snapshot().cwd,async()=>s.invokePluginAction(g.sessionId,g.pluginId,g.action,"input"in g?g.input:void 0));I(v,200,{value:A});return}if(x==="/api/update/channel"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in g)||g.channel!=="stable"&&g.channel!=="alpha"){I(v,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!s.selfUpdate?.setChannel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}I(v,200,await s.selfUpdate.setChannel(g.channel));return}if(x==="/api/update/cancel"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.selfUpdate?.cancel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await s.selfUpdate.cancel(),I(v,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(_){I(v,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.snapshot().idle){I(v,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!s.selfUpdate){I(v,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let S=p.restartBlocker();if((s.busyGitWorkspaces?.()??[]).length||S){I(v,409,{error:S??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let A=g,C="channel"in A||"version"in A||"allowDowngrade"in A;if(C&&(A.channel!=="stable"&&A.channel!=="alpha"||typeof A.version!="string"||A.allowDowngrade!==void 0&&typeof A.allowDowngrade!="boolean")){I(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}_=!0;let q;try{q=await s.selfUpdate.prepare(C?{channel:A.channel,version:A.version,allowDowngrade:A.allowDowngrade}:void 0);let be=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||be)throw new Error(be??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");E=!0,await s.selfUpdate.requestRestart(q)}catch(be){throw E=!1,be}finally{_=!1}I(v,202,{accepted:!0,version:q.version});return}if(x==="/api/provider/custom"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in g)||!er(g.provider)||!s.addCustomProvider){I(v,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await s.addCustomProvider(g.sessionId,g.provider),I(v,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in g)||typeof g.providerId!="string"){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(x==="/api/provider/models"){if(!("change"in g)||!on(g.change)||!s.updateProviderModel){I(v,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await s.updateProviderModel(g.sessionId,g.providerId,g.change)}else{if(!s.logoutProvider){I(v,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await s.logoutProvider(g.sessionId,g.providerId)}I(v,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(x==="/api/provider/login"){if(!("providerId"in g)||typeof g.providerId!="string"||!("method"in g)||g.method!=="api_key"&&g.method!=="oauth"||!s.loginProvider||!s.providers){I(v,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await s.providers()).some(q=>q.id===g.providerId&&q.methods.includes(g.method))){I(v,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let A="initialSecret"in g?g.initialSecret:void 0;if(A!==void 0&&(g.method!=="api_key"||typeof A!="string"||!A.trim()||A.length>16384)){I(v,400,{error:"API Key \u65E0\u6548"});return}let C=w.start(g.providerId,g.method,s.loginProvider,A,se);I(v,202,{id:C.id});return}if(!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(x==="/api/provider/login/cancel"){I(v,w.cancel(g.id)?202:404,{accepted:!0});return}if(!("value"in g)||typeof g.value!="string"||g.value.length>16384||!w.respond(g.id,g.value)){I(v,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}I(v,202,{accepted:!0});return}if(x==="/api/attachment/remove"){if(!("id"in g)||typeof g.id!="string"||g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}f.get(g.id)?.sessionId===g.sessionId&&f.delete(g.id),I(v,202,{accepted:!0});return}if(x==="/api/directory/pick"){if(c!=="native"){I(v,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let S=new AbortController;v.once("close",()=>S.abort()),I(v,200,{path:await Ys(S.signal)});return}if(x==="/api/directory/list"){if("path"in g&&(typeof g.path!="string"||g.path.length>4096)){I(v,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}I(v,200,await Js("path"in g?g.path:void 0));return}if(x==="/api/directory/create"){if(!("path"in g)||typeof g.path!="string"||g.path.length>4096||!("name"in g)||typeof g.name!="string"||g.name.length>255){I(v,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}I(v,200,{path:await Ks(g.path,g.name)});return}if(x==="/api/workspace/add"){if(!("path"in g)||typeof g.path!="string"||g.path.length>4096||!("create"in g)||typeof g.create!="boolean"){I(v,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await s.addWorkspace(g.path,g.create),I(v,202,{accepted:!0});return}if(x==="/api/workspace/select"||x==="/api/workspace/remove"||x==="/api/workspace/new-session"){if(!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}x==="/api/workspace/select"?await s.selectWorkspace(g.id):x==="/api/workspace/new-session"?await s.newSessionInWorkspace(g.id):await s.removeWorkspace(g.id),I(v,202,{accepted:!0});return}if(x==="/api/session/select"){if(!("workspaceId"in g)||typeof g.workspaceId!="string"||!("id"in g)||typeof g.id!="string"||!("path"in g)||typeof g.path!="string"){I(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await s.selectSession(g.workspaceId,g.id,g.path),I(v,202,{accepted:!0});return}if(x==="/api/session/rename"||x==="/api/session/delete"){if(!("workspaceId"in g)||typeof g.workspaceId!="string"||!("id"in g)||typeof g.id!="string"||!("path"in g)||typeof g.path!="string"||g.path.length>4096){I(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(x==="/api/session/rename"){if(!("name"in g)||typeof g.name!="string"){I(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!s.renameSession){I(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await s.renameSession(g.workspaceId,g.id,g.path,g.name)}else{if(!s.deleteSession){I(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await s.deleteSession(g.workspaceId,g.id,g.path)}I(v,202,{accepted:!0});return}if(x==="/api/thinking-level"){if(!("level"in g)||typeof g.level!="string"){I(v,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await s.setThinkingLevel(g.sessionId,g.level)}else if(x==="/api/model"){if(!("provider"in g)||typeof g.provider!="string"||!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await s.setModel(g.sessionId,g.provider,g.id)}else if(x==="/api/config"){let S=g;if(!["packages","extensions","skills"].includes(S.kind)||!["global","project"].includes(S.scope)||!["add","remove"].includes(S.action)||typeof S.value!="string"||!S.value.trim()||S.value.length>2048){I(v,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(S.action==="add"&&S.kind!=="packages"&&pn(S.value)){I(v,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}I(v,200,await s.updateConfig(S));return}else if(x==="/api/prompt-queue"){let S=g,A=S.action;if(typeof S.id!="string"||S.id.length>100||!Number.isSafeInteger(S.revision)||S.revision<1||!A||typeof A!="object"||!["edit","remove","steer"].includes(A.kind)||A.kind==="edit"&&(typeof A.text!="string"||A.text.length>32e3)){I(v,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let C=s.snapshot();if(S.sessionId!==C.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(A.kind==="steer"&&C.idle){I(v,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(A.kind==="steer"&&C.interactions?.length){I(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!s.updateQueuedPrompt){I(v,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(C.cwd,async()=>s.updateQueuedPrompt(g.sessionId,S.id,S.revision,A))}else if(x==="/api/message"){let S="delivery"in g?g.delivery:void 0;if(S!==void 0&&S!=="steer"&&S!=="followUp"){I(v,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let A="attachments"in g?g.attachments:[];if(!Array.isArray(A)||A.length>Zs||A.some(oe=>typeof oe!="string")||new Set(A).size!==A.length){I(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=A.map(oe=>f.get(oe));if(C.some(oe=>!oe||oe.sessionId!==g.sessionId)){I(v,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in g)||typeof g.text!="string"||!g.text.trim()&&A.length===0||g.text.length>32e3){I(v,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let q=s.snapshot();if(g.sessionId!==q.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{We(q,g.text,S)}catch(oe){I(v,409,{error:oe.message});return}let be=C,Jt=[g.text.trim(),...be.map(oe=>`\u9644\u4EF6 ${JSON.stringify(oe.name)}\uFF1A${oe.path}`)].filter(Boolean).join(`
|
|
33
33
|
|
|
34
|
-
`),
|
|
35
|
-
`;for(let
|
|
36
|
-
`);c.clear();let y;try{await new Promise((K,Pe)=>{S.close(Re=>Re?Pe(Re):K()),y=setTimeout(()=>S.closeAllConnections(),50).unref()})}finally{clearTimeout(y),await t.close()}}}}import{getSupportedThinkingLevels as Dc}from"@earendil-works/pi-ai";var xt="pi-webapp/paused",zr="pi-webapp/resume";function st(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(t.type==="custom_message"&&t.customType===zr)return!1;if(t.type==="custom"&&t.customType===xt)return!0;if(t.type==="message"){if(t.message.role==="user")return!1;if(t.message.role==="assistant"){if(t.message.stopReason==="aborted")return!0;if(t.message.stopReason==="stop"||t.message.stopReason==="length"||t.message.stopReason==="error")return!1}}}return!1}function qr(n,e){let t=[],r;for(let i of n){if(i.type==="message"&&(r=i.id),i.type!=="custom")continue;let s=e.find(o=>i.customType.startsWith(`${o}/`));if(s){try{if(JSON.stringify(i.data).length>128*1024)continue}catch{continue}t.push({id:i.id,pluginId:s,kind:i.customType,data:i.data,timestamp:i.timestamp,...r?{afterMessageId:r}:{}})}}return t}function Le(n){return typeof n=="string"?[{kind:"text",text:n}]:n.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function ir(n){if(n.type==="custom_message")return n.display?{id:n.id,role:"notice",timestamp:n.timestamp,blocks:Le(n.content)}:null;if(n.type!=="message")return null;let{message:e}=n;return e.role==="user"||e.role==="assistant"?{id:n.id,role:e.role,timestamp:n.timestamp,blocks:Le(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:n.id,role:"tool",timestamp:n.timestamp,blocks:Le(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function nr(n,e){let t=n?.trim();if(t)return t;let r=e.find(s=>s.role==="user"),i=Et(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim();return i?i.slice(0,50):"\u5F53\u524D\u4F1A\u8BDD"}function ns(n,e,t=[]){let r=n.sessionManager.getBranch().flatMap(i=>{let s=ir(i);return s?[s]:[]});return{schemaVersion:1,sessionId:n.sessionManager.getSessionId(),cwd:n.cwd,name:nr(e,r),model:n.model?`${n.model.provider}/${n.model.id}`:null,thinkingLevel:n.thinkingLevel??null,thinkingLevels:n.model?Dc(n.model):["off"],idle:n.isIdle(),paused:st(n.sessionManager.getBranch()),contextUsage:n.getContextUsage()??null,messages:r,pluginEntries:qr(n.sessionManager.getBranch(),t)}}import{randomUUID as Gr}from"node:crypto";import{mkdir as ss,readFile as Mc,realpath as Jr,rename as jc,rm as Wc,stat as Kr,writeFile as Vc}from"node:fs/promises";import{basename as os,dirname as $c,isAbsolute as as,join as Fc}from"node:path";var _t=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function ot(n){try{let e=await Jr(n);return(await Kr(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Ue(n){let e=await ot(n);if(e===null)throw new _t;return e}var sr=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Mc(this.file,"utf8")),t,r=[];if(Array.isArray(e)?t=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(t=e.items,r=e.hiddenPaths),!Array.isArray(t)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=t.filter(i=>typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.path=="string"&&typeof i.title=="string"),this.hiddenPaths=r.filter(i=>typeof i=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(t=>t.id===e)}async add(e,t=!1){if(!as(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await ss(e,{recursive:!0});let r=await Jr(e);if(!(await Kr(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let i=this.hiddenPaths.filter(c=>c!==r),s=this.items.find(c=>c.path===r);if(s)return i.length!==this.hiddenPaths.length&&(await this.save(this.items,i),this.hiddenPaths=i),s;let o={id:Gr(),path:r,title:os(r)||r},a=[o,...this.items];return await this.save(a,i),this.items=a,this.hiddenPaths=i,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter(as).map(async r=>{try{let i=await Jr(r);return(await Kr(i)).isDirectory()?i:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),i=[];for(let o of t)r.has(o)||(r.add(o),i.push({id:Gr(),path:o,title:os(o)||o}));if(i.length===0)return;let s=[...this.items,...i];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let t=this.get(e);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),i=[...new Set([...this.hiddenPaths,t.path])];await this.save(r,i),this.items=r,this.hiddenPaths=i})}mutate(e){let t=this.mutationChain.then(e,e);return this.mutationChain=t.then(()=>{},()=>{}),t}async save(e,t){await ss($c(this.file),{recursive:!0});let r=`${this.file}.${Gr()}.tmp`;try{await Vc(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await jc(r,this.file)}catch(i){throw await Wc(r,{force:!0}),i}}};function cs(n){return Fc(n,"pi-web","workspaces.json")}import{createAgentSession as Rl,createEventBus as Cl,DefaultResourceLoader as Nl,getAgentDir as Ol,SessionManager as lr,VERSION as dr}from"@earendil-works/pi-coding-agent";var Bc="pi-webapp:interaction-open:v1",Lc="pi-webapp:interaction-accept:v1",ls="pi-webapp:interaction-settle:v1",Uc="pi-webapp:interaction-cancel:v1";var at=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,r){this.bus=e,this.accepts=t,this.changed=r,this.detach=[e.on(Bc,i=>{!zc(i)||!t(i)||this.requests.has(i.requestId)||(this.requests.set(i.requestId,i),e.emit(Lc,{requestId:i.requestId}),r())}),e.on(Uc,i=>{let s=i,o=this.requests.get(s?.requestId);o&&o.sessionId===s.sessionId&&o.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,r,i){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==t||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(ls,{requestId:r,value:i}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(ls,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function zc(n){if(!n||typeof n!="object")return!1;let e=n;for(let t of["requestId","sessionId","pluginId","kind"])if(typeof e[t]!="string"||!e[t]||e[t].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function ze(n){return typeof n=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(n)&&n.length<=512&&!n.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function ct(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&ze(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&ze(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&ze(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&ze(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(t=>Number.isSafeInteger(t)&&t>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(t=>typeof t=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(t))}var qc=1,Gc="pi-webapp:action:v1",Jc="pi-webapp:action-response:v1",or="pi-webapp:plugin-changed:v1";function ds(n){if(!n||typeof n!="object")return!1;let e=n;return e.apiVersion===qc&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function ar(n,e,t=15e3,r){return new Promise((i,s)=>{let o=!1,a=(f,u)=>{o||(o=!0,clearTimeout(l),c(),r?.removeEventListener("abort",p),f?s(f):i(u))},c=n.on(Jc,f=>{let u=f;u?.requestId===e.requestId&&a(u.ok?null:new Error(u.error??"Plugin action failed"),u.value)}),l=setTimeout(()=>a(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),t),p=()=>a(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{n.emit(Gc,e)}catch(f){a(f instanceof Error?f:new Error(String(f)))}})}import{realpath as Hl}from"node:fs/promises";import{readFile as Xr,realpath as hs,stat as gs}from"node:fs/promises";import{createHash as Kc}from"node:crypto";import{dirname as ps,isAbsolute as Xc,join as Yr,parse as Yc,resolve as Qc,sep as Zc,delimiter as el}from"node:path";import{DefaultPackageManager as tl,getAgentDir as rl,SettingsManager as il}from"@earendil-works/pi-coding-agent";async function us(n,e){let t=await Xr(n),r=e?await Xr(e):void 0;if(t.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let i=Kc("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:i}}function nl(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(el).filter(Boolean).map(n=>Qc(n))}async function sl(n){let e=ps(n);for(;e!==Yc(e).root;)try{return await gs(Yr(e,"package.json")),e}catch{e=ps(e)}return null}async function fs(n,e){let t=await hs(Yr(n,e));if(!t.startsWith(n+Zc))throw new Error("Asset escapes package root");let r=await gs(t);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return t}var qe=class n{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=nl()){let i=il.create(e,void 0,{projectTrusted:t}),s=new tl({cwd:e,agentDir:rl(),settingsManager:i}),o=await s.resolve(async()=>"skip"),a=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},c=new Set;for(let h of[...o.extensions,...a.extensions]){if(!h.enabled)continue;let g=await sl(h.path);g&&c.add(g)}for(let h of r)Xc(h)&&c.add(h);let l=[],p=[],f=[],u=new Set;for(let h of c)try{let g=await hs(h),v=JSON.parse(await Xr(Yr(g,"package.json"),"utf8"));if(v.piWebapp===void 0)continue;if(typeof v.name!="string"||!v.name)throw new Error("Missing package name");if(!ds(v.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(u.has(v.name))throw new Error(`Duplicate plugin id: ${v.name}`);let x=await fs(g,v.piWebapp.client),I=v.piWebapp.style?await fs(g,v.piWebapp.style):void 0;u.add(v.name),l.push({id:v.name,root:g,manifest:v.piWebapp,clientPath:x,stylePath:I,...await us(x,I)}),f.push(g)}catch(g){p.push(`${h}: ${g instanceof Error?g.message:String(g)}`)}return l.sort((h,g)=>h.id.localeCompare(g.id)),new n(l,p,f)}has(e){return this.plugins.some(t=>t.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await us(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let t=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(t.pathname);if(!r)return null;let i;try{i=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(a=>a.id===i);if(!s||t.searchParams.has("v")&&t.searchParams.get("v")!==s.revision)return null;let o=r[2]==="client.js"?s.clientBytes:s.styleBytes;return o?{bytes:o,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as ol}from"node:fs/promises";import{SessionManager as al}from"@earendil-works/pi-coding-agent";async function Tt(n,e){let t=await Ue(n),r=e??await al.listAll(),i=await Promise.all(r.map(async s=>s.cwd!==""&&await ol(s.cwd).catch(()=>null)===t));return r.filter((s,o)=>i[o])}var Ge=class{tail=Promise.resolve();run(e){let t=this.tail.then(e);return this.tail=t.catch(()=>{}),t}wrap(e){return(...t)=>this.run(()=>e(...t))}},ms=new WeakMap;function ws(n,e,t,r=5e3,i=()=>{}){let s=ms.get(n);if(s)return s;let o=(async()=>{let a;try{await Promise.race([n.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((c,l)=>{a=setTimeout(()=>l(new Error("Plugin shutdown timed out")),r)})])}catch(c){t(c instanceof Error?c.message:String(c))}finally{clearTimeout(a);try{i()}finally{n.dispose()}}})();return ms.set(n,o),o}function cr(n){let t=[...n].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
|
|
37
|
-
`);return{customType:
|
|
34
|
+
`),la=await Promise.all(be.filter(oe=>["image/png","image/jpeg","image/webp","image/gif"].includes(oe.mediaType)).map(tn));se.operationId??=rr(),v.setHeader("X-Operation-ID",se.operationId),t.breadcrumb("send",{...se,attachmentCount:be.length}),await p.coordinateStart(q.cwd,async()=>s.send(g.sessionId,Jt,la,se,S));for(let oe of A)f.delete(oe)}else if(x==="/api/compact"){if(!s.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await s.compact(g.sessionId)}else if(x==="/api/resume"){let S=s.snapshot();if(g.sessionId!==S.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!S.idle){I(v,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!S.paused){I(v,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(S.interactions?.length){I(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!s.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");se.operationId??=rr(),v.setHeader("X-Operation-ID",se.operationId),t.breadcrumb("resume",{...se}),await p.coordinateStart(S.cwd,async()=>s.resume(g.sessionId,se))}else x==="/api/abort"?await s.abort(g.sessionId):await s.newSession(g.sessionId);I(v,202,{accepted:!0})}catch(g){if(g instanceof ae){I(v,g.status,{error:g.message});return}let S=p.requestFailure(g);if(S){I(v,S.status,S.body);return}let A=g instanceof Error?g.message:"\u8BF7\u6C42\u5931\u8D25";de(g,A==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,A)}return}I(v,404,{error:"\u672A\u627E\u5230"})}catch(pe){v.headersSent?(t.capture(pe,{...se,route:x,stage:"http_stream"}),v.end()):de(pe,500,"\u8BF7\u6C42\u5931\u8D25")}}),T=Number(process.env.PI_WEBAPP_RESTART_PORT),Y;try{Y=await ml(N,Number.isInteger(T)&&T>0&&T<65536&&r===n?T:0)}catch(b){throw t.capture(b,{stage:"listen"}),await t.close(),b}return P=`http://127.0.0.1:${Y}`,{protocolVersion:7,buildId:Se,runPluginTool:(b,v,$,ye,ve)=>p.runAgentAction(b,v,$,ye,ve),reportError(b,v){return t.capture(b,v)},breadcrumb(b,v){t.breadcrumb(b,v)},url:`${P}/#${n}`,publish(b){if(b.type==="snapshot"&&k(b.session),b.type==="error"&&!b.errorCode&&(b={...b,errorCode:"unexpected_error",errorId:t.capture(new Error("Agent execution failed"),{stage:"agent",requestId:b.requestId,operationId:b.operationId})}),b.type==="error"&&(b={...b,errorReported:b.errorReported??t.enabled}),b.type==="snapshot")for(let[$,ye]of f)ye.sessionId!==b.session.sessionId&&f.delete($);let v=`${JSON.stringify(b)}
|
|
35
|
+
`;for(let $ of a)$.write(v)},async close(b){w.close(),await p.close();for(let $ of a)$.end(`${JSON.stringify({type:"shutdown",reconnect:b?.reconnect??E})}
|
|
36
|
+
`);a.clear();let v;try{await new Promise(($,ye)=>{N.close(ve=>ve?ye(ve):$()),v=setTimeout(()=>N.closeAllConnections(),50).unref()})}finally{clearTimeout(v),await t.close()}}}}import{getSupportedThinkingLevels as wl}from"@earendil-works/pi-ai";var Dt="pi-webapp/paused",nr="pi-webapp/resume";function pt(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="custom_message"&&t.customType===nr)return!1;if(t.type==="custom"&&t.customType===Dt)return!0;if(t.type==="message"){if(t.message.role==="user")return!1;if(t.message.role==="assistant"){if(t.message.stopReason==="aborted")return!0;if(t.message.stopReason==="stop"||t.message.stopReason==="length"||t.message.stopReason==="error")return!1}}}return!1}function or(s,e){let t=[],i;for(let r of s){if(r.type==="message"&&(i=r.id),r.type!=="custom")continue;let n=e.find(o=>r.customType.startsWith(`${o}/`));if(n){try{if(JSON.stringify(r.data).length>128*1024)continue}catch{continue}t.push({id:r.id,pluginId:n,kind:r.customType,data:r.data,timestamp:r.timestamp,...i?{afterMessageId:i}:{}})}}return t}function Je(s){return typeof s=="string"?[{kind:"text",text:s}]:s.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function Nt(s){if(s.type==="custom_message")return s.display?{id:s.id,role:"notice",timestamp:s.timestamp,blocks:Je(s.content)}:null;if(s.type!=="message")return null;let{message:e}=s;return e.role==="user"||e.role==="assistant"?{id:s.id,role:e.role,timestamp:s.timestamp,blocks:Je(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:s.id,role:"tool",timestamp:s.timestamp,blocks:Je(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function pi(s,e){let t=s?.trim();if(t)return t;let i=e.find(n=>n.role==="user");return Rt(i?.blocks.find(n=>n.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function En(s,e,t=[]){let i=s.sessionManager.getBranch().flatMap(r=>{let n=Nt(r);return n?[n]:[]});return{schemaVersion:1,sessionId:s.sessionManager.getSessionId(),cwd:s.cwd,name:pi(e,i),model:s.model?`${s.model.provider}/${s.model.id}`:null,thinkingLevel:s.thinkingLevel??null,thinkingLevels:s.model?wl(s.model):["off"],idle:s.isIdle(),paused:pt(s.sessionManager.getBranch()),contextUsage:s.getContextUsage()??null,messages:i,pluginEntries:or(s.sessionManager.getBranch(),t)}}import{randomUUID as ar}from"node:crypto";import{mkdir as xn,readFile as yl,realpath as cr,rename as vl,rm as bl,stat as lr,writeFile as kl}from"node:fs/promises";import{basename as _n,dirname as Pl,isAbsolute as An,join as Il}from"node:path";var Ht=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function Ke(s){try{let e=await cr(s);return(await lr(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Ae(s){let e=await Ke(s);if(e===null)throw new Ht;return e}var ui=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await yl(this.file,"utf8")),t,i=[];if(Array.isArray(e)?t=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(t=e.items,i=e.hiddenPaths),!Array.isArray(t)||!Array.isArray(i))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=t.filter(r=>typeof r=="object"&&r!==null&&typeof r.id=="string"&&typeof r.path=="string"&&typeof r.title=="string"),this.hiddenPaths=i.filter(r=>typeof r=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(t=>t.id===e)}async add(e,t=!1){if(!An(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await xn(e,{recursive:!0});let i=await cr(e);if(!(await lr(i)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let r=this.hiddenPaths.filter(a=>a!==i),n=this.items.find(a=>a.path===i);if(n)return r.length!==this.hiddenPaths.length&&(await this.save(this.items,r),this.hiddenPaths=r),n;let o={id:ar(),path:i,title:_n(i)||i},c=[o,...this.items];return await this.save(c,r),this.items=c,this.hiddenPaths=r,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter(An).map(async i=>{try{let r=await cr(i);return(await lr(r)).isDirectory()?r:null}catch{return null}}))).filter(i=>i!==null);await this.mutate(async()=>{let i=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),r=[];for(let o of t)i.has(o)||(i.add(o),r.push({id:ar(),path:o,title:_n(o)||o}));if(r.length===0)return;let n=[...this.items,...r];await this.save(n,this.hiddenPaths),this.items=n})}async remove(e){await this.mutate(async()=>{let t=this.get(e);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let i=this.items.filter(n=>n.id!==e),r=[...new Set([...this.hiddenPaths,t.path])];await this.save(i,r),this.items=i,this.hiddenPaths=r})}mutate(e){let t=this.mutationChain.then(e,e);return this.mutationChain=t.then(()=>{},()=>{}),t}async save(e,t){await xn(Pl(this.file),{recursive:!0});let i=`${this.file}.${ar()}.tmp`;try{await kl(i,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await vl(i,this.file)}catch(r){throw await bl(i,{force:!0}),r}}};function Tn(s){return Il(s,"pi-web","workspaces.json")}import{createAgentSession as ud,createEventBus as hd,DefaultResourceLoader as fd,getAgentDir as gd,SessionManager as Mt,VERSION as mi}from"@earendil-works/pi-coding-agent";var Sl="pi-webapp:interaction-open:v1",El="pi-webapp:interaction-accept:v1",Rn="pi-webapp:interaction-settle:v1",xl="pi-webapp:interaction-cancel:v1";var ut=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,i){this.bus=e,this.accepts=t,this.changed=i,this.detach=[e.on(Sl,r=>{!_l(r)||!t(r)||this.requests.has(r.requestId)||(this.requests.set(r.requestId,r),e.emit(El,{requestId:r.requestId}),i())}),e.on(xl,r=>{let n=r,o=this.requests.get(n?.requestId);o&&o.sessionId===n.sessionId&&o.pluginId===n.pluginId&&(this.requests.delete(n.requestId),i())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,i,r){let n=this.requests.get(i);if(!n||n.sessionId!==e||n.pluginId!==t||!this.accepts(n))throw new Error("Interaction expired or session changed");this.requests.delete(i),this.bus.emit(Rn,{requestId:i,value:r}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(Rn,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function _l(s){if(!s||typeof s!="object")return!1;let e=s;for(let t of["requestId","sessionId","pluginId","kind"])if(typeof e[t]!="string"||!e[t]||e[t].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function Xe(s){return typeof s=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(s)&&s.length<=512&&!s.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function Ue(s){if(!s||typeof s!="object"||Array.isArray(s))return!1;let e=s;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&Xe(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Xe(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Xe(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Xe(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(t=>Number.isSafeInteger(t)&&t>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(t=>typeof t=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(t))}var Al=1,Tl="pi-webapp:action:v1",Rl="pi-webapp:action-response:v1",hi="pi-webapp:plugin-changed:v1";function Cn(s){if(!s||typeof s!="object")return!1;let e=s;return e.apiVersion===Al&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function fi(s,e,t=15e3,i){return new Promise((r,n)=>{let o=!1,c=(u,y)=>{o||(o=!0,clearTimeout(l),a(),i?.removeEventListener("abort",p),u?n(u):r(y))},a=s.on(Rl,u=>{let y=u;y?.requestId===e.requestId&&c(y.ok?null:new Error(y.error??"Plugin action failed"),y.value)}),l=setTimeout(()=>c(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),t),p=()=>c(new Error("Plugin action runtime unloaded"));if(i?.addEventListener("abort",p,{once:!0}),i?.aborted)p();else try{s.emit(Tl,e)}catch(u){c(u instanceof Error?u:new Error(String(u)))}})}import{realpath as md}from"node:fs/promises";import{readFile as dr,realpath as On,stat as Mn}from"node:fs/promises";import{createHash as Cl}from"node:crypto";import{dirname as Dn,isAbsolute as Dl,join as pr,parse as Nl,resolve as Hl,sep as Ol,delimiter as Ml}from"node:path";import{DefaultPackageManager as jl,getAgentDir as Wl,SettingsManager as $l}from"@earendil-works/pi-coding-agent";async function Nn(s,e){let t=await dr(s),i=e?await dr(e):void 0;if(t.length>8*1024*1024||(i?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let r=Cl("sha256").update(t).update("\0").update(i??"").digest("hex");return{clientBytes:t,styleBytes:i,revision:r}}function Vl(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Ml).filter(Boolean).map(s=>Hl(s))}async function Fl(s){let e=Dn(s);for(;e!==Nl(e).root;)try{return await Mn(pr(e,"package.json")),e}catch{e=Dn(e)}return null}async function Hn(s,e){let t=await On(pr(s,e));if(!t.startsWith(s+Ol))throw new Error("Asset escapes package root");let i=await Mn(t);if(!i.isFile()||i.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return t}var Ye=class s{plugins;errors;extensionRoots;constructor(e,t,i){this.plugins=e,this.errors=t,this.extensionRoots=i}static async discover(e,t,i=Vl()){let r=$l.create(e,void 0,{projectTrusted:t}),n=new jl({cwd:e,agentDir:Wl(),settingsManager:r}),o=await n.resolve(async()=>"skip"),c=i.length?await n.resolveExtensionSources(i,{temporary:!0}):{extensions:[]},a=new Set;for(let m of[...o.extensions,...c.extensions]){if(!m.enabled)continue;let f=await Fl(m.path);f&&a.add(f)}for(let m of i)Dl(m)&&a.add(m);let l=[],p=[],u=[],y=new Set;for(let m of a)try{let f=await On(m),w=JSON.parse(await dr(pr(f,"package.json"),"utf8"));if(w.piWebapp===void 0)continue;if(typeof w.name!="string"||!w.name)throw new Error("Missing package name");if(!Cn(w.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(y.has(w.name))throw new Error(`Duplicate plugin id: ${w.name}`);let k=await Hn(f,w.piWebapp.client),P=w.piWebapp.style?await Hn(f,w.piWebapp.style):void 0;y.add(w.name),l.push({id:w.name,root:f,manifest:w.piWebapp,clientPath:k,stylePath:P,...await Nn(k,P)}),u.push(f)}catch(f){p.push(`${m}: ${f instanceof Error?f.message:String(f)}`)}return l.sort((m,f)=>m.id.localeCompare(f.id)),new s(l,p,u)}has(e){return this.plugins.some(t=>t.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await Nn(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let t=new URL(e,"http://localhost"),i=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(t.pathname);if(!i)return null;let r;try{r=decodeURIComponent(i[1])}catch{return null}let n=this.plugins.find(c=>c.id===r);if(!n||t.searchParams.has("v")&&t.searchParams.get("v")!==n.revision)return null;let o=i[2]==="client.js"?n.clientBytes:n.styleBytes;return o?{bytes:o,type:i[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as Bl}from"node:fs/promises";import{SessionManager as Ul}from"@earendil-works/pi-coding-agent";async function ht(s,e){let t=await Ae(s),i=e??await Ul.listAll(),r=await Promise.all(i.map(async n=>n.cwd!==""&&await Bl(n.cwd).catch(()=>null)===t));return i.filter((n,o)=>r[o])}var Qe=class{tail=Promise.resolve();run(e){let t=this.tail.then(e);return this.tail=t.catch(()=>{}),t}wrap(e){return(...t)=>this.run(()=>e(...t))}},jn=new WeakMap;function Wn(s,e,t,i=5e3,r=()=>{}){let n=jn.get(s);if(n)return n;let o=(async()=>{let c;try{await Promise.race([s.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((a,l)=>{c=setTimeout(()=>l(new Error("Plugin shutdown timed out")),i)})])}catch(a){t(a instanceof Error?a.message:String(a))}finally{clearTimeout(c);try{r()}finally{s.dispose()}}})();return jn.set(s,o),o}function gi(s){let t=[...s].reverse().find(i=>i.role==="assistant")?.blocks.filter(i=>i.kind==="text").map(i=>i.text).join(`
|
|
37
|
+
`);return{customType:nr,display:!1,details:{action:"resume"},content:"The user clicked Continue for the interrupted turn. Continue the response to the latest user request from the interrupted point. Preserve completed work and do not repeat text already delivered. Check existing task progress when needed."+(t?`
|
|
38
38
|
Already displayed assistant text (reference data):
|
|
39
|
-
${JSON.stringify(t)}`:"")}}import{createHash as
|
|
39
|
+
${JSON.stringify(t)}`:"")}}import{createHash as Ll}from"node:crypto";import{readFile as zl,writeFile as ql,unlink as Gl}from"node:fs/promises";import{basename as Jl,dirname as Kl,extname as Xl,join as Yl}from"node:path";import{DefaultPackageManager as Ql,getAgentDir as Zl,SettingsManager as ed}from"@earendil-works/pi-coding-agent";var Ot=new Map;async function $n(s,e){let i=await new Ql({cwd:s,agentDir:Zl(),settingsManager:ed.create(s)}).resolveExtensionSources([...e],{temporary:!0}),r=[],n=[],o=async()=>{for(let c of r.splice(0)){let a=(Ot.get(c)??1)-1;a?Ot.set(c,a):(Ot.delete(c),await Gl(c).catch(()=>{}))}};try{for(let c of i.extensions){if(!c.enabled)continue;let a=Xl(c.path);if(![".js",".mjs"].includes(a)){n.push(c.path);continue}let l=await zl(c.path),p=Ll("sha256").update(l).digest("hex"),u=Yl(Kl(c.path),`.pi-web-runtime-${Jl(c.path,a)}-${p}${a}`);await ql(u,l,{flag:"wx"}).catch(y=>{if(y.code!=="EEXIST")throw y}),Ot.set(u,(Ot.get(u)??0)+1),r.push(u),n.push(u)}return{paths:n,release:o}}catch(c){throw await o(),c}}import{createHash as td}from"node:crypto";var ur={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},Le=s=>s!==null&&typeof s=="object"?s:void 0,id=[{pattern:/^Could not find (?:the exact text in [^\r\n]+\. The old text|edits\[\d+\] in [^\r\n]+\. The oldText) must match exactly including all whitespace and newlines\.$/,code:"edit_text_not_found",summary:"Edit text does not match the file"},{pattern:/^Found \d+ occurrences of (?:the text in [^\r\n]+\. The text|edits\[\d+\] in [^\r\n]+\. Each oldText) must be unique\. Please provide more context to make it unique\.$/,code:"edit_text_ambiguous",summary:"Edit text matches multiple locations"},{pattern:/^(?:edits\[\d+\]\.)?oldText must not be empty in [^\r\n]+\.$/,code:"invalid_arguments",summary:"Edit oldText must not be empty"},{pattern:/^No changes made to [^\r\n]+\. (?:The replacement produced identical content\. This might indicate an issue with special characters or the text not existing as expected\.|The replacements produced identical content\.)$/,code:"edit_no_change",summary:"Edit replacement produced no changes"},{pattern:/^edits\[\d+\] and edits\[\d+\] overlap in [^\r\n]+\. Merge them into one edit or target disjoint regions\.$/,code:"edit_overlap",summary:"Edit replacements overlap"}];function Fn(s,e){let t=s instanceof Error?s:Le(s)?.error instanceof Error?Le(s).error:void 0,i={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},r=(p,u,y)=>{Object.assign(i,{failureKind:p,errorCode:u,errorSummary:y.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete i.summaryOmittedReason},n=Le(t)?.code;if(typeof n=="string"&&ur[n]){let p=ur[n];return r(p.kind,n,`${n}: ${p.summary}`),i}let o=t?.message??"";if(!t){let p=Le(s)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(u=>{let y=Le(u);return y?.type==="text"&&typeof y.text=="string"?[y.text.length>16384?`${y.text.slice(0,8192)}
|
|
40
40
|
[truncated]
|
|
41
|
-
${
|
|
42
|
-
`))}let
|
|
43
|
-
`)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let
|
|
44
|
-
${
|
|
41
|
+
${y.text.slice(-8192)}`:y.text]:[]}).join(`
|
|
42
|
+
`))}let c=e==="bash"||e==="powershell",a=o.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(c){let p=a.match(/^Command exited with code (-?\d{1,10})$/),u=a.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return r("process_exit","nonzero_exit",a),i.exitCode=Number(p[1]),i;if(u&&Number.isFinite(Number(u[1]))&&Number(u[1])>0)return r("timeout","timeout",a),i.timeoutMs=Number(u[1])*1e3,i;if(a==="Command aborted")return r("cancelled","cancelled",a),i}let l=o.slice(0,8192).split(/\r?\n/,1)[0]??"";if(o==="Operation aborted"||t?.name==="AbortError")r("cancelled","cancelled","Operation aborted");else if(o==="Tool execution was blocked")r("blocked","blocked",o);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(o))r("not_found","ENOENT","Working directory does not exist");else if(!c||!o.includes(`
|
|
43
|
+
`)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=ur[p[1]],y=l.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);r(u.kind,p[1],`${p[1]}: ${u.summary}${y?`; operation=${y[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))r("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(l)||l==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(l))r("validation","invalid_arguments",l.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(o))r("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=id.find(y=>y.pattern.test(o));u&&r("validation",u.code,u.summary)}}return i}var rd=256;function Vn(s,e,t){s.delete(e),s.set(e,t),s.size>rd&&s.delete(s.keys().next().value)}var ft=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:Qt.has(e.toolName)?e.toolName:"custom",...Qt.has(e.toolName)?{}:{toolId:td("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,t){try{this.options.breadcrumb(e,t)}catch{}}start(e,t={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let i=e.toolName==="bash"||e.toolName==="powershell"?Le(e.args)?.timeout:void 0,r=typeof i=="number"&&i>0&&Number.isFinite(i*1e3)?i*1e3:void 0,n={...Ie(t),...this.identity(e),stage:"tool"};Vn(this.pending,e.toolCallId,{context:n,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:r}),this.breadcrumb("tool_start",n)}catch{}}end(e,t={}){this.finish(e,t,"tool_execution_end")}message(e,t={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},t,"message_end")}catch{}}finish(e,t,i){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let r=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),Vn(this.completed,e.toolCallId,!0);let n={...r?.context??{...Ie(t),...this.identity(e),stage:"tool"},diagnosticSource:i};if(r&&(n.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-r.started)),r.timeoutMs!==void 0&&(n.timeoutMs=r.timeoutMs)),!e.isError){this.breadcrumb("tool_end",n);return}let o=e.result instanceof Error?e.result:Le(e.result)?.error instanceof Error?Le(e.result).error:void 0,c=r?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:Fn(e.result,e.toolName);if(Object.assign(n,c,{code:"tool_failed"}),this.breadcrumb(c.failureKind==="cancelled"?"tool_cancelled":c.failureKind==="blocked"?"tool_blocked":"tool_failed",n),c.failureKind==="cancelled"||c.failureKind==="blocked")return;let a;o?a=Bn(o,e.toolName):(a=new Error(`${n.toolName}: ${c.failureKind} (${c.errorCode??"unknown"})`),a.name="ToolResultFailure",a.stack=void 0),this.options.capture(a,n)}catch{}}cancel(){try{if(!this.enabled())return;for(let e of this.pending.values())e.cancelled=!0}catch{}}clear(){this.pending.clear(),this.completed.clear()}};function Bn(s,e,t=0){let i=Fn(s,e),r=new Error(i.errorSummary??"Tool exception (diagnostic text unavailable)");return r.name=s.name,r.stack=s.stack?`${r.name}: ${r.message}
|
|
44
|
+
${s.stack.split(`
|
|
45
45
|
`).slice(1).join(`
|
|
46
|
-
`)}`:void 0,t<3&&n.cause instanceof Error&&(i.cause=ks(n.cause,e,t+1)),rt(i)}import{randomUUID as Es}from"node:crypto";import{randomUUID as Pl}from"node:crypto";import{EnvHttpProxyAgent as Il,getGlobalDispatcher as sg,setGlobalDispatcher as og}from"undici";var Ps=n=>({httpProxy:n.http_proxy??n.HTTP_PROXY??n.all_proxy??n.ALL_PROXY??"",httpsProxy:n.https_proxy??n.HTTPS_PROXY??n.all_proxy??n.ALL_PROXY??"",noProxy:n.no_proxy??n.NO_PROXY??""});function El(n,e){let t=Ps(n),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let i=t.noProxy.toLowerCase();if(i==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),o=r.hostname.toLowerCase();return!i.split(/[,\s]/).filter(Boolean).some(a=>{let c=a.match(/^(.+):(\d+)$/),l=(c?.[1]??a).replace(/^\*?\./,"");return(!c||Number(c[2])===s)&&(o===l||o.endsWith("."+l))})}function Sl(n){let e=Ps(n);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new Il(e)}function Zr({env:n=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:r=!1}={}){let i,s=new Set,o=t===globalThis.fetch,a=(p,f)=>{try{e(p,f)}catch{}},c=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,f)=>{let u={requestId:Pl(),phase:"headers",proxied:o&&El(n,p)},h=r?void 0:i,g=!1,v=f?.signal??(p instanceof Request?p.signal:void 0),x=()=>I(),I=()=>{v?.removeEventListener("abort",x),!g&&r&&(g=!0,c(h).catch(()=>{}))},T;try{o?(h??=Sl(n),s.add(h),r||(i=h),T=await t(p,{...f,dispatcher:h})):T=await t(p,f)}catch(R){throw a(R,u),I(),R}if(T.ok||a(void 0,{...u,status:T.status}),!T.body)return I(),T;let O=T.body.getReader();v?.addEventListener("abort",x,{once:!0}),v?.aborted&&I();let W=new ReadableStream({async pull(R){try{let L=await O.read();L.done?(R.close(),O.releaseLock(),I()):R.enqueue(L.value)}catch(L){a(L,{...u,phase:"body"}),R.error(L),O.releaseLock(),I()}},async cancel(R){try{await O.cancel(R)}finally{O.releaseLock(),I()}}}),S=new Response(W,{status:T.status,statusText:T.statusText,headers:T.headers});return Object.defineProperties(S,{url:{value:T.url},redirected:{value:T.redirected},type:{value:T.type}}),S},close:async()=>{await Promise.all([...s].map(c))}}}var Is=(n,e)=>Zr({autoClose:!0}).fetch(n,e);var xl=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),_l=n=>typeof n=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(n)?n:void 0;function ei(n,e={}){let t=[],r=new Set,i=(c,l=0)=>{if(!c||l>4||r.has(c)||t.length>=8)return;r.add(c);let p=_l(c.code);if(t.push({name:xl.has(c.name)?c.name:"Error",...p?{code:p}:{}}),i(c.cause,l+1),c instanceof AggregateError)for(let f of c.errors.slice(0,4))i(f,l+1)};i(n);let s=t.flatMap(c=>c.code?[c.code]:[]),o=e.stage==="model_admission"||s.some(c=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(c))?"lifecycle":s.some(c=>/CERT|TLS|SSL/.test(c))?"tls":s.some(c=>/^PROXY_/.test(c))||e.proxied&&s.some(c=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(c))?"proxy":s.some(c=>/TIMEOUT|ETIMEDOUT/.test(c))||t.some(c=>/TimeoutError$/.test(c.name))?"timeout":t.some(c=>c.name==="AbortError"||c.code==="ABORT_ERR"||c.code==="UND_ERR_ABORTED")?"cancelled":s.some(c=>/ENOTFOUND|EAI_AGAIN/.test(c))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",a=c=>typeof c=="string"&&/^[\w-]{1,80}$/.test(c)?c:void 0;return{errorId:Es(),requestId:a(e.requestId)??Es(),...a(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:o,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:t}}function Ss({env:n=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return Zr({env:n,fetchRequest:t,onFailure:(r,i)=>e(ei(r,{...i,stage:i.phase==="body"?"model_stream":"model_headers"}))})}function Tl(n){let e={...process.env,...n};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])n&&t.toUpperCase()in n&&!(t in n)&&delete e[t];return e}var Al=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function xs(n,e,t=()=>{}){let r=n.agent.streamFunction;n.agent.streamFunction=async(i,s,o)=>{if(!Al.has(i.api))return r(i,s,o);let a=t(),c=Ss({env:Tl(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...a?{operationId:a}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await r(i,s,{...o,fetch:c.fetch});return l.result().finally(()=>c.close()).catch(()=>{}),l}catch(l){throw await c.close(),l}}}function dt(n,e,t){try{n()}catch(r){let i=ei(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...i})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:i.errorId,requestId:i.requestId,stage:i.stage,code:"hosted_admission_blocked",networkKind:i.kind,networkStage:i.stage,causeCodes:i.causes.flatMap(s=>s.code?[s.code]:[]).join(",")})}catch{}throw r}}var pr=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Ge;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,r=()=>!1,i=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},a=[],c){this.hosted=c,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=r,this.reportError=i,this.onSessionsChanged=o,this.customTools=a,this.offHosted=c?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return s.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{s.enabled()&&s.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return s.enabled()?s.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let r=await Ue(e),i=t==="continue"?this.selectedByWorkspace.get(r):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.sessionId):void 0;if(i){if(i.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(i);return}if(typeof t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(t==="new")s=lr.create(r);else if(t==="continue"){let a=(await Tt(r))[0];s=a?lr.open(a.path):lr.create(r)}else s="sessionManager"in t?t.sessionManager:lr.open(t.sessionFile);if(await Hl(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(s.getSessionId());if(o){if(o.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(r,s,t==="new"?"new":"resume")})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(({session:e,cwd:t,prompts:r})=>{let i=e.sessionManager.getBranch(),s=i.flatMap(o=>{let a=ir(o);return a?[a]:[]});return{sessionId:e.sessionManager.getSessionId(),cwd:t,path:e.sessionManager.getSessionFile()??null,idle:e.isIdle&&!r.sending,name:nr(e.sessionManager.getSessionName(),s),modified:i.at(-1)?.timestamp??new Date().toISOString()}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,r,i){let s=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${i}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,t,r){let i=this.runtimes.get(t.getSessionId()),s=await qe.discover(e,this.isProjectTrusted(e)),o=Cl(),a=await ys(e,s.extensionRoots),c=new Nl({cwd:e,agentDir:Ol(),noExtensions:!0,additionalExtensionPaths:a.paths,eventBus:o,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,t.getSessionId()))]:[]}),l=null;try{await c.reload();let p=c.getExtensions().errors;if(p.length)throw new Error(p.map(S=>`${S.path}: ${S.error}`).join("; "));let f=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:u}=await Rl({cwd:e,sessionManager:t,model:f,resourceLoader:c,customTools:this.customTools}),h=new lt({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(S,R)=>this.telemetry.breadcrumb(S,R),anonymize:S=>this.telemetry.anonymize(S)}),g={session:u,cwd:e,catalog:s,bus:o,generation:++this.generation,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:h,streaming:null,prompts:null};g.prompts=i?.prompts??new je(()=>{let S=this.runtimes.get(t.getSessionId())??g;this.publishFor(S,{type:"snapshot",session:this.snapshotOf(S)}),!this.disposed&&!S.closing&&this.onSessionsChanged()}),l=g,xs(u,S=>{g.networkDiagnostic=S},()=>g.operation?.operationId);let v=S=>this.publishFor(g,S);g.interactions=new at(o,S=>!g.closing&&S.sessionId===u.sessionManager.getSessionId()&&s.has(S.pluginId),()=>v({type:"snapshot",session:this.snapshotOf(g)}));let x=0,I=o.on(or,()=>v({type:"snapshot",session:this.snapshotOf(g)})),T=u.subscribe(S=>{if(!this.disposed&&!g.closing){let R={...g.operation,session:this.telemetry.anonymize(u.sessionManager.getSessionId()),piVersion:dr,model:u.model?`${u.model.provider}/${u.model.id}`:null,thinkingLevel:u.thinkingLevel};if(S.type==="agent_start"&&this.telemetry.breadcrumb("agent_start",R),S.type==="tool_execution_start"&&h.start(S,R),S.type==="tool_execution_end"&&h.end(S,R),S.type==="message_end"&&S.message.role==="assistant"&&S.message.stopReason==="error"){g.agentErrorReported=!0;let L=g.networkDiagnostic,k=this.reportError(new Error("Agent response failed"),{...g.operation,stage:"agent",code:"agent_failed",piVersion:dr,...L?{networkKind:L.kind,networkStage:L.stage,causeCodes:L.causes.flatMap(y=>y.code?[y.code]:[]).join(","),requestId:L.requestId}:{}})??L?.errorId;v({type:"error",message:S.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:k,...g.operation})}S.type==="message_end"&&S.message.role==="toolResult"&&h.message(S.message,R),S.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",R),h.clear(),g.operation=void 0)}S.type==="message_update"&&S.message.role==="assistant"&&(g.streaming={id:"stream",role:"assistant",timestamp:new Date(S.message.timestamp).toISOString(),blocks:Le(S.message.content)},Date.now()-x>=60&&(x=Date.now(),v({type:"stream",message:g.streaming}))),S.type==="agent_settled"&&this.scheduleQueued(g),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(S.type)&&((S.type==="message_end"&&S.message.role==="assistant"||S.type==="agent_settled")&&(g.streaming=null,v({type:"stream",message:null})),v({type:"snapshot",session:this.snapshotOf(g)}),!this.disposed&&!g.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(S.type)&&this.onSessionsChanged())});g.detach=()=>{I(),T()},g.releaseHosted=this.hosted?.adapter.attach(u);let O=[],W=!0;if(await u.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:S=>{W&&O.push(S.error),this.diagnostic(g,s.plugins.find(R=>S.extensionPath.startsWith(R.root+"/"))?.id??S.extensionPath,S.event??"runtime",S.error)}}),W=!1,O.length)throw new Error(O.join("; "));if(this.ensureAvailable(),i&&(!i.session.isIdle||i.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(i&&await this.close(i,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");this.runtimes.set(u.sessionManager.getSessionId(),g),l=null,this.activate(g)}catch(p){throw this.hosted?.adapter.releasePending(t.getSessionId()),l?await this.close(l,"quit"):(o.clear(),await a.release()),p}}async close(e,t){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await ws(e.session,t,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:r,catalog:i}=e,s=t.sessionManager.getBranch().flatMap(o=>{let a=ir(o);return a?[a]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:nr(t.sessionManager.getSessionName(),s),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,paused:st(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:qr(t.sessionManager.getBranch(),i.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=t.session.extensionRunner,i=await ar(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||r!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),i}resolveInteraction(e,t,r,i){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,r,i)}async send(e,t=[],r,i){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(Me(this.snapshot(),e,i),i==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,t,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new se("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,t,r,i)}async prompt(e,t,r,i,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),i,this.reportError),Me({...this.snapshotOf(e),idle:e.session.isIdle},t,s);let o=e.session,a=o.isIdle;a&&(e.operation=i,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...i,piVersion:dr});let c=!1,l,p,f=new Promise((u,h)=>{l=u,p=h});o.prompt(t,{images:r,streamingBehavior:s,preflightResult:u=>{u&&(c=!0,l())}}).then(()=>{c||l()}).catch(u=>{if(!c)p(u);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let h=this.reportError(Ne(u,"Agent response failed"),{...i,stage:"agent",code:"agent_failed",piVersion:dr});this.publishFor(e,{type:"error",message:u instanceof Error?u.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:h,...i})}});try{await f}catch(u){throw a&&(e.operation=void 0),u}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!st(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,r,i)=>this.prompt(e,t,r,i))}async updateQueuedPrompt(e,t,r){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&i.session.isIdle)throw new se("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await i.prompts.update(e,t,r,(s,o,a)=>this.prompt(i,s,o,a,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(xt),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=t.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!st(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!st(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=cr(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let a=this.reportError(Ne(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:a,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=r.session.modelRuntime.getModel(e,t);if(!i)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(i),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{basename as ti,dirname as Dl}from"node:path";function _s(n,e){let t=r=>e[r].map(i=>({name:r==="skills"&&ti(i.path).toLowerCase()==="skill.md"?ti(Dl(i.path)):ti(i.path),path:i.path,source:i.metadata.source,scope:i.metadata.scope,enabled:i.enabled}));return{packages:n.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as Ml}from"node:child_process";var jl=(n,e)=>new Promise((t,r)=>{Ml(n,[...e],{windowsHide:!0},i=>{i?r(i):t()})});async function ri(n,e=process.platform,t=process.env,r=jl){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let i=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return i===null?!1:(await r(i,[n]),!0)}import{execFile as hd}from"node:child_process";import{randomUUID as hr}from"node:crypto";import{existsSync as Us}from"node:fs";import{access as ui,mkdir as gr,mkdtemp as gd,readFile as ge,realpath as md,rename as fi,rm as Nt,writeFile as mr}from"node:fs/promises";import{dirname as zs,join as D}from"node:path";import{createHash as si,randomUUID as zl}from"node:crypto";import{mkdir as ql,readFile as Gl,readdir as Jl,realpath as Os}from"node:fs/promises";import{join as xe}from"node:path";import{constants as ii}from"node:fs";import{DatabaseSync as Wl}from"node:sqlite";import{lstat as Rs,mkdir as Vl,open as Rt,rename as $l,unlink as Cs}from"node:fs/promises";import{dirname as Fl,join as Ts,resolve as Bl}from"node:path";import{randomUUID as Ll}from"node:crypto";import{setTimeout as Ul}from"node:timers/promises";async function Q(n){await Vl(n,{recursive:!0,mode:448});let e=await Rs(n);if(!e.isDirectory()||e.isSymbolicLink())throw new w("invalid_storage","Plugin storage must be a real directory")}async function G(n,e){let t;try{t=await Rt(n,ii.O_RDONLY|ii.O_NONBLOCK|(ii.O_NOFOLLOW??0))}catch(r){if(it(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new w("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<i.length;){let o=await t.read(i,s,i.length-s,s);if(!o.bytesRead)break;s+=o.bytesRead}if(s>e||s!==r.size)throw new w("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function ee(n,e=2*1024*1024){let t=await G(n,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new w("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function oe(n){let e=await G(n,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new w("gc_recovery_required",`Invalid journal ${n}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new w("gc_recovery_required",`Invalid journal ${n}; original bytes preserved`);return t}async function M(n,e){let t=`${n}.${Ll()}.tmp`,r=await Rt(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await $l(t,n);let i;try{i=await Rt(Fl(n),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await Cs(t).catch(()=>{})}}var Ns='{"version":2,"mechanism":"sqlite-exclusive"}',As=n=>n.toString("utf8")===Ns,ur=new Set;async function ni(n,e,t=0){await Q(n);let r=Ts(n,`${e}.lock`),i=Ts(n,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new w(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),a;try{a=await Rt(i,"wx",384)}catch(g){if(g.code!=="EEXIST")throw g}finally{await a?.close()}let c=await Rs(i);if(!c.isFile()||c.isSymbolicLink()||c.nlink!==1||c.size>1024*1024)throw new w("invalid_storage","Ownership database must be a small, single-link regular file");let l=new Wl(i,{allowExtension:!1}),p=Bl(i),f=Date.now()+t,u=!1;try{for(;;){if(!ur.has(p))try{l.exec("BEGIN EXCLUSIVE"),ur.add(p),u=!0;break}catch(v){if(v.errcode!==5)throw v}if(Date.now()>=f)throw new w(s,"Another host owns this plugin storage; wait for it to stop before retrying");await Ul(10)}let g=await G(r,4096);if(g===null){let v;try{v=await Rt(r,"wx",384),await v.writeFile(Ns),await v.sync()}catch(x){if(x.code!=="EEXIST")throw x}finally{await v?.close()}g=await G(r,4096)}if(g===null||!As(g))throw o()}catch(g){throw l.close(),u&&ur.delete(p),g}let h=!1;return async()=>{if(h)return;let g=await G(r,4096);if(g===null||!As(g))throw new w("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Cs(r),l.close(),ur.delete(p),h=!0}}async function j(n,e,t=2e3){let r=await ni(n,"transaction",t);try{return await e()}finally{await r()}}var ke=n=>xe(n,"host-pair"),Z=n=>si("sha256").update(JSON.stringify(n)).digest("hex");async function Kl(n){let e=si("sha256"),t=0,r=0;async function i(s){let o=(await Jl(xe(n,s),{withFileTypes:!0})).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(let a of o){if(!s&&a.name==="node_modules")continue;let c=s?`${s}/${a.name}`:a.name;if(a.isSymbolicLink()||!a.isFile()&&!a.isDirectory())throw new w("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new w("host_pair_required","Candidate package resource budget exceeded");if(a.isDirectory()){await i(c);continue}let l=await G(xe(n,c),64*1024*1024);if(!l||(r+=l.length)>256*1024*1024)throw new w("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([c,si("sha256").update(l).digest("hex")]))}}return await i(""),e.digest("hex")}async function Je(n,e){let t=await Os(e),r=xe(e,"dist","hosted-worker.js");if(await Os(r)!==xe(t,"dist","hosted-worker.js"))throw new w("host_pair_required","Candidate worker must remain inside the staged host");let i=await G(xe(e,"package.json"),512*1024);if(!i)throw new w("host_pair_required","Candidate package metadata missing");let s=JSON.parse(i.toString("utf8")),o=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==n||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(c=>o.capabilities.includes(c)))throw new w("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let a=await G(r,32*1024*1024);if(!a)throw new w("host_pair_required","Candidate worker missing");return Z([i.toString("base64"),a.toString("base64"),await Kl(e)])}async function He(n){let e=await oe(xe(ke(n),"intent.json"));if(e&&(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||typeof e.packageRoot!="string"||!/^[a-f0-9]{64}$/.test(e.hostDigest)||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!Array.isArray(e.selections)||e.selections.some(t=>!t||typeof t.id!="string"||typeof t.version!="string"||!/^[a-f0-9]{64}$/.test(t.digest)||!Object.hasOwn(t,"before"))||e.selection&&(typeof e.selection.path!="string"||!/^[a-f0-9]{64}$/.test(e.selection.digest))||!["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(e.phase)))throw new w("host_pair_required","Invalid host pair journal; preserve data and inspect intent.json with all owners stopped");if(e){let{lifecyclePhase:t,...r}=e;e={...r,phase:r.phase==="selected"&&t==="restart-requested"?"restart-requested":r.phase==="reconciled"&&t==="cancelled"?"cancelled":r.phase}}return e}async function Se(n,e){let{lifecyclePhase:t,...r}=e,i=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await M(xe(ke(n),"intent.json"),i)}var pt=n=>n&&!["prepared","reconciled","cancelled"].includes(n.phase);async function Ct(n){let e=await He(n);if(e&&pt(e))throw new w("host_pair_required",`Host pair selection pending (${e.version}, ${e.phase}): ${e.message??"restart selected host, or stop all owners and inspect host-pair/intent.json"}; data retained`)}function Hs(n,e,t,r=async()=>{}){let i=async o=>{let a=xe(ke(n),"history");await ql(a,{recursive:!0,mode:448}),await M(xe(a,`${o.id}.json`),o)},s=async(o,a,c)=>{let l=await Je(o,a),p=Z(await t()),f=await e(o,c);if(c?.throwIfAborted(),Z(await t())!==p)throw new w("host_pair_changed","Plugin policy/activation changed during preflight; recheck update");return await r(o,f),{schema:1,id:zl(),phase:"prepared",version:o,packageRoot:a,hostDigest:l,fingerprint:p,selections:f}};return{status:()=>He(n),stage:(o,a,c)=>j(ke(n),async()=>{await Ct(n);let l=await He(n);l&&await i(l.phase==="prepared"?{...l,phase:"cancelled",message:"Superseded before version selection; no code or data changed"}:l),await Se(n,await s(o,a,c))}),cancel:(o,a,c)=>j(ke(n),async()=>{let l=await He(n);if(!l||l.phase==="cancelled"||l.phase==="reconciled")return;if(o&&l.version!==o||a&&l.packageRoot!==a)throw new w("host_pair_changed","Another update owns this transaction");if(pt(l)&&!c)throw new w("host_pair_required","Selected update requires its owned pointer recovery receipt before cancellation");await c?.();let p={...l,phase:"cancelled",message:"Update cancelled; current runtime and plugin data retained"};await Se(n,p),await i(p)}),select:(o,a,c)=>j(ke(n),async()=>{await Ct(n);let l=await He(n),p=l?.phase==="prepared"&&l.version===o&&l.packageRoot===a&&l.fingerprint===Z(await t())?l:await s(o,a),{hostDigest:f,selections:u}=p,h=p.fingerprint;if(await Se(n,p),await r(o,u),await Je(o,a)!==f||Z(await t())!==h)throw await Se(n,{...p,phase:"required-action",message:"Preflight changed; host pointer not written"}),new w("host_pair_changed","Preflight changed; host pointer not written");await Se(n,{...p,phase:"selecting"});let g=await c();await Se(n,{...p,phase:"selected",...g?{selection:g}:{}})}),restart:(o,a,c)=>j(ke(n),async()=>{let l=await He(n);if(!l||l.phase!=="selected"||l.version!==o||l.packageRoot!==a||l.hostDigest!==await Je(o,a)||l.fingerprint!==Z(await t()))throw new w("host_pair_changed","Selected pair changed; restart refused, inspect pair journal");if(l.selection&&Z((await Gl(l.selection.path)).toString("base64"))!==l.selection.digest)throw new w("host_pair_changed","Host selection pointer changed; restart refused");if(await r(o,l.selections),l.hostDigest!==await Je(o,a)||l.fingerprint!==Z(await t()))throw new w("host_pair_changed","Selected pair changed during restart validation");await Se(n,{...l,phase:"restart-requested",message:"Restart authorized; awaiting launcher receipt and selected host health admission"}),await c()})}}import{promisify as wd}from"node:util";import{realpathSync as js,statSync as Xl}from"node:fs";import{basename as Yl,delimiter as Ql,dirname as Ds,join as oi,resolve as Zl}from"node:path";function Ms(n){if(!n)return null;try{let e=js(n);return Yl(e)==="npm-cli.js"&&Xl(e).isFile()?e:null}catch{return null}}function ed({execPath:n=process.execPath,env:e=process.env}={}){let t=Ms(e.npm_execpath);if(t)return t;let r=new Set([Ds(n)]);try{r.add(Ds(js(n)))}catch{}let i=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of i.split(Ql).filter(Boolean))r.add(Zl(s));for(let s of r)for(let o of[oi(s,"node_modules","npm","bin","npm-cli.js"),oi(s,"..","lib","node_modules","npm","bin","npm-cli.js"),oi(s,"npm")]){let a=Ms(o);if(a)return a}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function Ws(n){return{file:process.execPath,args:[ed(),...n]}}import{readFile as td,rename as rd,writeFile as id,unlink as nd}from"node:fs/promises";import{join as sd}from"node:path";import{randomUUID as od}from"node:crypto";var ai=1,Vs=n=>sd(n,"pi-web","launcher-handoff.json");function $s(n){return n?.protocol===ai&&typeof n.nonce=="string"&&n.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(n.requestId)&&Number.isSafeInteger(n.pid)&&n.pid>0&&["requested","draining","stopped","refused","failed"].includes(n.phase)}async function ci(n){try{let e=JSON.parse(await td(Vs(n),"utf8"));if(!$s(e))throw new Error("Invalid launcher handoff journal; original data retained");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async function ad(n,e){let t=`${n}.${od()}.tmp`;try{await id(t,JSON.stringify(e),{mode:384}),await rd(t,n)}finally{await nd(t).catch(()=>{})}}async function Fs(n,e){if(!$s(e))throw new Error("Invalid launcher handoff receipt");await ad(Vs(n),e)}import{execFile as cd}from"node:child_process";import{cp as ld,readFile as li,realpath as dd,rm as pd}from"node:fs/promises";import{join as ut,sep as ud}from"node:path";import{promisify as fd}from"node:util";var Bs=fd(cd),di=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function pi(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=n;return di.map(t=>{let r=e[t];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${r}`})}async function fr(n){return Promise.all(di.map(async e=>{let t=await nt(n,e),r=JSON.parse(await li(ut(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Ls(n,e){let t=JSON.parse(await li(ut(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=t.peerDependencies===void 0?await fr(n):pi(t.peerDependencies);if(JSON.stringify(await fr(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let i=await nt(n,"node-pty"),s=await nt(e,"node-pty"),o=await dd(ut(e,"../.."));if(i===s||!s.startsWith(o+ud))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let a=async f=>JSON.parse(await li(ut(f,"package.json"),"utf8")).version;if(await a(i)!==await a(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await pd(s,{recursive:!0,force:!0}),await ld(i,s,{recursive:!0});let c={...process.env};delete c.NODE_OPTIONS,delete c.NODE_PATH,delete c.ELECTRON_RUN_AS_NODE,await Bs(process.execPath,[ut(e,"desktop","check-pty.cjs")],{cwd:e,env:c,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await nt(e,di[0]),{stdout:p}=await Bs(process.execPath,[ut(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:c,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}var yd=wd(hd);function qs(n){let e=n.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function vd(n,e){try{let t=Ws(n),{stdout:r}=await yd(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(t){let r=t;throw new Error(r.stderr?.trim()||r.message)}}var wr=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;validateHostedPair;hostedPair;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??vd,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let r=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return fr(this.packageRoot);let i=JSON.parse(r),s=Array.isArray(i)&&i.length===1?i[0]:i;return pi(s)},this.verifyPackage=e.verifyPackage??Ls,this.validateHostedPair=e.validateHostedPair,this.hostedPair=e.hostedPair,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?ai:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!["committed","cancelled","failed"].includes(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let i=D(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await ge(i,"utf8")),o=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let a=await ci(this.agentDir);if(a?.nonce===e&&["requested","draining"].includes(a.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let c,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(c=await this.beforeRestart(),!o(JSON.parse(await ge(i,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:s.pid,phase:"requested"};try{await Fs(this.agentDir,p),l=!0}catch(f){let u=await ci(this.agentDir).catch(()=>null);if(l=u?.nonce===e&&u?.requestId===t&&["requested","draining","stopped"].includes(u.phase),!l)throw f}this.restartPending=!0}finally{!l&&c&&await c()}}async current(){let e=JSON.parse(await ge(D(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return We(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();return t?.phase==="restart-requested"&&t.version===e&&(!this.hostedPair||(await this.hostedPair.status?.())?.phase==="reconciled")&&await this.record({...t,phase:"committed",message:"Selected host is running and hosted protocol health admission completed"}),e}get transactionPath(){return D(this.agentDir,"pi-web","update-transaction.json")}async transaction(){try{let e=await oe(this.transactionPath);if(!e)return null;if(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||e.selectionPath!==D(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json")||e.selectedDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.selectedDigest)||e.before!==void 0&&e.before!==null&&(typeof e.before!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.before)))throw new Error("\u66F4\u65B0\u4E8B\u52A1\u8BB0\u5F55\u65E0\u6548\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u8BCA\u65AD");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async record(e){if(await gr(D(this.agentDir,"pi-web"),{recursive:!0}),await M(this.transactionPath,e),["failed","cancelled","committed"].includes(e.phase)){let t=D(this.agentDir,"pi-web","update-history");await gr(t,{recursive:!0}),await M(D(t,`${e.id}-${e.phase}.json`),e)}}async admittedFallback(e,t){if(!e.ownerNonce||!this.launcherNonce||e.ownerNonce===this.launcherNonce||e.before===void 0)return!1;let r=t??await this.current();if(e.version===r)return!1;try{let i=await oe(D(this.agentDir,"pi-web","launcher.json"));if(i?.nonce!==this.launcherNonce||i.version!==r||i.piPid!==process.pid)return!1;let s;try{s=(await ge(e.selectionPath)).toString("base64")}catch(o){if(o.code!=="ENOENT")return!1;s=null}return s===e.before}catch{return!1}}async admittedLegacyRecovery(e){if(!this.launcherNonce)return!1;try{let t=await oe(D(this.agentDir,"pi-web","launcher.json"));if(t?.nonce!==this.launcherNonce||t.piPid!==process.pid||t.version!==(e??await this.current()))return!1;try{return await ui(D(this.agentDir,"pi-web","launcher.restart")),!1}catch(r){return r.code==="ENOENT"}}catch{return!1}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction();if(!e||["cancelled","failed","committed"].includes(e.phase)){let i=await this.hostedPair?.status?.();if(i&&!["cancelled","reconciled","prepared"].includes(i.phase)){if(!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u9700\u8981\u5F53\u524D\u540E\u53F0\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E14\u4E0D\u80FD\u4E2D\u65AD\u542F\u52A8\u5668\u5DF2\u63A5\u53D7\u7684\u4EA4\u63A5");let s=D(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");if(!i.selection||i.selection.path!==s)throw new Error("\u65E7\u5347\u7EA7\u4E8B\u52A1\u7F3A\u5C11\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u6062\u590D\u8BCA\u65AD");let o=await ge(s);if(Z(o.toString("base64"))!==i.selection.digest)throw new Error("\u65E7\u5347\u7EA7\u9009\u62E9\u5DF2\u53D8\u5316\uFF0C\u6062\u590D\u672A\u8986\u76D6\u5176\u4ED6\u64CD\u4F5C");let a=JSON.parse(o.toString("utf8")),c=await this.current(),l=D(this.packageRoot,"bin","pi-webapp.mjs");await ui(l);let p=a.previous?.version===c&&a.previous.launcher===l?a.previous:this.desktopManaged?await rr(this.agentDir,{version:c,launcher:l,desktopProtocolVersion:Ve}):{version:c,launcher:l,baseVersion:a.baseVersion??c};e={schema:1,id:i.id,phase:"selected",version:i.version,channel:await this.channel(),packageRoot:i.packageRoot,selectionPath:s,before:Buffer.from(JSON.stringify(p)).toString("base64"),selectedDigest:i.selection.digest,ownerNonce:this.launcherNonce,legacyRecovery:!0},await this.record(e)}else i?.phase==="prepared"&&await this.hostedPair?.cancel?.(i.version,i.packageRoot)}if(!e||["cancelled","failed","committed"].includes(e.phase)){let i=await this.hostedPair?.status?.();i?.phase==="prepared"&&await this.hostedPair?.cancel?.(i.version,i.packageRoot),this.preparedUpdate=void 0,this.restartPending=!1;return}if(e.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u540E\u53F0\u5F52\u5C5E\u6216\u4EA4\u63A5\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u8BF7\u4ECE\u5F53\u524D\u8FD0\u884C\u5B9E\u4F8B\u6062\u590D");if(e.phase==="restart-requested"&&!await this.admittedFallback(e))throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u5F53\u524D\u5165\u53E3\u6CA1\u6709\u5DF2\u786E\u8BA4\u56DE\u9000\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E0D\u80FD\u53D6\u6D88\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B\u7684\u4EA4\u63A5");let t=e,r=async()=>{if(t.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u5F52\u5C5E\u6216\u4EA4\u63A5\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(t.phase==="restart-requested"&&!await this.admittedFallback(t))throw new Error("\u91CD\u542F\u4EA4\u63A5\u7684\u5F52\u5C5E\u6216\u56DE\u9000\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(!t.selectedDigest)return;let i;try{i=await ge(t.selectionPath)}catch(s){if(s.code!=="ENOENT")throw s;i=null}if((i?.toString("base64")??null)!==t.before){if(!i||Z(i.toString("base64"))!==t.selectedDigest)throw new Error("\u7248\u672C\u9009\u62E9\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u66F4\u6539\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u8BE5\u9009\u62E9\uFF1B\u5F53\u524D\u6570\u636E\u5DF2\u4FDD\u7559");if(t.before===null)await Nt(t.selectionPath);else if(typeof t.before=="string"){let s=`${t.selectionPath}.${hr()}.tmp`;try{await mr(s,Buffer.from(t.before,"base64"),{mode:384}),await fi(s,t.selectionPath)}finally{await Nt(s,{force:!0})}}else throw new Error("\u7F3A\u5C11\u65E7\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u4E0D\u80FD\u81EA\u52A8\u6062\u590D\uFF1B\u8BF7\u4FDD\u7559\u4E8B\u52A1\u8BB0\u5F55")}};this.hostedPair?.cancel?await this.hostedPair.cancel(e.version,e.packageRoot,r):await j(D(this.agentDir,"pi-web","update-control"),r),await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0,this.restartPending=!1}get preferencePath(){return D(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ge(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${hr()}.tmp`;try{await gr(D(this.agentDir,"pi-web"),{recursive:!0}),await mr(t,JSON.stringify({channel:e}),{mode:384}),await fi(t,this.preferencePath)}finally{this.savingPreference=!1,await Nt(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=Us(D(this.packageRoot,".git")),i={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(i.launcher=this.launcherIdentity(),i.launcherHandoff={supported:i.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(i.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction(),o=await this.hostedPair?.status?.();if(s&&!["failed","cancelled","committed"].includes(s.phase)?i.recovery={version:s.version,phase:s.phase,canCancel:s.legacyRecovery?await this.admittedLegacyRecovery(e):s.phase!=="restart-requested"||await this.admittedFallback(s,e)}:o&&!["cancelled","reconciled"].includes(o.phase)&&(i.recovery={version:o.version,phase:o.phase,canCancel:o.phase==="prepared"||await this.admittedLegacyRecovery(e)}),this.desktopManaged&&!this.desktopPackageUpdates)return{...i,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...i,canRestart:!1,reason:i.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?i.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":i.canRestart||(i.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&i.canRestart&&(i.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let a=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),c=Array.isArray(a)&&a.length===1?a[0]:a,l=t==="alpha"?c:{latest:c};if(!l||!Xn(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let p=l.latest;if(t==="alpha"&&l.alpha!==void 0){if(!Zt(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ue(l.alpha,p)>0&&(p=l.alpha)}i.latest=p,i.downgrade=ue(p,e)<0,i.available=t==="stable"?ue(p,e)!==0:ue(p,e)>0,this.desktopManaged&&i.downgrade&&!this.desktopReleaseChannels&&ue(p,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(i.canRestart=!1,i.requiresDesktopUpgrade=!0,i.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(a){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`)}return i}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(Us(D(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=D(this.agentDir,"pi-web","releases");await gr(r,{recursive:!0});let i=await gd(D(await md(r),`${t.latest}-`)),s=D(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:hr(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};await this.record(o);let a=!1;try{let c=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...c,"--prefix",i,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=D(i,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:l},await this.record(o);let p=JSON.parse(await ge(D(l,"package.json"),"utf8"));if(p.name!=="pi-webapp"||p.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let f=JSON.parse(await ge(D(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&qs(p)!==qs(f))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let u=D(l,"bin","pi-webapp.mjs");await Promise.all([u,D(l,"dist","extension.js"),D(l,"web","dist","index.html")].map(v=>ui(v))),await this.validateHostedPair?.(t.latest,l);let h=this.desktopManaged?await rr(this.agentDir,{version:t.latest,launcher:u,desktopProtocolVersion:Ve}):null;this.desktopManaged&&await this.verifyPackage(this.packageRoot,l);let g=async()=>{let v;try{v=await ge(s)}catch(I){if(I.code!=="ENOENT")throw I;v=null}if(o={...o,phase:"selecting",before:v?.toString("base64")??null},await this.record(o),a=!0,this.desktopManaged){let I=h,T=await Zn(this.agentDir,t.current),O=T?.version===t.current?T:null,W=process.env.PI_WEBAPP_DESKTOP_VERSION??T?.fallbackVersion??t.current,S={...I,...t.downgrade||T?.fallbackVersion?{fallbackVersion:W}:{},...O?{previous:O}:{}};o={...o,selectedDigest:Z(Buffer.from(JSON.stringify(S)).toString("base64"))},await this.record(o),await es(this.agentDir,S)}else{let I=D(this.agentDir,"pi-web"),T=D(I,`update.${hr()}.tmp`);try{let O;try{O=JSON.parse(await ge(D(I,"update.json"),"utf8"))}catch{}let W=O?.baseVersion??t.current,S=O?.version===t.current?O:void 0;S&&delete S.previous;let R={version:t.latest,launcher:u,baseVersion:W,...t.downgrade||O?.allowDowngrade===!0?{allowDowngrade:!0}:{},...S?{previous:S}:{}};o={...o,selectedDigest:Z(Buffer.from(JSON.stringify(R)).toString("base64"))},await this.record(o),await mr(T,JSON.stringify(R),{mode:384}),await fi(T,D(I,"update.json"))}finally{await Nt(T,{force:!0})}}let x=D(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");return{path:x,digest:Z((await ge(x)).toString("base64"))}};return this.hostedPair?.stage&&await this.hostedPair.stage(t.latest,l,this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted(),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={update:{version:t.latest,launcher:u},channel:t.channel??"stable",select:async()=>{this.hostedPair?await this.hostedPair.select(t.latest,l,g):await j(D(this.agentDir,"pi-web","update-control"),g),o={...o,phase:"selected"},await this.record(o)}},{version:t.latest,launcher:u}}catch(c){throw a||await Nt(i,{recursive:!0,force:!0}),await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":"\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),c}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let t,r=!1;try{t=await this.beforeRestart?.(),await this.preparedUpdate?.select();let i=async()=>{let s=D(this.agentDir,"pi-web","launcher.restart"),o=await this.transaction();o&&await this.record({...o,phase:"restart-requested"});try{await mr(s,JSON.stringify({nonce:this.launcherNonce,launcher:e.launcher}),{mode:384,flag:"wx"}),r=!0}catch(a){try{let c=JSON.parse(await ge(s,"utf8"));r=c.nonce===this.launcherNonce&&c.launcher===e.launcher}catch{}if(!r)throw a}};this.hostedPair?await this.hostedPair.restart(e.version,zs(zs(e.launcher)),i):await i(),this.restartPending=!0}catch(i){if(r){this.restartPending=!0;return}this.restartPending=!1;let s=await this.transaction();s?.phase==="restart-requested"&&await this.record({...s,phase:"selected",message:"Restart marker was not accepted; reverting owned selection"});let o=this.preparedUpdate;try{await this.cancel(),this.preparedUpdate=o}finally{t&&await t()}throw i}}};import{createHash as vo,randomUUID as _p}from"node:crypto";import{randomUUID as lp}from"node:crypto";import{access as dp}from"node:fs/promises";import{join as Sr}from"node:path";import{randomUUID as Ks}from"node:crypto";import{randomUUID as bd}from"node:crypto";function Gs(n){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof n[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let r=`__pi_web_contract_${bd().replaceAll("-","")}`,i;try{if(i=n.getActiveTools(),!Array.isArray(i))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{n.registerTool(s),n.setActiveTools([...i,r]),(n.getAllTools().find(a=>a.name===r)?.exposure!=="hidden"||n.getActiveTools().includes(r))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};n.registerTool({...s,parameters:o}),n.getAllTools().find(a=>a.name===r)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{n.setActiveTools(i)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var kd;function Js(){return kd??=Pd().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function Pd(){let{createAgentSession:n,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:i,rm:s}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:a}=await import("node:path"),c=await i(a(o(),"pi-sdk-contract-")),l,p=[],f=0,u=0,h=!1,g=!1;try{let v=(S,R,L)=>({name:S,label:S,description:"Inert host SDK contract check",exposure:R,parameters:{type:"object",properties:{}},execute:L}),x=()=>({content:[],details:void 0}),I=new e({cwd:c,agentDir:c,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[S=>{S.on("tool_call",R=>{if(R.toolName==="__contract_direct"&&(h=!!R.parentToolCallId),R.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let R of["hidden","model-only"])S.registerTool(v(`__contract_${R.replace("-","_")}`,R,async()=>(u++,x())));S.registerTool(v("__contract_protected","direct",async()=>(u++,x()))),S.registerTool(v("__contract_direct","direct",async()=>(f++,x()))),S.registerTool(v("__contract_driver","direct",async(R,L,k,y,K)=>{let Pe=await K.executeTool("__contract_hidden",{}),Re=await K.executeTool("__contract_model_only",{}),te=await K.executeTool("__contract_direct",{}),E=await K.executeTool("__contract_protected",{});return(!Pe.isError||!Re.isError)&&p.push("nested-tool-exposure"),(te.isError||f!==1)&&p.push("nested-tool-execution"),(!E.isError||u!==0)&&p.push("nested-tool-permission-guard"),h||p.push("nested-parent-identity"),g=!0,x()}))}]});await I.reload(),{session:l}=await n({cwd:c,agentDir:c,sessionManager:t.inMemory(c),resourceLoader:I}),await l.bindExtensions({mode:"print"});let T=l.modelRuntime.getModels("openai")[0];if(!T)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(T);let O=0;l.agent.streamFunction=async S=>{let R=O++===0,L={role:"assistant",api:S.api,provider:S.provider,model:S.id,timestamp:Date.now(),content:R?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:R?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},k=r();return k.push({type:"start",partial:L}),k.push({type:"done",reason:R?"toolUse":"stop",message:L}),k.end(L),k};let W;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((S,R)=>{W=setTimeout(()=>R(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(W)}return g||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await s(c,{recursive:!0,force:!0})}}var yr=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=Js().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,i)=>{t=setTimeout(()=>i(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let r=this.install(e,t);r.ready=!0;try{this.publish(r)}catch(i){throw this.release(r),i}return()=>this.release(r)}install(e,t){let r={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let i=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{i(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),i(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),i(e.on("tool_call",s=>{let o=r.owned.get(s.toolName);if(!o)return;let a=this.descriptors.get(o)?.find(c=>c.name===s.toolName);if(!a||!this.allowed(r,o,a,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),i(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),i(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let t=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(r=>{r.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(r){throw this.release(t),r}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,r,i=!1){let s=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!i||s.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(i=>i.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(t);this.validateChange(e,r),this.descriptors.set(e,r);for(let i of this.bindings)i.ready&&this.publish(i)}validateChange(e,t){for(let i of this.bindings)if(i.compatible!==!1)for(let[s,o]of i.owned)this.assertOwner(i,o,s);let r=new Set;for(let i of t){if(!i.name||!i.action||!i.parameters||i.parameters.type!=="object"||r.has(i.name))throw new Error("Invalid hosted tool descriptor");r.add(i.name);for(let[s,o]of this.descriptors)if(s!==e&&o.some(a=>a.name===i.name))throw new Error(`Hosted tool ownership conflict: ${i.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,i.name)}}assertOwner(e,t,r){let i=e.owned.get(r);if(i&&i!==t)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(o=>o.name===r);if(s&&(!i||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=Gs(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,i]of e.owned)this.assertOwner(e,i,r);for(let[r,i]of this.descriptors)for(let s of i)this.assertOwner(e,r,s.name);let t=new Set;for(let[r,i]of this.descriptors)for(let s of i){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;t.add(s.name);let o=this.service.policy(r,e.scope),a=o.exposure??"direct",c=!o.allowNested&&a==="direct"?"model-only":a,l={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:c,execute:async(p,f,u)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:Ks(),scope:{...e.scope},kind:"tool",action:s.action,input:f},u)}};e.pi.registerTool(l),e.definitions.set(s.name,l)}for(let r of e.owned.keys())if(!t.has(r)){let i={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:Id};e.pi.registerTool(i),e.definitions.set(r,i)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let i=e.definitions.get(r);return!i||i.exposure==="direct"||i.exposure==="model-only"}))}async invokeAction(e,t,r,i,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(a=>a.scope.sessionId===t.sessionId&&a.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:Ks(),scope:t,kind:"action",action:r,input:i},s)}};async function Id(){throw new Error("Hosted tool unavailable")}import{randomBytes as op,timingSafeEqual as ap}from"node:crypto";import{join as ye}from"node:path";import{createHash as Vd,timingSafeEqual as $d}from"node:crypto";import{lstat as oo,mkdtemp as Fd,readdir as Bd,rename as Ld,rm as ht}from"node:fs/promises";import{join as J}from"node:path";import{gunzipSync as Rd}from"node:zlib";import{mkdir as Cd,writeFile as Nd}from"node:fs/promises";import{dirname as Od,join as Hd}from"node:path";import{constants as hi}from"node:fs";import{lstat as Qs,open as Ed,readdir as Xs,realpath as Zs}from"node:fs/promises";import{createHash as Sd}from"node:crypto";import{join as eo,relative as xd,resolve as _d,sep as Td}from"node:path";var re={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},Ad={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"]},q=n=>Sd("sha256").update(n).digest("hex");function $(n){throw new w("invalid_package",n)}async function vr(n,e,t){let r=e.split("/");(!r.length||r.some(a=>!a||a==="."||a===".."||!/^[\w.-]+$/.test(a)))&&$("Invalid resource path");let i=n;for(let a=0;a<r.length;a++){i=eo(i,r[a]);let c=await Qs(i);(c.isSymbolicLink()||(a<r.length-1?!c.isDirectory():!c.isFile()||c.nlink!==1))&&$("Links and non-regular package files are forbidden")}let s=await Zs(i);(s!==_d(n,e)||xd(n,s).startsWith(`..${Td}`))&&$("Resource escapes package root");let o=await Ed(i,hi.O_RDONLY|hi.O_NONBLOCK|(hi.O_NOFOLLOW??0));try{let a=await o.stat();(!a.isFile()||a.nlink!==1||a.size>t)&&$("Oversized or non-regular package file");let c=Buffer.alloc(Math.min(a.size+1,t+1)),l=0;for(;l<c.length;){let p=await o.read(c,l,c.length-l,l);if(!p.bytesRead)break;l+=p.bytesRead}return(l>t||l!==a.size)&&$("Package resource changed during read"),c.subarray(0,l)}finally{await o.close()}}function Ys(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return $("Invalid package JSON")}}async function br(n,e){let t=await Zs(n);(await Qs(n)).isSymbolicLink()&&$("Package root cannot be a symlink");let r=Ys(await vr(t,"package.json",re.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&$("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&$("Invalid package version"),ct(r.piWebapp)||$("Unsupported hosted manifest"),r.type!=="module"&&$("Hosted package must declare ESM module type");for(let f of await Xs(t,{withFileTypes:!0}))f.name==="dist"&&f.isDirectory()||(!f.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(f.name))&&$("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(f=>/^(?:preinstall|install|postinstall|prepare)$/.test(f))&&$("Hosted packages cannot run install lifecycle scripts");for(let f of["dependencies","optionalDependencies"]){let u=r[f];u&&(typeof u!="object"||Object.keys(u).length>0)&&$("Hosted packages must contain all runtime dependencies")}let i=r.piWebapp,s=Ys(await vr(t,i.resourcesManifest.slice(2),re.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>re.files)&&$("Invalid resource manifest");let o=new Map,a=0;for(let f of s.files){(!f||typeof f!="object")&&$("Invalid resource entry");let u=f,h={...u,path:typeof u.path=="string"&&u.path.startsWith("./")?u.path.slice(2):u.path};(!ze(`./${h.path}`)||typeof h.sha256!="string"||!/^[a-f0-9]{64}$/.test(h.sha256)||!Number.isSafeInteger(h.bytes)||h.bytes<0||o.has(h.path))&&$("Invalid or duplicate resource");let g=h.path.split(".").at(-1);Ad[g]?.includes(h.mime)||$("Unsupported resource MIME");let v=g==="js"||g==="mjs"?re.js:g==="css"?re.css:g==="woff"||g==="woff2"?re.font:re.other;(h.bytes>v||(a+=h.bytes)>re.total)&&$("Resource budget exceeded");let x=await vr(t,h.path,v);(x.length!==h.bytes||q(x)!==h.sha256)&&$("Resource integrity mismatch"),o.set(h.path,Object.freeze({...h}))}for(let f of[i.backend.entry,i.frontend.document,i.frontend.controller])o.has(f.slice(2))||$("Entrypoint is absent from resource manifest");let c=0;async function l(f,u=0){u>16&&$("Package directory nesting limit exceeded");for(let h of await Xs(eo(t,f),{withFileTypes:!0})){++c>re.files*2&&$("Too many package entries");let g=`${f}/${h.name}`;(h.isSymbolicLink()||!h.isDirectory()&&!h.isFile())&&$("Invalid archive member"),h.isDirectory()?await l(g,u+1):g!==i.resourcesManifest.slice(2)&&!o.has(g)&&$("Undeclared distribution asset")}}await l("dist");let p=q(JSON.stringify({id:r.name,version:r.version,manifest:i,resources:[...o.values()].sort((f,u)=>f.path.localeCompare(u.path))}));return{id:r.name,version:r.version,root:t,manifest:i,resources:o,digest:p}}async function to(n,e,t){if(t!==n.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!ze(`./${r}`))return null;let i=n.resources.get(r);if(!i||r===n.manifest.backend.entry.slice(2))return null;let s=await vr(n.root,r,i.bytes);if(s.length!==i.bytes||q(s)!==i.sha256)throw new w("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:i.mime}}var kr=64*1024*1024,Dd=re.total+re.files*2048,V=n=>{throw new w("invalid_archive",n)};function ft(n){let e=n.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?n:n.subarray(0,e))}catch{return V("Archive has invalid UTF-8 paths")}}function ro(n){let e=ft(n).trim();if(!/^[0-7]+$/.test(e))return V("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:V("Archive number exceeds limits")}function Md(n){let e=n.endsWith("/")?n.slice(0,-1):n;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return V("Archive must have one package root");let t=e.slice(8);return t.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?V("Archive path is not a safe relative package path"):t}function jd(n){let e={},t=0;for(;t<n.length;){let r=n.indexOf(32,t);if(r<0)return V("Invalid PAX header");let i=n.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(i))return V("Invalid PAX record length");let s=Number(i),o=t+s;if(o>n.length||o<=r+2||n[o-1]!==10)return V("Truncated PAX record");let a=ft(n.subarray(r+1,o-1)),c=a.indexOf("=");if(c<1)return V("Invalid PAX record");let l=a.slice(0,c),p=a.slice(c+1);if(Object.hasOwn(e,l)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(l))return V("Unsupported PAX feature");e[l]=p,t=o}return e}function Wd(n){if(!n.length||n.length>kr)return V("Compressed archive exceeds budget");let e;try{e=Rd(n,{maxOutputLength:Dd})}catch{return V("Invalid or oversized gzip archive")}let t=[],r=new Set,i=0,s=0,o=0,a=0,c=null,l=!1;for(;i+512<=e.length;){let f=e.subarray(i,i+512);if(i+=512,f.every(W=>W===0)){if(c||e.subarray(i).some(W=>W!==0))return V("Unexpected archive data after end marker");l=!0;break}if(++a>re.files*2)return V("Too many archive headers");let u=0;for(let W=0;W<512;W++)u+=W>=148&&W<156?32:f[W];if(ro(f.subarray(148,156))!==u)return V("Invalid tar header checksum");let h=ft(f.subarray(257,263));if(h&&h!=="ustar"&&h!=="ustar ")return V("Unsupported tar format");let g=f[156],v=ft(f.subarray(345,500)),x=(v?v+"/":"")+ft(f.subarray(0,100)),I=ro(f.subarray(124,136));if(c&&(c.path!==void 0&&(x=c.path),c.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(c.size))return V("Invalid PAX size");I=Number(c.size)}if(!Number.isSafeInteger(I)||I<0||I>re.total||i+I>e.length)return V("Truncated or oversized tar member");let T=e.subarray(i,i+I);if(i+=Math.ceil(I/512)*512,g===120){if(c||I>8192)return V("Oversized or chained PAX header");c=jd(T);continue}if(c=null,g!==0&&g!==48&&g!==53)return V("Links and special archive members are forbidden");let O=g===53;if(O&&I!==0||ft(f.subarray(157,257)))return V("Invalid archive link or directory");if(x=Md(x),!x&&!O)return V("Invalid package root member");if(r.has(x))return V("Duplicate archive member");if(r.add(x),++s>re.files||(o+=I)>re.total)return V("Unpacked archive exceeds budget");t.push({path:x,data:T,directory:O})}if(!l||!r.has("package.json"))return V("Archive is incomplete or has no package.json");let p=new Set(t.filter(f=>!f.directory).map(f=>f.path));for(let f of t){let u=f.path.split("/");for(let h=1;h<u.length;h++)if(p.has(u.slice(0,h).join("/")))return V("Archive file/directory collision")}return t}async function io(n,e){let t=Wd(n);for(let r of t){if(!r.path)continue;let i=Hd(e,r.path);await Cd(r.directory?i:Od(i),{recursive:!0,mode:448}),r.directory||await Nd(i,r.data,{flag:"wx",mode:384})}}function _e(n){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(n);return!e||e[0]!==n||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Te(n,e){let t=_e(n),r=_e(e);if(!t||!r)throw new w("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function no(n){let e=_e(n);if(e)return e;if(!Zt(n))return null;let[t,r]=n.split("-alpha."),i=_e(t),s=Number(r);return i&&Number.isSafeInteger(s)?{...i,alpha:s}:null}function gi(n){return!!no(n)}function Ot(n,e){if(!gi(n)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(i=>!i.trim()))return!1;let r=[];for(let i of t){let s=i.trim().split(/\s+/),o=!0;for(let a of s){let c=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(a),l=c&&no(c[2]);if(!c||!l)return!1;let p=c[2],f=ue(n,p);switch(c[1]??"="){case"=":o&&=f===0;break;case">=":o&&=f>=0;break;case"<=":o&&=f<=0;break;case">":o&&=f>0;break;case"<":o&&=f<0;break;case"~":o&&=f>=0&&ue(n,`${l.major}.${l.minor+1}.0-0`)<0;break;case"^":{let u=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=f>=0&&ue(n,`${u}-0`)<0;break}}}r.push(o)}return r.some(Boolean)}var Ke=Object.freeze([Object.freeze({id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"]})]);function me(n,e=Ke){let t=e.find(r=>r.id===n);if(!t)throw new w("unknown_plugin","Plugin is not in the trusted official catalog");return t}function mi(n,e,t){let r=n.piWebapp;return n.name===e.id&&!!_e(n.version)&&!n.deprecated&&ct(r)&&Ot(t,r.hostRange)&&e.requiredCapabilities.every(i=>r.capabilities.includes(i))}function so(n,e,t,r,i){if(!n||typeof n!="object"||!("versions"in n)||!n.versions||typeof n.versions!="object"||Array.isArray(n.versions))throw new w("registry_invalid","Invalid registry version catalog");let s=Object.entries(n.versions);if(s.length>1e4)throw new w("registry_invalid","Registry version catalog exceeds budget");let a=s.flatMap(([c,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===c&&mi(p,e,t)&&(!i||c===i)&&(!r||Te(c,r)>=0)?[p]:[]}).sort((c,l)=>Te(l.version,c.version))[0];if(!a)throw new w("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!a.dist||typeof a.dist.tarball!="string"||typeof a.dist.integrity!="string")throw new w("registry_invalid","Release is missing its immutable tarball integrity");return a}function Ud(n,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new w("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),i=Vd("sha512").update(n).digest();if(r.length!==i.length||!$d(r,i))throw new w("integrity_mismatch","Downloaded package failed integrity verification")}var Xe=class{root;hostVersion;catalog;fetcher;constructor(e){if(!gi(e.hostVersion))throw new w("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Ke,this.fetcher=e.fetch??Is}async index(){let e=await ee(J(this.root,"installed.json"));if(!e){if(await G(J(this.root,"installed.json"),2*1024*1024))throw new w("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new w("invalid_storage","Invalid plugin installation index");for(let[t,r]of Object.entries(e.versions)){if(me(t,this.catalog),!Array.isArray(r)||r.length>16||new Set(r.map(i=>i.version)).size!==r.length)throw new w("invalid_storage","Invalid installed version list");for(let i of r)this.validateRecord(t,i)}return e}validateRecord(e,t){if(!t||!_e(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${q(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new w("invalid_storage","Invalid installed plugin record")}path(e){return J(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await oe(J(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(s=>!["schema","pluginId","next"].includes(s)))throw new w("invalid_storage","Invalid install journal");me(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let i=e.versions[t.pluginId]?.find(s=>s.version===t.next.version);if(i&&i.digest!==t.next.digest)throw new w("invalid_storage","Conflicting installation journal");await ht(J(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=J(this.root,"staging");await Q(r);for(let i of await Bd(r)){if(!/^stage-[A-Za-z0-9]+$/.test(i)||(await oo(J(r,i))).isSymbolicLink())throw new w("invalid_storage","Invalid abandoned staging directory");await ht(J(r,i),{recursive:!0})}return e}async recoverCollection(e){let t=J(this.root,"gc-journal.json"),r=await oe(t);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new w("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");me(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let i=r.records.filter(s=>e.versions[r.pluginId]?.some(o=>o.directory===s.directory));if(i.length&&i.length!==r.records.length)throw new w("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!i.length){await Q(J(this.root,"versions")),await Q(J(this.root,"versions",q(r.pluginId)));for(let s of r.records)await ht(this.path(s),{recursive:!0,force:!0})}await ht(t)}async collect(e,t){return me(e,this.catalog),j(this.root,async()=>{let r=await this.recoverLocked(),i=r.versions[e]??[],s=new Set(await t()),o=i.at(-1);o&&s.add(o.version);let a=i.filter(c=>!s.has(c.version));return await this.removeLocked(e,r,a),a.map(c=>c.version)})}async removeLocked(e,t,r){r.length&&(await Q(J(this.root,"versions")),await Q(J(this.root,"versions",q(e))),await M(J(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),t.versions[e]=(t.versions[e]??[]).filter(i=>!r.some(s=>s.directory===i.directory)),t.revision++,await M(J(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return j(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let r;try{r=new URL(e)}catch{throw new w("registry_denied","Invalid registry URL")}let i=new URL(t.registry);if(r.protocol!=="https:"||r.origin!==i.origin||r.username||r.password||r.hash||r.search)throw new w("registry_denied","Only the official registry origin is permitted");return r}async download(e,t,r,i="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(f){throw r?.aborted?r.reason:new w("registry_unreachable",f instanceof Error?f.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new w(o.status===404?`${i}_not_found`:"download_failed",`Registry ${i} request failed (${o.status})`);if(o.url&&new URL(o.url).origin!==e.origin)throw new w("registry_denied","Registry redirect is forbidden");let a=o.body.getReader(),c=[],l=0,p=()=>{a.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new w("download_too_large","Registry response exceeds budget");for(;;){let f=await a.read();if(f.done)break;if(l+=f.value.length,l>t)throw new w("download_too_large","Registry response exceeds budget");c.push(Buffer.from(f.value))}return s.throwIfAborted(),Buffer.concat(c)}catch(f){throw r?.aborted?r.reason:f instanceof w?f:new w("registry_unreachable",f instanceof Error?f.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await a.cancel().catch(()=>{}),a.releaseLock()}}async check(e,t,r,i){let s=me(e,this.catalog);if(r&&!_e(r))throw new w("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),a,c=await this.download(o,8*1024*1024,i,"metadata");try{a=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c))}catch{throw new w("registry_invalid","Invalid registry metadata JSON")}return so(a,s,this.hostVersion,t,r)}async install(e,t,r){let i=me(e,this.catalog);if(!mi(t,i,this.hostVersion))throw new w("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(t.dist.tarball,i),kr,r);return this.installArchive(e,s,t.dist.integrity,t.version,r)}async installArchive(e,t,r,i,s){let o=me(e,this.catalog);if(!_e(i))throw new w("invalid_version","Choose an exact stable version");if(t.length>kr)throw new w("download_too_large","Package archive exceeds budget");return Ud(t,r),j(this.root,async()=>{let a=await this.recoverLocked();s?.throwIfAborted();let c=await Fd(J(this.root,"staging","stage-"));try{await io(t,c),s?.throwIfAborted();let l=await br(c,e);if(l.version!==i||!ct(l.manifest)||!Ot(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(g=>l.manifest.capabilities.includes(g)))throw new w("incompatible_plugin","Archive version/capabilities differ from selected release");let p=a.versions[e]?.find(g=>g.version===l.version);if(p&&p.digest!==l.digest)throw new w("version_replaced","An installed immutable version cannot be replaced with different content");let f={version:l.version,digest:l.digest,integrity:r,directory:`${q(e)}/${l.version}-${l.digest}`,installedAt:new Date().toISOString()};if(await Q(J(this.root,"versions",q(e))),!p&&(a.versions[e]?.length??0)>=16)throw new w("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await M(J(this.root,"install-journal.json"),{schema:1,pluginId:e,next:f});let u=this.path(f),h=!1;try{await oo(u),h=!0}catch(g){if(!it(g))throw g}if(h){if((await br(u,e)).digest!==l.digest)throw new w("resource_changed","Installed package content was modified")}else await Ld(c,u);return s?.throwIfAborted(),p||(a.versions[e]=[...a.versions[e]??[],f],a.revision++,await M(J(this.root,"installed.json"),a)),await ht(J(this.root,"install-journal.json")),{...l,root:u}}finally{await ht(c,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=me(e,this.catalog);return j(this.root,async()=>{let i=await this.recoverLocked(),s=i.versions[e]?.find(a=>a.version===t);if(!s)throw new w("not_installed","Plugin version is not installed");let o=await br(this.path(s),e);if(o.digest!==s.digest)throw new w("resource_changed","Installed package integrity changed");if(!Ot(this.hostVersion,o.manifest.hostRange)||!r.requiredCapabilities.every(a=>o.manifest.capabilities.includes(a)))throw new w("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){me(e,this.catalog),await j(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,r,s)})}};import{lstat as Pr,mkdir as zd,open as ao,realpath as co,readdir as wi,link as qd,rename as Gd,unlink as Ye,copyFile as Jd,rm as Kd}from"node:fs/promises";import{dirname as Xd,isAbsolute as lo,join as H,relative as po,resolve as Yd,sep as yi,win32 as Qd}from"node:path";import{randomUUID as vi}from"node:crypto";var Ht=192*1024*1024,Dt=512*1024,fo=n=>typeof n=="string"&&/^[a-f0-9-]{36}$/.test(n);function Zd(n){if(!n||typeof n!="object"||Array.isArray(n))throw new w("invalid_input","Expected object input");return n}function uo(n){if(typeof n!="string"||!/^[\w.-]{1,160}$/.test(n)||n==="."||n==="..")throw new w("invalid_input","Invalid state key");return n}function Mt(n){if(n&&(!fo(n.stateRef)||typeof n.version!="string"||!Number.isSafeInteger(n.generation)||n.generation<1||!Number.isSafeInteger(n.schema)||n.schema<1||typeof n.enabled!="boolean"||typeof n.operationId!="string"))throw new w("invalid_storage","Invalid active plugin record");return n}var Qe=class{root;pluginId;legacy;checkpoint;constructor(e,t,r,i){this.root=H(e,q(t)),this.pluginId=t,this.legacy=r,this.checkpoint=i}active(){return ee(H(this.root,"active.json")).then(Mt)}async recover(){return j(this.root,async()=>{let e=await this.active(),t=await oe(H(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(o=>!["version","before","next"].includes(o))||Object.hasOwn(t,"version")&&t.version!==1)throw new w("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Mt(t.next),Mt(t.before);let r=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,a)=>o===null||a===null?o===a:["version","generation","stateRef","schema","enabled","operationId"].every(c=>o[c]===a[c]))(e,r==="committed"?t.next:t.before))throw new w("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await M(H(this.root,"previous.json"),s),r==="committed"){let o=await oe(H(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(a=>["version","stateRef"].includes(a))&&await Ye(H(this.root,"fork.json"))}return await Ye(H(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return j(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new w("stale_generation","Plugin activation changed concurrently");let i=await oe(H(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(o=>!["version","stateRef"].includes(o))))throw new w("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=Mt({...t,generation:e+1,operationId:vi()});await Q(H(this.root,"states")),await Q(H(this.root,"states",s.stateRef)),await M(H(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await M(H(this.root,"active.json"),s)}catch(o){if((await this.active())?.operationId!==s.operationId)throw o}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await M(H(this.root,"previous.json"),r),await Ye(H(this.root,"transition.json")),await Ye(H(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return j(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=vi(),i=H(this.root,"states",r);if(await oe(H(this.root,"fork.json")))throw new w("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await M(H(this.root,"fork.json"),{version:1,stateRef:r}),await Q(i);let s=H(this.root,"states",t.stateRef);for(let o of await wi(s)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new w("invalid_storage","Unexpected state file");if(!await G(H(s,o),Ht))throw new w("invalid_storage","Missing state file");await Jd(H(s,o),H(i,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return j(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await G(H(this.root,l),2*1024*1024))throw new w("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),r=Mt(await oe(H(this.root,"previous.json")));if(!t&&await G(H(this.root,"active.json"),2*1024*1024))throw new w("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,r].filter(l=>!!l),s=H(this.root,"states");await Q(s);let o=await wi(s),a=new Set(i.map(l=>l.stateRef));for(let l of o){if(!fo(l))throw new w("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=H(s,l),f=await Pr(p);if(!f.isDirectory()||f.isSymbolicLink())throw new w("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let u of await wi(p)){let h=await Pr(H(p,u));if(!/^[a-f0-9]{64}\.json$/.test(u)||!h.isFile()||h.isSymbolicLink()||h.nlink!==1)throw new w("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!a.has(l)){let g=await ee(H(p,u),Ht);if(!g)throw new w("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(g,"committed")){let v=g;if(Object.keys(v).some(x=>!["requestId","inputHash","nextHash","committed"].includes(x))||v.committed!==!0||!/^[a-f0-9]{64}$/.test(v.inputHash)||!/^[a-f0-9]{64}$/.test(v.nextHash)||typeof v.requestId!="string")throw new w("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(g).some(v=>!["revision","schema","value","requestId","inputHash"].includes(v)))throw new w("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(g)}}}}for(let l of a)if(!o.includes(l))throw new w("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let c=await e(i);for(let l of o)a.has(l)||await Kd(H(s,l),{recursive:!0,force:!0});return c})}async assertGeneration(e,t=!0){let r=await this.active();if(!r||r.generation!==e||t&&!r.enabled)throw new w("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new w("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,r){return H(this.root,"states",e.stateRef,`${q(this.scopeKey(t)+":state:"+r)}.json`)}async call(e,t,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new w("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=Zd(r);return j(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(s,e,uo(i.key)),Ht);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(s,e,uo(i.key));if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new w("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new w("invalid_input","State value must be JSON serializable");let a=JSON.stringify(i);if(Buffer.byteLength(a)>Ht)throw new w("state_too_large","Plugin state exceeds limit");let c=await ee(o,Ht);c&&this.validateState(c);let l=q(a);if(c?.requestId===e.requestId&&c.inputHash===l)return{revision:c.revision,schema:c.schema,value:c.value};if((c?.revision??0)!==i.expectedRevision)throw new w("revision_conflict","Plugin state changed concurrently");let p={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await M(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,i.path),a=i.maxBytes===void 0?Dt:i.maxBytes;if(!Number.isSafeInteger(a)||a<=0||a>Dt)throw new w("invalid_input","Invalid workspace read limit");let c=await G(o,a);return c?{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:q(c)}:null}case"workspace.commit":return this.commitFile(s,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new w("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new w("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,r=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||lo(t)||Qd.isAbsolute(t))throw new w("invalid_path","Use a workspace-relative .excalidraw path");let i=await co(e),s=Yd(i,t),o=po(i,s);if(!o||o===".."||o.startsWith(`..${yi}`)||lo(o))throw new w("invalid_path","Workspace path escapes root");let a=i,c=o.split(yi);for(let p=0;p<c.length;p++){a=H(a,c[p]);let f;try{f=await Pr(a)}catch(u){if(!it(u))throw u;if(p<c.length-1){if(!r||po(i,a)!=="diagrams")throw new w("invalid_path","Workspace directory does not exist");try{await zd(a,{mode:448})}catch(h){if(h.code!=="EEXIST")throw h}f=await Pr(a)}}if(f&&(f.isSymbolicLink()||(p<c.length-1?!f.isDirectory():!f.isFile()||f.nlink!==1)))throw new w("invalid_path","Workspace path contains a link or non-regular file")}let l=await co(Xd(s));if(l!==i&&!l.startsWith(i+yi))throw new w("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,r){if(typeof r.text!="string"||Buffer.byteLength(r.text)>Dt||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new w("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,r.path,!0),o=H(this.root,"states",e.stateRef,`${q(this.scopeKey(t)+":file:"+t.requestId+":"+String(r.path))}.json`),a=q(JSON.stringify(r)),c=q(r.text),l=await ee(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==a||l.nextHash!==c))throw new w("duplicate_request","Request ID was reused with different content");let p;try{p=await ao(`${i}.lock`,"wx",384)}catch(u){throw u.code==="EEXIST"?new w("file_busy","Workspace file is locked; original file preserved"):u}let f;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let u=await G(i,Dt),h=u?q(u):null;if(l&&h===c)return{hash:c};if(l?.committed||h!==r.expectedHash)throw new w("file_conflict","Workspace file already exists or changed externally");await M(o,{requestId:t.requestId,inputHash:a,nextHash:c,committed:!1}),f=H(s,`.plugin-${vi()}.tmp`);let g=await ao(f,"wx",384);try{await g.writeFile(r.text),await g.sync()}finally{await g.close()}if((await this.fileTarget(t.scope.cwd,r.path)).parent!==s)throw new w("file_conflict","Workspace directory changed during save");let x=await G(i,Dt);if((x?q(x):null)!==r.expectedHash)throw new w("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await qd(f,i)}catch(I){throw I.code==="EEXIST"?new w("file_conflict","Workspace file was created concurrently"):I}await Ye(f),f=void 0}else await Gd(f,i),f=void 0;return await M(o,{requestId:t.requestId,inputHash:a,nextHash:c,committed:!0}),{hash:c}}finally{f&&await Ye(f).catch(()=>{}),await p.close(),await Ye(`${i}.lock`)}}};import{randomUUID as np}from"node:crypto";import{fork as ep}from"node:child_process";import{randomUUID as tp}from"node:crypto";import{join as rp}from"node:path";import{EventEmitter as ip}from"node:events";var ho=192*1024*1024,jt=class n{child;pending=new Map;events=new ip;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,r,i){this.package=e,this.generation=t,this.broker=i;let s={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(s[o]=process.env[o]);this.child=ep(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new w("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,t,r,i,s=1e4){let o=new n(e,t,r,i);try{await o.request("initialize",{entry:rp(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},s);let a=await o.request("describe",void 0,s);if(!a||!Array.isArray(a.tools)||a.tools.length>128)throw new w("invalid_tools","Invalid hosted tool catalog");let c=new Set;for(let l of a.tools){if(!l||typeof l.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(l.name)||c.has(l.name)||typeof l.label!="string"||typeof l.description!="string"||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!l.parameters||typeof l.parameters!="object"||Array.isArray(l.parameters)||l.parameters.type!=="object")throw new w("invalid_tools","Invalid or duplicate tool descriptor");c.add(l.name)}return o.tools=structuredClone(a.tools),await o.request("health",void 0,s),o}catch(a){throw await o.dispose(),a}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>ho){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let i=this.pending.get(r.id);if(!i)return;if(clearTimeout(i.timer),this.pending.delete(r.id),!i.expired){let s=r.error;r.ok===!0?i.resolve(r.value):i.reject(new w(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let i=this.pending.get(r.invocationId);try{if(!i?.invocation||i.expired)throw new w("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(i.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:Y(s)})}}}request(e,t,r=3e4,i){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new w("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new w("worker_busy","Too many plugin requests"));let s=i?.requestId??tp();if(this.pending.has(s))return Promise.reject(new w("duplicate_request","An identical request is still running"));let o={type:"request",id:s,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>ho?Promise.reject(new w("message_too_large","Plugin request exceeds limit")):new Promise((a,c)=>{let l=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),c(new w("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:a,reject:c,timer:l,invocation:i,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(s),c(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new w("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,t,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(t=>{let r=()=>{clearTimeout(i),this.events.off("idle",r),t(!0)},i=setTimeout(()=>{this.events.off("idle",r),t(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new w("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let t=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var sp={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ir=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;constructor(e,t,r=sp){this.broker=e,this.workerEntry=t,this.hooks=r}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await ni(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,r)=>this.broker.call(e,t,r);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new w("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new w("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new w("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new w("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(l){throw this.worker||await this.releaseOwnership?.(),l}let i=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let o=null,a=!1,c=!1;try{if(o=await jt.start(e,i+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(t))throw new w("drain_pending","Plugin calls are still running; switch deferred without killing them");if(c=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(t))throw new w("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new w("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let l=r?await this.broker.forkState(i):np(),p=await this.broker.activate(i,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});a=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let f=!1;try{await this.hooks.committed(p)}catch{f=!0}return await s?.dispose(),{pending:!1,active:p,...f?{reconnectRequired:!0}:{}}}catch(l){throw a||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",c&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4){return this.serialize(async()=>{let t=this.worker,r=this.phaseValue,i=await this.broker.active(),s=async()=>{if(!(!t||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(i))throw await this.releaseOwnership?.(),this.phaseValue="failed",new w("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await jt.start(t.package,t.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(a){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),a}}};this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new w("drain_pending","Plugin work is still draining; current host retained");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new w("drain_pending","Checkpoint work is still draining; current host retained");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(a){try{await s(),this.phaseValue=r,await this.hooks.resume()}catch(c){throw this.phaseValue="failed",c}throw a}let o=!1;return()=>this.serialize(async()=>{o||(await s(),this.phaseValue=r,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,r;try{r=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!r){if(t)throw this.phaseValue="failed",new w("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let i=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(t&&!await t.waitForIdle(e))throw new w("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new w("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=i,s&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new w("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new w("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(i){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),i}})}};import{readFile as go}from"node:fs/promises";var Er=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;pairAdmittedValue=!1;get pairAdmitted(){return this.pairAdmittedValue}constructor(e){this.options=e,this.installer=new Xe({root:ye(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});for(let t of this.installer.catalog){let r=new Qe(ye(e.root,"data"),t.id,e.legacy?.(t.id)),i=e.hooks(t.id);this.supervisors.set(t.id,new Ir(r,e.workerEntry,{validateCandidate:s=>i.validateCandidate?.(s),canSwitch:()=>i.canSwitch(),freeze:()=>i.freeze(),resume:()=>i.resume(),committed:async s=>{s.enabled?(this.packages.set(t.id,await this.installer.load(t.id,s.version)),this.assetTokens.set(t.id,op(24).toString("base64url"))):(this.packages.delete(t.id),this.assetTokens.delete(t.id)),await i.committed(s)}}))}}supervisor(e){me(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new w("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new w("manager_closed","Plugin manager is shutting down"));let r=()=>j(ke(this.options.root),async()=>(await Ct(this.options.root),t())),i=(this.operations.get(e)??Promise.resolve()).then(r,r);return this.operations.set(e,i),i.then(()=>this.errors.delete(e),s=>{this.errors.set(e,Y(s))}).finally(()=>{this.operations.get(e)===i&&this.operations.delete(e)}),i}lifecycle(e,t,r=!1){return this.options.lifecycle?this.options.lifecycle(e,t,r):t()}async policies(){let e=await ee(ye(this.options.root,"policies","policies.json"));if(!e){if(await G(ye(this.options.root,"policies","policies.json"),2*1024*1024))throw new w("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,r]of Object.entries(e))if(me(t,this.installer.catalog),!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion))throw new w("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await ee(ye(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await j(ye(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await M(ye(this.options.root,"policies","update-checks.json"),r)})}async check(e,t,r,i){try{let s=await this.installer.check(e,t,r,i),o=!t||Te(s.version,t)>0;return o?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:s.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:Y(s).code,message:Y(s).message}),s}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new w("invalid_input","Invalid plugin update policy");await j(ke(this.options.root),async()=>{await Ct(this.options.root),await j(ye(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await M(ye(this.options.root,"policies","policies.json"),r)})})}async start(){await j(ke(this.options.root),()=>this.startLocked())}async startLocked(){await j(ye(this.options.root,"policies"),async()=>{let i=await this.policies();await M(ye(this.options.root,"policies","policies.json"),i)});let e=await He(this.options.root),t=pt(e);if(t&&e)try{if(await this.validatePairPackages(e.version,e.selections),e.version!==this.options.hostVersion||e.hostDigest!==await Je(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Je(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await go(this.options.workerEntry)).equals(await go(ye(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(i){let s=`Required action: restart the selected compatible host or inspect host-pair/intent.json with all owners stopped. ${Y(i).message}; data retained`;for(let o of this.installer.catalog)this.errors.set(o.id,Y(new w("host_pair_required",s)));await Se(this.options.root,{...e,phase:"required-action",message:s}),t=!1}await this.installer.inventory();let r=Z(await this.pairSnapshot());for(let i of this.installer.catalog){let s=this.supervisor(i.id),o=await s.broker.active();if(o?.enabled)try{let a=t?e?.selections.find(p=>p.id===i.id):void 0,c=a&&Z(o)===Z(a.before)&&e?.fingerprint===r,l=await this.installer.load(i.id,c?a.version:o.version);if(c&&l.digest!==a.digest)throw new Error("Staged plugin digest changed");await this.lifecycle(i.id,()=>s.replace(l)),this.packages.set(i.id,l),pt(e)||await this.collectSettled(i.id)}catch(a){let c=Y(a),l=["runtime_owned","storage_busy"].includes(c.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool; do not delete the pair journal.":"Choose a compatible host/plugin and inspect plugin diagnostics; do not delete the pair journal.";this.errors.set(i.id,{...c,message:`Required action: plugin startup failed (${c.code}): ${c.message}; data retained. ${l}`})}}t&&e&&(await Se(this.options.root,{...e,phase:this.errors.size?"required-action":"reconciled",message:this.errors.size?[...this.errors].map(([i,s])=>`${i}: ${s.message}`).join("; "):"Current compatible state admitted; no previous state restored"}),this.pairAdmittedValue=!this.errors.size)}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let o=this.supervisor(s.id),a=await o.broker.active(),c=this.packages.get(s.id),l=(e.versions[s.id]??[]).map(p=>p.version).sort((p,f)=>Te(f,p));return{id:s.id,name:s.name,description:s.description,official:!0,installed:!!l.length,installedVersions:l,version:l[0]??null,activeVersion:a?.version??null,enabled:a?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[s.id]?.updatePolicy??"notify",pinnedVersion:t[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...c&&o.phase==="active"?{digest:c.digest,document:c.manifest.frontend.document.slice(2),controller:c.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${c.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,r,i){return this.serialize(e,async()=>{let s=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],a=o.map(l=>l.version).sort((l,p)=>Te(p,l))[0],c=await(async()=>{switch(t){case"check":return{version:(await this.check(e,a,void 0,i)).version};case"install":{let l=await this.check(e,a,r,i),p=await this.installer.install(e,l,i);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:p.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:p.version}}case"enable":{let l=r??a;if(!l)throw new w("not_installed","Install the plugin first");let p=await this.installer.load(e,l),f=await this.lifecycle(e,()=>s.replace(p));return f.pending||this.packages.set(e,p),f}case"retry":{let l=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!a)throw new w("not_installed","Only installed plugins can be updated");let l=await this.check(e,a,r,i),p=await s.broker.active();if(l.version===a&&(!p?.enabled||p.version===a)&&!s.pendingVersion)return{unchanged:!0,version:a};let f=l.version===a?await this.installer.load(e,a):await this.installer.install(e,l,i);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:f.version,message:"Selected compatible release installed; activation may wait for editors"}),!p?.enabled)return{installed:!0,enabled:!1,version:f.version};let u=await this.lifecycle(e,()=>s.replace(f));return u.pending||this.packages.set(e,f),u}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new w("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=Y(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),c})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async r=>this.installer.collect(e,async()=>{let i=(await this.policies())[e];return[...r.map(s=>s.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...i?.pinnedVersion?[i.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new w("stale_generation","Reconnect the plugin view before editing",{status:409})):i.invoke(r)}flush(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new w("stale_generation","Flush generation changed",{status:409})):i.flushAction(r)}async asset(e,t,r){let i=this.packages.get(e);if(!i)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(i.version,(s.get(i.version)??0)+1);try{return await to(i,r,t)}finally{let o=s.get(i.version)-1;o?s.set(i.version,o):s.delete(i.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let r;try{r=decodeURIComponent(t[1])}catch{return null}let i=this.assetTokens.get(r),s=Buffer.from(t[2]);return!i||s.length!==Buffer.byteLength(i)||!ap(s,Buffer.from(i))?null:this.asset(r,t[3],t[4])}async reconcileHostUpgrade(){if(pt(await He(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),r=!0;for(let i of this.installer.catalog){let s=e.versions[i.id];if(s?.length)try{let o=await this.supervisor(i.id).broker.active(),a=o?.enabled?o.version:s.map(l=>l.version).sort((l,p)=>Te(p,l))[0];try{await this.installer.load(i.id,a);continue}catch(l){if(Y(l).code!=="incompatible_plugin")throw l}let c=await this.manage(i.id,"update");c&&typeof c=="object"&&"pending"in c&&c.pending&&(r=!1)}catch(o){r=!1;let a=Y(o);this.errors.set(i.id,a),await this.recordCheck(i.id,{status:"failed",code:a.code,message:a.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}get hostPair(){return Hs(this.options.root,(e,t)=>this.prepareHostPair(e,t),()=>this.pairSnapshot(),(e,t)=>this.validatePairPackages(e,t))}async validatePairPackages(e,t){let r=new Xe({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog});for(let i of t)if((await r.load(i.id,i.version)).digest!==i.digest)throw new w("host_pair_changed","Staged plugin digest changed; selection refused")}async prepareHostPair(e,t){let r=new Xe({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),i=await this.installer.inventory(),s=await this.policies(),o=[];for(let a of this.installer.catalog){let c=i.versions[a.id];if(!c?.length)continue;let l=await this.supervisor(a.id).broker.active(),p=c.map(u=>u.version).sort((u,h)=>Te(h,u))[0],f;try{f=await r.load(a.id,l?.enabled?l.version:p),o.push({id:a.id,version:f.version,digest:f.digest,before:l});continue}catch(u){if(Y(u).code!=="incompatible_plugin")throw u}try{let u=await r.check(a.id,p,void 0,t);f=u.version===p?await r.load(a.id,p):await r.install(a.id,u,t),await this.recordCheck(a.id,{status:"up-to-date",version:f.version,message:"Compatible combination prepared for software update"}),this.errors.delete(a.id)}catch(u){let h=Y(u);await this.recordCheck(a.id,{status:"failed",code:h.code,message:h.message}),this.errors.set(a.id,h);try{f=await r.load(a.id,p)}catch(g){throw new w("host_pair_required",`${h.message}; ${Y(g).message}; current host/plugin and data retained`)}}o.push({id:a.id,version:f.version,digest:f.digest,before:l})}return o}async validateHostUpdate(e){let t=new Xe({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),i=await this.policies(),s=!1;for(let o of this.installer.catalog){let a=r.versions[o.id];if(!a?.length)continue;s=!0;let c=await this.supervisor(o.id).broker.active(),l=a.map(f=>f.version).sort((f,u)=>Te(u,f))[0],p=new Set([l,...c?[c.version]:[],...i[o.id]?.pinnedVersion?[i[o.id].pinnedVersion]:[],...this.supervisor(o.id).pendingVersion?[this.supervisor(o.id).pendingVersion]:[]]);for(let f of p)try{await t.load(o.id,f)}catch(u){throw new w("host_pair_required",`Host update blocked for ${o.id}@${f}: ${Y(u).message}. Prepare a compatible pair; installed code/data retained`)}}return s}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[],t=async()=>{let r=await Promise.allSettled(e.map(s=>s()));this.closing=!1;let i=r.find(s=>s.status==="rejected");if(i?.status==="rejected")throw i.reason};try{for(let r of this.supervisors.values())e.push(await r.suspendForRestart());return t}catch(r){throw await t(),r}}};import{randomUUID as cp}from"node:crypto";var N=n=>Object.assign(new Error(n),{status:409,code:"view_barrier"}),Wt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;constructor(e,t,r=2e4,i=15e3){this.pluginId=e,this.generation=t,this.pollMs=r,this.freezeMs=i}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}sameScope(e,t,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&r.scope.ownerId===t.ownerId&&r.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||t.ownerId!==r.scope.ownerId||t.workspaceId!==r.scope.workspaceId||t.sessionId!==r.identity.sessionId)throw N("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw N("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,t,r=++this.sequence){return e.commands.push({id:r,type:t,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw N("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw N("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw N("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw N("Invalid registration capability");let o=e.viewToken??cp();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw N("View initialization was cancelled; register a new document identity");let a=this.views.get(o);if(a){if(!this.sameScope(a,e,t)||a.kind!==e.kind)throw N("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(c=>c.scope.ownerId===t.ownerId&&c.identity.mountId===e.mountId))throw N("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[]}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw N("Invalid view capability");let r=this.views.get(e.viewToken),i=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,t))throw N("Unknown or stale view capability");if(e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw N("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw N("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&i&&this.sameScope(i,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!i){if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");if(this.switching)throw N("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,t))throw N("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw N("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw N("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw N("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(N("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw N("Invalid acknowledgement");let o=r.commands.find(a=>a.id===e.commandId);if(!o)throw N("Unknown command acknowledgement");r.commands=r.commands.filter(a=>a.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(N(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw N("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw N("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw N("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw N("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw N("Invalid poll cursor");if(r.waiter)throw N("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw N("Invalid poll mode");return!e.immediate&&!r.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let a=setTimeout(c,Math.min(25e3,Math.max(50,this.pollMs)));function c(){clearTimeout(a),r.waiter=void 0,o()}r.waiter=c}),{viewToken:r.token,commands:r.commands.filter(o=>o.id>e.after)}}default:throw N("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw N("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(r=>r.activeActions||r.kind!=="controller"&&!r.frozen&&(r.busy||!this.immediate&&["editor","workspace"].includes(r.kind)));throw N(`Close editors before updating; old version retained. Pending views: ${t.map(r=>`${r.kind}:${r.identity.mountId}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let i=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>i(),reject:s=>i(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));i(N(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||i()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw N("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(N("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(N("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var bi="@chengzhiyi/pi-excalidraw",pp={entry:{label:"Excalidraw",description:{zh:"\u624B\u7ED8\u56FE\u7A3F",en:"Editable drawings"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["excalidraw_create_view","diagram_create","diagram_patch"],toolViews:["excalidraw_create_view","diagram_create","diagram_patch"],panelAlias:{prefix:"diagram:",kind:"editor",title:"Excalidraw"}},mo=new Map(Object.entries({excalidraw_read_me:"reference",excalidraw_create_view:"view",diagram_reference:"reference",diagram_create:"create",diagram_read:"read",diagram_patch:"patch"})),up=new Set(["list","new","open","import","get","focus","sync","initialize","accept","reject","save"]),fp=new Set(["sync","get","list"]),xr=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;restartPreparation;restartResume;closing=!1;started=!1;stopping;options;constructor(e){this.options=e,this.adapter=new yr({policy:(t,r)=>{let i=e.policy?.(t,r);return{...i,enabled:!this.recovery.has(t)&&this.manager.tools.some(s=>s.pluginId===t)&&i?.enabled!==!1}},invoke:async(t,r,i)=>{i?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(a=>a.pluginId===t);if(!s)throw new w("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,s.generation,r);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Er({...e,lifecycle:(t,r,i)=>this.lifecycle(t,r,i),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:r=>{if(r.length!==mo.size)throw new w("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,r),this.adapter.validateChange(t,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async r=>{try{let i=r.enabled?this.manager.tools.find(s=>s.pluginId===t)?.descriptors:[];if(!i)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,i),r.enabled){let s=await this.manager.installer.load(t,r.version);this.documents.set(t,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,"")})}else this.documents.delete(t);this.adapter.change(t,i),await this.coordinator(t).committed(r),e.changed?.(),this.recovery.delete(t)}catch(i){throw this.recovery.set(t,i),await this.coordinator(t).committed(r).catch(()=>{}),i}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),action:(t,r)=>this.action(t,r?.checkpointOnly),views:async t=>{let r=t,i=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(i))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){if(e!==bi)throw new w("unreviewed_plugin","No trusted tool policy for this package");for(let r of t)if(mo.get(r.name)!==r.action||r.readonly!==["read","reference"].includes(r.action))throw new w("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new w("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||t&&(r.cwd!==t.cwd||r.workspaceId!==t.workspaceId))throw new w("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let r=this.manager.tools.find(i=>i.pluginId===e);if(!r||r.generation!==t)throw new w("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,t=!1){let r=this.queue.then(async()=>{if(this.closing&&!t)throw new w("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,t,r=!1){let i=this.switches.then(async()=>{if(this.closing&&!r)throw new w("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await t();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new Qe(Sr(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new w("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=i.catch(()=>{}),i.catch(s=>{throw r&&this.adapter.thaw(),s})}async start(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Ke)try{let t=await new Qe(Sr(this.options.root,"data"),e.id).active();this.views.set(e.id,new Wt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new Wt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Sr(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&(this.manager.pairAdmitted?!(await this.manager.inventory()).plugins.some(r=>r.updateDiagnostic?.status==="failed"):await this.manager.reconcileHostUpgrade())&&(await Q(this.options.root),await M(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Ke)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0}}async validateHostUpdate(e,t){await this.enqueue(async()=>{if(await this.manager.validateHostUpdate(e))try{await dp(Sr(t,"dist","hosted-worker.js"))}catch{throw new w("host_pair_required","Selected host has no hosted worker; keep current host/plugin pair")}})}async inventory(){return{plugins:(await this.manager.inventory()).plugins.map(t=>({pluginId:t.id,name:t.name,official:t.official,installed:t.installed,enabled:t.enabled,icon:Ke.find(r=>r.id===t.id)?.icon,hasRetainedData:t.activeVersion!==null,phase:this.recovery.has(t.id)?"reconnect-required":t.phase,updatePolicy:t.updatePolicy,pinnedVersion:t.pinnedVersion,updateDiagnostic:t.updateDiagnostic,...t.enabled&&t.activeVersion?{version:t.activeVersion}:t.version?{version:t.version}:{},...t.availableVersion?{availableVersion:t.availableVersion}:{},...t.pendingVersion?{pendingVersion:t.pendingVersion}:{},...t.generation!==null?{generation:t.generation}:{},...this.recovery.has(t.id)||t.error?{error:this.recovery.get(t.id)instanceof Error?this.recovery.get(t.id).message:t.error?.message??"Recovery required",errorCode:this.recovery.has(t.id)?"reconnect_required":t.error?.code}:{},...t.enabled&&t.assetBase&&this.documents.has(t.id)&&t.id===bi?{documentUrl:t.assetBase+this.documents.get(t.id).document,controllerUrl:t.assetBase+this.documents.get(t.id).controller,contribution:structuredClone(pp)}:{}}))}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new w("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new w("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let t=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(t){if(this.downloads.has(e.pluginId))throw new w("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,t)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new w("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let i=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||i&&typeof i=="object"&&"reconnectRequired"in i&&i.reconnectRequired)throw new w("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let r=this.scope(e.sessionId);if(e.pluginId!==bi||!up.has(e.action))throw new w("action_denied","Action is not reviewed by this host",{status:403});let i=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:lp(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&fp.has(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new w("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new w("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{i()}}prepareRestart(){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0;try{await this.adapter.freeze();for(let i of this.views.values())i.allowImmediateReopen(!0);let e=await this.manager.suspendForRestart(),t=!1,r=async()=>{if(!t)try{await e(),t=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw()}};return this.restartResume=r,r}catch(e){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),e}finally{for(let e of this.views.values())e.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).catch(e=>{throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),e}),this.stopping}};import{open as hp,readdir as gp,unlink as mp}from"node:fs/promises";import{join as gt}from"node:path";import{randomUUID as wp}from"node:crypto";var ki="hosted-migration.json";function wo(n,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:i}=t.scope,s=gt(n,q(JSON.stringify([r,i])));await Q(n),await Q(s);let o=gt(s,"scope.lock"),a;try{a=await hp(o,"wx",384)}catch(c){throw c.code==="EEXIST"?new w("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):c}try{await a.writeFile(JSON.stringify({pid:process.pid,operationId:wp()}));let c=await ee(gt(s,ki));if(c&&(c.version!==1||c.pluginId!==e))throw new w("invalid_storage","Legacy scope belongs to another migration");let l=await gp(s),p=[];for(let u of l){if(u==="scope.lock"||u==="focus.json"||u===ki||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(u))continue;if(!/^[\w-]{1,80}\.json$/.test(u))throw new w("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new w("invalid_storage","Too many legacy checkpoints");let h=await ee(gt(s,u),3*512*1024);if(!h||h.version!==1||h.cwd!==r||h.sessionId!==i||!h.draft||u!==`${h.draft.id}.json`)throw new w("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(h.draft)}let f=await ee(gt(s,"focus.json"),1024);if(f!==null&&(typeof f!="string"||!p.some(u=>u.id===f)))throw new w("invalid_storage","Invalid legacy focused drawing");return c||await M(gt(s,ki),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:f}}finally{await a.close(),await mp(o)}}}async function yp(){for(let n of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Yt(n),t=new Ie({env:n,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:It,buildId:be,browser:Yt({}).browser}}async function yo(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let n=new Ie({monitor:!1});try{if(await n.ready,!n.enabled)throw new Error("Sentry verification transport is disabled");let e=n.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await n.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:It,buildId:be}}finally{await n.close()}}var Vt=yt(bp(Ip(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),Tp=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[Tp]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new je(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:De()}),ce()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Ge,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Ge;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new je(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:De()}),ce()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function _r(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var Ap=null;function Rp(){return Ap??=Ep.create({refreshOnCreate:!1})}var Tr=new Map;async function wt(){let n=await Rp(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Tr.keys())t.has(r)||(n.unregisterProvider(r),Tr.delete(r));for(let r of t){let i=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),o=i??s;!o||Tr.get(r)===o||(i?n.registerNativeProvider(i):s&&n.registerProvider(r,s),Tr.set(r,o))}return await n.refresh({allowNetwork:!1}),n}function le(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():De()}function De(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...ns(d.current,d.current.sessionManager.getSessionName(),d.tuiCatalog?.ids()??[]),idle:d.current.isIdle()&&!d.tuiPrompts.sending,streaming:d.tuiStreaming,queuedPrompts:d.tuiPrompts.view(),hasPendingPrompts:d.current.hasPendingMessages?.()??!1,interactions:d.interactions?.pending(d.current.sessionManager.getSessionId())??[]}}async function xi(n,e,t,r,i){let s=fe(n);Me({...De(),idle:s.isIdle()},e,i);let o=s.isIdle();o&&dt(()=>d.hosted?.adapter.assertAdmission(),r,(a,c)=>d.bridge?.reportError?.(a,c)),o&&(d.operation=r);try{let a=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===n)await d.replacementContext.sendUserMessage(a,{expandPromptTemplates:!0,deliverAs:i});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(a,{expandPromptTemplates:!0,deliverAs:i})}d.current?.sessionManager.getSessionId()===n&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:De()})}catch(a){throw o&&(d.operation=void 0),a}}function Ei(){let n=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!n||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==n||d.tuiAgentError)return!1;let r=De();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!r.paused&&!r.interactions.length};d.tuiPrompts.schedule(t,(r,i,s)=>xi(n,r,i,s))}function ie(n){if(le().sessionId!==n)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function Io(){let n=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=le(),i=d.current?De():null,s=await ot(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=i?await ot(i.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,a=await Po.listAll(),c=d.workspaceSessions?.retainedSessions()??[];i&&o&&c.push({sessionId:i.sessionId,cwd:o,path:null,name:i.name,modified:i.messages.at(-1)?.timestamp??new Date().toISOString(),idle:i.idle});let l=(await Promise.all(n.map(async p=>{let u=(await Tt(p.path,a).catch(h=>(h instanceof _t?p.available=!1:d.bridge?.reportError?.(h,{stage:"workspace_sessions"}),[]))).map(h=>({id:h.id,workspaceId:p.id,path:h.path,name:h.name||h.firstMessage?.slice(0,50)||"\u5F53\u524D\u4F1A\u8BDD",modified:h.modified.toISOString(),idle:!0}));for(let h of c.filter(g=>g.cwd===p.path)){let g=u.findIndex(x=>x.id===h.sessionId),v={id:h.sessionId,workspaceId:p.id,path:h.path??u[g]?.path??null,name:h.name,modified:h.modified,idle:h.idle};g<0?u.unshift(v):u[g]=v}return p.path===s&&!u.some(h=>h.id===t.sessionId)&&u.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),u}))).flat();return{items:n,activeId:e,sessions:l}}var bo=0;async function ce(){if(!d.bridge)return;let n=++bo;try{let e=await Io();n===bo&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function Si(n,e=!1){let t=d.workspaces?.get(n);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ue(t.path),!e&&d.current&&t.path===await ot(d.current.cwd)&&!d.workspaceSessions?.hasWorkspace(t.path))d.selected="tui",d.activeWorkspaceId=n,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:le()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=n,d.bridge?.publish({type:"snapshot",session:le()})}await ce()}function fe(n){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==n)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function ae(n){d.current=n,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:le()})}function Eo(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let n=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!n)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return Sp.create(n,void 0,{projectTrusted:e})}async function So(){let n=Eo(),e=i=>({packages:(i.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:i.extensions??[],skills:i.skills??[]}),t=new ko({cwd:le().cwd,agentDir:Ae(),settingsManager:n}),r=_s(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:n.isProjectTrusted(),global:e(n.getGlobalSettings()),project:e(n.getProjectSettings()),installed:r}}async function Cp(n){ie(n.sessionId);let e=d.selected==="tui"?fe(n.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=Eo();if(n.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=n.value.trim(),i=n.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(n.kind==="packages"){let s=new ko({cwd:le().cwd,agentDir:Ae(),settingsManager:t});n.action==="add"?await s.installAndPersist(r,{local:n.scope==="project"}):await s.removeAndPersist(r,{local:n.scope==="project"})}else if(n.kind==="extensions"){let s=i.extensions??[],o=n.action==="add"?[...new Set([...s,r])]:s.filter(a=>a!==r);n.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let s=i.skills??[],o=n.action==="add"?[...new Set([...s,r])]:s.filter(a=>a!==r);n.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&ae(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await So()}function Ar(n,e=ri){if(d.hostedMode===!1||d.hostedMode===void 0&&d.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");d.hostedMode=!0;let t=(o,a)=>{let c=Pi(o);return{cwd:c,sessionId:a,workspaceId:vo("sha256").update(c).digest("hex")}};d.hosted??=new xr({root:mt(Ae(),"pi-web","hosted"),hostVersion:JSON.parse(kp(yt(Vt,"../../package.json"),"utf8")).version,packageRoot:yt(Vt,"../.."),workerEntry:yt(Vt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${vo("sha256").update(Ae()).digest("hex")}`,resolveSession:o=>{let a=d.current;if(a?.sessionManager.getSessionId()===o)return t(a.cwd,o);let c=d.workspaceSessions?.hostedScope(o);return c?t(c.cwd,o):null},legacy:()=>wo(mt(Ae(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Ei),d.pi=n,d.tools?.clear(),d.tools=new lt({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(o,a)=>d.bridge?.reportError?.(o,a),breadcrumb:(o,a)=>d.bridge?.breadcrumb?.(o,a),anonymize:o=>d.telemetry?.session(o)??"unavailable"});let r=o=>({...d.operation,session:d.telemetry?.session(o.sessionManager.getSessionId()),piVersion:Ii,model:o.model?`${o.model.provider}/${o.model.id}`:null,thinkingLevel:o.thinkingLevel});d.interactions?.dispose(),d.interactions=new at(n.events,o=>!!d.bridge&&o.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(o.pluginId),()=>{d.current&&d.selected==="tui"&&ae(d.current)});let i=()=>{d.stopChanged?.(),d.stopChanged=n.events.on(or,()=>{d.selected==="tui"&&d.current&&ae(d.current)})};i(),n.on("session_start",async(o,a)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,i(),d.current=a,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(n,t(a.cwd,a.sessionManager.getSessionId())),await d.hosted?.start(),d.tuiPromptSessionId!==a.sessionManager.getSessionId()&&(d.tuiPrompts=new je(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:De()}),ce()}),d.tuiPromptSessionId=a.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let c=await qe.discover(a.cwd,a.isProjectTrusted?.()??!1);if(d.current!==a)return;d.tuiCatalog=c}d.replacementSessionId!==a.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),ae(a),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(a.cwd).then(async c=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==a.sessionManager.getSessionId()||(d.activeWorkspaceId=c.id,await ce())}).catch(c=>{d.bridge?.publish({type:"error",message:c instanceof Error?c.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(c,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&a.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,s(a).catch(c=>{a.ui.notify(c instanceof Error?c.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),n.on("agent_start",(o,a)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",r(a)),ae(a),ce()}),n.on("agent_end",(o,a)=>ae(a)),n.on("agent_settled",(o,a)=>{d.bridge?.breadcrumb?.("agent_end",r(a)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Ei(),ae(a),ce()}),n.on("tool_execution_start",(o,a)=>{d.tools?.start(o,r(a))}),n.on("tool_execution_end",(o,a)=>{d.tools?.end(o,r(a))}),n.on("model_select",(o,a)=>ae(a)),n.on("thinking_level_select",(o,a)=>ae(a)),n.on("message_end",(o,a)=>{if(o.message.role==="assistant"&&o.message.stopReason==="error"){d.tuiAgentError=!0;let c=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion:Ii});d.selected==="tui"&&d.bridge?.publish({type:"error",message:o.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:c,...d.operation})}o.message.role==="toolResult"&&d.tools?.message(o.message,r(a)),o.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&o.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),ae(a),ce()}),n.on("session_info_changed",(o,a)=>ae(a)),n.on("message_update",(o,a)=>{if(d.current=a,o.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(o.message.timestamp).toISOString(),blocks:Le(o.message.content)},d.selected!=="tui"||d.bridge===null))return;let c=Date.now();c-d.lastStreamAt<60||(d.lastStreamAt=c,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),n.on("session_shutdown",async o=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,o.reason==="new"||o.reason==="resume"||o.reason==="fork"||o.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let a=d.bridge,c=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let l=d.workspaceSessions;d.workspaceSessions=null,await l?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,a?await a.close():await c?.close()});let s=async o=>{d.telemetry??=new Ie;try{d.current=o,d.commandContext="newSession"in o?o:null,d.pi=n,d.tuiCatalog=await qe.discover(o.cwd,o.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new sr(cs(Ae())),await d.workspaces.load());try{await d.workspaces.discover((await Po.listAll()).map(l=>l.cwd))}catch(l){o.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${l instanceof Error?l.message:String(l)}`,"warning")}let a=await d.workspaces.add(o.cwd);if(d.selected==="tui"&&(d.activeWorkspaceId=a.id),d.bridge&&(d.bridge.protocolVersion!==7||d.bridge.buildId!==be||typeof d.bridge.reportError!="function"||typeof d.bridge.runPluginTool!="function")){let l=d.bridge;if(d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)&&d.workspaceSessions.session&&!d.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");d.bridge=null,await l.close(),await d.telemetry.close(),d.telemetry=new Ie}if(d.bridge===null){let l=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,p=l?.session&&l.path?{path:l.path,sessionManager:l.session.sessionManager}:null;l&&(await l.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new pr(u=>{d.selected==="sdk"&&d.bridge?.publish(u)},()=>d.current?.model,u=>{try{return!!d.current&&Pi(d.current.cwd)===u&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(u,h)=>d.bridge?.reportError?.(u,h),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(u,h)=>d.bridge?.breadcrumb?.(u,h),anonymize:u=>d.telemetry?.session(u)??"unavailable"},()=>{ce()},[],{adapter:d.hosted.adapter,scope:t}),p&&await d.workspaceSessions.open(p.path,{sessionManager:p.sessionManager});let f={hosted:d.hosted?.handlers,selfUpdate:new wr({agentDir:Ae(),packageRoot:yt(Vt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,hostedPair:d.hosted.manager.hostPair,beforeRestart:()=>d.hosted.prepareRestart()}),snapshot:le,busyGitWorkspaces:()=>{let u=(d.workspaceSessions?.retainedSessions()??[]).filter(h=>!h.idle).map(h=>h.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{u.push(Pi(d.current.cwd))}catch{u.push(d.current.cwd)}return u},plugins:async()=>{let u=_r();return await u?.refreshAssets(),u?.view()??{plugins:[],errors:[]}},pluginAsset:async u=>_r()?.asset(u)??null,async invokePluginAction(u,h,g,v){if(ie(u),!_r()?.has(h))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let x=d.selected,I=d.tuiGeneration,T=d.workspaceSessions?.session,O={requestId:_p(),sessionId:u,pluginId:h,action:g,input:v},W=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(O):await ar(d.pi.events,O,15e3,d.tuiWaitController.signal);if(ie(u),x!==d.selected||(x==="tui"?I!==d.tuiGeneration:T!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&ae(d.current),W},async resolvePluginInteraction(u,h,g,v){if(ie(u),!_r()?.has(h))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(u,h,g,v):d.interactions.resolve(u,h,g,v)},image(u,h,g){ie(u);let x=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(T=>T.id===h);if(x?.type!=="message"||x.message.role!=="user"||!Array.isArray(x.message.content))return null;let I=x.message.content[g];return I?.type!=="image"?null:{data:Buffer.from(I.data,"base64"),mimeType:I.mimeType}},async workspaces(){return Io()},async addWorkspace(u,h){let g=await d.workspaces.add(u,h);try{await Si(g.id,!0)}catch(v){throw await ce(),v}},async selectWorkspace(u){await Si(u)},async newSessionInWorkspace(u){await Si(u,!0)},async removeWorkspace(u){if(u===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(u),await ce()},async selectSession(u,h,g){let v=d.workspaces?.get(u);if(!v)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ue(v.path),h===d.current?.sessionManager.getSessionId()&&v.path===await ot(d.current.cwd))d.selected="tui",d.activeWorkspaceId=u,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:le()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===h&&d.workspaceSessions.path===v.path)return;if(d.workspaceSessions?.hasSession(v.path,h))await d.workspaceSessions.open(v.path,{sessionId:h});else{if(!(await Tt(v.path)).some(I=>I.id===h&&I.path===g))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(v.path,{sessionFile:g})}d.selected="sdk",d.activeWorkspaceId=u,d.bridge?.publish({type:"snapshot",session:le()})}await ce()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let u=d.current;if(!u)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let h=u.scopedModels?.map(g=>`${g.model.provider}/${g.model.id}`)??[];return u.modelRegistry.getAvailable().filter(g=>h.length===0||h.includes(`${g.provider}/${g.id}`)).map(g=>({provider:g.provider,id:g.id,name:g.name}))},async providers(){let u=await wt(),h=new Set((await u.listCredentials()).map(g=>g.providerId));return u.getProviders().map(g=>({id:g.id,name:g.name,configured:u.getProviderAuthStatus(g.id).configured,storedCredential:h.has(g.id),methods:[g.auth.apiKey?.login?"api_key":null,g.auth.oauth?"oauth":null].filter(v=>v!==null)}))},async providerModels(u){let h=await wt();return Bn(mt(Ae(),"models.json"),u,h)},async updateProviderModel(u,h,g){if(ie(u),d.selected==="tui"?!fe(u).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let v=le().model;if(g.action==="remove"&&v===`${h}/${g.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(g.action==="save"&&g.originalId&&g.originalId!==g.model.id&&v===`${h}/${g.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let x=await wt();await Ln(mt(Ae(),"models.json"),h,g,x),await x.refresh({providers:[h],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[h],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[h],allowNetwork:!1});let I=g.action==="save"?g.model.id:g.action==="base_url"&&v?.startsWith(`${h}/`)?v.slice(h.length+1):null;if(I&&v===`${h}/${I}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(h,I)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let T=fe(u),O=T.modelRegistry.find(h,I);if(!O||!d.pi||!await d.pi.setModel(O))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");ae(T)}},async logoutProvider(u,h){if(ie(u),d.selected==="tui"?!fe(u).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let g=await wt();if(!(await g.listCredentials()).some(v=>v.providerId===h))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await g.logout(h),await d.current?.modelRegistry.refresh({providers:[h],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[h],allowNetwork:!1})},async loginProvider(u,h,g){let v=await wt();await v.login(u,h,Mn(u,h,g)),await v.refresh({providers:[u],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[u],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[u],allowNetwork:!1})},async addCustomProvider(u,h){if(ie(u),d.selected==="tui"?!fe(u).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let g=await wt();if(g.getProvider(h.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await jn(mt(Ae(),"models.json"),h),await g.refresh({allowNetwork:!1}),await d.current?.modelRegistry.refresh({allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return d.selected==="tui"?(d.pi?.getCommands()??[]).filter(u=>u.name!=="web"&&u.name!=="web-dev-reload").map(u=>({name:u.name,description:u.description})):[]},async compact(u){if(ie(u),d.selected==="sdk"){let g=d.workspaceSessions?.session;if(!g||!g.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await g.compact(),d.bridge?.publish({type:"snapshot",session:le()});return}let h=fe(u);if(!h.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");h.compact()},async setModel(u,h,g){if(ie(u),d.selected==="sdk"){await d.workspaceSessions.setModel(h,g);return}let v=fe(u);if(!v.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let x=v.modelRegistry.find(h,g);if(!x||!v.modelRegistry.getAvailable().some(I=>I.provider===h&&I.id===g))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(x))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");ae(v)},async setThinkingLevel(u,h){if(ie(u),!["off","minimal","low","medium","high","xhigh"].includes(h))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(d.selected==="sdk"){let x=d.workspaceSessions?.session;if(!x||!x.isIdle||!x.getAvailableThinkingLevels().includes(h))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");x.setThinkingLevel(h),d.bridge?.publish({type:"snapshot",session:le()});return}let v=fe(u);if(!v.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!v.model||!xp(v.model).includes(h))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.setThinkingLevel(h),ae(v)},config:So,updateConfig:Cp,async send(u,h,g=[],v,x){if(ie(u),d.selected==="sdk"){await d.workspaceSessions.send(h,g,v,x);return}let I=fe(u);if(Me(De(),h,x),x==="followUp"&&(!I.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(h,g,v),Ei();return}if(I.isIdle()&&d.tuiPrompts.sending)throw new se("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await xi(u,h,g,v,x)},async updateQueuedPrompt(u,h,g,v){if(ie(u),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(h,g,v);return}if(v.kind==="steer"&&fe(u).isIdle())throw new se("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(h,g,v,(x,I,T)=>xi(u,x,I,T,"steer"))},async abort(u){if(ie(u),d.selected==="sdk")await d.workspaceSessions.stop();else{let h=fe(u);if(h.isIdle()&&!d.tuiPrompts.sending)return;if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.tools?.cancel(),d.bridge?.breadcrumb?.("cancel",{...d.operation}),d.pi.appendEntry(xt),h.abort()}},async resume(u,h){if(ie(u),d.selected==="sdk"){await d.workspaceSessions.resume(h);return}let g=fe(u);if(dt(()=>d.hosted?.adapter.assertAdmission(),h,(v,x)=>d.bridge?.reportError?.(v,x)),!g.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!g.model||!d.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!g.modelRegistry.hasConfiguredAuth(g.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");d.operation=h;try{d.pi.sendMessage(cr(le().messages),{triggerTurn:!0})}catch(v){throw d.operation=void 0,v}},async newSession(u){if(ie(u),d.selected==="sdk"){let v=d.workspaces?.get(d.activeWorkspaceId??"");if(!v)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.open(v.path,"new"),await ce();return}let h=fe(u);if(!h.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(h.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:le()}),await ce();return}if((await d.commandContext.newSession({withSession:async v=>{d.commandContext=v,d.replacementContext=v,d.replacementSessionId=v.sessionManager.getSessionId(),d.current=v}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await ce()}};f.addWorkspace=d.lifecycle.wrap(f.addWorkspace),f.selectWorkspace=d.lifecycle.wrap(f.selectWorkspace),f.newSessionInWorkspace=d.lifecycle.wrap(f.newSessionInWorkspace),f.removeWorkspace=d.lifecycle.wrap(f.removeWorkspace),f.selectSession=d.lifecycle.wrap(f.selectSession),f.newSession=d.lifecycle.wrap(f.newSession),f.updateConfig=d.lifecycle.wrap(f.updateConfig),d.bridge=await is(f,Vt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let l=[],p=null;for(let f of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(vp).filter(Boolean))try{l.push(Pp(mt(yt(f),"dist"),(u,h)=>{let g=String(h??"");["client.js","client.css"].includes(g)&&(p&&clearTimeout(p),p=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(u){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${f}: ${String(u)}`})}d.stopPluginWatch=()=>{for(let f of l)f.close();p&&clearTimeout(p)}}let c=await e(d.bridge.url).catch(()=>!1);o.ui.notify(`pi-webapp: ${d.bridge.url}`,c?"info":"warning"),o.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(a){throw d.telemetry?.capture(a,{stage:"open_web",piVersion:Ii}),d.bridge||(await d.telemetry?.close(),d.telemetry=null),a}};n.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(o,a)=>s(a)}),n.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(o,a)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(o))throw new Error("Launcher stop receipt ID required");try{await d.hosted?.shutdown(),a.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:o,ok:!0})}`,"info")}catch{a.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:o,ok:!1})}`,"warning")}}}),n.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(o,a)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await a.waitForIdle(),await d.lifecycle.run(async()=>{let c=d.workspaceSessions?.session;c&&(await c.waitForIdle(),await d.workspaceSessions.reload()),await a.reload()}))}})}var Fy=Ar;export{Fy as default,yp as verifySentryDisabledRelease,yo as verifySentryNodeRelease};
|
|
46
|
+
`)}`:void 0,t<3&&s.cause instanceof Error&&(r.cause=Bn(s.cause,e,t+1)),lt(r)}import{randomUUID as zn}from"node:crypto";import{randomUUID as sd}from"node:crypto";import{EnvHttpProxyAgent as nd,getGlobalDispatcher as Um,setGlobalDispatcher as Lm}from"undici";var Un=s=>({httpProxy:s.http_proxy??s.HTTP_PROXY??s.all_proxy??s.ALL_PROXY??"",httpsProxy:s.https_proxy??s.HTTPS_PROXY??s.all_proxy??s.ALL_PROXY??"",noProxy:s.no_proxy??s.NO_PROXY??""});function od(s,e){let t=Un(s),i;try{i=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(i.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let r=t.noProxy.toLowerCase();if(r==="*")return!1;let n=Number(i.port)||(i.protocol==="https:"?443:80),o=i.hostname.toLowerCase();return!r.split(/[,\s]/).filter(Boolean).some(c=>{let a=c.match(/^(.+):(\d+)$/),l=(a?.[1]??c).replace(/^\*?\./,"");return(!a||Number(a[2])===n)&&(o===l||o.endsWith("."+l))})}function ad(s){let e=Un(s);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new nd(e)}function hr({env:s=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:i=!1}={}){let r,n=new Set,o=t===globalThis.fetch,c=(p,u)=>{try{e(p,u)}catch{}},a=p=>p?p.close().finally(()=>n.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let y={requestId:sd(),phase:"headers",proxied:o&&od(s,p)},m=i?void 0:r,f=!1,w=u?.signal??(p instanceof Request?p.signal:void 0),k=()=>P(),P=()=>{w?.removeEventListener("abort",k),!f&&i&&(f=!0,a(m).catch(()=>{}))},E;try{o?(m??=ad(s),n.add(m),i||(r=m),E=await t(p,{...u,dispatcher:m})):E=await t(p,u)}catch(T){throw c(T,y),P(),T}if(E.ok||c(void 0,{...y,status:E.status}),!E.body)return P(),E;let _=E.body.getReader();w?.addEventListener("abort",k,{once:!0}),w?.aborted&&P();let H=new ReadableStream({async pull(T){try{let Y=await _.read();Y.done?(T.close(),_.releaseLock(),P()):T.enqueue(Y.value)}catch(Y){c(Y,{...y,phase:"body"}),T.error(Y),_.releaseLock(),P()}},async cancel(T){try{await _.cancel(T)}finally{_.releaseLock(),P()}}}),N=new Response(H,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(N,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),N},close:async()=>{await Promise.all([...n].map(a))}}}var Ln=(s,e)=>hr({autoClose:!0}).fetch(s,e);var cd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),ld=s=>typeof s=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(s)?s:void 0;function fr(s,e={}){let t=[],i=new Set,r=(a,l=0)=>{if(!a||l>4||i.has(a)||t.length>=8)return;i.add(a);let p=ld(a.code);if(t.push({name:cd.has(a.name)?a.name:"Error",...p?{code:p}:{}}),r(a.cause,l+1),a instanceof AggregateError)for(let u of a.errors.slice(0,4))r(u,l+1)};r(s);let n=t.flatMap(a=>a.code?[a.code]:[]),o=e.stage==="model_admission"||n.some(a=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(a))?"lifecycle":n.some(a=>/CERT|TLS|SSL/.test(a))?"tls":n.some(a=>/^PROXY_/.test(a))||e.proxied&&n.some(a=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(a))?"proxy":n.some(a=>/TIMEOUT|ETIMEDOUT/.test(a))||t.some(a=>/TimeoutError$/.test(a.name))?"timeout":t.some(a=>a.name==="AbortError"||a.code==="ABORT_ERR"||a.code==="UND_ERR_ABORTED")?"cancelled":n.some(a=>/ENOTFOUND|EAI_AGAIN/.test(a))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",c=a=>typeof a=="string"&&/^[\w-]{1,80}$/.test(a)?a:void 0;return{errorId:zn(),requestId:c(e.requestId)??zn(),...c(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:o,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:t}}function qn({env:s=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return hr({env:s,fetchRequest:t,onFailure:(i,r)=>e(fr(i,{...r,stage:r.phase==="body"?"model_stream":"model_headers"}))})}function dd(s){let e={...process.env,...s};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])s&&t.toUpperCase()in s&&!(t in s)&&delete e[t];return e}var pd=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Gn(s,e,t=()=>{}){let i=s.agent.streamFunction;s.agent.streamFunction=async(r,n,o)=>{if(!pd.has(r.api))return i(r,n,o);let c=t(),a=qn({env:dd(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...c?{operationId:c}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await i(r,n,{...o,fetch:a.fetch});return l.result().finally(()=>a.close()).catch(()=>{}),l}catch(l){throw await a.close(),l}}}function gt(s,e,t){try{s()}catch(i){let r=fr(i,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...r})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:r.errorId,requestId:r.requestId,stage:r.stage,code:"hosted_admission_blocked",networkKind:r.kind,networkStage:r.stage,causeCodes:r.causes.flatMap(n=>n.code?[n.code]:[]).join(",")})}catch{}throw i}}var wd=["read","grep","find","ls"],Jn=200,wi=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Qe;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,i=()=>!1,r=()=>{},n={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},c=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=i,this.reportError=r,this.onSessionsChanged=o,this.customTools=c,this.offHosted=a?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return n.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{n.enabled()&&n.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return n.enabled()?n.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let i=await Ae(e),r=t==="continue"?this.selectedByWorkspace.get(i):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.sessionId):void 0;if(r){if(r.cwd!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(r);return}if(typeof t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let n;if(t==="new")n=Mt.create(i);else if(t==="continue"){let c=(await ht(i))[0];n=c?Mt.open(c.path):Mt.create(i)}else n="sessionManager"in t?t.sessionManager:Mt.open(t.sessionFile);if(await md(n.getCwd())!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(n.getSessionId());if(o){if(o.cwd!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(i,n,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await Ae(e));return!t||!this.blank(t)?!1:(this.activate(t),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:t,cwd:i,prompts:r}=e,n=t.sessionManager.getBranch(),o=n.flatMap(c=>{let a=Nt(c);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:i,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!r.sending,name:pi(t.sessionManager.getSessionName(),o),modified:n.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(t=>Nt(t)?.role==="user")}rename(e,t){let i=this.runtimes.get(e);if(!i||i.closing)return!1;if(i.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return i.session.setSessionName(t),!0}discard(e){return this.queue.run(async()=>{let t=this.runtimes.get(e);if(!t||t.closing)return null;if(t.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!t.session.isIdle||t.prompts.sending||t.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=this.active===t,r=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),i&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:r,cwd:t.cwd,wasActive:i}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,i,r){let n=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${i}: ${r}`;console.error(n),this.publishFor(e,{type:"error",message:n})}async replace(e,t,i,r){let n=this.runtimes.get(t.getSessionId()),o=await Ye.discover(e,this.isProjectTrusted(e)),c=hd(),a=await $n(e,o.extensionRoots),l=new fd({cwd:e,agentDir:gd(),noExtensions:!0,additionalExtensionPaths:a.paths,eventBus:c,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,t.getSessionId()))]:[]}),p=null;try{await l.reload();let u=l.getExtensions().errors;if(u.length)throw new Error(u.map(b=>`${b.path}: ${b.error}`).join("; "));let y=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:m}=await ud({cwd:e,sessionManager:t,model:y,resourceLoader:l,customTools:this.customTools}),f=new ft({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(b,v)=>this.telemetry.breadcrumb(b,v),anonymize:b=>this.telemetry.anonymize(b)}),w={session:m,cwd:e,catalog:o,bus:c,generation:++this.generation,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:f,streaming:null,prompts:null,detached:r?{owner:r,events:[],seq:0,lastText:"",restoreTools:null}:void 0};w.prompts=n?.prompts??new $e(()=>{let b=this.runtimes.get(t.getSessionId())??w;this.publishFor(b,{type:"snapshot",session:this.snapshotOf(b)}),!this.disposed&&!b.closing&&this.onSessionsChanged()}),p=w,Gn(m,b=>{w.networkDiagnostic=b},()=>w.operation?.operationId);let k=b=>this.publishFor(w,b),P=w.detached,E=(b,v)=>{P&&(P.events.push({seq:++P.seq,type:b,...v===void 0?{}:{text:v}}),P.events.length>Jn&&P.events.splice(0,P.events.length-Jn))};w.interactions=new ut(c,b=>!w.closing&&b.sessionId===m.sessionManager.getSessionId()&&o.has(b.pluginId),()=>k({type:"snapshot",session:this.snapshotOf(w)}));let _=0,H=c.on(hi,()=>k({type:"snapshot",session:this.snapshotOf(w)})),N=m.subscribe(b=>{if(P&&!w.closing&&(b.type==="message_end"&&b.message.role==="assistant"&&(b.message.stopReason==="error"?E("error",b.message.errorMessage??"Agent response failed"):P.lastText=b.message.content.flatMap(v=>v.type==="text"?[v.text]:[]).join(`
|
|
47
|
+
`)),b.type==="agent_settled"&&E("turn_end",P.lastText)),!this.disposed&&!w.closing){let v={...w.operation,session:this.telemetry.anonymize(m.sessionManager.getSessionId()),piVersion:mi,model:m.model?`${m.model.provider}/${m.model.id}`:null,thinkingLevel:m.thinkingLevel};if(b.type==="agent_start"&&this.telemetry.breadcrumb("agent_start",v),b.type==="tool_execution_start"&&f.start(b,v),b.type==="tool_execution_end"&&f.end(b,v),b.type==="message_end"&&b.message.role==="assistant"&&b.message.stopReason==="error"){w.agentErrorReported=!0;let $=w.networkDiagnostic,ye=this.reportError(new Error("Agent response failed"),{...w.operation,stage:"agent",code:"agent_failed",piVersion:mi,...$?{networkKind:$.kind,networkStage:$.stage,causeCodes:$.causes.flatMap(ve=>ve.code?[ve.code]:[]).join(","),requestId:$.requestId}:{}})??$?.errorId;k({type:"error",message:b.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:ye,...w.operation})}b.type==="message_end"&&b.message.role==="toolResult"&&f.message(b.message,v),b.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",v),f.clear(),w.operation=void 0)}b.type==="message_update"&&b.message.role==="assistant"&&(w.streaming={id:"stream",role:"assistant",timestamp:new Date(b.message.timestamp).toISOString(),blocks:Je(b.message.content)},Date.now()-_>=60&&(_=Date.now(),k({type:"stream",message:w.streaming}))),b.type==="agent_settled"&&this.scheduleQueued(w),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(b.type)&&((b.type==="message_end"&&b.message.role==="assistant"||b.type==="agent_settled")&&(w.streaming=null,k({type:"stream",message:null})),k({type:"snapshot",session:this.snapshotOf(w)}),!this.disposed&&!w.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(b.type)&&this.onSessionsChanged())});w.detach=()=>{H(),N()},w.releaseHosted=this.hosted?.adapter.attach(m);let T=[],Y=!0;if(await m.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Y&&T.push(b.error),this.diagnostic(w,o.plugins.find(v=>b.extensionPath.startsWith(v.root+"/"))?.id??b.extensionPath,b.event??"runtime",b.error)}}),Y=!1,T.length)throw new Error(T.join("; "));if(this.ensureAvailable(),n&&(!n.session.isIdle||n.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(n&&await this.close(n,i),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");w.detached&&(w.detached.restoreTools=m.getActiveToolNames(),m.setActiveToolsByName(wd)),this.runtimes.set(m.sessionManager.getSessionId(),w),p=null,w.detached?this.onSessionsChanged():this.activate(w)}catch(u){throw this.hosted?.adapter.releasePending(t.getSessionId()),p?await this.close(p,"quit"):(c.clear(),await a.release()),u}}async close(e,t){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await Wn(e.session,t,i=>this.diagnostic(e,"host","shutdown",i),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:i,catalog:r}=e,n=t.sessionManager.getBranch().flatMap(o=>{let c=Nt(o);return c?[c]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:i,name:pi(t.sessionManager.getSessionName(),n),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,paused:pt(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:n,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:or(t.sessionManager.getBranch(),r.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let i=t.session.extensionRunner,r=await fi(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||i!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),r}resolveInteraction(e,t,i,r){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,i,r)}async send(e,t=[],i,r){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let n=this.active;if(We(this.snapshot(),e,r),r==="followUp"&&(!n.session.isIdle||n.prompts.length>0)){n.prompts.enqueue(e,t,i),this.scheduleQueued(n);return}if(n.session.isIdle&&n.prompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(n,e,t,i,r)}async prompt(e,t,i,r,n){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");gt(()=>this.hosted?.adapter.assertAdmission(),r,this.reportError),We({...this.snapshotOf(e),idle:e.session.isIdle},t,n);let o=e.session,c=o.isIdle;c&&(e.operation=r,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...r,piVersion:mi});let a=!1,l,p,u=new Promise((y,m)=>{l=y,p=m});o.prompt(t,{images:i,streamingBehavior:n,preflightResult:y=>{y&&(a=!0,l())}}).then(()=>{a||l()}).catch(y=>{if(!a)p(y);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let m=this.reportError(Ne(y,"Agent response failed"),{...r,stage:"agent",code:"agent_failed",piVersion:mi});this.publishFor(e,{type:"error",message:y instanceof Error?y.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:m,...r})}});try{await u}catch(y){throw c&&(e.operation=void 0),y}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!pt(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,i,r)=>this.prompt(e,t,i,r))}async updateQueuedPrompt(e,t,i){let r=this.active;if(this.disposed||!r||r.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(i.kind==="steer"&&r.session.isIdle)throw new ae("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await r.prompts.update(e,t,i,(n,o,c)=>this.prompt(r,n,o,c,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Dt),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");gt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let i=t.session;if(!i.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!pt(i.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!i.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(i.modelRuntime.hasConfiguredAuth(i.model.provider)||await i.modelRuntime.checkAuth(i.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!pt(i.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let n=gi(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),i.sendCustomMessage(n,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let c=this.reportError(Ne(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:c,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let i=this.active;if(this.disposed||!i||i.closing||!i.session.isIdle||i.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=i.session.modelRuntime.getModel(e,t);if(!r)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await i.session.setModel(r),this.publishFor(i,{type:"snapshot",session:this.snapshotOf(i)})}createDetached(e,t,i){return this.queue.run(async()=>{this.ensureAvailable();let r=await Ae(e),n=Mt.create(r);return await this.replace(r,n,"new",t),this.runtimes.get(n.getSessionId()).session.setSessionName(i),n.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,i){let r=this.detachedRuntime(e);if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(i&&r.detached.restoreTools&&(r.session.setActiveToolsByName(r.detached.restoreTools),r.detached.restoreTools=null),!r.session.isIdle||r.prompts.length>0){r.prompts.enqueue(t,[],void 0),this.scheduleQueued(r);return}await this.prompt(r,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let i=this.detachedRuntime(e)?.detached;if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:i.events.filter(r=>r.seq>t),next:i.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as yd,mkdir as vd,rename as bd,unlink as kd}from"node:fs/promises";import{basename as Pd,join as Kn}from"node:path";var Id=s=>Kn(s,"pi-web","trash");async function Xn(s,e){let t=Id(e);await vd(t,{recursive:!0});let i=Kn(t,`${Date.now()}_${Pd(s)}`);try{await bd(s,i)}catch(r){let n=r.code;if(n==="ENOENT")return null;if(n!=="EXDEV")throw r;await yd(s,i),await kd(s)}return i}import{basename as gr,dirname as Sd}from"node:path";function Yn(s,e){let t=i=>e[i].map(r=>({name:i==="skills"&&gr(r.path).toLowerCase()==="skill.md"?gr(Sd(r.path)):gr(r.path),path:r.path,source:r.metadata.source,scope:r.metadata.scope,enabled:r.enabled}));return{packages:s.map(i=>({name:i.source,path:i.installedPath??"",source:i.source,scope:i.scope,enabled:!!i.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as Ed}from"node:child_process";var xd=(s,e)=>new Promise((t,i)=>{Ed(s,[...e],{windowsHide:!0},r=>{r?i(r):t()})});async function mr(s,e=process.platform,t=process.env,i=xd){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let r=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return r===null?!1:(await i(r,[s]),!0)}import{execFile as rp}from"node:child_process";import{randomUUID as bi}from"node:crypto";import{existsSync as go}from"node:fs";import{access as xr,mkdir as ki,mkdtemp as sp,readFile as ge,realpath as np,rename as _r,rm as $t,writeFile as Pi}from"node:fs/promises";import{dirname as mo,join as M}from"node:path";import{createHash as vr,randomUUID as Hd}from"node:crypto";import{mkdir as Od,readFile as Md,readdir as jd,realpath as ro}from"node:fs/promises";import{join as Re}from"node:path";import{constants as wr}from"node:fs";import{DatabaseSync as _d}from"node:sqlite";import{lstat as eo,mkdir as Ad,open as jt,rename as Td,unlink as to}from"node:fs/promises";import{dirname as Rd,join as Qn,resolve as Cd}from"node:path";import{randomUUID as Dd}from"node:crypto";import{setTimeout as Nd}from"node:timers/promises";async function Z(s){await Ad(s,{recursive:!0,mode:448});let e=await eo(s);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function X(s,e){let t;try{t=await jt(s,wr.O_RDONLY|wr.O_NONBLOCK|(wr.O_NOFOLLOW??0))}catch(i){if(Ve(i))return null;throw i}try{let i=await t.stat();if(!i.isFile()||i.nlink>1||i.size>e)throw new h("invalid_storage","Invalid storage record size or type");let r=Buffer.alloc(Math.min(i.size+1,e+1)),n=0;for(;n<r.length;){let o=await t.read(r,n,r.length-n,n);if(!o.bytesRead)break;n+=o.bytesRead}if(n>e||n!==i.size)throw new h("invalid_storage","Storage record changed during read");return r.subarray(0,n)}finally{await t.close()}}async function ee(s,e=2*1024*1024){let t=await X(s,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new h("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function ce(s){let e=await X(s,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new h("gc_recovery_required",`Invalid journal ${s}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new h("gc_recovery_required",`Invalid journal ${s}; original bytes preserved`);return t}async function j(s,e){let t=`${s}.${Dd()}.tmp`,i=await jt(t,"wx",384);try{try{await i.writeFile(JSON.stringify(e)),await i.sync()}finally{await i.close()}await Td(t,s);let r;try{r=await jt(Rd(s),"r"),await r.sync()}catch(n){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(n.code??""))throw n}finally{await r?.close()}}finally{await to(t).catch(()=>{})}}var io='{"version":2,"mechanism":"sqlite-exclusive"}',Zn=s=>s.toString("utf8")===io,yi=new Set;async function yr(s,e,t=0){await Z(s);let i=Qn(s,`${e}.lock`),r=Qn(s,`${e}.ownership.sqlite`),n=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new h(n,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await jt(r,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await eo(r);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new h("invalid_storage","Ownership database must be a small, single-link regular file");let l=new _d(r,{allowExtension:!1}),p=Cd(r),u=Date.now()+t,y=!1;try{for(;;){if(!yi.has(p))try{l.exec("BEGIN EXCLUSIVE"),yi.add(p),y=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=u)throw new h(n,"Another host owns this plugin storage; wait for it to stop before retrying");await Nd(10)}let f=await X(i,4096);if(f===null){let w;try{w=await jt(i,"wx",384),await w.writeFile(io),await w.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await w?.close()}f=await X(i,4096)}if(f===null||!Zn(f))throw o()}catch(f){throw l.close(),y&&yi.delete(p),f}let m=!1;return async()=>{if(m)return;let f=await X(i,4096);if(f===null||!Zn(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await to(i),l.close(),yi.delete(p),m=!0}}async function W(s,e,t=2e3){let i=await yr(s,"transaction",t);try{return await e()}finally{await i()}}var Ee=s=>Re(s,"host-pair"),te=s=>vr("sha256").update(JSON.stringify(s)).digest("hex");async function Wd(s){let e=vr("sha256"),t=0,i=0;async function r(n){let o=(await jd(Re(s,n),{withFileTypes:!0})).sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(let c of o){if(!n&&c.name==="node_modules")continue;let a=n?`${n}/${c.name}`:c.name;if(c.isSymbolicLink()||!c.isFile()&&!c.isDirectory())throw new h("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new h("host_pair_required","Candidate package resource budget exceeded");if(c.isDirectory()){await r(a);continue}let l=await X(Re(s,a),64*1024*1024);if(!l||(i+=l.length)>256*1024*1024)throw new h("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,vr("sha256").update(l).digest("hex")]))}}return await r(""),e.digest("hex")}async function Ze(s,e){let t=await ro(e),i=Re(e,"dist","hosted-worker.js");if(await ro(i)!==Re(t,"dist","hosted-worker.js"))throw new h("host_pair_required","Candidate worker must remain inside the staged host");let r=await X(Re(e,"package.json"),512*1024);if(!r)throw new h("host_pair_required","Candidate package metadata missing");let n=JSON.parse(r.toString("utf8")),o=n.piWebappHostedRuntime;if(n.name!=="pi-webapp"||n.version!==s||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(a=>o.capabilities.includes(a)))throw new h("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let c=await X(i,32*1024*1024);if(!c)throw new h("host_pair_required","Candidate worker missing");return te([r.toString("base64"),c.toString("base64"),await Wd(e)])}async function Oe(s){let e=await ce(Re(Ee(s),"intent.json"));if(e&&(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||typeof e.packageRoot!="string"||!/^[a-f0-9]{64}$/.test(e.hostDigest)||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!Array.isArray(e.selections)||e.selections.some(t=>!t||typeof t.id!="string"||typeof t.version!="string"||!/^[a-f0-9]{64}$/.test(t.digest)||!Object.hasOwn(t,"before"))||e.selection&&(typeof e.selection.path!="string"||!/^[a-f0-9]{64}$/.test(e.selection.digest))||!["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(e.phase)))throw new h("host_pair_required","Invalid host pair journal; preserve data and inspect intent.json with all owners stopped");if(e){let{lifecyclePhase:t,...i}=e;e={...i,phase:i.phase==="selected"&&t==="restart-requested"?"restart-requested":i.phase==="reconciled"&&t==="cancelled"?"cancelled":i.phase}}return e}async function Te(s,e){let{lifecyclePhase:t,...i}=e,r=i.phase==="cancelled"?{...i,phase:"reconciled",lifecyclePhase:"cancelled"}:i.phase==="restart-requested"?{...i,phase:"selected",lifecyclePhase:"restart-requested"}:i;await j(Re(Ee(s),"intent.json"),r)}var mt=s=>s&&!["prepared","reconciled","cancelled"].includes(s.phase);async function Wt(s){let e=await Oe(s);if(e&&mt(e))throw new h("host_pair_required",`Host pair selection pending (${e.version}, ${e.phase}): ${e.message??"restart selected host, or stop all owners and inspect host-pair/intent.json"}; data retained`)}function so(s,e,t,i=async()=>{}){let r=async o=>{let c=Re(Ee(s),"history");await Od(c,{recursive:!0,mode:448}),await j(Re(c,`${o.id}.json`),o)},n=async(o,c,a)=>{let l=await Ze(o,c),p=te(await t()),u=await e(o,a);if(a?.throwIfAborted(),te(await t())!==p)throw new h("host_pair_changed","Plugin policy/activation changed during preflight; recheck update");return await i(o,u),{schema:1,id:Hd(),phase:"prepared",version:o,packageRoot:c,hostDigest:l,fingerprint:p,selections:u}};return{status:()=>Oe(s),stage:(o,c,a)=>W(Ee(s),async()=>{await Wt(s);let l=await Oe(s);l&&await r(l.phase==="prepared"?{...l,phase:"cancelled",message:"Superseded before version selection; no code or data changed"}:l),await Te(s,await n(o,c,a))}),cancel:(o,c,a)=>W(Ee(s),async()=>{let l=await Oe(s);if(!l||l.phase==="cancelled"||l.phase==="reconciled")return;if(o&&l.version!==o||c&&l.packageRoot!==c)throw new h("host_pair_changed","Another update owns this transaction");if(mt(l)&&!a)throw new h("host_pair_required","Selected update requires its owned pointer recovery receipt before cancellation");await a?.();let p={...l,phase:"cancelled",message:"Update cancelled; current runtime and plugin data retained"};await Te(s,p),await r(p)}),select:(o,c,a)=>W(Ee(s),async()=>{await Wt(s);let l=await Oe(s),p=l?.phase==="prepared"&&l.version===o&&l.packageRoot===c&&l.fingerprint===te(await t())?l:await n(o,c),{hostDigest:u,selections:y}=p,m=p.fingerprint;if(await Te(s,p),await i(o,y),await Ze(o,c)!==u||te(await t())!==m)throw await Te(s,{...p,phase:"required-action",message:"Preflight changed; host pointer not written"}),new h("host_pair_changed","Preflight changed; host pointer not written");await Te(s,{...p,phase:"selecting"});let f=await a();await Te(s,{...p,phase:"selected",...f?{selection:f}:{}})}),restart:(o,c,a)=>W(Ee(s),async()=>{let l=await Oe(s);if(!l||l.phase!=="selected"||l.version!==o||l.packageRoot!==c||l.hostDigest!==await Ze(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed; restart refused, inspect pair journal");if(l.selection&&te((await Md(l.selection.path)).toString("base64"))!==l.selection.digest)throw new h("host_pair_changed","Host selection pointer changed; restart refused");if(await i(o,l.selections),l.hostDigest!==await Ze(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed during restart validation");await Te(s,{...l,phase:"restart-requested",message:"Restart authorized; awaiting launcher receipt and selected host health admission"}),await a()})}}import{promisify as op}from"node:util";import{realpathSync as ao,statSync as $d}from"node:fs";import{basename as Vd,delimiter as Fd,dirname as no,join as br,resolve as Bd}from"node:path";function oo(s){if(!s)return null;try{let e=ao(s);return Vd(e)==="npm-cli.js"&&$d(e).isFile()?e:null}catch{return null}}function Ud({execPath:s=process.execPath,env:e=process.env}={}){let t=oo(e.npm_execpath);if(t)return t;let i=new Set([no(s)]);try{i.add(no(ao(s)))}catch{}let r=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of r.split(Fd).filter(Boolean))i.add(Bd(n));for(let n of i)for(let o of[br(n,"node_modules","npm","bin","npm-cli.js"),br(n,"..","lib","node_modules","npm","bin","npm-cli.js"),br(n,"npm")]){let c=oo(o);if(c)return c}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function co(s){return{file:process.execPath,args:[Ud(),...s]}}import{readFile as Ld,rename as zd,writeFile as qd,unlink as Gd}from"node:fs/promises";import{join as Jd}from"node:path";import{randomUUID as Kd}from"node:crypto";var kr=1,lo=s=>Jd(s,"pi-web","launcher-handoff.json");function po(s){return s?.protocol===kr&&typeof s.nonce=="string"&&s.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(s.requestId)&&Number.isSafeInteger(s.pid)&&s.pid>0&&["requested","draining","stopped","refused","failed"].includes(s.phase)}async function Pr(s){try{let e=JSON.parse(await Ld(lo(s),"utf8"));if(!po(e))throw new Error("Invalid launcher handoff journal; original data retained");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Xd(s,e){let t=`${s}.${Kd()}.tmp`;try{await qd(t,JSON.stringify(e),{mode:384}),await zd(t,s)}finally{await Gd(t).catch(()=>{})}}async function uo(s,e){if(!po(e))throw new Error("Invalid launcher handoff receipt");await Xd(lo(s),e)}import{execFile as Yd}from"node:child_process";import{cp as Qd,readFile as Ir,realpath as Zd,rm as ep}from"node:fs/promises";import{join as wt,sep as tp}from"node:path";import{promisify as ip}from"node:util";var ho=ip(Yd),Sr=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Er(s){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=s;return Sr.map(t=>{let i=e[t];if(typeof i!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(i))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${i}`})}async function vi(s){return Promise.all(Sr.map(async e=>{let t=await dt(s,e),i=JSON.parse(await Ir(wt(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(i.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${i.version}`}))}async function fo(s,e){let t=JSON.parse(await Ir(wt(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let i=t.peerDependencies===void 0?await vi(s):Er(t.peerDependencies);if(JSON.stringify(await vi(e))!==JSON.stringify(i))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let r=await dt(s,"node-pty"),n=await dt(e,"node-pty"),o=await Zd(wt(e,"../.."));if(r===n||!n.startsWith(o+tp))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let c=async u=>JSON.parse(await Ir(wt(u,"package.json"),"utf8")).version;if(await c(r)!==await c(n))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await ep(n,{recursive:!0,force:!0}),await Qd(r,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await ho(process.execPath,[wt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await dt(e,Sr[0]),{stdout:p}=await ho(process.execPath,[wt(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:a,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==i[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}var ap=op(rp);function wo(s){let e=s.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function cp(s,e){try{let t=co(s),{stdout:i}=await ap(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return i}catch(t){let i=t;throw new Error(i.stderr?.trim()||i.message)}}var Ii=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;validateHostedPair;hostedPair;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??cp,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let i=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!i)return vi(this.packageRoot);let r=JSON.parse(i),n=Array.isArray(r)&&r.length===1?r[0]:r;return Er(n)},this.verifyPackage=e.verifyPackage??fo,this.validateHostedPair=e.validateHostedPair,this.hostedPair=e.hostedPair,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?kr:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let i=await this.transaction();if(i&&!["committed","cancelled","failed"].includes(i.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let r=M(this.agentDir,"pi-web","launcher.json"),n=JSON.parse(await ge(r,"utf8")),o=p=>p.nonce===e&&p.pid===n.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(n))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let c=await Pr(this.agentDir);if(c?.nonce===e&&["requested","draining"].includes(c.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let a,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(a=await this.beforeRestart(),!o(JSON.parse(await ge(r,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:n.pid,phase:"requested"};try{await uo(this.agentDir,p),l=!0}catch(u){let y=await Pr(this.agentDir).catch(()=>null);if(l=y?.nonce===e&&y?.requestId===t&&["requested","draining","stopped"].includes(y.phase),!l)throw u}this.restartPending=!0}finally{!l&&a&&await a()}}async current(){let e=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Fe(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();return t?.phase==="restart-requested"&&t.version===e&&(!this.hostedPair||(await this.hostedPair.status?.())?.phase==="reconciled")&&await this.record({...t,phase:"committed",message:"Selected host is running and hosted protocol health admission completed"}),e}get transactionPath(){return M(this.agentDir,"pi-web","update-transaction.json")}async transaction(){try{let e=await ce(this.transactionPath);if(!e)return null;if(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||e.selectionPath!==M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json")||e.selectedDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.selectedDigest)||e.before!==void 0&&e.before!==null&&(typeof e.before!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.before)))throw new Error("\u66F4\u65B0\u4E8B\u52A1\u8BB0\u5F55\u65E0\u6548\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u8BCA\u65AD");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async record(e){if(await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await j(this.transactionPath,e),["failed","cancelled","committed"].includes(e.phase)){let t=M(this.agentDir,"pi-web","update-history");await ki(t,{recursive:!0}),await j(M(t,`${e.id}-${e.phase}.json`),e)}}async admittedFallback(e,t){if(!e.ownerNonce||!this.launcherNonce||e.ownerNonce===this.launcherNonce||e.before===void 0)return!1;let i=t??await this.current();if(e.version===i)return!1;try{let r=await ce(M(this.agentDir,"pi-web","launcher.json"));if(r?.nonce!==this.launcherNonce||r.version!==i||r.piPid!==process.pid)return!1;let n;try{n=(await ge(e.selectionPath)).toString("base64")}catch(o){if(o.code!=="ENOENT")return!1;n=null}return n===e.before}catch{return!1}}async admittedLegacyRecovery(e){if(!this.launcherNonce)return!1;try{let t=await ce(M(this.agentDir,"pi-web","launcher.json"));if(t?.nonce!==this.launcherNonce||t.piPid!==process.pid||t.version!==(e??await this.current()))return!1;try{return await xr(M(this.agentDir,"pi-web","launcher.restart")),!1}catch(i){return i.code==="ENOENT"}}catch{return!1}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction();if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();if(r&&!["cancelled","reconciled","prepared"].includes(r.phase)){if(!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u9700\u8981\u5F53\u524D\u540E\u53F0\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E14\u4E0D\u80FD\u4E2D\u65AD\u542F\u52A8\u5668\u5DF2\u63A5\u53D7\u7684\u4EA4\u63A5");let n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");if(!r.selection||r.selection.path!==n)throw new Error("\u65E7\u5347\u7EA7\u4E8B\u52A1\u7F3A\u5C11\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u6062\u590D\u8BCA\u65AD");let o=await ge(n);if(te(o.toString("base64"))!==r.selection.digest)throw new Error("\u65E7\u5347\u7EA7\u9009\u62E9\u5DF2\u53D8\u5316\uFF0C\u6062\u590D\u672A\u8986\u76D6\u5176\u4ED6\u64CD\u4F5C");let c=JSON.parse(o.toString("utf8")),a=await this.current(),l=M(this.packageRoot,"bin","pi-webapp.mjs");await xr(l);let p=c.previous?.version===a&&c.previous.launcher===l?c.previous:this.desktopManaged?await di(this.agentDir,{version:a,launcher:l,desktopProtocolVersion:Be}):{version:a,launcher:l,baseVersion:c.baseVersion??a};e={schema:1,id:r.id,phase:"selected",version:r.version,channel:await this.channel(),packageRoot:r.packageRoot,selectionPath:n,before:Buffer.from(JSON.stringify(p)).toString("base64"),selectedDigest:r.selection.digest,ownerNonce:this.launcherNonce,legacyRecovery:!0},await this.record(e)}else r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot)}if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot),this.preparedUpdate=void 0,this.restartPending=!1;return}if(e.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u540E\u53F0\u5F52\u5C5E\u6216\u4EA4\u63A5\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u8BF7\u4ECE\u5F53\u524D\u8FD0\u884C\u5B9E\u4F8B\u6062\u590D");if(e.phase==="restart-requested"&&!await this.admittedFallback(e))throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u5F53\u524D\u5165\u53E3\u6CA1\u6709\u5DF2\u786E\u8BA4\u56DE\u9000\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E0D\u80FD\u53D6\u6D88\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B\u7684\u4EA4\u63A5");let t=e,i=async()=>{if(t.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u5F52\u5C5E\u6216\u4EA4\u63A5\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(t.phase==="restart-requested"&&!await this.admittedFallback(t))throw new Error("\u91CD\u542F\u4EA4\u63A5\u7684\u5F52\u5C5E\u6216\u56DE\u9000\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(!t.selectedDigest)return;let r;try{r=await ge(t.selectionPath)}catch(n){if(n.code!=="ENOENT")throw n;r=null}if((r?.toString("base64")??null)!==t.before){if(!r||te(r.toString("base64"))!==t.selectedDigest)throw new Error("\u7248\u672C\u9009\u62E9\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u66F4\u6539\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u8BE5\u9009\u62E9\uFF1B\u5F53\u524D\u6570\u636E\u5DF2\u4FDD\u7559");if(t.before===null)await $t(t.selectionPath);else if(typeof t.before=="string"){let n=`${t.selectionPath}.${bi()}.tmp`;try{await Pi(n,Buffer.from(t.before,"base64"),{mode:384}),await _r(n,t.selectionPath)}finally{await $t(n,{force:!0})}}else throw new Error("\u7F3A\u5C11\u65E7\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u4E0D\u80FD\u81EA\u52A8\u6062\u590D\uFF1B\u8BF7\u4FDD\u7559\u4E8B\u52A1\u8BB0\u5F55")}};this.hostedPair?.cancel?await this.hostedPair.cancel(e.version,e.packageRoot,i):await W(M(this.agentDir,"pi-web","update-control"),i),await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0,this.restartPending=!1}get preferencePath(){return M(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ge(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${bi()}.tmp`;try{await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await Pi(t,JSON.stringify({channel:e}),{mode:384}),await _r(t,this.preferencePath)}finally{this.savingPreference=!1,await $t(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),i=go(M(this.packageRoot,".git")),r={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!i};this.desktopManaged&&(r.launcher=this.launcherIdentity(),r.launcherHandoff={supported:r.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(r.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let n=await this.transaction(),o=await this.hostedPair?.status?.();if(n&&!["failed","cancelled","committed"].includes(n.phase)?r.recovery={version:n.version,phase:n.phase,canCancel:n.legacyRecovery?await this.admittedLegacyRecovery(e):n.phase!=="restart-requested"||await this.admittedFallback(n,e)}:o&&!["cancelled","reconciled"].includes(o.phase)&&(r.recovery={version:o.version,phase:o.phase,canCancel:o.phase==="prepared"||await this.admittedLegacyRecovery(e)}),this.desktopManaged&&!this.desktopPackageUpdates)return{...r,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...r,canRestart:!1,reason:r.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};i?r.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":r.canRestart||(r.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&r.canRestart&&(r.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let c=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),a=Array.isArray(c)&&c.length===1?c[0]:c,l=t==="alpha"?a:{latest:a};if(!l||!wn(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let p=l.latest;if(t==="alpha"&&l.alpha!==void 0){if(!ai(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ue(l.alpha,p)>0&&(p=l.alpha)}r.latest=p,r.downgrade=ue(p,e)<0,r.available=t==="stable"?ue(p,e)!==0:ue(p,e)>0,this.desktopManaged&&r.downgrade&&!this.desktopReleaseChannels&&ue(p,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(r.canRestart=!1,r.requiresDesktopUpgrade=!0,r.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(c){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${c instanceof Error?c.message:String(c)}`)}return r}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(go(M(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let i=M(this.agentDir,"pi-web","releases");await ki(i,{recursive:!0});let r=await sp(M(await np(i),`${t.latest}-`)),n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:bi(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:n,ownerNonce:this.launcherNonce};await this.record(o);let c=!1;try{let a=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...a,"--prefix",r,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=M(r,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:l},await this.record(o);let p=JSON.parse(await ge(M(l,"package.json"),"utf8"));if(p.name!=="pi-webapp"||p.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let u=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&wo(p)!==wo(u))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let y=M(l,"bin","pi-webapp.mjs");await Promise.all([y,M(l,"dist","extension.js"),M(l,"web","dist","index.html")].map(w=>xr(w))),await this.validateHostedPair?.(t.latest,l);let m=this.desktopManaged?await di(this.agentDir,{version:t.latest,launcher:y,desktopProtocolVersion:Be}):null;this.desktopManaged&&await this.verifyPackage(this.packageRoot,l);let f=async()=>{let w;try{w=await ge(n)}catch(P){if(P.code!=="ENOENT")throw P;w=null}if(o={...o,phase:"selecting",before:w?.toString("base64")??null},await this.record(o),c=!0,this.desktopManaged){let P=m,E=await bn(this.agentDir,t.current),_=E?.version===t.current?E:null,H=process.env.PI_WEBAPP_DESKTOP_VERSION??E?.fallbackVersion??t.current,N={...P,...t.downgrade||E?.fallbackVersion?{fallbackVersion:H}:{},..._?{previous:_}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(N)).toString("base64"))},await this.record(o),await kn(this.agentDir,N)}else{let P=M(this.agentDir,"pi-web"),E=M(P,`update.${bi()}.tmp`);try{let _;try{_=JSON.parse(await ge(M(P,"update.json"),"utf8"))}catch{}let H=_?.baseVersion??t.current,N=_?.version===t.current?_:void 0;N&&delete N.previous;let T={version:t.latest,launcher:y,baseVersion:H,...t.downgrade||_?.allowDowngrade===!0?{allowDowngrade:!0}:{},...N?{previous:N}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(T)).toString("base64"))},await this.record(o),await Pi(E,JSON.stringify(T),{mode:384}),await _r(E,M(P,"update.json"))}finally{await $t(E,{force:!0})}}let k=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");return{path:k,digest:te((await ge(k)).toString("base64"))}};return this.hostedPair?.stage&&await this.hostedPair.stage(t.latest,l,this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted(),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={update:{version:t.latest,launcher:y},channel:t.channel??"stable",select:async()=>{this.hostedPair?await this.hostedPair.select(t.latest,l,f):await W(M(this.agentDir,"pi-web","update-control"),f),o={...o,phase:"selected"},await this.record(o)}},{version:t.latest,launcher:y}}catch(a){throw c||await $t(r,{recursive:!0,force:!0}),await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":"\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),a}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let t,i=!1;try{t=await this.beforeRestart?.(),await this.preparedUpdate?.select();let r=async()=>{let n=M(this.agentDir,"pi-web","launcher.restart"),o=await this.transaction();o&&await this.record({...o,phase:"restart-requested"});try{await Pi(n,JSON.stringify({nonce:this.launcherNonce,launcher:e.launcher}),{mode:384,flag:"wx"}),i=!0}catch(c){try{let a=JSON.parse(await ge(n,"utf8"));i=a.nonce===this.launcherNonce&&a.launcher===e.launcher}catch{}if(!i)throw c}};this.hostedPair?await this.hostedPair.restart(e.version,mo(mo(e.launcher)),r):await r(),this.restartPending=!0}catch(r){if(i){this.restartPending=!0;return}this.restartPending=!1;let n=await this.transaction();n?.phase==="restart-requested"&&await this.record({...n,phase:"selected",message:"Restart marker was not accepted; reverting owned selection"});let o=this.preparedUpdate;try{await this.cancel(),this.preparedUpdate=o}finally{t&&await t()}throw r}}};import{createHash as ta,randomUUID as ph}from"node:crypto";import{randomUUID as $u}from"node:crypto";import{access as Vu}from"node:fs/promises";import{join as ji}from"node:path";import{randomUUID as bo}from"node:crypto";import{randomUUID as lp}from"node:crypto";function yo(s){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof s[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let i=`__pi_web_contract_${lp().replaceAll("-","")}`,r;try{if(r=s.getActiveTools(),!Array.isArray(r))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let n={name:i,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{s.registerTool(n),s.setActiveTools([...r,i]),(s.getAllTools().find(c=>c.name===i)?.exposure!=="hidden"||s.getActiveTools().includes(i))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};s.registerTool({...n,parameters:o}),s.getAllTools().find(c=>c.name===i)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{s.setActiveTools(r)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var dp;function vo(){return dp??=pp().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function pp(){let{createAgentSession:s,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:i}=await import("@earendil-works/pi-ai"),{mkdtemp:r,rm:n}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:c}=await import("node:path"),a=await r(c(o(),"pi-sdk-contract-")),l,p=[],u=0,y=0,m=!1,f=!1;try{let w=(N,T,Y)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:T,parameters:{type:"object",properties:{}},execute:Y}),k=()=>({content:[],details:void 0}),P=new e({cwd:a,agentDir:a,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[N=>{N.on("tool_call",T=>{if(T.toolName==="__contract_direct"&&(m=!!T.parentToolCallId),T.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let T of["hidden","model-only"])N.registerTool(w(`__contract_${T.replace("-","_")}`,T,async()=>(y++,k())));N.registerTool(w("__contract_protected","direct",async()=>(y++,k()))),N.registerTool(w("__contract_direct","direct",async()=>(u++,k()))),N.registerTool(w("__contract_driver","direct",async(T,Y,b,v,$)=>{let ye=await $.executeTool("__contract_hidden",{}),ve=await $.executeTool("__contract_model_only",{}),se=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!ye.isError||!ve.isError)&&p.push("nested-tool-exposure"),(se.isError||u!==1)&&p.push("nested-tool-execution"),(!x.isError||y!==0)&&p.push("nested-tool-permission-guard"),m||p.push("nested-parent-identity"),f=!0,k()}))}]});await P.reload(),{session:l}=await s({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:P}),await l.bindExtensions({mode:"print"});let E=l.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(E);let _=0;l.agent.streamFunction=async N=>{let T=_++===0,Y={role:"assistant",api:N.api,provider:N.provider,model:N.id,timestamp:Date.now(),content:T?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:T?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},b=i();return b.push({type:"start",partial:Y}),b.push({type:"done",reason:T?"toolUse":"stop",message:Y}),b.end(Y),b};let H;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((N,T)=>{H=setTimeout(()=>T(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(H)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await n(a,{recursive:!0,force:!0})}}var Si=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=vo().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(i=>i.compatible===!1||!i.busy)),new Promise((i,r)=>{t=setTimeout(()=>r(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(i){throw this.thaw(),i}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let i=this.install(e,t);i.ready=!0;try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}install(e,t){let i={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(i),typeof e.on!="function")return i.compatible=!1,i.missing=["on"],i;let r=n=>{if(typeof n!="function")throw new Error("SDK event subscription cannot be released");i.handlers.push(n)};try{r(e.on("before_agent_start",async()=>{for(;this.frozen&&i.compatible!==!1&&!i.busy&&!i.disposed;)await new Promise(n=>this.waiters.add(n));if(i.disposed)throw new Error("Hosted session disposed");i.busy=i.compatible!==!1})),r(e.on("agent_settled",()=>{i.busy=!1,this.notify()})),r(e.on("tool_call",n=>{let o=i.owned.get(n.toolName);if(!o)return;let c=this.descriptors.get(o)?.find(a=>a.name===n.toolName);if(!c||!this.allowed(i,o,c,!!n.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),r(e.on("session_start",()=>{i.ready=!0,this.publish(i)})),r(e.on("session_shutdown",()=>this.release(i)))}catch{for(let n of i.handlers)try{n()}catch{}i.handlers=[],i.compatible=!1,i.missing=["hosted-lifecycle-events"]}return i}attach(e){let t=[...this.bindings].find(i=>i.scope.sessionId===e.sessionManager.getSessionId()&&!i.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(i=>{i.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(i){throw this.release(t),i}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,i,r=!1){let n=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&n.enabled&&(!n.allowlist||n.allowlist.includes(i.name))&&(!n.planMode||i.readonly===!0)&&(!r||n.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(r=>r.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let i=structuredClone(t);this.validateChange(e,i),this.descriptors.set(e,i);for(let r of this.bindings)r.ready&&this.publish(r)}validateChange(e,t){for(let r of this.bindings)if(r.compatible!==!1)for(let[n,o]of r.owned)this.assertOwner(r,o,n);let i=new Set;for(let r of t){if(!r.name||!r.action||!r.parameters||r.parameters.type!=="object"||i.has(r.name))throw new Error("Invalid hosted tool descriptor");i.add(r.name);for(let[n,o]of this.descriptors)if(n!==e&&o.some(c=>c.name===r.name))throw new Error(`Hosted tool ownership conflict: ${r.name}`);for(let n of this.bindings)n.compatible!==!1&&this.assertOwner(n,e,r.name)}}assertOwner(e,t,i){let r=e.owned.get(i);if(r&&r!==t)throw new Error(`Hosted tool ownership conflict: ${i}`);let n=e.pi.getAllTools().find(o=>o.name===i);if(n&&(!r||n.parameters!==e.definitions.get(i)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${i}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let i=yo(e.pi);e.compatible=i.supported,e.missing=i.missing}if(!e.compatible)return;for(let[i,r]of e.owned)this.assertOwner(e,r,i);for(let[i,r]of this.descriptors)for(let n of r)this.assertOwner(e,i,n.name);let t=new Set;for(let[i,r]of this.descriptors)for(let n of r){if(e.owned.set(n.name,i),!this.allowed(e,i,n))continue;t.add(n.name);let o=this.service.policy(i,e.scope),c=o.exposure??"direct",a=!o.allowNested&&c==="direct"?"model-only":c,l={name:n.name,label:n.label,description:n.description,parameters:structuredClone(n.parameters),exposure:a,execute:async(p,u,y)=>{if(!this.allowed(e,i,n))throw new Error("Hosted tool denied by host policy");return this.service.invoke(i,{requestId:bo(),scope:{...e.scope},kind:"tool",action:n.action,input:u},y)}};e.pi.registerTool(l),e.definitions.set(n.name,l)}for(let i of e.owned.keys())if(!t.has(i)){let r={name:i,label:i,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:up};e.pi.registerTool(r),e.definitions.set(i,r)}e.pi.setActiveTools(e.pi.getActiveTools().filter(i=>{let r=e.definitions.get(i);return!r||r.exposure==="direct"||r.exposure==="model-only"}))}async invokeAction(e,t,i,r,n){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(c=>c.scope.sessionId===t.sessionId&&c.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:bo(),scope:t,kind:"action",action:i,input:r},n)}};async function up(){throw new Error("Hosted tool unavailable")}import{randomBytes as uu,randomUUID as hu,timingSafeEqual as fu}from"node:crypto";import{join as Pe}from"node:path";var hp=30,ko=/^[a-z][a-z0-9-]{0,63}$/,fp=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Vt=s=>{throw new h("invalid_package",s)},Ar=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?Vt(`Invalid ${e} declaration`):s;function yt(s){let e=s&&typeof s=="object"?s:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),i=t.has("secrets")?Ar(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&ko.test(a)?a:Vt("Invalid secret name")}):[],r=e.network,n=t.has("network")?Ar(r?.hosts,"network").map(c=>typeof c=="string"&&fp.test(c)?c:Vt("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Ar(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!ko.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<hp||a.intervalSec>86400?Vt("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&Vt("Duplicate schedule id"),{secrets:i,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as gp}from"node:dns/promises";import{isIP as mp}from"node:net";var wp=new Set(["GET","POST","PATCH","PUT","DELETE"]),yp=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),vp=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Ei=(s,e)=>{throw new h("network_denied",s,{status:403,reason:e})};function bp(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if(mp(e)===4){let[t,i]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&i===254||t===172&&i>=16&&i<=31||t===192&&i===168||t===100&&i>=64&&i<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function Po(s,e,t,i,r){let n=i;if(!n||typeof n!="object"||typeof n.url!="string")throw new h("invalid_input","Invalid network request");let o;try{o=new URL(n.url)}catch{throw new h("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Ei("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Ei("Host is not declared by the plugin","host");let c=(n.method??"GET").toUpperCase();if(!wp.has(c))throw new h("invalid_input","Unsupported method");if(n.body!==void 0&&(typeof n.body!="string"||n.body.length>1024*1024))throw new h("invalid_input","Invalid body");let a={};for(let[E,_]of Object.entries(n.headers??{})){if(typeof _!="string"||yp.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(_))throw new h("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=_}let l=null;if(n.secret!==void 0){if(t.includes(n.secret)||Ei("Secret is not declared by the plugin","secret"),l=await r.secrets.get(s,n.secret),!l)throw new h("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(r.resolve??(async E=>(await gp(E,{all:!0})).map(_=>_.address)))(o.hostname);(!p.length||p.some(bp))&&Ei("Host resolves to a non-public address","address");let u=r.timeoutMs??2e4,y=r.maxResponseBytes??2*1024*1024,m=await(r.fetch??fetch)(o,{method:c,headers:a,body:n.body,redirect:"manual",signal:AbortSignal.timeout(u)}),f=[],w=0;if(m.body)for await(let E of m.body){if(w+=E.byteLength,w>y)throw new h("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let k=Buffer.concat(f).toString("utf8"),P={};return m.headers.forEach((E,_)=>{vp.has(_.toLowerCase())&&(P[_.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:m.status,headers:P,body:k}}var xi=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new h("invalid_input",`Invalid ${t}`);return s};async function Io(s,e,t,i,r,n){let o=r&&typeof r=="object"&&!Array.isArray(r)?r:{};if(i==="sessions.create"){if(o.mode!=="plan")throw new h("invalid_input","Plugin sessions must start in plan mode");if(s.activeCount(e)>=n)throw new h("quota_exceeded","Too many active plugin sessions",{status:429});return s.create({pluginId:e,cwd:t,title:xi(o.title,200,"title"),prompt:xi(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=xi(o.sessionId,200,"sessionId");if(s.ownerOf(c)!==e)throw new h("session_denied","Session was not created by this plugin",{status:403});switch(i){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new h("invalid_input","Invalid mode");return await s.send(c,xi(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await s.release(c),{ok:!0};case"sessions.abort":return await s.abort(c),{ok:!0};case"sessions.events":return s.events(c,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new h("method_denied","Unknown sessions method")}}var kp=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),_i=class{options;constructor(e){this.options=e}handles(e){return kp.has(e)}async call(e,t,i,r,n){let o=yt(t);if(r==="network.fetch"){if(!o.networkHosts.length)throw new h("capability_denied","Plugin did not declare network access",{status:403});return Po(e,o.networkHosts,o.secrets,n,this.options)}if(!o.sessions||!this.options.sessions)throw new h("capability_denied","Sessions capability is unavailable",{status:403});return Io(this.options.sessions,e,i.scope.cwd,r,n,this.options.maxActiveSessions??3)}};var Ai=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let i=this.deps.setInterval??((r,n)=>{let o=setInterval(r,n);return o.unref(),o});this.timers.set(e,t.map(r=>i(()=>{this.tick(e,r)},r.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(i=>clearInterval(i));for(let i of this.timers.get(e)??[])t(i);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let i=`${e}\0${t.id}`;if(this.running.has(i))return!1;this.running.add(i);try{return await this.deps.invoke(e,t),!0}catch(r){return this.deps.onError?.(e,t,r),!1}finally{this.running.delete(i)}}};import{createHash as Or,timingSafeEqual as Up}from"node:crypto";import{lstat as Ho,mkdtemp as Hr,readdir as Lp,readFile as zp,realpath as qp,rename as Gp,rm as ze,writeFile as Jp}from"node:fs/promises";import{tmpdir as Kp}from"node:os";import{join as U}from"node:path";import{gunzipSync as Ap}from"node:zlib";import{mkdir as Tp,writeFile as Rp}from"node:fs/promises";import{dirname as Cp,join as Dp}from"node:path";import{constants as Tr}from"node:fs";import{lstat as xo,open as Pp,readdir as So,realpath as _o}from"node:fs/promises";import{createHash as Ip}from"node:crypto";import{join as Ao,relative as Sp,resolve as Ep,sep as xp}from"node:path";var K={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},_p={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"]},B=s=>Ip("sha256").update(s).digest("hex");function F(s){throw new h("invalid_package",s)}async function et(s,e,t){let i=e.split("/");(!i.length||i.some(c=>!c||c==="."||c===".."||!/^[\w.-]+$/.test(c)))&&F("Invalid resource path");let r=s;for(let c=0;c<i.length;c++){r=Ao(r,i[c]);let a=await xo(r);(a.isSymbolicLink()||(c<i.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&F("Links and non-regular package files are forbidden")}let n=await _o(r);(n!==Ep(s,e)||Sp(s,n).startsWith(`..${xp}`))&&F("Resource escapes package root");let o=await Pp(r,Tr.O_RDONLY|Tr.O_NONBLOCK|(Tr.O_NOFOLLOW??0));try{let c=await o.stat();(!c.isFile()||c.nlink!==1||c.size>t)&&F("Oversized or non-regular package file");let a=Buffer.alloc(Math.min(c.size+1,t+1)),l=0;for(;l<a.length;){let p=await o.read(a,l,a.length-l,l);if(!p.bytesRead)break;l+=p.bytesRead}return(l>t||l!==c.size)&&F("Package resource changed during read"),a.subarray(0,l)}finally{await o.close()}}function Eo(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return F("Invalid package JSON")}}async function tt(s,e){let t=await _o(s);(await xo(s)).isSymbolicLink()&&F("Package root cannot be a symlink");let i=Eo(await et(t,"package.json",K.other));(!i||typeof i.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(i.name)||i.name.length>214||e&&i.name!==e)&&F("Package identity mismatch"),(typeof i.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(i.version))&&F("Invalid package version"),Ue(i.piWebapp)||F("Unsupported hosted manifest"),i.type!=="module"&&F("Hosted package must declare ESM module type");for(let u of await So(t,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&F("Undeclared package-root asset or code");i.scripts&&Object.keys(i.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&F("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let y=i[u];y&&(typeof y!="object"||Object.keys(y).length>0)&&F("Hosted packages must contain all runtime dependencies")}let r=i.piWebapp,n=Eo(await et(t,r.resourcesManifest.slice(2),K.other));(!n||n.version!==1||!Array.isArray(n.files)||!n.files.length||n.files.length>K.files)&&F("Invalid resource manifest");let o=new Map,c=0;for(let u of n.files){(!u||typeof u!="object")&&F("Invalid resource entry");let y=u,m={...y,path:typeof y.path=="string"&&y.path.startsWith("./")?y.path.slice(2):y.path};(!Xe(`./${m.path}`)||typeof m.sha256!="string"||!/^[a-f0-9]{64}$/.test(m.sha256)||!Number.isSafeInteger(m.bytes)||m.bytes<0||o.has(m.path))&&F("Invalid or duplicate resource");let f=m.path.split(".").at(-1);_p[f]?.includes(m.mime)||F("Unsupported resource MIME");let w=f==="js"||f==="mjs"?K.js:f==="css"?K.css:f==="woff"||f==="woff2"?K.font:K.other;(m.bytes>w||(c+=m.bytes)>K.total)&&F("Resource budget exceeded");let k=await et(t,m.path,w);(k.length!==m.bytes||B(k)!==m.sha256)&&F("Resource integrity mismatch"),o.set(m.path,Object.freeze({...m}))}for(let u of[r.backend.entry,r.frontend.document,r.frontend.controller])o.has(u.slice(2))||F("Entrypoint is absent from resource manifest");let a=0;async function l(u,y=0){y>16&&F("Package directory nesting limit exceeded");for(let m of await So(Ao(t,u),{withFileTypes:!0})){++a>K.files*2&&F("Too many package entries");let f=`${u}/${m.name}`;(m.isSymbolicLink()||!m.isDirectory()&&!m.isFile())&&F("Invalid archive member"),m.isDirectory()?await l(f,y+1):f!==r.resourcesManifest.slice(2)&&!o.has(f)&&F("Undeclared distribution asset")}}await l("dist");let p=B(JSON.stringify({id:i.name,version:i.version,manifest:r,resources:[...o.values()].sort((u,y)=>u.path.localeCompare(y.path))}));return{id:i.name,version:i.version,root:t,manifest:r,resources:o,digest:p}}async function To(s,e,t){if(t!==s.digest||e.length>1536)return null;let i;try{i=decodeURIComponent(e)}catch{return null}if(!Xe(`./${i}`))return null;let r=s.resources.get(i);if(!r||i===s.manifest.backend.entry.slice(2))return null;let n=await et(s.root,i,r.bytes);if(n.length!==r.bytes||B(n)!==r.sha256)throw new h("resource_changed","Installed resource integrity mismatch");return{bytes:n,mime:r.mime}}var Ti=64*1024*1024,Np=K.total+K.files*2048,V=s=>{throw new h("invalid_archive",s)};function vt(s){let e=s.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?s:s.subarray(0,e))}catch{return V("Archive has invalid UTF-8 paths")}}function Ro(s){let e=vt(s).trim();if(!/^[0-7]+$/.test(e))return V("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:V("Archive number exceeds limits")}function Hp(s){let e=s.endsWith("/")?s.slice(0,-1):s;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return V("Archive must have one package root");let t=e.slice(8);return t.split("/").some(i=>!i||i==="."||i===".."||!/^[A-Za-z0-9_@.-]+$/.test(i))?V("Archive path is not a safe relative package path"):t}function Op(s){let e={},t=0;for(;t<s.length;){let i=s.indexOf(32,t);if(i<0)return V("Invalid PAX header");let r=s.subarray(t,i).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(r))return V("Invalid PAX record length");let n=Number(r),o=t+n;if(o>s.length||o<=i+2||s[o-1]!==10)return V("Truncated PAX record");let c=vt(s.subarray(i+1,o-1)),a=c.indexOf("=");if(a<1)return V("Invalid PAX record");let l=c.slice(0,a),p=c.slice(a+1);if(Object.hasOwn(e,l)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(l))return V("Unsupported PAX feature");e[l]=p,t=o}return e}function Mp(s){if(!s.length||s.length>Ti)return V("Compressed archive exceeds budget");let e;try{e=Ap(s,{maxOutputLength:Np})}catch{return V("Invalid or oversized gzip archive")}let t=[],i=new Set,r=0,n=0,o=0,c=0,a=null,l=!1;for(;r+512<=e.length;){let u=e.subarray(r,r+512);if(r+=512,u.every(H=>H===0)){if(a||e.subarray(r).some(H=>H!==0))return V("Unexpected archive data after end marker");l=!0;break}if(++c>K.files*2)return V("Too many archive headers");let y=0;for(let H=0;H<512;H++)y+=H>=148&&H<156?32:u[H];if(Ro(u.subarray(148,156))!==y)return V("Invalid tar header checksum");let m=vt(u.subarray(257,263));if(m&&m!=="ustar"&&m!=="ustar ")return V("Unsupported tar format");let f=u[156],w=vt(u.subarray(345,500)),k=(w?w+"/":"")+vt(u.subarray(0,100)),P=Ro(u.subarray(124,136));if(a&&(a.path!==void 0&&(k=a.path),a.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(a.size))return V("Invalid PAX size");P=Number(a.size)}if(!Number.isSafeInteger(P)||P<0||P>K.total||r+P>e.length)return V("Truncated or oversized tar member");let E=e.subarray(r,r+P);if(r+=Math.ceil(P/512)*512,f===120){if(a||P>8192)return V("Oversized or chained PAX header");a=Op(E);continue}if(a=null,f!==0&&f!==48&&f!==53)return V("Links and special archive members are forbidden");let _=f===53;if(_&&P!==0||vt(u.subarray(157,257)))return V("Invalid archive link or directory");if(k=Hp(k),!k&&!_)return V("Invalid package root member");if(i.has(k))return V("Duplicate archive member");if(i.add(k),++n>K.files||(o+=P)>K.total)return V("Unpacked archive exceeds budget");t.push({path:k,data:E,directory:_})}if(!l||!i.has("package.json"))return V("Archive is incomplete or has no package.json");let p=new Set(t.filter(u=>!u.directory).map(u=>u.path));for(let u of t){let y=u.path.split("/");for(let m=1;m<y.length;m++)if(p.has(y.slice(0,m).join("/")))return V("Archive file/directory collision")}return t}async function Rr(s,e){let t=Mp(s);for(let i of t){if(!i.path)continue;let r=Dp(e,i.path);await Tp(i.directory?r:Cp(r),{recursive:!0,mode:448}),i.directory||await Rp(r,i.data,{flag:"wx",mode:384})}}import{lstat as jp,mkdir as Wp,readdir as $p,realpath as Vp,writeFile as Fp}from"node:fs/promises";import{dirname as Bp,join as Cr}from"node:path";async function Co(s,e){let t=await Vp(s),i=await et(t,"package.json",K.other),r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new h("invalid_package","package.json is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new h("invalid_package","package.json must be an object");let n=[],o=0,c=0;async function a(y,m){if(m>16)throw new h("invalid_package","Package directory nesting limit exceeded");for(let f of await $p(Cr(t,y),{withFileTypes:!0})){let w=`${y}/${f.name}`;if(++o>K.files)throw new h("invalid_package","Too many package entries");if(f.isDirectory()){await a(w,m+1);continue}if(!f.isFile())throw new h("invalid_package",`Links and non-regular files are forbidden: ${w}`);let k=await et(t,w,K.js);if((c+=k.length)>K.total)throw new h("invalid_package","Resource budget exceeded");let P=Cr(e,w);await Wp(Bp(P),{recursive:!0,mode:448}),await Fp(P,k,{flag:"wx",mode:384}),n.push([w,B(k)])}}let l;try{l=await jp(Cr(t,"dist"))}catch(y){throw y.code==="ENOENT"?new h("dist_missing","dist/ does not exist yet; build the plugin first"):y}if(!l.isDirectory())throw new h("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...u}=r;return n.sort((y,m)=>y[0].localeCompare(m[0])),{contentHash:B(JSON.stringify({package:u,files:n})),packageJson:r}}function ke(s){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(s);return!e||e[0]!==s||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Ce(s,e){let t=ke(s),i=ke(e);if(!t||!i)throw new h("invalid_version","Only exact stable semantic versions are supported");return t.major-i.major||t.minor-i.minor||t.patch-i.patch}function Do(s){let e=ke(s);if(e)return e;if(!ai(s))return null;let[t,i]=s.split("-alpha."),r=ke(t),n=Number(i);return r&&Number.isSafeInteger(n)?{...r,alpha:n}:null}function Dr(s){return!!Do(s)}function bt(s,e){if(!Dr(s)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(r=>!r.trim()))return!1;let i=[];for(let r of t){let n=r.trim().split(/\s+/),o=!0;for(let c of n){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&Do(a[2]);if(!a||!l)return!1;let p=a[2],u=ue(s,p);switch(a[1]??"="){case"=":o&&=u===0;break;case">=":o&&=u>=0;break;case"<=":o&&=u<=0;break;case">":o&&=u>0;break;case"<":o&&=u<0;break;case"~":o&&=u>=0&&ue(s,`${l.major}.${l.minor+1}.0-0`)<0;break;case"^":{let y=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&ue(s,`${y}-0`)<0;break}}}i.push(o)}return i.some(Boolean)}var Me=Object.freeze([Object.freeze({id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"]})]);function me(s,e=Me){let t=e.find(i=>i.id===s);if(!t)throw new h("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Nr(s,e,t){let i=s.piWebapp;return s.name===e.id&&!!ke(s.version)&&!s.deprecated&&Ue(i)&&bt(t,i.hostRange)&&e.requiredCapabilities.every(r=>i.capabilities.includes(r))}function No(s,e,t,i,r){if(!s||typeof s!="object"||!("versions"in s)||!s.versions||typeof s.versions!="object"||Array.isArray(s.versions))throw new h("registry_invalid","Invalid registry version catalog");let n=Object.entries(s.versions);if(n.length>1e4)throw new h("registry_invalid","Registry version catalog exceeds budget");let c=n.flatMap(([a,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===a&&Nr(p,e,t)&&(!r||a===r)&&(!i||Ce(a,i)>=0)?[p]:[]}).sort((a,l)=>Ce(l.version,a.version))[0];if(!c)throw new h("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!c.dist||typeof c.dist.tarball!="string"||typeof c.dist.integrity!="string")throw new h("registry_invalid","Release is missing its immutable tarball integrity");return c}function Xp(s,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new h("invalid_integrity","A single SHA-512 tarball integrity is required");let i=Buffer.from(t[1],"base64"),r=Or("sha512").update(s).digest();if(i.length!==r.length||!Up(i,r))throw new h("integrity_mismatch","Downloaded package failed integrity verification")}var it=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Dr(e.hostVersion))throw new h("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Me,this.fetcher=e.fetch??Ln}async index(){let e=await ee(U(this.root,"installed.json"));if(!e){if(await X(U(this.root,"installed.json"),2*1024*1024))throw new h("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new h("invalid_storage","Invalid plugin installation index");for(let[t,i]of Object.entries(e.versions))if(this.catalog.some(r=>r.id===t)){if(!Array.isArray(i)||i.length>16||new Set(i.map(r=>r.version)).size!==i.length)throw new h("invalid_storage","Invalid installed version list");for(let r of i)this.validateRecord(t,r)}return e}validateRecord(e,t){if(!t||!ke(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${B(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new h("invalid_storage","Invalid installed plugin record")}path(e){return U(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await ce(U(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(n=>!["schema","pluginId","next"].includes(n)))throw new h("invalid_storage","Invalid install journal");me(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let r=e.versions[t.pluginId]?.find(n=>n.version===t.next.version);if(r&&r.digest!==t.next.digest)throw new h("invalid_storage","Conflicting installation journal");await ze(U(this.root,"install-journal.json"))}await this.recoverCollection(e);let i=U(this.root,"staging");await Z(i);for(let r of await Lp(i)){if(!/^stage-[A-Za-z0-9]+$/.test(r)||(await Ho(U(i,r))).isSymbolicLink())throw new h("invalid_storage","Invalid abandoned staging directory");await ze(U(i,r),{recursive:!0})}return e}async recoverCollection(e){let t=U(this.root,"gc-journal.json"),i=await ce(t);if(!i)return;if(i.schema!==1||Object.keys(i).some(n=>!["schema","pluginId","records"].includes(n))||!Array.isArray(i.records)||!i.records.length)throw new h("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");me(i.pluginId,this.catalog);for(let n of i.records)this.validateRecord(i.pluginId,n);let r=i.records.filter(n=>e.versions[i.pluginId]?.some(o=>o.directory===n.directory));if(r.length&&r.length!==i.records.length)throw new h("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!r.length){await Z(U(this.root,"versions")),await Z(U(this.root,"versions",B(i.pluginId)));for(let n of i.records)await ze(this.path(n),{recursive:!0,force:!0})}await ze(t)}async collect(e,t){return me(e,this.catalog),W(this.root,async()=>{let i=await this.recoverLocked(),r=i.versions[e]??[],n=new Set(await t()),o=r.at(-1);o&&n.add(o.version);let c=r.filter(a=>!n.has(a.version));return await this.removeLocked(e,i,c),c.map(a=>a.version)})}async removeLocked(e,t,i){i.length&&(await Z(U(this.root,"versions")),await Z(U(this.root,"versions",B(e))),await j(U(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:i}),t.versions[e]=(t.versions[e]??[]).filter(r=>!i.some(n=>n.directory===r.directory)),t.revision++,await j(U(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return W(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let i;try{i=new URL(e)}catch{throw new h("registry_denied","Invalid registry URL")}let r=new URL(t.registry);if(i.protocol!=="https:"||i.origin!==r.origin||i.username||i.password||i.hash||i.search)throw new h("registry_denied","Only the official registry origin is permitted");return i}async download(e,t,i,r="tarball"){let n=AbortSignal.any([AbortSignal.timeout(6e4),...i?[i]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:n,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw i?.aborted?i.reason:new h("registry_unreachable",u instanceof Error?u.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new h(o.status===404?`${r}_not_found`:"download_failed",`Registry ${r} request failed (${o.status})`);if(o.url&&new URL(o.url).origin!==e.origin)throw new h("registry_denied","Registry redirect is forbidden");let c=o.body.getReader(),a=[],l=0,p=()=>{c.cancel(n.reason).catch(()=>{})};n.addEventListener("abort",p,{once:!0});try{if(n.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new h("download_too_large","Registry response exceeds budget");for(;;){let u=await c.read();if(u.done)break;if(l+=u.value.length,l>t)throw new h("download_too_large","Registry response exceeds budget");a.push(Buffer.from(u.value))}return n.throwIfAborted(),Buffer.concat(a)}catch(u){throw i?.aborted?i.reason:u instanceof h?u:new h("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{n.removeEventListener("abort",p),await c.cancel().catch(()=>{}),c.releaseLock()}}async check(e,t,i,r){let n=me(e,this.catalog);if(i&&!ke(i))throw new h("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${n.registry}/${encodeURIComponent(e)}`,n),c,a=await this.download(o,8*1024*1024,r,"metadata");try{c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{throw new h("registry_invalid","Invalid registry metadata JSON")}return No(c,n,this.hostVersion,t,i)}async install(e,t,i){let r=me(e,this.catalog);if(!Nr(t,r,this.hostVersion))throw new h("incompatible_plugin","Plugin release is incompatible with this host");let n=await this.download(this.trustedUrl(t.dist.tarball,r),Ti,i);return this.installArchive(e,n,t.dist.integrity,t.version,i)}async installArchive(e,t,i,r,n){let o=me(e,this.catalog);if(!ke(r))throw new h("invalid_version","Choose an exact stable version");if(t.length>Ti)throw new h("download_too_large","Package archive exceeds budget");return Xp(t,i),W(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await Hr(U(this.root,"staging","stage-"));try{await Rr(t,a),n?.throwIfAborted();let l=await tt(a,e);if(l.version!==r||!Ue(l.manifest)||!bt(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(p=>l.manifest.capabilities.includes(p)))throw new h("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,c,a,l,i,n)}finally{await ze(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,i,r,n,o){let c=t.versions[e]?.find(u=>u.version===r.version);if(c&&c.digest!==r.digest)throw new h("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:r.version,digest:r.digest,integrity:n,directory:`${B(e)}/${r.version}-${r.digest}`,installedAt:new Date().toISOString()};if(await Z(U(this.root,"versions",B(e))),!c&&(t.versions[e]?.length??0)>=16)throw new h("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await j(U(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await Ho(l),p=!0}catch(u){if(!Ve(u))throw u}if(p){if((await tt(l,e)).digest!==r.digest)throw new h("resource_changed","Installed package content was modified")}else await Gp(i,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await j(U(this.root,"installed.json"),t)),await ze(U(this.root,"install-journal.json")),{...r,root:await qp(l)}}async installDevArchive(e,t,i){me(e,this.catalog);let r=await zp(t),n="sha512-"+Or("sha512").update(r).digest("base64"),o=await Hr(U(Kp(),"pi-dev-archive-"));try{await Rr(r,o);let c=(await tt(o,e)).version;return await this.installArchive(e,r,n,c,i)}finally{await ze(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,i){let r=me(e,this.catalog);return W(this.root,async()=>{let n=await this.recoverLocked();i?.throwIfAborted();let o=await Hr(U(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await Co(t,o);i?.throwIfAborted();let l=U(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],y=n.versions[e]??[],m=u?.contentHash===c?y.find(T=>T.version===u.version):void 0;if(m){let T=await tt(this.path(m),e);if(T.digest!==m.digest)throw new h("resource_changed","Installed package integrity changed");return T}let f=typeof a.version=="string"?ke(a.version):null;if(!f)throw new h("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let w=Math.max(-1,...y.map(T=>ke(T.version)).filter(T=>T&&T.major===f.major&&T.minor===f.minor).map(T=>T.patch)),k=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),w+1),P=`${f.major}.${f.minor}.${k}`;await Jp(U(o,"package.json"),JSON.stringify({...a,version:P},null,2),{flag:"wx",mode:384});let E=await tt(o,e);if(!bt(this.hostVersion,E.manifest.hostRange))throw new h("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let _=r.requiredCapabilities.filter(T=>!E.manifest.capabilities.includes(T));if(_.length)throw new h("incompatible_plugin",`Package lacks required capabilities: ${_.join(", ")}`);let H="sha512-"+Or("sha512").update(c).digest("base64"),N=await this.commitStaged(e,n,o,E,H,i);return p[e]={contentHash:c,version:P},await j(l,p),N}finally{await ze(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let i=me(e,this.catalog);return W(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]?.find(c=>c.version===t);if(!n)throw new h("not_installed","Plugin version is not installed");let o=await tt(this.path(n),e);if(o.digest!==n.digest)throw new h("resource_changed","Installed package integrity changed");if(!bt(this.hostVersion,o.manifest.hostRange)||!i.requiredCapabilities.every(c=>o.manifest.capabilities.includes(c)))throw new h("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){me(e,this.catalog),await W(this.root,async()=>{let i=await this.recoverLocked(),n=(i.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,i,n)})}};import{lstat as Ri,mkdir as Yp,open as Oo,realpath as Mo,readdir as Mr,link as Qp,rename as Zp,unlink as rt,copyFile as eu,rm as tu}from"node:fs/promises";import{dirname as iu,isAbsolute as jo,join as O,relative as Wo,resolve as ru,sep as jr,win32 as su}from"node:path";import{randomUUID as Wr}from"node:crypto";var Ft=192*1024*1024,Bt=512*1024,Vo=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function nu(s){if(!s||typeof s!="object"||Array.isArray(s))throw new h("invalid_input","Expected object input");return s}function $o(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new h("invalid_input","Invalid state key");return s}function Ut(s){if(s&&(!Vo(s.stateRef)||typeof s.version!="string"||!Number.isSafeInteger(s.generation)||s.generation<1||!Number.isSafeInteger(s.schema)||s.schema<1||typeof s.enabled!="boolean"||typeof s.operationId!="string"))throw new h("invalid_storage","Invalid active plugin record");return s}var st=class{root;pluginId;legacy;checkpoint;constructor(e,t,i,r){this.root=O(e,B(t)),this.pluginId=t,this.legacy=i,this.checkpoint=r}active(){return ee(O(this.root,"active.json")).then(Ut)}async recover(){return W(this.root,async()=>{let e=await this.active(),t=await ce(O(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(o=>!["version","before","next"].includes(o))||Object.hasOwn(t,"version")&&t.version!==1)throw new h("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ut(t.next),Ut(t.before);let i=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,c)=>o===null||c===null?o===c:["version","generation","stateRef","schema","enabled","operationId"].every(a=>o[a]===c[a]))(e,i==="committed"?t.next:t.before))throw new h("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let n=t.before;if(i==="committed"&&n&&n.stateRef!==e.stateRef&&await j(O(this.root,"previous.json"),n),i==="committed"){let o=await ce(O(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(c=>["version","stateRef"].includes(c))&&await rt(O(this.root,"fork.json"))}return await rt(O(this.root,"transition.json")),{active:e,recovered:i}})}async activate(e,t){return W(this.root,async()=>{let i=await this.active();if((i?.generation??0)!==e)throw new h("stale_generation","Plugin activation changed concurrently");let r=await ce(O(this.root,"fork.json"));if(r&&(r.version!==1||r.stateRef!==t.stateRef||Object.keys(r).some(o=>!["version","stateRef"].includes(o))))throw new h("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let n=Ut({...t,generation:e+1,operationId:Wr()});await Z(O(this.root,"states")),await Z(O(this.root,"states",n.stateRef)),await j(O(this.root,"transition.json"),{version:1,before:i,next:n}),await this.checkpoint?.("prepared");try{await j(O(this.root,"active.json"),n)}catch(o){if((await this.active())?.operationId!==n.operationId)throw o}await this.checkpoint?.("committed");try{i&&i.stateRef!==n.stateRef&&await j(O(this.root,"previous.json"),i),await rt(O(this.root,"transition.json")),await rt(O(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),n})}async forkState(e){return W(this.root,async()=>{let t=await this.assertGeneration(e,!1),i=Wr(),r=O(this.root,"states",i);if(await ce(O(this.root,"fork.json")))throw new h("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await j(O(this.root,"fork.json"),{version:1,stateRef:i}),await Z(r);let n=O(this.root,"states",t.stateRef);for(let o of await Mr(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await X(O(n,o),Ft))throw new h("invalid_storage","Missing state file");await eu(O(n,o),O(r,o))}return await this.checkpoint?.("forked"),i})}async collect(e){return W(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await X(O(this.root,l),2*1024*1024))throw new h("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),i=Ut(await ce(O(this.root,"previous.json")));if(!t&&await X(O(this.root,"active.json"),2*1024*1024))throw new h("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let r=[t,i].filter(l=>!!l),n=O(this.root,"states");await Z(n);let o=await Mr(n),c=new Set(r.map(l=>l.stateRef));for(let l of o){if(!Vo(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(n,l),u=await Ri(p);if(!u.isDirectory()||u.isSymbolicLink())throw new h("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let y of await Mr(p)){let m=await Ri(O(p,y));if(!/^[a-f0-9]{64}\.json$/.test(y)||!m.isFile()||m.isSymbolicLink()||m.nlink!==1)throw new h("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let f=await ee(O(p,y),Ft);if(!f)throw new h("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(f,"committed")){let w=f;if(Object.keys(w).some(k=>!["requestId","inputHash","nextHash","committed"].includes(k))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new h("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(f).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new h("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(f)}}}}for(let l of c)if(!o.includes(l))throw new h("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let a=await e(r);for(let l of o)c.has(l)||await tu(O(n,l),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let i=await this.active();if(!i||i.generation!==e||t&&!i.enabled)throw new h("stale_generation","Plugin generation is no longer active");return i}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new h("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,i,r="session"){if(r!=="session"&&r!=="workspace")throw new h("invalid_input","Invalid state scope");let n=r==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return O(this.root,"states",e.stateRef,`${B(n+":state:"+i)}.json`)}async call(e,t,i){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new h("invalid_lease","Invalid invocation lease");this.scopeKey(e);let r=nu(i);return W(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(n,e,$o(r.key),r.scope),Ft);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(n,e,$o(r.key),r.scope);if(!Number.isSafeInteger(r.expectedRevision)||r.expectedRevision<0||r.schema!==n.schema||!Object.hasOwn(r,"value"))throw new h("invalid_input","Invalid state revision or schema");if(JSON.stringify(r.value)===void 0)throw new h("invalid_input","State value must be JSON serializable");let c=JSON.stringify(r);if(Buffer.byteLength(c)>Ft)throw new h("state_too_large","Plugin state exceeds limit");let a=await ee(o,Ft);a&&this.validateState(a);let l=B(c);if(a?.requestId===e.requestId&&a.inputHash===l)return{revision:a.revision,schema:a.schema,value:a.value};if((a?.revision??0)!==r.expectedRevision)throw new h("revision_conflict","Plugin state changed concurrently");let p={revision:r.expectedRevision+1,schema:n.schema,value:r.value,requestId:e.requestId,inputHash:l};return await j(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,r.path),c=r.maxBytes===void 0?Bt:r.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>Bt)throw new h("invalid_input","Invalid workspace read limit");let a=await X(o,c);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash:B(a)}:null}case"workspace.commit":return this.commitFile(n,e,r);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new h("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new h("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,i=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||jo(t)||su.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let r=await Mo(e),n=ru(r,t),o=Wo(r,n);if(!o||o===".."||o.startsWith(`..${jr}`)||jo(o))throw new h("invalid_path","Workspace path escapes root");let c=r,a=o.split(jr);for(let p=0;p<a.length;p++){c=O(c,a[p]);let u;try{u=await Ri(c)}catch(y){if(!Ve(y))throw y;if(p<a.length-1){if(!i||Wo(r,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await Yp(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Ri(c)}}if(u&&(u.isSymbolicLink()||(p<a.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new h("invalid_path","Workspace path contains a link or non-regular file")}let l=await Mo(iu(n));if(l!==r&&!l.startsWith(r+jr))throw new h("invalid_path","Workspace directory changed");return{target:n,parent:l}}async commitFile(e,t,i){if(typeof i.text!="string"||Buffer.byteLength(i.text)>Bt||!(i.expectedHash===null||typeof i.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(i.expectedHash)))throw new h("invalid_input","Invalid file content or expected hash");let{target:r,parent:n}=await this.fileTarget(t.scope.cwd,i.path,!0),o=O(this.root,"states",e.stateRef,`${B(this.scopeKey(t)+":file:"+t.requestId+":"+String(i.path))}.json`),c=B(JSON.stringify(i)),a=B(i.text),l=await ee(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==a))throw new h("duplicate_request","Request ID was reused with different content");let p;try{p=await Oo(`${r}.lock`,"wx",384)}catch(y){throw y.code==="EEXIST"?new h("file_busy","Workspace file is locked; original file preserved"):y}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let y=await X(r,Bt),m=y?B(y):null;if(l&&m===a)return{hash:a};if(l?.committed||m!==i.expectedHash)throw new h("file_conflict","Workspace file already exists or changed externally");await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=O(n,`.plugin-${Wr()}.tmp`);let f=await Oo(u,"wx",384);try{await f.writeFile(i.text),await f.sync()}finally{await f.close()}if((await this.fileTarget(t.scope.cwd,i.path)).parent!==n)throw new h("file_conflict","Workspace directory changed during save");let k=await X(r,Bt);if((k?B(k):null)!==i.expectedHash)throw new h("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),i.expectedHash===null){try{await Qp(u,r)}catch(P){throw P.code==="EEXIST"?new h("file_conflict","Workspace file was created concurrently"):P}await rt(u),u=void 0}else await Zp(u,r),u=void 0;return await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await rt(u).catch(()=>{}),await p.close(),await rt(`${r}.lock`)}}};import{randomUUID as du}from"node:crypto";import{fork as ou}from"node:child_process";import{randomUUID as au}from"node:crypto";import{join as cu}from"node:path";import{EventEmitter as lu}from"node:events";var Fo=192*1024*1024,Lt=class s{child;pending=new Map;events=new lu;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,i,r){this.package=e,this.generation=t,this.broker=r;let n={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(n[o]=process.env[o]);this.child=ou(i,[],{env:n,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new h("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,t,i,r,n=1e4){let o=new s(e,t,i,r);try{await o.request("initialize",{entry:cu(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},n);let c=await o.request("describe",void 0,n);if(!c||!Array.isArray(c.tools)||c.tools.length>128)throw new h("invalid_tools","Invalid hosted tool catalog");let a=new Set;for(let l of c.tools){if(!l||typeof l.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(l.name)||a.has(l.name)||typeof l.label!="string"||typeof l.description!="string"||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!l.parameters||typeof l.parameters!="object"||Array.isArray(l.parameters)||l.parameters.type!=="object")throw new h("invalid_tools","Invalid or duplicate tool descriptor");a.add(l.name)}return o.tools=structuredClone(c.tools),await o.request("health",void 0,n),o}catch(c){throw await o.dispose(),c}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>Fo){this.unhealthy=!0;return}let i=e;if(i.type==="response"&&typeof i.id=="string"){let r=this.pending.get(i.id);if(!r)return;if(clearTimeout(r.timer),this.pending.delete(i.id),!r.expired){let n=i.error;i.ok===!0?r.resolve(i.value):r.reject(new h(n?.code??"plugin_failed",n?.message??"Plugin request failed",n))}this.inFlight||this.events.emit("idle")}else if(i.type==="broker-request"&&typeof i.id=="string"&&typeof i.invocationId=="string"&&typeof i.method=="string"){let r=this.pending.get(i.invocationId);try{if(!r?.invocation||r.expired)throw new h("invalid_lease","Plugin invocation lease is no longer writable");let n=await this.broker(r.invocation,i.method,i.input);this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!0,value:n})}catch(n){this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!1,error:G(n)})}}}request(e,t,i=3e4,r){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new h("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new h("worker_busy","Too many plugin requests"));let n=r?.requestId??au();if(this.pending.has(n))return Promise.reject(new h("duplicate_request","An identical request is still running"));let o={type:"request",id:n,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>Fo?Promise.reject(new h("message_too_large","Plugin request exceeds limit")):new Promise((c,a)=>{let l=setTimeout(()=>{let p=this.pending.get(n);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(n),a(new h("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},i);this.pending.set(n,{resolve:c,reject:a,timer:l,invocation:r,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(n),a(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,t,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(t=>{let i=()=>{clearTimeout(r),this.events.off("idle",i),t(!0)},r=setTimeout(()=>{this.events.off("idle",i),t(!1)},e);this.events.once("idle",i)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new h("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let t=()=>{clearTimeout(i),e()},i=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var pu={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ci=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,i=pu,r){this.broker=e,this.workerEntry=t,this.hooks=i,this.capabilities=r}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await yr(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,i)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,i):this.broker.call(e,t,i);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new h("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new h("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new h("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let i;try{if(i=(await this.broker.recover()).active,i&&i.schema!==e.manifest.dataSchemaVersion)throw new h("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(l){throw this.worker||await this.releaseOwnership?.(),l}let r=i?.generation??0,n=this.worker;n||(this.phaseValue="starting");let o=null,c=!1,a=!1;try{if(o=await Lt.start(e,r+1,this.workerEntry,this.callBroker),this.phaseValue="draining",n&&!await n.waitForIdle(t))throw new h("drain_pending","Plugin calls are still running; switch deferred without killing them");if(a=!0,await this.hooks.freeze(),n&&!await n.waitForIdle(t))throw new h("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new h("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let l=i?await this.broker.forkState(r):du(),p=await this.broker.activate(r,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});c=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await n?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw c||(this.phaseValue=n?.healthy?"active":n?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue,r=await this.broker.active(),n=async()=>{if(!(!t||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(r))throw await this.releaseOwnership?.(),this.phaseValue="failed",new h("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Lt.start(t.package,t.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(c){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),c}}};this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin work is still draining; current host retained");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint work is still draining; current host retained");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(c){try{await n(),this.phaseValue=i,await this.hooks.resume()}catch(a){throw this.phaseValue="failed",a}throw c}let o=!1;return()=>this.serialize(async()=>{o||(await n(),this.phaseValue=i,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,i;try{i=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!i){if(t)throw this.phaseValue="failed",new h("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!i.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let r=this.phaseValue;this.phaseValue="draining";let n=!1;try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin still has in-flight work; not killed");if(n=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(i.generation,{version:i.version,stateRef:i.stateRef,schema:i.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=r,n&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(r){throw this.phaseValue=i,await this.hooks.resume().catch(()=>{}),r}})}};import{readFile as Bo}from"node:fs/promises";var Di=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;pairAdmittedValue=!1;get pairAdmitted(){return this.pairAdmittedValue}constructor(e){this.options=e,this.installer=new it({root:Pe(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new _i(e.capabilities):void 0;this.scheduler=new Ai({invoke:async(i,r)=>{let n=this.closing?null:e.scheduledScope?.(i)??null;n&&await this.supervisor(i).invoke({requestId:hu(),scope:n,kind:"action",action:r.action,input:{schedule:r.id}})},onError:(i,r,n)=>e.onScheduleError?.(i,r.id,n),...e.scheduleTimers});for(let i of this.installer.catalog){let r=new st(Pe(e.root,"data"),i.id,e.legacy?.(i.id)),n=e.hooks(i.id);this.supervisors.set(i.id,new Ci(r,e.workerEntry,{validateCandidate:o=>n.validateCandidate?.(o),canSwitch:()=>n.canSwitch(),freeze:()=>n.freeze(),resume:()=>n.resume(),committed:async o=>{if(o.enabled){let c=await this.installer.load(i.id,o.version);this.packages.set(i.id,c),this.assetTokens.set(i.id,uu(24).toString("base64url"));try{this.scheduler.start(i.id,yt(c.manifest).schedules)}catch(a){this.scheduler.stop(i.id),this.errors.set(i.id,G(a))}}else this.scheduler.stop(i.id),this.packages.delete(i.id),this.assetTokens.delete(i.id);await n.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),i=this.options.devArchives?.get(e);return t?r=>this.installer.installDevDirectory(e,t,r):i?r=>this.installer.installDevArchive(e,i,r):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){me(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new h("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new h("manager_closed","Plugin manager is shutting down"));let i=()=>W(Ee(this.options.root),async()=>(await Wt(this.options.root),t())),r=(this.operations.get(e)??Promise.resolve()).then(i,i);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,G(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,i=!1){return this.options.lifecycle?this.options.lifecycle(e,t,i):t()}async policies(){let e=await ee(Pe(this.options.root,"policies","policies.json"));if(!e){if(await X(Pe(this.options.root,"policies","policies.json"),2*1024*1024))throw new h("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,i]of Object.entries(e))if(this.installer.catalog.some(r=>r.id===t)&&(!i||!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion)))throw new h("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await ee(Pe(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await W(Pe(this.options.root,"policies"),async()=>{let i=await this.diagnostics();i[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await j(Pe(this.options.root,"policies","update-checks.json"),i)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,i,r){try{let n=await this.installer.check(e,t,i,r),o=!t||Ce(n.version,t)>0;return o?this.available.set(e,n):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:n.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),n}catch(n){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:G(n).code,message:G(n).message}),n}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new h("invalid_input","Invalid plugin update policy");await W(Ee(this.options.root),async()=>{await Wt(this.options.root),await W(Pe(this.options.root,"policies"),async()=>{let i=await this.policies();i[e]={updatePolicy:"notify"},await j(Pe(this.options.root,"policies","policies.json"),i)})})}async start(){await W(Ee(this.options.root),()=>this.startLocked())}async startLocked(){await W(Pe(this.options.root,"policies"),async()=>{let r=await this.policies();await j(Pe(this.options.root,"policies","policies.json"),r)});let e=await Oe(this.options.root),t=mt(e);if(t&&e)try{if(await this.validatePairPackages(e.version,e.selections),e.version!==this.options.hostVersion||e.hostDigest!==await Ze(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Ze(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Bo(this.options.workerEntry)).equals(await Bo(Pe(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(r){let n=`Required action: restart the selected compatible host or inspect host-pair/intent.json with all owners stopped. ${G(r).message}; data retained`;for(let o of this.installer.catalog)this.errors.set(o.id,G(new h("host_pair_required",n)));await Te(this.options.root,{...e,phase:"required-action",message:n}),t=!1}await this.installer.inventory();let i=te(await this.pairSnapshot());for(let r of this.installer.catalog){let n=this.supervisor(r.id),o=await n.broker.active();if(o?.enabled)try{let c=t?e?.selections.find(p=>p.id===r.id):void 0,a=c&&te(o)===te(c.before)&&e?.fingerprint===i,l=await this.installer.load(r.id,a?c.version:o.version);if(a&&l.digest!==c.digest)throw new Error("Staged plugin digest changed");await this.lifecycle(r.id,()=>n.replace(l)),this.packages.set(r.id,l),mt(e)||await this.collectSettled(r.id)}catch(c){let a=G(c),l=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool; do not delete the pair journal.":"Choose a compatible host/plugin and inspect plugin diagnostics; do not delete the pair journal.";this.errors.set(r.id,{...a,message:`Required action: plugin startup failed (${a.code}): ${a.message}; data retained. ${l}`})}}t&&e&&(await Te(this.options.root,{...e,phase:this.errors.size?"required-action":"reconciled",message:this.errors.size?[...this.errors].map(([r,n])=>`${r}: ${n.message}`).join("; "):"Current compatible state admitted; no previous state restored"}),this.pairAdmittedValue=!this.errors.size)}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),i=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async n=>{let o=this.supervisor(n.id),c=await o.broker.active(),a=this.packages.get(n.id),l=(e.versions[n.id]??[]).map(p=>p.version).sort((p,u)=>Ce(u,p));return{id:n.id,name:n.name,description:n.description,official:!0,installed:!!l.length,installedVersions:l,version:l[0]??null,activeVersion:c?.version??null,enabled:c?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[n.id]?.updatePolicy??"notify",pinnedVersion:t[n.id]?.pinnedVersion,updateDiagnostic:i[n.id],availableVersion:this.available.get(n.id)?.version??(i[n.id]?.status==="available"?i[n.id].version??null:null),...this.errors.has(n.id)?{error:this.errors.get(n.id)}:{},...a&&o.phase==="active"?{digest:a.digest,document:a.manifest.frontend.document.slice(2),controller:a.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(n.id)}/${this.assetTokens.get(n.id)}/${a.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,i,r){return this.serialize(e,async()=>{let n=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],c=o.map(l=>l.version).sort((l,p)=>Ce(p,l))[0],a=await(async()=>{switch(t){case"check":return this.isDevPlugin(e)?{version:c??null,dev:!0}:{version:(await this.check(e,c,void 0,r)).version};case"install":{let l=this.devSource(e);if(l){let y=await l(r);return await this.recordDevSync(e,y.version),{installed:!0,version:y.version}}let p=await this.check(e,c,i,r),u=await this.installer.install(e,p,r);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:u.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:u.version}}case"enable":{let l=i??c;if(!l)throw new h("not_installed","Install the plugin first");let p=await this.installer.load(e,l),u=await this.lifecycle(e,()=>n.replace(p));return u.pending||this.packages.set(e,p),u}case"retry":{let l=n.pendingVersion,p=await this.lifecycle(e,()=>n.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!c)throw new h("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let f=await l(r),w=await n.broker.active();if(await this.recordDevSync(e,f.version),!w?.enabled)return{installed:!0,enabled:!1,version:f.version};if(w.version===f.version&&!n.pendingVersion)return{unchanged:!0,version:f.version};let k=await this.lifecycle(e,()=>n.replace(f));return k.pending||this.packages.set(e,f),k}let p=await this.check(e,c,i,r),u=await n.broker.active();if(p.version===c&&(!u?.enabled||u.version===c)&&!n.pendingVersion)return{unchanged:!0,version:c};let y=p.version===c?await this.installer.load(e,c):await this.installer.install(e,p,r);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:y.version,message:"Selected compatible release installed; activation may wait for editors"}),!u?.enabled)return{installed:!0,enabled:!1,version:y.version};let m=await this.lifecycle(e,()=>n.replace(y));return m.pending||this.packages.set(e,y),m}case"uninstall":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new h("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=G(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async i=>this.installer.collect(e,async()=>{let r=(await this.policies())[e];return[...i.map(n=>n.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...r?.pinnedVersion?[r.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Reconnect the plugin view before editing",{status:409})):r.invoke(i)}flush(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Flush generation changed",{status:409})):r.flushAction(i)}async asset(e,t,i){let r=this.packages.get(e);if(!r)return null;let n=this.assetLeases.get(e);n||(n=new Map,this.assetLeases.set(e,n)),n.set(r.version,(n.get(r.version)??0)+1);try{return await To(r,i,t)}finally{let o=n.get(r.version)-1;o?n.set(r.version,o):n.delete(r.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let i;try{i=decodeURIComponent(t[1])}catch{return null}let r=this.assetTokens.get(i),n=Buffer.from(t[2]);return!r||n.length!==Buffer.byteLength(r)||!fu(n,Buffer.from(r))?null:this.asset(i,t[3],t[4])}async reconcileHostUpgrade(){if(mt(await Oe(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),i=!0;for(let r of this.installer.catalog){let n=e.versions[r.id];if(n?.length)try{let o=await this.supervisor(r.id).broker.active(),c=o?.enabled?o.version:n.map(l=>l.version).sort((l,p)=>Ce(p,l))[0];try{await this.installer.load(r.id,c);continue}catch(l){if(G(l).code!=="incompatible_plugin")throw l}let a=await this.manage(r.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(i=!1)}catch(o){i=!1;let c=G(o);this.errors.set(r.id,c),await this.recordCheck(r.id,{status:"failed",code:c.code,message:c.message})}}return i}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}get hostPair(){return so(this.options.root,(e,t)=>this.prepareHostPair(e,t),()=>this.pairSnapshot(),(e,t)=>this.validatePairPackages(e,t))}async validatePairPackages(e,t){let i=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog});for(let r of t)if((await i.load(r.id,r.version)).digest!==r.digest)throw new h("host_pair_changed","Staged plugin digest changed; selection refused")}async prepareHostPair(e,t){let i=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),r=await this.installer.inventory(),n=await this.policies(),o=[];for(let c of this.installer.catalog){let a=r.versions[c.id];if(!a?.length)continue;let l=await this.supervisor(c.id).broker.active(),p=a.map(y=>y.version).sort((y,m)=>Ce(m,y))[0],u;try{u=await i.load(c.id,l?.enabled?l.version:p),o.push({id:c.id,version:u.version,digest:u.digest,before:l});continue}catch(y){if(G(y).code!=="incompatible_plugin")throw y}try{let y=await i.check(c.id,p,void 0,t);u=y.version===p?await i.load(c.id,p):await i.install(c.id,y,t),await this.recordCheck(c.id,{status:"up-to-date",version:u.version,message:"Compatible combination prepared for software update"}),this.errors.delete(c.id)}catch(y){let m=G(y);await this.recordCheck(c.id,{status:"failed",code:m.code,message:m.message}),this.errors.set(c.id,m);try{u=await i.load(c.id,p)}catch(f){throw new h("host_pair_required",`${m.message}; ${G(f).message}; current host/plugin and data retained`)}}o.push({id:c.id,version:u.version,digest:u.digest,before:l})}return o}async validateHostUpdate(e){let t=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),i=await this.installer.inventory(),r=await this.policies(),n=!1;for(let o of this.installer.catalog){let c=i.versions[o.id];if(!c?.length)continue;n=!0;let a=await this.supervisor(o.id).broker.active(),l=c.map(u=>u.version).sort((u,y)=>Ce(y,u))[0],p=new Set([l,...a?[a.version]:[],...r[o.id]?.pinnedVersion?[r[o.id].pinnedVersion]:[],...this.supervisor(o.id).pendingVersion?[this.supervisor(o.id).pendingVersion]:[]]);for(let u of p)try{await t.load(o.id,u)}catch(y){throw new h("host_pair_required",`Host update blocked for ${o.id}@${u}: ${G(y).message}. Prepare a compatible pair; installed code/data retained`)}}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[],t=async()=>{let i=await Promise.allSettled(e.map(n=>n()));this.closing=!1;let r=i.find(n=>n.status==="rejected");if(r?.status==="rejected")throw r.reason};try{for(let i of this.supervisors.values())e.push(await i.suspendForRestart());return t}catch(i){throw await t(),i}}};import{randomUUID as gu}from"node:crypto";var D=s=>Object.assign(new Error(s),{status:409,code:"view_barrier"}),zt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;constructor(e,t,i=2e4,r=15e3){this.pluginId=e,this.generation=t,this.pollMs=i,this.freezeMs=r}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,i){return e.scope.ownerId===i.ownerId&&e.scope.workspaceId===i.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let i=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&i&&this.barrier.pending.has(i.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&i.identity.generation===e.generation&&i.identity.mountId===e.mountId&&i.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&i.scope.ownerId===t.ownerId&&i.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let i=e.viewToken?this.views.get(e.viewToken):void 0;if(!i||i.identity.generation!==this.generation||e.generation!==i.identity.generation||e.mountId!==i.identity.mountId||e.sessionId!==i.identity.sessionId||t.ownerId!==i.scope.ownerId||t.workspaceId!==i.scope.workspaceId||t.sessionId!==i.identity.sessionId)throw D("Unknown or stale view action capability");if(this.switching&&i.kind==="controller")throw D("Controller admission paused during plugin switching");return i.initialized=!0,i.activeActions=(i.activeActions??0)+1,()=>{i.activeActions--}}enqueue(e,t,i=++this.sequence){return e.commands.push({id:i,type:t,generation:this.generation}),e.waiter?.(),i}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw D("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw D("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw D("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw D("Invalid registration capability");let o=e.viewToken??gu();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw D("View initialization was cancelled; register a new document identity");let c=this.views.get(o);if(c){if(!this.sameScope(c,e,t)||c.kind!==e.kind)throw D("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw D("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[]}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw D("Invalid view capability");let i=this.views.get(e.viewToken),r=this.recoveries.get(e.viewToken),n=this.retired.get(e.viewToken);if(n&&!this.sameScope(n,e,t))throw D("Unknown or stale view capability");if(e.operation==="reconcile"||e.operation==="recover"){if(i&&!this.sameScope(i,e,t)||r&&!this.sameScope(r,e,t))throw D("Unknown or stale view capability");if(r)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(r,"retained")};if(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!i)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||i.activeActions)return{viewToken:i.token,commands:[],recovery:this.recovery(i,"active")};if(i.kind==="controller")return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw D("Explicit recovery confirmation required");return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),this.recoveries.set(i.token,i),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retained")}}return{viewToken:i.token,commands:[],recovery:this.recovery(i,"unconfirmed")}}if(e.operation==="discard"&&r&&this.sameScope(r,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!i&&!r){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching)throw D("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!i||!this.sameScope(i,e,t))throw D("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(i.initialized||i.activeActions||this.switching)throw D("View already initialized; preserve its recovery record");this.retire(i);break;case"change":if(e.generation!==this.generation)throw D("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw D("Invalid view status");i.initialized=!0,i.dirty=e.dirty,i.busy=e.busy,(i.dirty||i.busy)&&i.frozen&&(i.frozen=!1,this.barrier?.reject(D("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw D("Invalid acknowledgement");let o=i.commands.find(c=>c.id===e.commandId);if(!o)throw D("Unknown command acknowledgement");i.commands=i.commands.filter(c=>c.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(i.frozen=!0,i.dirty=!1,i.busy=!1,this.barrier.pending.delete(i.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(D(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching||i.activeActions)throw D("View has an active barrier or action; discard refused");this.retire(i);break;case"close":if(i.activeActions)throw D("View action still in flight");if(i.kind!=="controller"&&(i.dirty||i.busy)&&!i.frozen)throw D("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(i.token))throw D("View must acknowledge freeze before closing");this.retire(i);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw D("Invalid poll cursor");if(i.waiter)throw D("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw D("Invalid poll mode");return!e.immediate&&!i.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),i.waiter=void 0,o()}i.waiter=a}),{viewToken:i.token,commands:i.commands.filter(o=>o.id>e.after)}}default:throw D("Unknown view operation")}return{viewToken:i.token,commands:[]}}freeze=async()=>{if(this.switching)throw D("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(i=>i.activeActions||i.kind!=="controller"&&!i.frozen&&(i.busy||!this.immediate&&["editor","workspace"].includes(i.kind)));throw D(`Close editors before updating; old version retained. Pending views: ${t.map(i=>`${i.kind}:${i.identity.mountId}${i.activeActions?` (action in flight x${i.activeActions})`:i.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,i)=>{let r=n=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,n?i(n):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(n=>n.token)),resolve:()=>r(),reject:n=>r(n),timer:setTimeout(()=>{let n=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));r(D(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${n.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let n of this.authoringViews())this.enqueue(n,"freeze",e);this.authoringViews().length||r()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw D("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(D("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(D("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var mu="@chengzhiyi/pi-excalidraw",wu={tools:{excalidraw_read_me:"reference",excalidraw_create_view:"view",diagram_reference:"reference",diagram_create:"create",diagram_read:"read",diagram_patch:"patch"},readonlyActions:["read","reference"],actions:["list","new","open","import","get","focus","sync","initialize","accept","reject","save"],checkpointActions:["sync","get","list"],contribution:{entry:{label:"Excalidraw",description:{zh:"\u624B\u7ED8\u56FE\u7A3F",en:"Editable drawings"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["excalidraw_create_view","diagram_create","diagram_patch"],toolViews:["excalidraw_create_view","diagram_create","diagram_patch"],panelAlias:{prefix:"diagram:",kind:"editor",title:"Excalidraw"}}},yu="@chengzhiyi/pi-github",vu={tools:{},readonlyActions:[],actions:["get","configure","pickup","sync","cancel","approve","reject","answer","remove"],checkpointActions:["get"],contribution:{entry:{label:"GitHub",description:{zh:"GitHub \u4EFB\u52A1",en:"GitHub tasks"},kind:"workspace"},panels:["workspace"],artifactTools:[],toolViews:[],panelAlias:{prefix:"github:",kind:"workspace",title:"GitHub"}}},Uo=new Map([[mu,wu],[yu,vu]]);function $r(s,e){let t=s.get(e);if(!t)throw new h("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as bu}from"node:crypto";var ku="https://github.com/settings/personal-access-tokens/new?"+new URLSearchParams({name:"pi-webapp",description:"pi-webapp GitHub plugin",issues:"write",pull_requests:"write",contents:"write"}),Pu="Ov23limJmKiuu8cOP83E";function Vr(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||Pu,scope:"repo",createUrl:ku}}var Iu="https://github.com/login/device/code",Su="https://github.com/login/oauth/access_token",Eu=8,Ni=class{flows=new Map;fetcher;now;constructor(e=(i,r)=>fetch(i,{...r,signal:r.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let i;try{i=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new h("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let r=await i.json().catch(()=>null);if(!r||typeof r!="object"||!i.ok&&!("error"in r))throw new h("oauth_failed",`GitHub sign-in failed (${i.status})`,{status:502});return r}async start(e,t,i){if(!i.clientId)throw new h("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[u,y]of this.flows)y.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=Eu)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let r=await this.post(Iu,{client_id:i.clientId,scope:i.scope}),{device_code:n,user_code:o,verification_uri:c}=r,a=Number(r.expires_in),l=Math.max(Number(r.interval)||5,1);if(typeof n!="string"||typeof o!="string"||typeof c!="string"||!c.startsWith("https://github.com/")||!Number.isFinite(a))throw new h("oauth_failed",typeof r.error_description=="string"?r.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=bu();return this.flows.set(p,{pluginId:e,name:t,clientId:i.clientId,deviceCode:n,expiresAt:this.now()+a*1e3,interval:l,nextPoll:this.now()+l*1e3}),{deviceId:p,userCode:o,verificationUri:c,interval:l,expiresIn:a}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let i=await this.post(Su,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof i.access_token=="string"&&i.access_token)return this.flows.delete(e),{status:"granted",token:i.access_token,pluginId:t.pluginId,name:t.name};switch(i.error){case"authorization_pending":return{status:"pending"};case"slow_down":return t.interval+=5,t.nextPoll=this.now()+t.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as zo,readFileSync as qo,statSync as xu}from"node:fs";import{lstat as _u,readdir as Au,writeFile as Tu,mkdir as Ru,rename as Cu}from"node:fs/promises";import{delimiter as Du,dirname as Nu,isAbsolute as Hu,join as nt,resolve as qt}from"node:path";var Lo="@chengzhiyi/pi-github",Mi={[Lo]:{id:Lo,name:"GitHub",icon:"github",description:{zh:"\u628A GitHub issue \u4EA4\u7ED9 agent\uFF1A\u5148\u51FA\u65B9\u6848\uFF0C\u7ECF\u4F60\u6279\u51C6\u540E\u5B9E\u73B0\u5E76\u63D0\u4EA4\u8349\u7A3F PR\u3002",en:"Hand GitHub issues to an agent: it plans, you approve, then it implements and opens a draft PR."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","panels","scheduler","network","secrets","sessions"]}},Go=()=>Object.keys(Mi).join(", ");function Ou(s=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(s??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=n.lastIndexOf("="),c=n.slice(0,o),a=n.slice(o+1),l=Mi[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?zo(qt(a))?null:`archive not found: ${qt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Go()})`;if(p){i.push({level:"error",source:r,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,qt(a))}return{catalog:e,archives:t,notices:i}}var Jo=s=>nt(s,"pi-web","hosted-dev.json"),Ko=s=>nt(s,"pi-web","hosted-dev-status.json");function Mu(s,e,t=process.cwd()){let i=[],r=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(Du).map(c=>c.trim()).filter(Boolean);for(let c of n)i.push({path:qt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&zo(e)){o=!0;try{let c=JSON.parse(qo(e,"utf8")),a=c&&typeof c=="object"?c.roots:void 0;if(!Array.isArray(a))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let l of a)typeof l!="string"||!Hu(l)?r.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):i.push({path:qt(l),source:e})}catch(c){r.push({level:"error",source:e,message:`cannot read dev configuration: ${c instanceof Error?c.message:String(c)}`})}}return{specs:i,notices:r,configured:o}}function ju(s){let e=(r,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${r}`}}),t;try{t=xu(s.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let i;try{i=JSON.parse(qo(nt(s.path,"package.json"),"utf8"))}catch(r){return e(r.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof i.name!="string"?e("package.json has no name"):Mi[i.name]?Ue(i.piWebapp)?{pluginId:i.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',i.name):e(`unknown plugin id "${i.name}" (known: ${Go()})`)}var Hi=class{catalog;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let t=Ou(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let i=this.refresh(!0);this.enabled||=i.configured}refresh(e=!1){let t=Mu(this.env,this.configPath,this.cwd),i=[],r=new Map,n=new Map;for(let o of t.specs){let c=ju(o);if(c.notice){i.push(c.notice);continue}let a=c.pluginId;if(r.has(a)){i.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${r.get(a)}`});continue}if(this.archives.has(a)&&i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${a}; the dev directory wins`}),!this.catalog.some(l=>l.id===a)){if(!e){i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: ${a} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}this.catalog.push(Mi[a])}r.set(a,o.path),n.set(a,o.source)}for(let o of[...this.roots.keys()])r.has(o)||this.roots.delete(o);for(let[o,c]of r)this.roots.set(o,c);this.rootSource.clear();for(let[o,c]of n)this.rootSource.set(o,c);return this.fileNotices=t.notices,this.rootNotices=i,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Oi=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${G(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,i]of e){let r=this.roots.get(t);(!r||r.root!==i)&&(r={root:i,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,r));let n=await Wu(i);if(n===null){this.set(t,r,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),r.seen=void 0;continue}if(n!==r.seen){r.seen=n;continue}n===r.applied||this.stopped||await this.apply(t,r,n)}await this.publish()}set(e,t,i,r={}){let n=t.state!==i||t.message!==r.message||t.version!==r.version;t.state=i,t.message=r.message,t.code=r.code,t.version=r.version??t.version,n&&(t.at=new Date().toISOString(),this.log(`${e}: ${i}${r.version?` ${r.version}`:""}${r.message?` \u2014 ${r.message}`:""}`))}async apply(e,t,i){this.set(e,t,"switching");try{let n=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=i,n?.installed?n.pendingVersion?this.set(e,t,"pending",{version:n.version,message:`Waiting for editors to close before switching to ${n.pendingVersion}`}):this.set(e,t,"synced",{version:n.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(r){let n=G(r);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(n.code)||(t.applied=i),n.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:n.code,message:`${n.message} (${n.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let i=this.options.statusPath;if(!i)return;let r=Object.fromEntries([...this.roots].map(([c,a])=>[c,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),n=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(c=>c.id),plugins:r,notices:e.notices});if(n===this.lastStatus)return;this.lastStatus=n;let o=`${i}.${process.pid}.tmp`;try{await Ru(Nu(i),{recursive:!0}),await Tu(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await Cu(o,i)}catch{}}};async function Wu(s){let e=[],t=async(i,r)=>{let n=await _u(i);e.push(`${r}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(nt(s,"package.json"),"package.json");let i=async(r,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await Au(r,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await i(nt(r,c.name),`${n}/${c.name}`,o+1):await t(nt(r,c.name),`${n}/${c.name}`)};if(await i(nt(s,"dist"),"dist",0),!e.some(r=>r.startsWith("dist/resources.json:")))return null}catch(i){if(i.code==="ENOENT")return null;throw i}return e.join("|")}function Fu(s){try{return[...yt(s).secrets]}catch{return[]}}var Wi=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ni;restartPreparation;restartResume;closing=!1;started=!1;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Uo,e.dev?.enabled&&(this.devWatcher=new Oi({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let i=await this.inventory();return i.plugins.find(r=>r.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):i}}})),this.adapter=new Si({policy:(t,i)=>{let r=e.policy?.(t,i);return{...r,enabled:!this.recovery.has(t)&&this.manager.tools.some(n=>n.pluginId===t)&&r?.enabled!==!1}},invoke:async(t,i,r)=>{r?.throwIfAborted(),this.scope(i.scope.sessionId,i.scope);let n=this.manager.tools.find(c=>c.pluginId===t);if(!n)throw new h("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,n.generation,i);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Di({...e,lifecycle:(t,i,r)=>this.lifecycle(t,i,r),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:i=>{if(i.length!==Object.keys($r(this.trusted,t).tools).length)throw new h("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,i),this.adapter.validateChange(t,i)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async i=>{try{let r=i.enabled?this.manager.tools.find(n=>n.pluginId===t)?.descriptors:[];if(!r)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,r),i.enabled){let n=await this.manager.installer.load(t,i.version);this.documents.set(t,{document:n.manifest.frontend.document.replace(/^\.\//,""),controller:n.manifest.frontend.controller.replace(/^\.\//,""),secrets:Fu(n.manifest)})}else this.documents.delete(t);this.adapter.change(t,r),await this.coordinator(t).committed(i),e.changed?.(),this.recovery.delete(t)}catch(r){throw this.recovery.set(t,r),await this.coordinator(t).committed(i).catch(()=>{}),r}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,i,r)=>{let n=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!n)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(i))throw new h("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return r===null?await n.delete(t,i):await n.set(t,i,r),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let i=this.options.capabilities?.secrets;if(!i)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let n=this.documents.get(t.pluginId)?.secrets.includes(t.name)?Vr(t.pluginId,t.name):void 0;if(!n)throw new h("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,n)}let r=await this.deviceFlows.poll(t.deviceId);return r.status!=="granted"?{status:r.status}:(await i.set(r.pluginId,r.name,r.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,i)=>{if(!this.options.approvals)throw new h("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,i),this.inventory()},action:(t,i)=>this.action(t,i?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new h("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let i=t,r=this.scope(i.sessionId);return i.operation==="register"&&this.generation(i.pluginId,i.generation),this.coordinator(i.pluginId).handle(i,this.viewScope(r))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let i=$r(this.trusted,e);for(let r of t)if(!Object.hasOwn(i.tools,r.name)||i.tools[r.name]!==r.action||r.readonly!==i.readonlyActions.includes(r.action))throw new h("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new h("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let i=typeof e=="string"?this.options.resolveSession(e):null;if(!i||i.sessionId!==e||!i.cwd||!i.workspaceId||t&&(i.cwd!==t.cwd||i.workspaceId!==t.workspaceId))throw new h("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...i}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let i=this.manager.tools.find(r=>r.pluginId===e);if(!i||i.generation!==t)throw new h("stale_generation","Reconnect and re-handshake hosted views",{status:409});return i}enqueue(e,t=!1){let i=this.queue.then(async()=>{if(this.closing&&!t)throw new h("manager_closed","Host is shutting down");return e()});return this.queue=i.catch(()=>{}),i}lifecycle(e,t,i=!1){let r=this.switches.then(async()=>{if(this.closing&&!i)throw new h("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let n=await t();if(n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new st(ji(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!i)throw new h("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return n}finally{if(!i)for(let n of this.views.values())n.allowImmediateReopen(!1);i||this.adapter.thaw()}});return this.switches=r.catch(()=>{}),r.catch(n=>{throw i&&this.adapter.thaw(),n})}async start(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Me)try{let t=await new st(ji(this.options.root,"data"),e.id).active();this.views.set(e.id,new zt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new zt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=ji(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&(this.manager.pairAdmitted?!(await this.manager.inventory()).plugins.some(i=>i.updateDiagnostic?.status==="failed"):await this.manager.reconcileHostUpgrade())&&(await Z(this.options.root),await j(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Me)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}async validateHostUpdate(e,t){await this.enqueue(async()=>{if(await this.manager.validateHostUpdate(e))try{await Vu(ji(t,"dist","hosted-worker.js"))}catch{throw new h("host_pair_required","Selected host has no hosted worker; keep current host/plugin pair")}})}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,i=new Map;for(let r of e.plugins){let n=r.enabled?this.documents.get(r.id)?.secrets??[]:[];t&&n.length&&i.set(r.id,await Promise.all(n.map(async o=>{let c=Vr(r.id,o);return{name:o,configured:await t.has(r.id,o),...c?{signIn:c.clientId?"browser":"token-page",...c.createUrl?{createUrl:c.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(r=>({pluginId:r.id,name:r.name,official:r.official,installed:r.installed,enabled:r.enabled,description:r.description,...i.has(r.id)?{secrets:i.get(r.id)}:{},icon:(this.options.catalog??Me).find(n=>n.id===r.id)?.icon,hasRetainedData:r.activeVersion!==null,phase:this.recovery.has(r.id)?"reconnect-required":r.phase,updatePolicy:r.updatePolicy,pinnedVersion:r.pinnedVersion,updateDiagnostic:r.updateDiagnostic,...r.enabled&&r.activeVersion?{version:r.activeVersion}:r.version?{version:r.version}:{},...r.availableVersion?{availableVersion:r.availableVersion}:{},...r.pendingVersion?{pendingVersion:r.pendingVersion}:{},...r.generation!==null?{generation:r.generation}:{},...this.recovery.has(r.id)||r.error?{error:this.recovery.get(r.id)instanceof Error?this.recovery.get(r.id).message:r.error?.message??"Recovery required",errorCode:this.recovery.has(r.id)?"reconnect_required":r.error?.code}:{},...r.enabled&&r.assetBase&&this.documents.has(r.id)&&this.trusted.has(r.id)?{documentUrl:r.assetBase+this.documents.get(r.id).document,controllerUrl:r.assetBase+this.documents.get(r.id).controller,contribution:structuredClone(this.trusted.get(r.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let i=this.downloads.get(e.pluginId);if(!i||i.id!==e.downloadId)throw new h("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return i.abort.abort(new h("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let t=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(t){if(this.downloads.has(e.pluginId))throw new h("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,t)}try{return await this.enqueue(async()=>{let i=this.coordinator(e.pluginId);i.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new h("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let r=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||r&&typeof r=="object"&&"reconnectRequired"in r&&r.reconnectRequired)throw new h("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{i.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let i=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new h("action_denied","Action is not reviewed by this host",{status:403});let r=this.coordinator(e.pluginId).admitAction(e,this.viewScope(i));try{let n={requestId:$u(),scope:i,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(i)))return await this.manager.flush(e.pluginId,e.generation,n);throw new h("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new h("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...n,kind:"action"})}finally{r()}}prepareRestart(){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let r of this.views.values())r.allowImmediateReopen(!0);let e=await this.manager.suspendForRestart(),t=!1,i=async()=>{if(!t)try{await e(),t=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(e){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}finally{for(let e of this.views.values())e.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as Bu,readdir as Uu,unlink as Lu}from"node:fs/promises";import{join as kt}from"node:path";import{randomUUID as zu}from"node:crypto";var Fr="hosted-migration.json";function Xo(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:i,sessionId:r}=t.scope,n=kt(s,B(JSON.stringify([i,r])));await Z(s),await Z(n);let o=kt(n,"scope.lock"),c;try{c=await Bu(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new h("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):a}try{await c.writeFile(JSON.stringify({pid:process.pid,operationId:zu()}));let a=await ee(kt(n,Fr));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Uu(n),p=[];for(let y of l){if(y==="scope.lock"||y==="focus.json"||y===Fr||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(y))continue;if(!/^[\w-]{1,80}\.json$/.test(y))throw new h("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new h("invalid_storage","Too many legacy checkpoints");let m=await ee(kt(n,y),3*512*1024);if(!m||m.version!==1||m.cwd!==i||m.sessionId!==r||!m.draft||y!==`${m.draft.id}.json`)throw new h("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(m.draft)}let u=await ee(kt(n,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(y=>y.id===u)))throw new h("invalid_storage","Invalid legacy focused drawing");return a||await j(kt(n,Fr),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Lu(o)}}}import{join as eh}from"node:path";import{randomUUID as qu}from"node:crypto";var Gu=6e4,$i=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:i,title:r})=>({id:e,pluginId:t,sessionId:i,title:r}))}async authorize(e,t){let i=this.entries.get(t);if(i&&i.pluginId!==e)throw new h("execute_denied","Session belongs to another plugin",{status:403});if(i?.status==="allowed")return!0;throw i?.status==="pending"?new h("approval_required","Waiting for the user to approve execution",{status:409}):i?.status==="denied"&&this.now()-i.decidedAt<Gu?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:qu(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new h("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,t){let i=[...this.entries.values()].find(r=>r.id===e&&r.status==="pending");if(!i)throw new h("unknown_approval","No such pending approval",{status:404});i.status=t?"allowed":"denied",i.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as Ju,readFile as Ku,rename as Xu,writeFile as Yu}from"node:fs/promises";import{randomUUID as Qu,createHash as Zu}from"node:crypto";import{join as Yo}from"node:path";var Vi=class{dir;queue=Promise.resolve();constructor(e){this.dir=Yo(e,"secrets")}file=e=>Yo(this.dir,`${Zu("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Ku(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Ve(t))throw new h("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let t=this.queue.then(e,e);return this.queue=t.catch(()=>{}),t}async get(e,t){return(await this.read(e))[t]??null}has(e,t){return this.get(e,t).then(i=>i!==null)}set(e,t,i){return this.mutate(e,r=>{r[t]=i})}delete(e,t){return this.mutate(e,i=>{delete i[t]})}mutate(e,t){return this.serialize(async()=>{let i=await this.read(e);t(i),await Ju(this.dir,{recursive:!0,mode:448});let r=`${this.file(e)}.${Qu()}.tmp`;await Yu(r,JSON.stringify(i),{mode:384}),await Xu(r,this.file(e))})}};function Qo(s,e){let t=i=>({seq:i.seq,type:i.type,...i.text===void 0?{}:{text:i.text}});return{async create({pluginId:i,cwd:r,title:n,prompt:o}){let c=await s.createDetached(r,i,n);try{await s.sendDetached(c,o,!1)}catch(a){throw await s.releaseDetached(c),a}return{sessionId:c}},ownerOf:i=>s.detachedOwner(i),activeCount:i=>s.detachedCount(i),async send(i,r,n){let o=s.detachedOwner(i);if(n==="execute"&&(!o||!await e(o,i)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await s.sendDetached(i,r,n==="execute")},abort:i=>s.abortDetached(i),release:i=>s.releaseDetached(i),async events(i,r){let n=s.detachedEvents(i,r);return{events:n.events.map(t),next:n.next}}}}var th="scheduler";function Zo(s){let e=new $i({describe:s.sessionTitle,changed:s.changed}),t=()=>{let r=s.sessions();if(!r)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return r},i={createDetached:(...r)=>t().createDetached(...r),detachedOwner:r=>s.sessions()?.detachedOwner(r)??null,detachedCount:r=>s.sessions()?.detachedCount(r)??0,sendDetached:(...r)=>t().sendDetached(...r),abortDetached:r=>t().abortDetached(r),releaseDetached:async r=>{e.forget(r),await t().releaseDetached(r)},detachedEvents:(...r)=>t().detachedEvents(...r)};return{approvals:e,capabilities:{secrets:new Vi(eh(s.root,"capability-secrets")),sessions:Qo(i,(r,n)=>e.authorize(r,n))},scheduledScope:()=>{let r=s.activeWorkspace();if(!r)return null;try{return s.trustedScope(r,th)}catch{return null}}}}async function ih(){for(let s of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=ni(s),t=new xe({env:s,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:Tt,buildId:Se,browser:ni({}).browser}}async function ea(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let s=new xe({monitor:!1});try{if(await s.ready,!s.enabled)throw new Error("Sentry verification transport is disabled");let e=s.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await s.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Tt,buildId:Se}}finally{await s.close()}}var Gt=St(sh(ah(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),uh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[uh]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Qe,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Qe;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function Fi(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var hh=null;function fh(){return hh??=ch.create({refreshOnCreate:!1})}var Bi=new Map;async function It(){let s=await fh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let i of Bi.keys())t.has(i)||(s.unregisterProvider(i),Bi.delete(i));for(let i of t){let r=e?.getRegisteredNativeProvider(i),n=e?.getRegisteredProviderConfig(i),o=r??n;!o||Bi.get(i)===o||(r?s.registerNativeProvider(r):n&&s.registerProvider(i,n),Bi.set(i,o))}return await s.refresh({allowNetwork:!1}),s}function re(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():je()}function je(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...En(d.current,d.current.sessionManager.getSessionName(),d.tuiCatalog?.ids()??[]),idle:d.current.isIdle()&&!d.tuiPrompts.sending,streaming:d.tuiStreaming,queuedPrompts:d.tuiPrompts.view(),hasPendingPrompts:d.current.hasPendingMessages?.()??!1,interactions:d.interactions?.pending(d.current.sessionManager.getSessionId())??[]}}async function Gr(s,e,t,i,r){let n=he(s);We({...je(),idle:n.isIdle()},e,r);let o=n.isIdle();o&>(()=>d.hosted?.adapter.assertAdmission(),i,(c,a)=>d.bridge?.reportError?.(c,a)),o&&(d.operation=i);try{let c=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===s)await d.replacementContext.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:r});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:r})}d.current?.sessionManager.getSessionId()===s&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:je()})}catch(c){throw o&&(d.operation=void 0),c}}function Lr(){let s=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!s||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==s||d.tuiAgentError)return!1;let i=je();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!i.paused&&!i.interactions.length};d.tuiPrompts.schedule(t,(i,r,n)=>Gr(s,i,r,n))}function ne(s){if(re().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function na(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=re(),r=d.current?je():null,n=await Ke(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=r?await Ke(r.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await qr.listAll(),a=d.workspaceSessions?.retainedSessions()??[];r&&o&&a.push({sessionId:r.sessionId,cwd:o,path:null,name:r.name,modified:r.messages.at(-1)?.timestamp??new Date().toISOString(),idle:r.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&r.idle&&d.tuiPrompts.length===0&&!r.messages.some(p=>p.role==="user")});let l=(await Promise.all(s.map(async p=>{let y=(await ht(p.path,c).catch(m=>(m instanceof Ht?p.available=!1:d.bridge?.reportError?.(m,{stage:"workspace_sessions"}),[]))).map(m=>({id:m.id,workspaceId:p.id,path:m.path,name:m.name||m.firstMessage?.slice(0,50)||"",modified:m.modified.toISOString(),idle:!0}));for(let m of a.filter(f=>f.cwd===p.path)){if(m.blank&&m.sessionId!==t.sessionId)continue;let f=y.findIndex(k=>k.id===m.sessionId),w={id:m.sessionId,workspaceId:p.id,path:m.path??y[f]?.path??null,name:m.name,modified:m.modified,idle:m.idle};f<0?y.unshift(w):y[f]=w}return p.path===n&&!y.some(m=>m.id===t.sessionId)&&y.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),y}))).flat();return{items:s,activeId:e,sessions:l}}var ia=0;async function ie(){if(!d.bridge)return;let s=++ia;try{let e=await na();s===ia&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function zr(s,e=!1){let t=d.workspaces?.get(s);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(t.path),!e&&d.current&&t.path===await Ke(d.current.cwd)&&!d.workspaceSessions?.hasWorkspace(t.path))d.selected="tui",d.activeWorkspaceId=s,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:re()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await d.workspaceSessions.reuseBlank(t.path))&&await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=s,d.bridge?.publish({type:"snapshot",session:re()})}await ie()}async function ra(s,e,t){let i=d.workspaces?.get(s);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=await Ae(i.path);if(d.workspaceSessions?.hasSession(r,e)||d.current?.sessionManager.getSessionId()===e&&await Ke(d.current.cwd)===r)return i;if(!(await ht(r)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return i}function he(s){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function le(s){d.current=s,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:re()})}function oa(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let s=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!s)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return lh.create(s,void 0,{projectTrusted:e})}async function aa(){let s=oa(),e=r=>({packages:(r.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:r.extensions??[],skills:r.skills??[]}),t=new sa({cwd:re().cwd,agentDir:we(),settingsManager:s}),i=Yn(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:i}}async function gh(s){ne(s.sessionId);let e=d.selected==="tui"?he(s.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=oa();if(s.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let i=s.value.trim(),r=s.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(s.kind==="packages"){let n=new sa({cwd:re().cwd,agentDir:we(),settingsManager:t});s.action==="add"?await n.installAndPersist(i,{local:s.scope==="project"}):await n.removeAndPersist(i,{local:s.scope==="project"})}else if(s.kind==="extensions"){let n=r.extensions??[],o=s.action==="add"?[...new Set([...n,i])]:n.filter(c=>c!==i);s.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let n=r.skills??[],o=s.action==="add"?[...new Set([...n,i])]:n.filter(c=>c!==i);s.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&le(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await aa()}function Ui(s,e=mr){if(d.hostedMode===!1||d.hostedMode===void 0&&d.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");d.hostedMode=!0;let t=(a,l)=>{let p=Br(a);return{cwd:p,sessionId:l,workspaceId:ta("sha256").update(p).digest("hex")}},i=Pt(we(),"pi-web","hosted"),r=new Hi({configPath:Jo(we())});d.hosted??=new Wi({root:i,...r.enabled?{dev:r,devStatusPath:Ko(we())}:{},...r.catalog.length?{catalog:[...Me,...r.catalog],devArchives:r.archives,devRoots:r.roots}:{},...Zo({root:i,sessions:()=>d.workspaceSessions,activeWorkspace:()=>d.workspaceSessions?.path??null,trustedScope:t,sessionTitle:a=>d.workspaceSessions?.retainedSessions().find(l=>l.sessionId===a)?.name,changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(nh(St(Gt,"../../package.json"),"utf8")).version,packageRoot:St(Gt,"../.."),workerEntry:St(Gt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${ta("sha256").update(we()).digest("hex")}`,resolveSession:a=>{let l=d.current;if(l?.sessionManager.getSessionId()===a)return t(l.cwd,a);let p=d.workspaceSessions?.hostedScope(a);return p?t(p.cwd,a):null},legacy:()=>Xo(Pt(we(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Lr),d.pi=s,d.tools?.clear(),d.tools=new ft({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(a,l)=>d.bridge?.reportError?.(a,l),breadcrumb:(a,l)=>d.bridge?.breadcrumb?.(a,l),anonymize:a=>d.telemetry?.session(a)??"unavailable"});let n=a=>({...d.operation,session:d.telemetry?.session(a.sessionManager.getSessionId()),piVersion:Ur,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new ut(s.events,a=>!!d.bridge&&a.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(a.pluginId),()=>{d.current&&d.selected==="tui"&&le(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=s.events.on(hi,()=>{d.selected==="tui"&&d.current&&le(d.current)})};o(),s.on("session_start",async(a,l)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,o(),d.current=l,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(s,t(l.cwd,l.sessionManager.getSessionId())),await d.hosted?.start(),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Ye.discover(l.cwd,l.isProjectTrusted?.()??!1);if(d.current!==l)return;d.tuiCatalog=p}d.replacementSessionId!==l.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),le(l),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(l.cwd).then(async p=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==l.sessionManager.getSessionId()||(d.activeWorkspaceId=p.id,await ie())}).catch(p=>{d.bridge?.publish({type:"error",message:p instanceof Error?p.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(p,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&l.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,c(l).catch(p=>{l.ui.notify(p instanceof Error?p.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),s.on("agent_start",(a,l)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",n(l)),le(l),ie()}),s.on("agent_end",(a,l)=>le(l)),s.on("agent_settled",(a,l)=>{d.bridge?.breadcrumb?.("agent_end",n(l)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Lr(),le(l),ie()}),s.on("tool_execution_start",(a,l)=>{d.tools?.start(a,n(l))}),s.on("tool_execution_end",(a,l)=>{d.tools?.end(a,n(l))}),s.on("model_select",(a,l)=>le(l)),s.on("thinking_level_select",(a,l)=>le(l)),s.on("message_end",(a,l)=>{if(a.message.role==="assistant"&&a.message.stopReason==="error"){d.tuiAgentError=!0;let p=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion:Ur});d.selected==="tui"&&d.bridge?.publish({type:"error",message:a.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:p,...d.operation})}a.message.role==="toolResult"&&d.tools?.message(a.message,n(l)),a.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&a.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),le(l),ie()}),s.on("session_info_changed",(a,l)=>le(l)),s.on("message_update",(a,l)=>{if(d.current=l,a.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(a.message.timestamp).toISOString(),blocks:Je(a.message.content)},d.selected!=="tui"||d.bridge===null))return;let p=Date.now();p-d.lastStreamAt<60||(d.lastStreamAt=p,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),s.on("session_shutdown",async a=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,a.reason==="new"||a.reason==="resume"||a.reason==="fork"||a.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let l=d.bridge,p=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let u=d.workspaceSessions;d.workspaceSessions=null,await u?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,l?await l.close():await p?.close()});let c=async a=>{d.telemetry??=new xe;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=s,d.tuiCatalog=await Ye.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ui(Tn(we())),await d.workspaces.load());try{await d.workspaces.discover((await qr.listAll()).map(u=>u.cwd))}catch(u){a.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${u instanceof Error?u.message:String(u)}`,"warning")}let l=await d.workspaces.add(a.cwd);if(d.selected==="tui"&&(d.activeWorkspaceId=l.id),d.bridge&&(d.bridge.protocolVersion!==7||d.bridge.buildId!==Se||typeof d.bridge.reportError!="function"||typeof d.bridge.runPluginTool!="function")){let u=d.bridge;if(d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)&&d.workspaceSessions.session&&!d.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");d.bridge=null,await u.close(),await d.telemetry.close(),d.telemetry=new xe}if(d.bridge===null){let u=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,y=u?.session&&u.path?{path:u.path,sessionManager:u.session.sessionManager}:null;u&&(await u.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new wi(f=>{d.selected==="sdk"&&d.bridge?.publish(f)},()=>d.current?.model,f=>{try{return!!d.current&&Br(d.current.cwd)===f&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,w)=>d.bridge?.reportError?.(f,w),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(f,w)=>d.bridge?.breadcrumb?.(f,w),anonymize:f=>d.telemetry?.session(f)??"unavailable"},()=>{ie()},[],{adapter:d.hosted.adapter,scope:t}),y&&await d.workspaceSessions.open(y.path,{sessionManager:y.sessionManager});let m={hosted:d.hosted?.handlers,selfUpdate:new Ii({agentDir:we(),packageRoot:St(Gt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,hostedPair:d.hosted.manager.hostPair,beforeRestart:()=>d.hosted.prepareRestart()}),snapshot:re,busyGitWorkspaces:()=>{let f=(d.workspaceSessions?.retainedSessions()??[]).filter(w=>!w.idle).map(w=>w.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{f.push(Br(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=Fi();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Fi()?.asset(f)??null,async invokePluginAction(f,w,k,P){if(ne(f),!Fi()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,_=d.tuiGeneration,H=d.workspaceSessions?.session,N={requestId:ph(),sessionId:f,pluginId:w,action:k,input:P},T=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(N):await fi(d.pi.events,N,15e3,d.tuiWaitController.signal);if(ne(f),E!==d.selected||(E==="tui"?_!==d.tuiGeneration:H!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&le(d.current),T},async resolvePluginInteraction(f,w,k,P){if(ne(f),!Fi()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(f,w,k,P):d.interactions.resolve(f,w,k,P)},image(f,w,k){ne(f);let E=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(H=>H.id===w);if(E?.type!=="message"||E.message.role!=="user"||!Array.isArray(E.message.content))return null;let _=E.message.content[k];return _?.type!=="image"?null:{data:Buffer.from(_.data,"base64"),mimeType:_.mimeType}},async workspaces(){return na()},async addWorkspace(f,w){let k=await d.workspaces.add(f,w);try{await zr(k.id,!0)}catch(P){throw await ie(),P}},async selectWorkspace(f){await zr(f)},async newSessionInWorkspace(f){await zr(f,!0)},async removeWorkspace(f){if(f===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(f),await ie()},async selectSession(f,w,k){let P=d.workspaces?.get(f);if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(P.path),w===d.current?.sessionManager.getSessionId()&&P.path===await Ke(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:re()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===w&&d.workspaceSessions.path===P.path)return;if(d.workspaceSessions?.hasSession(P.path,w))await d.workspaceSessions.open(P.path,{sessionId:w});else{if(!(await ht(P.path)).some(_=>_.id===w&&_.path===k))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(P.path,{sessionFile:k})}d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:re()})}await ie()},async renameSession(f,w,k,P){let E=P.replace(/\s+/g," ").trim();if(E.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await ra(f,w,k),d.current?.sessionManager.getSessionId()===w&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(w,E)||qr.open(k).appendSessionInfo(E),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===w&&d.bridge?.publish({type:"snapshot",session:re()}),await ie()},async deleteSession(f,w,k){let P=await ra(f,w,k);if(d.current?.sessionManager.getSessionId()===w)throw new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664");let E=await d.workspaceSessions?.discard(w)??null,_=E?.path??(k||null);_&&await Xn(_,we()),E?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(P.path,"new"),d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:re()})),await ie()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let f=d.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let w=f.scopedModels?.map(k=>`${k.model.provider}/${k.model.id}`)??[];return f.modelRegistry.getAvailable().filter(k=>w.length===0||w.includes(`${k.provider}/${k.id}`)).map(k=>({provider:k.provider,id:k.id,name:k.name}))},async providers(){let f=await It(),w=new Set((await f.listCredentials()).map(k=>k.providerId));return f.getProviders().map(k=>({id:k.id,name:k.name,configured:f.getProviderAuthStatus(k.id).configured,storedCredential:w.has(k.id),methods:[k.auth.apiKey?.login?"api_key":null,k.auth.oauth?"oauth":null].filter(P=>P!==null)}))},async providerModels(f){let w=await It();return ln(Pt(we(),"models.json"),f,w)},async updateProviderModel(f,w,k){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let P=re().model;if(k.action==="remove"&&P===`${w}/${k.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(k.action==="save"&&k.originalId&&k.originalId!==k.model.id&&P===`${w}/${k.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let E=await It();await dn(Pt(we(),"models.json"),w,k,E),await E.refresh({providers:[w],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[w],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[w],allowNetwork:!1});let _=k.action==="save"?k.model.id:k.action==="base_url"&&P?.startsWith(`${w}/`)?P.slice(w.length+1):null;if(_&&P===`${w}/${_}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(w,_)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let H=he(f),N=H.modelRegistry.find(w,_);if(!N||!d.pi||!await d.pi.setModel(N))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");le(H)}},async logoutProvider(f,w){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let k=await It();if(!(await k.listCredentials()).some(P=>P.providerId===w))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await k.logout(w),await d.current?.modelRegistry.refresh({providers:[w],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[w],allowNetwork:!1})},async loginProvider(f,w,k){let P=await It();await P.login(f,w,rn(f,w,k)),await P.refresh({providers:[f],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[f],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[f],allowNetwork:!1})},async addCustomProvider(f,w){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let k=await It();if(k.getProvider(w.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await sn(Pt(we(),"models.json"),w),await k.refresh({allowNetwork:!1}),await d.current?.modelRegistry.refresh({allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return d.selected==="tui"?(d.pi?.getCommands()??[]).filter(f=>f.name!=="web"&&f.name!=="web-dev-reload").map(f=>({name:f.name,description:f.description})):[]},async compact(f){if(ne(f),d.selected==="sdk"){let k=d.workspaceSessions?.session;if(!k||!k.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await k.compact(),d.bridge?.publish({type:"snapshot",session:re()});return}let w=he(f);if(!w.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");w.compact()},async setModel(f,w,k){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.setModel(w,k);return}let P=he(f);if(!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=P.modelRegistry.find(w,k);if(!E||!P.modelRegistry.getAvailable().some(_=>_.provider===w&&_.id===k))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(E))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");le(P)},async setThinkingLevel(f,w){if(ne(f),!["off","minimal","low","medium","high","xhigh"].includes(w))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(d.selected==="sdk"){let E=d.workspaceSessions?.session;if(!E||!E.isIdle||!E.getAvailableThinkingLevels().includes(w))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");E.setThinkingLevel(w),d.bridge?.publish({type:"snapshot",session:re()});return}let P=he(f);if(!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!P.model||!dh(P.model).includes(w))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.setThinkingLevel(w),le(P)},config:aa,updateConfig:gh,async send(f,w,k=[],P,E){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.send(w,k,P,E);return}let _=he(f);if(We(je(),w,E),E==="followUp"&&(!_.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(w,k,P),Lr();return}if(_.isIdle()&&d.tuiPrompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Gr(f,w,k,P,E)},async updateQueuedPrompt(f,w,k,P){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(w,k,P);return}if(P.kind==="steer"&&he(f).isIdle())throw new ae("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(w,k,P,(E,_,H)=>Gr(f,E,_,H,"steer"))},async abort(f){if(ne(f),d.selected==="sdk")await d.workspaceSessions.stop();else{let w=he(f);if(w.isIdle()&&!d.tuiPrompts.sending)return;if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.tools?.cancel(),d.bridge?.breadcrumb?.("cancel",{...d.operation}),d.pi.appendEntry(Dt),w.abort()}},async resume(f,w){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.resume(w);return}let k=he(f);if(gt(()=>d.hosted?.adapter.assertAdmission(),w,(P,E)=>d.bridge?.reportError?.(P,E)),!k.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!k.model||!d.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!k.modelRegistry.hasConfiguredAuth(k.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");d.operation=w;try{d.pi.sendMessage(gi(re().messages),{triggerTurn:!0})}catch(P){throw d.operation=void 0,P}},async newSession(f){if(ne(f),d.selected==="sdk"){let P=d.workspaces?.get(d.activeWorkspaceId??"");if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(P.path)||await d.workspaceSessions.open(P.path,"new"),await ie();return}let w=he(f);if(!w.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(w.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:re()}),await ie();return}if((await d.commandContext.newSession({withSession:async P=>{d.commandContext=P,d.replacementContext=P,d.replacementSessionId=P.sessionManager.getSessionId(),d.current=P}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await ie()}};m.addWorkspace=d.lifecycle.wrap(m.addWorkspace),m.selectWorkspace=d.lifecycle.wrap(m.selectWorkspace),m.newSessionInWorkspace=d.lifecycle.wrap(m.newSessionInWorkspace),m.removeWorkspace=d.lifecycle.wrap(m.removeWorkspace),m.selectSession=d.lifecycle.wrap(m.selectSession),m.renameSession=d.lifecycle.wrap(m.renameSession),m.deleteSession=d.lifecycle.wrap(m.deleteSession),m.newSession=d.lifecycle.wrap(m.newSession),m.updateConfig=d.lifecycle.wrap(m.updateConfig),d.bridge=await Sn(m,Gt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let u=[],y=null;for(let m of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(rh).filter(Boolean))try{u.push(oh(Pt(St(m),"dist"),(f,w)=>{let k=String(w??"");["client.js","client.css"].includes(k)&&(y&&clearTimeout(y),y=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(f){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${m}: ${String(f)}`})}d.stopPluginWatch=()=>{for(let m of u)m.close();y&&clearTimeout(y)}}let p=await e(d.bridge.url).catch(()=>!1);a.ui.notify(`pi-webapp: ${d.bridge.url}`,p?"info":"warning"),a.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(l){throw d.telemetry?.capture(l,{stage:"open_web",piVersion:Ur}),d.bridge||(await d.telemetry?.close(),d.telemetry=null),l}};s.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(a,l)=>c(l)}),s.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(a,l)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(a))throw new Error("Launcher stop receipt ID required");try{await d.hosted?.shutdown(),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!0})}`,"info")}catch(p){console.error("pi-webapp: plugin shutdown refused the stop request:",p),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!1})}`,"warning")}}}),s.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(a,l)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await l.waitForIdle(),await d.lifecycle.run(async()=>{let p=d.workspaceSessions?.session;p&&(await p.waitForIdle(),await d.workspaceSessions.reload()),await l.reload()}))}})}var Ck=Ui;export{Ck as default,ih as verifySentryDisabledRelease,ea as verifySentryNodeRelease};
|
|
47
48
|
|
|
48
|
-
//# debugId=
|
|
49
|
+
//# debugId=21797faa-38d4-4a0e-a037-226896d3ebe4
|