pi-webapp 0.1.52-alpha.1 → 0.1.52-alpha.2
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 +9 -9
- package/README.zh-CN.md +9 -9
- package/bin/pi-webapp.mjs +47 -2
- package/bin/upgrade-transaction.d.mts +17 -0
- package/bin/upgrade-transaction.mjs +122 -0
- package/dist/extension.js +32 -32
- package/dist/hosted-recovery.js +5 -4
- package/dist/hosted-worker.js +2 -2
- package/docs/desktop.md +1 -1
- package/docs/hosted-paired-updater.md +7 -0
- package/docs/hosted-update-recovery.md +42 -12
- package/package.json +2 -2
- package/web/dist/.vite/manifest.json +4 -4
- package/web/dist/assets/{app-DfKyBs-O.js → app-tKAlvGnx.js} +5 -5
- package/web/dist/assets/app.js +4 -4
- package/web/dist/assets/{plugin-Dxe-jeoN.js → plugin-3Ib-WXMi.js} +2 -2
- package/web/dist/assets/{plugin-PPPcE84v.js → plugin-DJaiYPEQ.js} +2 -2
- package/web/dist/assets/{plugin-D9ANR1a4.js → plugin-DObSoug1.js} +2 -2
package/dist/extension.js
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
(function(){try{var s=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="9ad1b12a-70d9-40b6-96f7-8543bf368fd1",s._sentryDebugIdIdentifier="sentry-dbid-9ad1b12a-70d9-40b6-96f7-8543bf368fd1")}catch{}})();import{delimiter as dh,dirname as ph,join as Pt,resolve as St}from"node:path";import{readFileSync as uh,realpathSync as zr,watch as hh}from"node:fs";import{fileURLToPath as fh}from"node:url";import{DefaultPackageManager as da,getAgentDir as we,ModelRuntime as gh,SessionManager as Kr,SettingsManager as mh,VERSION as qr}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as wh}from"@earendil-works/pi-ai";import{randomBytes as An,randomUUID as nr,timingSafeEqual as ul}from"node:crypto";import{readFile as hl,readdir as fl}from"node:fs/promises";import{createServer as gl}from"node:http";import{join as or}from"node:path";import{getAgentDir as ml}from"@earendil-works/pi-coding-agent";import{isAbsolute as Ua,relative as La}from"node:path";var at={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var es={id:at.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 ga}from"node:child_process";import{realpath as ma}from"node:fs/promises";import{isAbsolute as ts,relative as wa,sep as ya,win32 as va}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 z(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=ga("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 ma(s),t;try{t=(await z(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=wa(t,e).split(ya).join("/");if(i===".."||i.startsWith("../")||ts(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 Ge(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||ts(s)||va.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 Ca}from"node:crypto";import{lstat as Ki,realpath as ms}from"node:fs/promises";import{dirname as gs,isAbsolute as Da,relative as Na,resolve as _t}from"node:path";import{lstat as Aa}from"node:fs/promises";import{resolve as Ta}from"node:path";import{constants as ct}from"node:fs";import{open as ns,opendir as ba,realpath as is,stat as qi}from"node:fs/promises";import{isAbsolute as os,relative as ka,resolve as Pa,sep as Ia,win32 as Sa}from"node:path";var Ea=1e3,xa=512*1024,as=8*1024*1024,rs=1e4,_a=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 ss(s,e){let t=ka(s,e);return t!==".."&&!t.startsWith(`..${Ia}`)&&!os(t)}async function Kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||os(e)||Sa.isAbsolute(e))throw new J("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await is(s),i=Pa(t,e);if(!ss(t,i))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let r=await is(i);if(!ss(t,r))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return r}async function Gi(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 cs(s,e){return Gi(async()=>{let t=await Kt(s,e),i=[],r=!1;for await(let n of await ba(t)){if(i.length===Ea){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 qi(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")||_a.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:i,truncated:r}})}function ls(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 xt(s,e){return Gi(async()=>{let t=await Kt(s,e);if(!(await qi(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await ns(t,ct.O_RDONLY|ct.O_NONBLOCK|(ct.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=ls(o),a=c?as:xa;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>rs)return{...n,kind:"too-large",limit:rs,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 ds(s,e){return Gi(async()=>{let t=await Kt(s,e);if(!(await qi(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await ns(t,ct.O_RDONLY|ct.O_NONBLOCK|(ct.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>as)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=ls(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 Ra=1e3,ps=512*1024,us=1e4;function hs(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function lt(s){let e=await De(s);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,r=await z(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=hs(i,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!y)continue;if(n.entries.length===Ra){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:hs(i,m);k&&(w.originalPath=k),n.entries.push(w)}return n}async function fs(s,e,t){if(Ge(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await lt(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 Aa(Ta(s,e))).isFile())return{...r,kind:"unsupported"};let c=await xt(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(`
|
|
1
|
+
(function(){try{var s=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="9e20e653-5bbf-464a-a434-24bf112c8a35",s._sentryDebugIdIdentifier="sentry-dbid-9e20e653-5bbf-464a-a434-24bf112c8a35")}catch{}})();import{delimiter as xf,dirname as _f,join as wt,resolve as vt}from"node:path";import{readFileSync as Af,realpathSync as qi,watch as Tf}from"node:fs";import{fileURLToPath as Rf}from"node:url";import{DefaultPackageManager as va,getAgentDir as ge,ModelRuntime as Cf,SessionManager as Xi,SettingsManager as Nf,VERSION as Gi}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as Df}from"@earendil-works/pi-ai";import{randomBytes as _n,randomUUID as Zr,timingSafeEqual as wl}from"node:crypto";import{readFile as yl,readdir as vl}from"node:fs/promises";import{createServer as bl}from"node:http";import{join as ei}from"node:path";import{getAgentDir as kl}from"@earendil-works/pi-coding-agent";import{isAbsolute as Qa,relative as Za}from"node:path";var tt={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var ts={id:tt.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 Sa}from"node:child_process";import{realpath as Ea}from"node:fs/promises";import{isAbsolute as rs,relative as xa,sep as _a,win32 as Aa}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function B(s,e,t=2*1024*1024,r={}){let i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=Sa("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,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,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,r.write?"outcome_unknown":"git_failed"));return}n(p);return}if(r.write){let w=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",w==="outcome_unknown"?503:409,w));return}let v=l.code;v==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):v==="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}),r.input!==void 0&&a.stdin?.end(r.input)})}async function _e(s){let e=await Ea(s),t;try{t=(await B(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(i){if(i instanceof R&&i.status===404)return{kind:"not-repository"};if(i instanceof R&&i.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw i}let r=xa(t,e).split(_a).join("/");if(r===".."||r.startsWith("../")||rs(r))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function Be(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||rs(s)||Aa.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 Va}from"node:crypto";import{lstat as Br,realpath as ws}from"node:fs/promises";import{dirname as ms,isAbsolute as Fa,relative as Ua,resolve as Pt}from"node:path";import{lstat as ja}from"node:fs/promises";import{resolve as Wa}from"node:path";import{constants as rt}from"node:fs";import{open as os,opendir as Ta,realpath as is,stat as Vr}from"node:fs/promises";import{isAbsolute as as,relative as Ra,resolve as Ca,sep as Na,win32 as Da}from"node:path";var Oa=1e3,Ha=512*1024,cs=8*1024*1024,ss=1e4,Ma=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),G=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function ns(s,e){let t=Ra(s,e);return t!==".."&&!t.startsWith(`..${Na}`)&&!as(t)}async function zt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||as(e)||Da.isAbsolute(e))throw new G("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await is(s),r=Ca(t,e);if(!ns(t,r))throw new G("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let i=await is(r);if(!ns(t,i))throw new G("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return i}async function Fr(s){try{return await s()}catch(e){if(e instanceof G)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new G("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new G("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function ls(s,e){return Fr(async()=>{let t=await zt(s,e),r=[],i=!1;for await(let n of await Ta(t)){if(r.length===Oa){i=!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 Vr(await zt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}r.push({name:n.name,path:o,kind:c})}return r.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Ma.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:r,truncated:i}})}function ds(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 kt(s,e){return Fr(async()=>{let t=await zt(s,e);if(!(await Vr(t)).isFile())throw new G("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await os(t,rt.O_RDONLY|rt.O_NONBLOCK|(rt.O_NOFOLLOW??0));try{let i=await r.stat();if(!i.isFile())throw new G("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n={path:e,size:i.size},o=Buffer.alloc(16);await r.read(o,0,o.length,0);let c=ds(o),a=c?cs:Ha;if(i.size>a)return{...n,kind:"too-large",limit:a,unit:"bytes"};let l=Buffer.alloc(Math.min(i.size+1,a+1)),p=0;for(;p<l.length;){let{bytesRead:w}=await r.read(l,p,l.length-p,p);if(!w)break;p+=w}if(p>i.size)throw new G("\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(w=>w===0||w<32&&![9,10,12,13,27].includes(w)))return{...n,kind:"unsupported"};let v=1;for(let w=0;w<u.length-1;w++)if(u[w]===10&&++v>ss)return{...n,kind:"too-large",limit:ss,unit:"lines"};try{return{...n,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(u)}}catch{return{...n,kind:"unsupported"}}}finally{await r.close()}})}async function ps(s,e){return Fr(async()=>{let t=await zt(s,e);if(!(await Vr(t)).isFile())throw new G("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await os(t,rt.O_RDONLY|rt.O_NONBLOCK|(rt.O_NOFOLLOW??0));try{let i=await r.stat();if(!i.isFile())throw new G("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(i.size>cs)throw new G("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(i.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await r.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>i.size)throw new G("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=ds(c);if(!a)throw new G("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:c}}finally{await r.close()}})}var $a=1e3,us=512*1024,fs=1e4;function hs(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function it(s){let e=await _e(s);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,i=await B(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={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 c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let I=a.slice(13);n.head=I==="(initial)"?null:I;continue}if(a.startsWith("# branch.head ")){let I=a.slice(14);n.branch=I==="(detached)"?null:I;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let I=a.match(/\+(\d+) -(\d+)/);I&&(n.ahead=Number(I[1]),n.behind=Number(I[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 I=0;I<p;I++)u=a.indexOf(" ",u)+1;let v=hs(r,a.slice(u)),w=l==="2"?o[++c]:void 0;if(!v)continue;if(n.entries.length===$a){n.truncated=!0;continue}let h=a.slice(0,u).split(" "),m={path:v,index:l==="?"?"?":h[1][0],worktree:l==="?"?"?":h[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&h[2]!=="N..."},k=w===void 0?void 0:hs(r,w);k&&(m.originalPath=k),n.entries.push(m)}return n}async function gs(s,e,t){if(Be(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await it(s);if(r.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i={path:e,area:t},n=r.entries.find(c=>c.path===e);if(!n)return{...i,kind:"empty"};if(n.conflict)return{...i,kind:"conflict"};if(n.submodule)return{...i,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...i,kind:"empty"};if(!(await ja(Wa(s,e))).isFile())return{...i,kind:"unsupported"};let c=await kt(s,e);if(c.kind==="too-large")return{...i,kind:"too-large"};if(c.kind!=="text")return{...i,kind:"binary"};if(!c.text)return{...i,kind:"empty"};let a=c.text.split(`
|
|
2
2
|
`),l=a.at(-1)==="";l&&a.pop();let p=`--- /dev/null
|
|
3
3
|
+++ b/${e.replace(/[\r\n]/g," ")}
|
|
4
4
|
@@ -0,0 +1,${a.length} @@
|
|
5
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[a,l,p,u,
|
|
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
|
|
13
|
-
`).slice(1,31).map(n=>{let o=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${
|
|
14
|
-
${
|
|
15
|
-
`)}`}else
|
|
8
|
+
`}`;return Buffer.byteLength(p)>us||a.length>fs?{...i,kind:"too-large"}:{...i,kind:"text",patch:p}}if(n.untracked||(t==="staged"?n.index:n.worktree)===".")return{...i,kind:"empty"};let o=t==="staged"&&n.originalPath?[e,n.originalPath]:[e];try{let c=await B(s,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],us);return c?c.split(`
|
|
9
|
+
`).length>fs?{...i,kind:"too-large"}:/^Binary files /m.test(c)?{...i,kind:"binary"}:{...i,kind:"text",patch:c}:{...i,kind:"empty"}}catch(c){if(c instanceof R&&c.status===413)return{...i,kind:"too-large"};throw c}}var Ur=new Set,L=(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 Ba(s){return ws(Pt(s,(await B(s,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Lr(s,e,t=!1){let r=null;try{let i=await _e(s);i.kind==="repository"&&(r=await Ba(i.cwd))}catch(i){if(!t)throw i}if(!r)return e();if(Ur.has(r))return L("busy");Ur.add(r);try{return await e()}finally{Ur.delete(r)}}async function qt(s){let e=await _e(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 r=await it(e.root);if(r.kind!=="repository")return t;let[i,n,o]=await Promise.all([B(e.cwd,["ls-files","--stage","-z"]),B(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),B(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 w=>{try{return await Br(Pt(o.replace(/\n$/,""),w)),w}catch(h){if(h.code==="ENOENT")return null;throw h}}))).filter(Boolean),l=await Promise.all(r.entries.map(async w=>{try{let h=await Br(Pt(e.root,w.path));return[w.path,h.size,h.mtimeMs,h.ctimeMs,h.ino,h.mode]}catch(h){if(["ENOENT","ENOTDIR"].includes(h.code??""))return[w.path,"missing"];throw h}})),p=n.split(`
|
|
10
|
+
`).filter(Boolean).map(w=>{let[h,,m]=w.split("\0");return{name:h,current:h===r.branch,occupied:!!m&&h!==r.branch}}),u=r.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||r.entries.some(w=>w.conflict)?"operation_in_progress":null,v=Va("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:i,refs:n,entries:r.entries,files:l,present:a})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:v,staged:r.entries.filter(w=>!w.untracked&&w.index!==".").length,dirty:r.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function La(s,e){Be(e);let t=ms(Pt(s.cwd,e));for(;;)try{let n=await ws(t),o=Ua(s.cwd,n);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||Fa(o))return L("invalid_path",403);break}catch(n){if(n.code!=="ENOENT")throw n;t=ms(t)}let r=await it(s.cwd),i=r.kind==="repository"?r.entries.find(n=>n.path===e):void 0;if(!i||i.submodule||i.conflict)return L("invalid_path",400);try{let n=await Br(Pt(s.cwd,e));if(!n.isFile()&&!n.isSymbolicLink())return L("invalid_path",400)}catch(n){if(n.code!=="ENOENT")throw n}return i}async function ys(s,e,t){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new R("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Lr(s,async()=>{let i=await _e(s);if(i.kind!=="repository")return L("invalid_path",404);t(i.root);let n=await qt(i.cwd);if(n.version!==e.expected)return L("state_changed");if(n.blocked)return L(n.blocked);let o,c;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return L("invalid_path",400);let p=await La(i,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return L("state_changed");let u=[e.path];r==="unstage"&&p.originalPath&&(Be(p.originalPath),u.push(p.originalPath)),o=r==="stage"?["add","--",...u]:n.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(r==="commit"){if(i.scope)return L("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return L("invalid_message",400);if(!n.staged)return L("nothing_staged",400);c=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!n.head)return L("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 L("invalid_branch",400);try{await B(i.cwd,["check-ref-format","--branch",e.branch])}catch{return L("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return L("invalid_branch",400);let p=n.branches.find(v=>v.name===e.branch),u=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return L("branch_exists");if(r==="switch-branch"&&(!p||p.current))return L("invalid_branch",400);if(u&&i.scope)return L("root_required",400);if(u&&n.dirty)return L("dirty_worktree");if(p?.occupied)return L("branch_in_use");o=r==="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 qt(i.cwd);if(a.version!==e.expected||a.blocked)return L(a.blocked??"state_changed");t(i.root),await B(i.cwd,o,2*1024*1024,{write:!0,input:c});let l=(await B(i.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:l}})}import{createHash as za}from"node:crypto";var It=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,vs="%H%x00%P%x00%an%x00%aI%x00%s",bs=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function ks(s){let[e,t,r]=await Promise.all([B(s,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),B(s,["rev-parse","--verify","--quiet","HEAD"]).then(c=>c.trim(),()=>null),B(s,["symbolic-ref","-q","HEAD"]).then(c=>c.trim(),()=>null)]),i=[];for(let c of e.split(`
|
|
11
|
+
`).filter(Boolean)){let[a,l,p,u,v]=c.split("\0"),w=l==="commit"?p:u==="commit"?v:void 0;if(!w||!It.test(w))continue;let h=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";i.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:w,kind:h})}if(i.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([...i.map(c=>c.hash),...t&&It.test(t)?[t]:[]])].sort(),o=za("sha256").update(JSON.stringify({refs:i,head:t,symbolic:r})).digest("hex");return{refs:i,tips:n,head:t,snapshot:o}}function Ps(s){let[e,t,r,i,n]=s;if(!e||!It.test(e)||!t?.split(" ").filter(Boolean).every(o=>It.test(o)))throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:r,authoredAt:i,subject:n}}async function Is(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 r=await _e(s),i={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return i;let n=await ks(r.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={...i,root:r.root,scope:r.scope,head:n.head,snapshot:n.snapshot,refs:n.refs};if(!n.tips.length)return c;let l=(await B(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${vs}`,`--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(Ps(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 Ss(s,e){if(typeof e!="string"||!It.test(e))throw new R("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await _e(s);if(t.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await ks(t.cwd);if(!r.tips.length)throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await B(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await B(t.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function Es(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 xs(s,e,t){let i=(await B(s.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${vs}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(i.at(-1)===""&&i.pop(),i.length!==10)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let n=Ps(i.slice(0,5)),o=Es(e,n.parents,t),c=["diff-tree","--root","-r","--no-commit-id",...bs],[a,l]=await Promise.all([B(s.cwd,[...c,"--name-status","-z",...o,"--","."]),B(s.cwd,[...c,"--numstat","-z",...o,"--","."])]),p=new Map;for(let w of l.split("\0").filter(Boolean)){let h=w.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);h&&p.set(h[3],[h[1]==="-"?null:Number(h[1]),h[2]==="-"?null:Number(h[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 v=[];for(let w=0;w<u.length&&v.length<1e3;w+=2){let h=u[w+1],[m,k]=p.get(h)??[null,null];v.push({path:h,status:u[w],additions:m,deletions:k})}return{...n,email:i[5],committer:i[6],committerEmail:i[7],committedAt:i[8],message:i[9],root:s.root,scope:s.scope,parentIndex:t,files:v,truncated:u.length>2e3}}async function _s(s,e,t=0){return xs(await Ss(s,e),e,t)}async function As(s,e,t,r=0){Be(t);let i=await Ss(s,e),n=await xs(i,e,r),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:r,parentHash:n.parents[r]??null};if(o.additions===null)return{...c,kind:"binary"};try{let a=await B(i.cwd,["diff-tree","--root","-r","--no-commit-id",...bs,"--src-prefix=a/","--dst-prefix=b/","-p",...Es(e,n.parents,r),"--",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 Ts=["/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 Rs(s,e,t){if(s.endsWith("/control"))return qt(e);if(s.endsWith("/status"))return it(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 Is(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 gs(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 r=t.parentIndex;if(s.endsWith("/commit-detail"))return _s(e,t.hash,r);if(s.endsWith("/commit-diff")&&typeof t.path=="string")return As(e,t.hash,t.path,r);throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Jt=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),qa=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Cs={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},Ga=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"]),Ja=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 Ns(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 pe(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 ke(s){let e={};for(let t of Ga){let r=s[t];t==="toolName"?typeof r=="string"&&(Jt.has(r)||r==="custom")&&(e[t]=r):t==="failureKind"?qa.has(r)&&(e[t]=r):t==="level"?(r==="warning"||r==="error")&&(e[t]=r):t==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[t]=r):t==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[t]=r):t==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[t]=r):t==="route"&&typeof r=="string"?e[t]=Ja.has(r.split("?")[0])?r.split("?")[0]:"[route]":t==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[t]=r.split("/").map(pe).join("/"):typeof r=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(r)?r:pe(r).slice(0,t==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[t]=r)}return e}function zr(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 st(s,e=0){let t=s instanceof Error?s:new Error(typeof s=="string"?s:"Non-Error rejection"),r=new Error(pe(t.message));if(r.name=pe(t.name).slice(0,100),t.stack){let i=t.stack.split(`
|
|
13
|
+
`).slice(1,31).map(n=>{let o=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${pe(n.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:pe(n)});r.stack=`${r.name}: ${r.message}
|
|
14
|
+
${i.join(`
|
|
15
|
+
`)}`}else r.stack=void 0;return e<3&&t.cause!==void 0&&(r.cause=st(t.cause,e+1)),r}function Ae(s,e){let t=new Error(e);return s instanceof Error&&(t.name=s.name,s.stack&&(t.stack=`${t.name}: ${e}
|
|
16
16
|
${s.stack.split(`
|
|
17
17
|
`).slice(1).join(`
|
|
18
|
-
`)}`)),t}function
|
|
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
|
|
20
|
-
`).map(
|
|
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
|
|
22
|
-
`);let l=new s(this.file);if(await l.load(),l.revision()!==
|
|
23
|
-
`,{mode:384}),r(),await nc(n,this.file),this.disabled=a}finally{this.changing=!1;try{await Ks(n,{force:!0})}finally{c&&(await c.close(),await Ks(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 Z("\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 Z("\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 Z("\u7ED8\u56FE\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new Z("\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 Z("\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 Z)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":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as cc,opendir as lc,stat as dc}from"node:fs/promises";import{homedir as pc}from"node:os";import{basename as uc,dirname as Xs,join as Ys,posix as hc,resolve as Qs,win32 as fc}from"node:path";function Zs(s){return process.platform==="win32"?fc.isAbsolute(s)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(s):hc.isAbsolute(s)}function gc(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 en(s){if(s!==void 0&&!Zs(s))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=pc(),t=Qs(s??e),i=[];for(let a=t;;a=Xs(a)){let l=Xs(a);if(i.unshift({name:l===a?a:uc(a),path:a,hidden:!1}),l===a)break}let r=[],n=!1,o=await lc(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||gc(r,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(n=!0);let c=[];for(let a of r){let l=Ys(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await dc(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 tn(s,e){if(!Zs(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=Ys(Qs(s),e);return await cc(t),t}import{execFile as mc}from"node:child_process";import{accessSync as wc,constants as yc}from"node:fs";import{delimiter as vc,join as bc}from"node:path";var kc=(s,e,t)=>new Promise((i,r)=>{mc(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 Pc(s){for(let e of(s??"").split(vc))if(e)for(let t of["zenity","kdialog"])try{return wc(bc(e,t),yc.X_OK),!0}catch{}return!1}function rn(s=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":s==="darwin"||s==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&Pc(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 Ic(s){return typeof s=="object"&&s!==null&&"stderr"in s&&typeof s.stderr=="string"?s.stderr:""}function tr(s){return s.replace(/[\r\n]+$/,"")||null}async function sn(s,e=process.platform,t=kc){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 tr(i.stdout)}catch(i){if(!s.aborted&&ii(i)===1&&/(?:User canceled|-128)/i.test(Ic(i)))return null;throw i}if(e==="linux"){try{return tr((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 tr((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 Sc,randomUUID as Ec}from"node:crypto";import{mkdir as xc,readFile as _c,writeFile as Ac}from"node:fs/promises";import{join as nn}from"node:path";import{getAgentDir as Tc}from"@earendil-works/pi-coding-agent";var ri=20*1024*1024,on=20,Rc=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function Cc(s){let e=s.indexOf("."),t=(e<0?s:s.slice(0,e)).replace(/[. ]+$/u,"");return Rc.test(t)}function Dc(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 Nc(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 Cc(t)&&(t=`_${t}`),t=Dc(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function Hc(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 an(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=Nc(e),n=Sc("sha256").update(i).digest("hex"),o=nn(Tc(),"pi-web","attachments",n);await xc(o,{recursive:!0});let c=nn(o,r);try{await Ac(c,i,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:Ec(),name:r,bytes:i.byteLength,path:c,mediaType:Hc(i)??t.replace(/^image\//,"application/"),sessionId:s}}async function cn(s){return{type:"image",data:(await _c(s.path)).toString("base64"),mimeType:s.mediaType}}import{randomBytes as Oc}from"node:crypto";function ln(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=Oc(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}
|
|
18
|
+
`)}`)),t}function Ka(s){return{...s.filename?{filename:zr(s.filename)}:{},...s.abs_path?{abs_path:zr(s.abs_path)}:{},...s.function?{function:pe(s.function)}:{},lineno:s.lineno,colno:s.colno,in_app:s.in_app}}function Xa(s){let e=ke(s.contexts?.diagnostic??{}),t=Ds(e);return{event_id:s.event_id,timestamp:s.timestamp,platform:s.platform,level:s.level,release:s.release,dist:s.dist,environment:pe(s.environment??"production"),...s.message?{message:pe(s.message)}:{},exception:s.exception?{values:s.exception.values?.slice(0,4).map(r=>({type:pe(r.type??"Error"),value:pe(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(Ka)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.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(r=>({timestamp:r.timestamp,category:pe(r.category??"app"),data:ke(r.data??{})})),debug_meta:s.debug_meta?{images:s.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:zr(r.code_file)}:{}}))}:void 0}}function Ds(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 Os(s,e){return e.attachments=[],Xa(s)}var St=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let r={timestamp:Date.now()/1e3,category:pe(e),data:ke(t)},i=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:i}),this.bytes+=i;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},qr=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 r=this.seen.get(e);if(r&&t-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:r?.repeats??0}}},Ya=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 Le(s){return s instanceof Error&&(s.name==="AbortError"||Ya.has(s.message))}var Gt=class{budget=new qr;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,r,i,n=new St){this.client=e,this.side=t,this.buildId=r,this.scopeClass=i.Scope,this.breadcrumbs=n,e.addIntegration(i.linkedErrorsIntegration({limit:4}))}setState(e){this.state=ke(e)}capture(e,t={},r){try{if(Le(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let i=st(e),n=ke({...this.state,...t}),o=Ds(n),c=o?JSON.stringify(o):`${i.name}:${i.message}:${i.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(i,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function Hs(s,e){return s({...e,bufferSize:20},async({body:t})=>{let r=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:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var Ms={metadata:ts,routes:Ts,coordinateStart:(s,e)=>Lr(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:r,json:i}){let n=t();if(e.sessionId!==n.sessionId){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||r().some(u=>{let v=(w,h)=>{let m=Za(w,h);return m!==".."&&!m.startsWith("../")&&!m.startsWith("..\\")&&!Qa(m)};return v(p,u)||v(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 ys(n.cwd,e,c):await Rs(s,n.cwd,e);if(!a){let p=t();if(p.sessionId!==n.sessionId||p.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(s.endsWith("/control")){let u=l;u.root&&o(u.root)&&(u.blocked??="agent_busy")}}i(200,l)}catch(o){if(o instanceof R||o instanceof G)i(o.status,{error:o.message,errorCode:"validation_error",...o instanceof R?{reason:o.reason}:{}});else throw Ae(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var js={id:tt.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 Ws={metadata:js,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw"],async handle({path:s,body:e,snapshot:t,json:r,res:i}){let n=t();if(e.sessionId!==n.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(typeof e.path!="string"||e.path.length>4096){r(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}try{if(s.endsWith("/raw")){let a=await ps(n.cwd,e.path),l=t();if(l.sessionId!==n.sessionId||l.cwd!==n.cwd){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}i.writeHead(200,{"Content-Type":a.mimeType,"Content-Length":a.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),i.end(a.bytes);return}let o=s.endsWith("/list")?await ls(n.cwd,e.path):await kt(n.cwd,e.path),c=t();if(c.sessionId!==n.sessionId||c.cwd!==n.cwd){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,o)}catch(o){if(o instanceof G)r(o.status,{error:o.message,errorCode:"validation_error"});else throw Ae(o,"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var $s={id:tt.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 Us,constants as Gr,statSync as Bs}from"node:fs";import{createRequire as cc}from"node:module";import{execFile as Ls}from"node:child_process";import{accessSync as ec,chmodSync as tc,constants as rc,statSync as ic}from"node:fs";import{createRequire as sc}from"node:module";import{dirname as nc,join as oc}from"node:path";var Vs=sc(import.meta.url);function ac(s){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=oc(s,e,"spawn-helper"),r;try{r=ic(t).mode}catch(i){if(i.code==="ENOENT")continue;throw i}try{ec(t,rc.X_OK)}catch{tc(t,r|73)}}}function Fs(...s){return ac(nc(Vs.resolve("node-pty/package.json"))),Vs("node-pty").spawn(...s)}var Te=class extends Error{reason;constructor(e,t,r){super(t,{cause:r}),this.reason=e}},zs=cc(import.meta.url),Jr=class{pid;pty;screen;serializer;followers=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,r,i,n,o,c,a){this.sessionId=e,this.abandoned=c,this.graceMs=a;let{Terminal:l}=zs("@xterm/headless"),{SerializeAddon:p}=zs("@xterm/addon-serialize");this.screen=new l({cols:r,rows:i,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([v,w])=>w!==void 0&&!/^PI_WEBAPP_RESTART_/.test(v)));try{this.pty=Fs(n,o,{name:"xterm-256color",cwd:t,cols:r,rows:i,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(v){throw this.screen.dispose(),new Te("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",v)}this.pid=this.pty.pid,this.screen.onData(v=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(v)}),this.pty.onData(v=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(w=>{if(this.disposed){w();return}this.screen.write(v,()=>{this.broadcast({type:"output",data:v}),w()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(v=>this.pty.onExit(({exitCode:w,signal:h})=>{this.exit={type:"exit",exitCode:w,signal:h},this.pending.then(()=>{this.broadcast(this.exit),v()})})),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=>Ls("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(i=>Ls("ps",["-axo","pid=,ppid="],(n,o)=>i(n?"":o)))).trim().split(`
|
|
20
|
+
`).map(i=>i.trim().split(/\s+/).map(Number)),r=i=>t.filter(([,n])=>n===i).flatMap(([n])=>[...r(n),n]);for(let i of[...r(this.pid),this.pid])try{process.kill(i,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending,this.followers.clear(),this.screen.dispose()}},Kt=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,r,i,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 Te("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(Us(o,Gr.X_OK),!Bs(o).isFile())throw new Error("Not a shell file")}catch(l){throw new Te("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(!Bs(r).isDirectory())throw new Error("Not a directory");Us(r,Gr.R_OK|Gr.X_OK)}catch(l){throw new Te("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 Jr(t,r,i,n,o,c,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,a),a}get(e,t){let r=this.terminals.get(e);if(!r||r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}async remove(e,t){let r=this.terminals.get(e);if(r){if(r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&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 qs=(s,e)=>Number.isInteger(s)&&Number.isInteger(e)&&Number(s)>=2&&Number(s)<=500&&Number(e)>=1&&Number(e)<=300;async function Gs(s,e,t,r,i,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=r();if(c!=="close"&&e.sessionId!==a.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((c==="create"||c==="resize")&&!qs(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"){i.create(e.id,e.sessionId,a.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(c==="close"){await i.remove(e.id,e.sessionId),o(200,{closed:!0});return}let l=i.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(v=>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(v)}
|
|
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 Te?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 Te?l.reason:c==="create"?"terminal_runtime_unavailable":void 0})}}function Js(){let s=new Kt,e=new Set,t=async()=>{for(let r of e)r.end();e.clear(),await s.clear()};return{metadata:$s,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),handle:r=>Gs(r.path,r.body,r.res,r.snapshot,s,e),restartBlocker:()=>s.size?`\u6709 ${s.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:t,disable:t,async close(){await t(),await s.close()}}}function Ks(){return[Ws,Js(),Ms]}import{createHash as lc,randomUUID as dc}from"node:crypto";import{mkdir as pc,open as uc,readFile as fc,rename as hc,rm as Xs,writeFile as gc}from"node:fs/promises";import{dirname as mc}from"node:path";var Q=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},Xt=class s{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await fc(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 lc("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,r,i){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}.${dc()}.tmp`,o=`${this.file}.lock`,c;try{if(r!==this.revision())throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");i();let a=new Set(this.disabled);t?a.delete(e):a.add(e),await pc(mc(this.file),{recursive:!0});try{c=await uc(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()!==r)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 gc(n,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
|
|
23
|
+
`,{mode:384}),i(),await hc(n,this.file),this.disabled=a}finally{this.changing=!1;try{await Xs(n,{force:!0})}finally{c&&(await c.close(),await Xs(o,{force:!0}))}}}};var Yt=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(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,r,i),t||await this.plugins.find(n=>n.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,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,r,i,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 r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let i=t;for(let n of this.plugins)if(n.coordinateStart&&this.preferences.enabled(n.metadata.id)){let o=i;i=()=>n.coordinateStart(e,o)}try{return await i()}finally{this.running.set(r,this.running.get(r)-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 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":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as wc,opendir as yc,stat as vc}from"node:fs/promises";import{homedir as bc}from"node:os";import{basename as kc,dirname as Ys,join as Qs,posix as Pc,resolve as Zs,win32 as Ic}from"node:path";function en(s){return process.platform==="win32"?Ic.isAbsolute(s)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(s):Pc.isAbsolute(s)}function Sc(s,e,t){if(s.length===t&&e.name.localeCompare(s[s.length-1].name)>=0)return!0;let r=0,i=s.length;for(;r<i;){let n=r+i>>>1;e.name.localeCompare(s[n].name)<0?i=n:r=n+1}return s.splice(r,0,e),s.length<=t?!1:(s.pop(),!0)}async function tn(s){if(s!==void 0&&!en(s))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=bc(),t=Zs(s??e),r=[];for(let a=t;;a=Ys(a)){let l=Ys(a);if(r.unshift({name:l===a?a:kc(a),path:a,hidden:!1}),l===a)break}let i=[],n=!1,o=await yc(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||Sc(i,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(n=!0);let c=[];for(let a of i){let l=Qs(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await vc(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:r,entries:c,truncated:n}}async function rn(s,e){if(!en(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=Qs(Zs(s),e);return await wc(t),t}import{execFile as Ec}from"node:child_process";import{accessSync as xc,constants as _c}from"node:fs";import{delimiter as Ac,join as Tc}from"node:path";var Rc=(s,e,t)=>new Promise((r,i)=>{Ec(s,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(n,o,c)=>{n?i(Object.assign(new Error(n.message,{cause:n}),{code:n.code,stdout:o,stderr:c})):r({stdout:o,stderr:c})})});function Cc(s){for(let e of(s??"").split(Ac))if(e)for(let t of["zenity","kdialog"])try{return xc(Tc(e,t),_c.X_OK),!0}catch{}return!1}function sn(s=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":s==="darwin"||s==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&Cc(e.PATH)?"native":"browse"}function Qt(s){if(!(typeof s!="object"||s===null||!("code"in s)))return typeof s.code=="string"||typeof s.code=="number"?s.code:void 0}function Nc(s){return typeof s=="object"&&s!==null&&"stderr"in s&&typeof s.stderr=="string"?s.stderr:""}function Kr(s){return s.replace(/[\r\n]+$/,"")||null}async function nn(s,e=process.platform,t=Rc){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"],s);return Kr(r.stdout)}catch(r){if(!s.aborted&&Qt(r)===1&&/(?:User canceled|-128)/i.test(Nc(r)))return null;throw r}if(e==="linux"){try{return Kr((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],s)).stdout)}catch(r){if(s.aborted)throw r;if(Qt(r)===1)return null;if(Qt(r)!=="ENOENT")throw r}try{return Kr((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],s)).stdout)}catch(r){if(s.aborted)throw r;if(Qt(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 Dc,randomUUID as Oc}from"node:crypto";import{mkdir as Hc,readFile as Mc,writeFile as jc}from"node:fs/promises";import{join as on}from"node:path";import{getAgentDir as Wc}from"@earendil-works/pi-coding-agent";var Zt=20*1024*1024,an=20,$c=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function Vc(s){let e=s.indexOf("."),t=(e<0?s:s.slice(0,e)).replace(/[. ]+$/u,"");return $c.test(t)}function Fc(s,e){let t=0,r="";for(let i of Buffer.from(s).toString("utf8")){let n=Buffer.byteLength(i);if(t+n>e)break;r+=i,t+=n}return r}function Uc(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 Vc(t)&&(t=`_${t}`),t=Fc(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function Bc(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 cn(s,e,t,r){if(r.byteLength===0||r.byteLength>Zt)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let i=Uc(e),n=Dc("sha256").update(r).digest("hex"),o=on(Wc(),"pi-web","attachments",n);await Hc(o,{recursive:!0});let c=on(o,i);try{await jc(c,r,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:Oc(),name:i,bytes:r.byteLength,path:c,mediaType:Bc(r)??t.replace(/^image\//,"application/"),sessionId:s}}async function ln(s){return{type:"image",data:(await Mc(s.path)).toString("base64"),mimeType:s.mediaType}}import{randomBytes as Lc}from"node:crypto";function dn(s,e,t){return s!=="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 er=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,r,i,n){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 c=Lc(18).toString("base64url"),a={view:{id:c,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(c,a),r(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"&&i!==void 0){let p=i;return i=void 0,Promise.resolve(p)}return new Promise((p,u)=>{let{signal:v,...w}=l;a.answer=p,a.reject=u,a.view={...a.view,status:"waiting",prompt:w},v?.aborted?u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):v?.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 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
|
|
27
|
-
`,{mode:n,flag:"wx"}),await
|
|
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 r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(n=>n.id===t))return!1;let i=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},i(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 zc}from"node:crypto";import{readFile as qc,rename as Gc,rm as Jc,stat as Kc,writeFile as Xc,mkdir as Yc}from"node:fs/promises";import{dirname as Qc}from"node:path";var Zc=["openai-completions","openai-responses","anthropic-messages"];function Xr(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||!Zc.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 pn(s,e){if(!Xr(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 qc(s,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let r;if(t===void 0)r={providers:{}};else{try{r=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(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let i={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await Yc(Qc(s),{recursive:!0});let n=t===void 0?384:(await Kc(s)).mode&511,o=`${s}.pi-web-${zc(6).toString("hex")}.tmp`;try{await Xc(o,`${JSON.stringify(i,null,2)}
|
|
27
|
+
`,{mode:n,flag:"wx"}),await Gc(o,s)}finally{await Jc(o,{force:!0})}}import{randomBytes as el}from"node:crypto";import{mkdir as tl,readFile as rl,rename as il,rm as sl,stat as nl,writeFile as ol}from"node:fs/promises";import{dirname as al}from"node:path";function un(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 fn(s){if(!s||typeof s!="object")return!1;let e=s;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&hn(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&un(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function hn(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 gn(s){let e;try{e=await rl(s,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}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 cl(s,e,t){await tl(al(s),{recursive:!0});let r=t===void 0?384:(await nl(s)).mode&511,i=`${s}.pi-web-${el(6).toString("hex")}.tmp`;try{await ol(i,`${JSON.stringify(e,null,2)}
|
|
28
|
+
`,{mode:r,flag:"wx"}),await il(i,s)}finally{await sl(i,{force:!0})}}async function mn(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await gn(s),i=r.providers[e],n=new Set(i?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:i?.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:!!i?.modelOverrides?.[o.id]}))}}async function wn(s,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i,existing:n}=await gn(s),o={...i.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!un(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(!hn(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(v=>v.id===p);if(p===void 0&&(c.some(v=>v.id===l.id)||r.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(c.some(w=>w.id===l.id)||r.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let v={...c[u],...l};for(let w of["name","contextWindow","maxTokens","input"])l[w]===void 0&&delete v[w];c[u]=v}else if(p!==void 0&&r.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:v,...w}=l;a[p]={...a[p],...w};for(let h of["name","contextWindow","maxTokens","input"])l[h]===void 0&&delete a[p][h]}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?i.providers[e]=o:delete i.providers[e],await cl(s,i,n)}function yn(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as vn,createHash as ll}from"node:crypto";import{fileURLToPath as dl}from"node:url";var Et="pi-webapp@0.1.52-alpha.2+dfb42ec2f20c96a203fd",Pe="dfb42ec2f20c96a203fd";var pl="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function tr(s=process.env,e=console.warn){let t=r=>{let i={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Et,buildId:Pe},n=s[`PI_WEB_SENTRY_${r}_DSN`]??s.PI_WEB_SENTRY_DSN??pl;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return i;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{...i,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),i}};return{browser:t("BROWSER"),node:t("NODE")}}var Se=class{config;ready;reporter;client;salt=vn(16);breadcrumbs=new St;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=tr(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=dl(import.meta.url).replace(/\\/g,"/"),r=t.lastIndexOf("/src/"),i=r>=0?t.slice(0,r+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:i)&&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:Pe,integrations:[],transport:e.transport??(r=>Hs(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:Os,sendClientReports:!1,dataCollection:{...Cs,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Gt(this.client,"node",Pe,t,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.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||Le(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 r=vn(16).toString("hex");return this.early.push({error:st(e),context:ke(t),eventId:r}),r}catch{return}}setState(e){this.state=ke({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return ll("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(r=>{t=setTimeout(r,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 Pl}from"@earendil-works/pi-coding-agent";function De(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 ul}from"node:crypto";function xt(s){let e=[],t=s;for(;;){let r=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!r||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(r[3]))break;let i;try{i=JSON.parse(r[2])}catch{break}e.unshift({name:i,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(i)}),t=t.slice(0,r.index)}return{text:t,attachments:e}}var _t=s=>Buffer.byteLength(s.text)+s.images.reduce((e,t)=>e+t.data.length,0),oe=class extends Error{status=409},Oe=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,...xt(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((i,n)=>i+_t(n),_t({text:e,images:t}))>64*1024*1024)throw new oe("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:ul(),revision:1,text:e,images:t.map(i=>({...i})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new oe("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let r=this.entries.find(i=>i.id===e);if(!r||r.revision!==t)throw new oe("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new oe("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,t,r,i){let n=this.find(e,t);if(r.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(r.kind==="edit"){let o=xt(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),c].filter(Boolean).join(`
|
|
29
29
|
|
|
30
|
-
`);if(this.validateText(a),this.entries.reduce((l,p)=>l+Dt(p),0)-Dt(n)+Dt({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 X(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 vn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function rr(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","status","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=X(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 bn}from"node:fs/promises";import{join as kn}from"node:path";async function Pn(s){try{let e=JSON.parse(await bn(kn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,i=await bn(kn(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 nl,readFile as sr,realpath as li,rename as ol,rm as al,writeFile as cl}from"node:fs/promises";import{randomUUID as ll}from"node:crypto";import{dirname as ci,join as _e,resolve as dl,sep as Sn}from"node:path";import{createRequire as pl}from"node:module";var sl=/^(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"&&sl.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 In(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,En=s=>_e(s,"pi-web","desktop-update.json");async function pt(s,e){let t=pl(_e(s,"package.json"));for(let i of t.resolve.paths(e)??[]){let r=_e(i,e);try{if(JSON.parse(await sr(_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(dl(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+Sn)||!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 sr(_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 pt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(r+Sn))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=>nl(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 xn(s,e,t=e){try{let i=JSON.parse(await sr(En(s),"utf8"));return ue(i.version,e)<0&&i.fallbackVersion!==t?null:await di(s,i)}catch{return null}}async function _n(s,e){let t=En(s),i=`${t}.${ll()}.tmp`;try{await cl(i,JSON.stringify(e),{mode:384}),await ol(i,t)}finally{await al(i,{force:!0})}}var yl={"/":{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 vl(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&&ul(i,e)}async function Tn(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 bl(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 kl(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 Rn(s,e,t=new xe,i={}){t.setState({piVersion:wl});let r=process.env.PI_WEBAPP_RESTART_TOKEN,n=r&&/^[A-Za-z0-9_-]{32}$/.test(r)?r:An(24).toString("base64url"),o=Buffer.from(n),c=rn(),a=new Set,l=new ei(i.pluginSettingsFile??or(ml(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new ti(Js(),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
|
-
`)},
|
|
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 Tn(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||Je(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()??p.restartConfirmations()[0];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 Z("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length)throw new Z("\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 Z)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 B="input"in g?g.input:{};if(!B||typeof B!="object"||Array.isArray(B)){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...B,sessionId:g.sessionId},res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(Pe,qe)=>I(v,Pe,Pe>=200&&Pe<300?{value:qe}:qe)});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}if(A.force!==void 0&&typeof A.force!="boolean"){I(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let B=A.force===!0,Pe=G=>I(v,409,{error:G.join("\uFF1B"),reason:"update_confirm_required"}),qe=p.restartConfirmations();if(qe.length&&!B){Pe(qe);return}_=!0;let Et;try{Et=await s.selfUpdate.prepare(C?{channel:A.channel,version:A.version,allowDowngrade:A.allowDowngrade}:void 0);let G=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||G)throw new Error(G??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let Yr=p.restartConfirmations();if(Yr.length&&!B){Pe(Yr);return}B&&await p.releaseForRestart(),E=!0;try{await s.selfUpdate.requestRestart(Et,{force:B})}catch(Qr){let Zr=Qr?.code;if(!B&&(Zr==="view_barrier"||Zr==="drain_pending")){E=!1,Pe(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw Qr}}catch(G){throw E=!1,G}finally{_=!1}I(v,202,{accepted:!0,version:Et.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)||!ir(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)||!un(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(B=>B.id===g.providerId&&B.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,ne);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 sn(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 en("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 tn(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"&&wn(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>on||A.some(G=>typeof G!="string")||new Set(A).size!==A.length){I(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=A.map(G=>f.get(G));if(C.some(G=>!G||G.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 B=s.snapshot();if(g.sessionId!==B.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{We(B,g.text,S)}catch(G){I(v,409,{error:G.message});return}let Pe=C,qe=[g.text.trim(),...Pe.map(G=>`\u9644\u4EF6 ${JSON.stringify(G.name)}\uFF1A${G.path}`)].filter(Boolean).join(`
|
|
30
|
+
`);if(this.validateText(a),this.entries.reduce((l,p)=>l+_t(p),0)-_t(n)+_t({text:a,images:n.images})>64*1024*1024)throw new oe("\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,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 f=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 K(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 He=s=>s.code==="ENOENT";var bn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function Yr(s,e,t,r){if(!s)throw new f("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 f("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","status","cancel-initialization"].includes(String(i.operation)))throw new f("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(i.operation!=="pollMany")return s.views(i);if(!Array.isArray(i.views)||!i.views.length||i.views.length>64||i.views.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.operation!=="poll"))throw new f("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(i.views.map(async n=>{try{return{reply:await s.views({...n,operation:"poll",immediate:!0})}}catch(o){return{failure:rr(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new f("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof i.id!="string"||!/^[a-f0-9-]{36}$/.test(i.id)||i.decision!=="allow"&&i.decision!=="deny")throw new f("invalid_input","Invalid approval decision",{status:400});if(!s.decide)throw new f("hosted_unavailable","Approvals are not available in this runtime",{status:503});return s.decide(i.id,i.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new f("host_restarting","Host is updating; secret changes are fenced",{status:409});if(i.auth!==void 0){if(!s.secretAuth)throw new f("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(i.auth==="start"&&typeof i.pluginId=="string"&&i.pluginId.length<=214&&typeof i.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(i.name))return s.secretAuth({phase:"start",pluginId:i.pluginId,name:i.name});if((i.auth==="poll"||i.auth==="cancel")&&typeof i.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(i.deviceId))return s.secretAuth({phase:i.auth,deviceId:i.deviceId});throw new f("invalid_input","Invalid sign-in request",{status:400})}if(typeof i.pluginId!="string"||i.pluginId.length>214||typeof i.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i.name)||!(i.value===null||typeof i.value=="string"&&i.value.length>=1&&i.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(i.value)))throw new f("invalid_input","Invalid secret request",{status:400});if(!s.secret)throw new f("hosted_unavailable","Secrets are not available in this runtime",{status:503});return s.secret(i.pluginId,i.name,i.value)}if(typeof i.pluginId!="string"||i.pluginId.length>214)throw new f("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new f("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 f("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 f("invalid_input","Exact download identity required",{status:400});if(i.reopenEditors!==void 0&&typeof i.reopenEditors!="boolean")throw new f("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 f("invalid_input","Invalid update policy or missing exact pin",{status:400});return s.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 f("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 f("invalid_input","Invalid view flush capability",{status:400});return s.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 f("invalid_route","Unknown hosted plugin route",{status:404})}function rr(s){let e=K(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 kn}from"node:fs/promises";import{join as Pn}from"node:path";async function In(s){try{let e=JSON.parse(await kn(Pn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await kn(Pn(s,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let n of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])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 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(n=>[`/${n}`,{path:n,type:i[n.split(".").pop()]}]))}catch{return{}}}import{access as hl,readFile as xn,realpath as nr,rename as em,rm as tm,writeFile as rm}from"node:fs/promises";import{dirname as sr,join as Re,resolve as gl,sep as En}from"node:path";import{createRequire as ml}from"node:module";var fl=/^(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 Ee(s){let e=typeof s=="string"&&fl.exec(s);if(!e||e[0]!==s)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(s,e){let t=Ee(s),r=Ee(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 n=t.prerelease[i],o=r.prerelease[i];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 Sn(s){try{return Ee(s).prerelease.length===0}catch{return!1}}function ir(s){try{return Ee(s),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(s)}catch{return!1}}var Me=1;async function nt(s,e){let t=ml(Re(s,"package.json"));for(let r of t.resolve.paths(e)??[]){let i=Re(r,e);try{if(JSON.parse(await xn(Re(i,"package.json"),"utf8")).name===e)return await nr(i)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function Qr(s,e){if(ue(e?.version,e?.version),e.desktopProtocolVersion!==Me||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await nr(gl(sr(e.launcher),"..")),r=await nr(Re(s,"pi-web","releases")),i=sr(sr(t));if(await nr(e.launcher)!==Re(t,"bin","pi-webapp.mjs")||sr(i)!==r||!i.startsWith(r+En)||!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 n=JSON.parse(await xn(Re(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!==Me)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+En))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let c=Re(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,c,Re(t,"dist","extension.js"),Re(t,"web","dist","index.html")].map(a=>hl(a))),e.fallbackVersion!==void 0&&Ee(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:Me,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var Il={"/":{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 P(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 Sl(s,e){let t=s.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let r=Buffer.from(t.slice(7),"utf8");return r.length===e.length&&wl(r,e)}async function An(s,e=64*1024){let t=0,r=[];for await(let i of s){let n=Buffer.isBuffer(i)?i:Buffer.from(i);if(t+=n.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(n)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function El(s){let e=0,t=[];for await(let r of s){let i=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=i.length,e>Zt)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(i)}return Buffer.concat(t)}async function xl(s,e=0){await new Promise((r,i)=>{s.once("error",i),s.listen(e,"127.0.0.1",()=>{s.off("error",i),r()})});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 Tn(s,e,t=new Se,r={}){t.setState({piVersion:Pl});let i=process.env.PI_WEBAPP_RESTART_TOKEN,n=i&&/^[A-Za-z0-9_-]{32}$/.test(i)?i:_n(24).toString("base64url"),o=Buffer.from(n),c=sn(),a=new Set,l=new Xt(r.pluginSettingsFile??ei(kl(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new Yt(Ks(),l),u=async()=>await s.plugins?.()??{plugins:[],errors:[]},v=()=>({type:"plugin_state",disabled:p.plugins.filter(b=>!l.enabled(b.metadata.id)).map(b=>b.metadata.id)}),w=()=>{for(let b of a)b.write(`${JSON.stringify(v())}
|
|
31
|
+
`)},h=new Map,m=new er((b,y)=>t.capture(b,y)),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}),I="",E=!1,A=!1,O={...Il,...await In(e)};for(let b of await vl(ei(e,"assets")).catch(()=>[])){let y=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(b);if(!y)continue;let j={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};O[`/assets/${b}`]={path:`assets/${b}`,type:j[y[1]]}}let H=bl(async(b,y)=>{let j=_n(18).toString("base64"),me=le=>typeof le=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(le),we=me(b.headers["x-request-id"])?b.headers["x-request-id"]:Zr(),se={requestId:we,operationId:me(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};y.setHeader("X-Request-ID",we),se.operationId&&y.setHeader("X-Operation-ID",se.operationId);let x="/",Ia=performance.now(),ce=(le,g,S)=>{let C=!Le(le)&&Ns(x)?Ae(le,"Agent or provider operation failed"):le,V=t.capture(C,{...se,route:x,method:b.method,status:g,stage:"http"});P(y,g,{error:S,errorId:V,errorReported:t.enabled,errorCode:Le(le)?"validation_error":"unexpected_error"})};y.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...se,route:x,method:b.method,status:y.statusCode,durationMs:Math.round(performance.now()-Ia)})});try{y.setHeader("X-Content-Type-Options","nosniff"),y.setHeader("Referrer-Policy","no-referrer"),y.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${j}'; 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??"/",I).pathname}catch{P(y,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let le=O[x];if(b.method==="GET"&&le){try{let g=await yl(ei(e,le.path));y.writeHead(200,{"Content-Type":le.type,"Cache-Control":"no-store"}),y.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${j}">`):g)}catch(g){ce(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){P(y,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}y.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'"),y.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),y.end(g.bytes)}catch{P(y,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){P(y,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}y.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),y.end(g.bytes)}catch(g){ce(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){P(y,404,{error:"\u672A\u627E\u5230"});return}if(!Sl(b,o)){P(y,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(b.method==="GET"&&x==="/api/hosted-plugins"){try{P(y,200,await Yr(s.hosted,x,void 0))}catch(g){let S=rr(g);P(y,S.status,S.body)}return}if(b.method==="POST"&&bn.includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==I){P(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){P(y,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let g;try{g=await An(b,2*1024*1024)}catch(S){P(y,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{P(y,200,await Yr(s.hosted,x,g,{draining:E}))}catch(S){let _=rr(S);P(y,_.status,_.body)}return}if(b.method==="GET"&&x==="/api/telemetry/config"){P(y,200,t.config.browser);return}if(b.method==="GET"&&x==="/api/update/version"){try{P(y,200,{current:await s.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Me,...s.selfUpdate?.launcherIdentity?{launcher:s.selfUpdate.launcherIdentity(),desktopHandoffProtocol:s.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){ce(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{P(y,200,await s.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){ce(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,I),S=g.searchParams.get("sessionId")??"",_=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==s.snapshot().sessionId||!_||!Number.isInteger(C)||C<0||C>100){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let V=s.image?.(S,_,C);if(!V||!["image/png","image/jpeg","image/webp","image/gif"].includes(V.mimeType)){P(y,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}y.writeHead(200,{"Content-Type":V.mimeType,"Cache-Control":"private, no-store"}),y.end(V.data);return}if(b.method==="POST"&&x==="/api/attachment"){if(b.headers.origin!==void 0&&b.headers.origin!==I){P(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let g=new URL(b.url??x,I),S=g.searchParams.get("sessionId"),_=g.searchParams.get("name");try{if(!S||!_||_.length>1024||S!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(b.headers["content-length"]??0)>Zt){P(y,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await cn(S,_,b.headers["content-type"]??"application/octet-stream",await El(b));if(S!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}h.set(C.id,C),P(y,201,{id:C.id,name:C.name,bytes:C.bytes})}catch(C){ce(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),P(y,200,g)}catch(g){ce(g,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugin-management"){try{P(y,200,p.inventory(await u()))}catch(g){ce(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugins"){try{P(y,200,p.catalog(await u()))}catch(g){ce(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/providers"){try{P(y,200,await s.providers?.()??[])}catch(g){ce(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,I).searchParams.get("providerId")??"";try{if(!g||!s.providerModels){P(y,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}P(y,200,await s.providerModels(g))}catch(S){ce(S,400,S instanceof Error?S.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/login/active"){P(y,200,{active:m.getActive()??null});return}if(b.method==="GET"&&x==="/api/provider/login"){let g=new URL(b.url??x,I).searchParams.get("id")??"",S=m.get(g);P(y,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{P(y,200,x==="/api/models"?await s.models():x==="/api/config"?await s.config():x==="/api/commands"?s.commands?.()??[]:await s.workspaces())}catch(g){ce(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/directory/capability"){P(y,200,{kind:c});return}if(b.method==="GET"&&x==="/api/events"){let g;try{g=s.snapshot(),k(g)}catch(S){ce(S,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}y.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),a.add(y),y.write(`${JSON.stringify({type:"snapshot",session:g})}
|
|
32
|
+
`),y.on("close",()=>a.delete(y));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!==I){P(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){P(y,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let g;try{g=await An(b,x==="/api/plugin-action"?544*1024:64*1024)}catch(S){if(S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){P(y,413,{error:S.message});return}if(S instanceof SyntaxError||Le(S)){P(y,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"){P(y,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!s.selfUpdate?.requestLauncherHandoff){P(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(E||A||m.getActive()){P(y,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let _=p.restartBlocker()??p.restartConfirmations()[0];if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||_){P(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}E=!0;try{await s.selfUpdate.requestLauncherHandoff(S.nonce,S.requestId)}catch(C){throw E=!1,C}P(y,202,{accepted:!0,protocol:1,requestId:S.requestId});return}if(typeof g!="object"||g===null||!("sessionId"in g)||typeof g.sessionId!="string"){P(y,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(E&&x!=="/api/update/cancel"){P(y,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"){P(y,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let _=()=>{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,_),P(y,200,p.inventory(await u()))}catch(C){if(C instanceof Q)P(y,C.status,{error:C.message});else throw C}finally{w()}return}if(p.mutating&&x!=="/api/abort"){P(y,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:y,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(S,_)=>P(y,S,_)}))return;if(x==="/api/plugin-interaction"){if(g.sessionId!==s.snapshot().sessionId){P(y,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)){P(y,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)),P(y,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(g.sessionId!==s.snapshot().sessionId){P(y,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){P(y,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){P(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let V="input"in g?g.input:{};if(!V||typeof V!="object"||Array.isArray(V)){P(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...V,sessionId:g.sessionId},res:y,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(be,Ue)=>P(y,be,be>=200&&be<300?{value:Ue}:Ue)});return}if(!s.invokePluginAction){P(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let _=await p.coordinateStart(s.snapshot().cwd,async()=>s.invokePluginAction(g.sessionId,g.pluginId,g.action,"input"in g?g.input:void 0));P(y,200,{value:_});return}if(x==="/api/update/channel"){if(g.sessionId!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in g)||g.channel!=="stable"&&g.channel!=="alpha"){P(y,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!s.selfUpdate?.setChannel){P(y,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}P(y,200,await s.selfUpdate.setChannel(g.channel));return}if(x==="/api/update/cancel"){if(g.sessionId!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.selfUpdate?.cancel){P(y,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await s.selfUpdate.cancel(),P(y,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(A){P(y,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(g.sessionId!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.snapshot().idle){P(y,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!s.selfUpdate){P(y,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let S=p.restartBlocker();if((s.busyGitWorkspaces?.()??[]).length||S){P(y,409,{error:S??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let _=g,C="channel"in _||"version"in _||"allowDowngrade"in _;if(C&&(_.channel!=="stable"&&_.channel!=="alpha"||typeof _.version!="string"||_.allowDowngrade!==void 0&&typeof _.allowDowngrade!="boolean")){P(y,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(_.force!==void 0&&typeof _.force!="boolean"){P(y,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let V=_.force===!0,be=z=>P(y,409,{error:z.join("\uFF1B"),reason:"update_confirm_required"}),Ue=p.restartConfirmations();if(Ue.length&&!V){be(Ue);return}A=!0;let bt;try{bt=await s.selfUpdate.prepare(C?{channel:_.channel,version:_.version,allowDowngrade:_.allowDowngrade}:void 0);let z=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||z)throw new Error(z??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let Qi=p.restartConfirmations();if(Qi.length&&!V){be(Qi);return}V&&await p.releaseForRestart(),E=!0;try{await s.selfUpdate.requestRestart(bt,{force:V})}catch(Zi){let es=Zi?.code;if(!V&&(es==="view_barrier"||es==="drain_pending")){E=!1,be(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw Zi}}catch(z){throw E=!1,z}finally{A=!1}P(y,202,{accepted:!0,version:bt.version});return}if(x==="/api/provider/custom"){if(g.sessionId!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in g)||!Xr(g.provider)||!s.addCustomProvider){P(y,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await s.addCustomProvider(g.sessionId,g.provider),P(y,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(g.sessionId!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in g)||typeof g.providerId!="string"){P(y,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(x==="/api/provider/models"){if(!("change"in g)||!fn(g.change)||!s.updateProviderModel){P(y,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await s.updateProviderModel(g.sessionId,g.providerId,g.change)}else{if(!s.logoutProvider){P(y,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await s.logoutProvider(g.sessionId,g.providerId)}P(y,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(g.sessionId!==s.snapshot().sessionId){P(y,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){P(y,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await s.providers()).some(V=>V.id===g.providerId&&V.methods.includes(g.method))){P(y,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let _="initialSecret"in g?g.initialSecret:void 0;if(_!==void 0&&(g.method!=="api_key"||typeof _!="string"||!_.trim()||_.length>16384)){P(y,400,{error:"API Key \u65E0\u6548"});return}let C=m.start(g.providerId,g.method,s.loginProvider,_,se);P(y,202,{id:C.id});return}if(!("id"in g)||typeof g.id!="string"){P(y,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(x==="/api/provider/login/cancel"){P(y,m.cancel(g.id)?202:404,{accepted:!0});return}if(!("value"in g)||typeof g.value!="string"||g.value.length>16384||!m.respond(g.id,g.value)){P(y,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}P(y,202,{accepted:!0});return}if(x==="/api/attachment/remove"){if(!("id"in g)||typeof g.id!="string"||g.sessionId!==s.snapshot().sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}h.get(g.id)?.sessionId===g.sessionId&&h.delete(g.id),P(y,202,{accepted:!0});return}if(x==="/api/directory/pick"){if(c!=="native"){P(y,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let S=new AbortController;y.once("close",()=>S.abort()),P(y,200,{path:await nn(S.signal)});return}if(x==="/api/directory/list"){if("path"in g&&(typeof g.path!="string"||g.path.length>4096)){P(y,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}P(y,200,await tn("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){P(y,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}P(y,200,{path:await rn(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"){P(y,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await s.addWorkspace(g.path,g.create),P(y,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"){P(y,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),P(y,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"){P(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await s.selectSession(g.workspaceId,g.id,g.path),P(y,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){P(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(x==="/api/session/rename"){if(!("name"in g)||typeof g.name!="string"){P(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!s.renameSession){P(y,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){P(y,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await s.deleteSession(g.workspaceId,g.id,g.path)}P(y,202,{accepted:!0});return}if(x==="/api/thinking-level"){if(!("level"in g)||typeof g.level!="string"){P(y,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"){P(y,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){P(y,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(S.action==="add"&&S.kind!=="packages"&&yn(S.value)){P(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}P(y,200,await s.updateConfig(S));return}else if(x==="/api/prompt-queue"){let S=g,_=S.action;if(typeof S.id!="string"||S.id.length>100||!Number.isSafeInteger(S.revision)||S.revision<1||!_||typeof _!="object"||!["edit","remove","steer"].includes(_.kind)||_.kind==="edit"&&(typeof _.text!="string"||_.text.length>32e3)){P(y,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let C=s.snapshot();if(S.sessionId!==C.sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(_.kind==="steer"&&C.idle){P(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){P(y,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!s.updateQueuedPrompt){P(y,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,_))}else if(x==="/api/message"){let S="delivery"in g?g.delivery:void 0;if(S!==void 0&&S!=="steer"&&S!=="followUp"){P(y,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let _="attachments"in g?g.attachments:[];if(!Array.isArray(_)||_.length>an||_.some(z=>typeof z!="string")||new Set(_).size!==_.length){P(y,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=_.map(z=>h.get(z));if(C.some(z=>!z||z.sessionId!==g.sessionId)){P(y,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in g)||typeof g.text!="string"||!g.text.trim()&&_.length===0||g.text.length>32e3){P(y,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let V=s.snapshot();if(g.sessionId!==V.sessionId){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{De(V,g.text,S)}catch(z){P(y,409,{error:z.message});return}let be=C,Ue=[g.text.trim(),...be.map(z=>`\u9644\u4EF6 ${JSON.stringify(z.name)}\uFF1A${z.path}`)].filter(Boolean).join(`
|
|
33
33
|
|
|
34
|
-
`),
|
|
35
|
-
`;for(let
|
|
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 Pl}from"@earendil-works/pi-ai";var Nt="pi-webapp/paused",ar="pi-webapp/resume";function ut(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="custom_message"&&t.customType===ar)return!1;if(t.type==="custom"&&t.customType===Nt)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 cr(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 Ke(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 Ht(s){if(s.type==="custom_message")return s.display?{id:s.id,role:"notice",timestamp:s.timestamp,blocks:Ke(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:Ke(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:Ke(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 Ct(i?.blocks.find(n=>n.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function Cn(s,e,t=[]){let i=s.sessionManager.getBranch().flatMap(r=>{let n=Ht(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?Pl(s.model):["off"],idle:s.isIdle(),paused:ut(s.sessionManager.getBranch()),contextUsage:s.getContextUsage()??null,messages:i,pluginEntries:cr(s.sessionManager.getBranch(),t)}}import{randomUUID as lr}from"node:crypto";import{mkdir as Dn,readFile as Il,realpath as dr,rename as Sl,rm as El,stat as pr,writeFile as xl}from"node:fs/promises";import{basename as Nn,dirname as _l,isAbsolute as Hn,join as Al}from"node:path";var Ot=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 Xe(s){try{let e=await dr(s);return(await pr(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 Xe(s);if(e===null)throw new Ot;return e}var ui=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Il(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(!Hn(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await Dn(e,{recursive:!0});let i=await dr(e);if(!(await pr(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:lr(),path:i,title:Nn(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(Hn).map(async i=>{try{let r=await dr(i);return(await pr(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:lr(),path:o,title:Nn(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 Dn(_l(this.file),{recursive:!0});let i=`${this.file}.${lr()}.tmp`;try{await xl(i,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await Sl(i,this.file)}catch(r){throw await El(i,{force:!0}),r}}};function On(s){return Al(s,"pi-web","workspaces.json")}import{createAgentSession as wd,createEventBus as yd,DefaultResourceLoader as vd,getAgentDir as bd,SessionManager as jt,VERSION as mi}from"@earendil-works/pi-coding-agent";var Tl="pi-webapp:interaction-open:v1",Rl="pi-webapp:interaction-accept:v1",Mn="pi-webapp:interaction-settle:v1",Cl="pi-webapp:interaction-cancel:v1";var ht=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(Tl,r=>{!Dl(r)||!t(r)||this.requests.has(r.requestId)||(this.requests.set(r.requestId,r),e.emit(Rl,{requestId:r.requestId}),i())}),e.on(Cl,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(Mn,{requestId:i,value:r}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(Mn,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function Dl(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 Ye(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&&Ye(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Ye(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Ye(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Ye(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 Nl=1,Hl="pi-webapp:action:v1",Ol="pi-webapp:action-response:v1",hi="pi-webapp:plugin-changed:v1";function jn(s){if(!s||typeof s!="object")return!1;let e=s;return e.apiVersion===Nl&&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(Ol,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(Hl,e)}catch(u){c(u instanceof Error?u:new Error(String(u)))}})}import{realpath as kd}from"node:fs/promises";import{readFile as ur,realpath as Fn,stat as Bn}from"node:fs/promises";import{createHash as Ml}from"node:crypto";import{dirname as Wn,isAbsolute as jl,join as hr,parse as Wl,resolve as $l,sep as Vl,delimiter as Fl}from"node:path";import{DefaultPackageManager as Bl,getAgentDir as Ul,SettingsManager as Ll}from"@earendil-works/pi-coding-agent";async function $n(s,e){let t=await ur(s),i=e?await ur(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=Ml("sha256").update(t).update("\0").update(i??"").digest("hex");return{clientBytes:t,styleBytes:i,revision:r}}function zl(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Fl).filter(Boolean).map(s=>$l(s))}async function ql(s){let e=Wn(s);for(;e!==Wl(e).root;)try{return await Bn(hr(e,"package.json")),e}catch{e=Wn(e)}return null}async function Vn(s,e){let t=await Fn(hr(s,e));if(!t.startsWith(s+Vl))throw new Error("Asset escapes package root");let i=await Bn(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 Qe=class s{plugins;errors;extensionRoots;constructor(e,t,i){this.plugins=e,this.errors=t,this.extensionRoots=i}static async discover(e,t,i=zl()){let r=Ll.create(e,void 0,{projectTrusted:t}),n=new Bl({cwd:e,agentDir:Ul(),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 ql(m.path);f&&a.add(f)}for(let m of i)jl(m)&&a.add(m);let l=[],p=[],u=[],y=new Set;for(let m of a)try{let f=await Fn(m),w=JSON.parse(await ur(hr(f,"package.json"),"utf8"));if(w.piWebapp===void 0)continue;if(typeof w.name!="string"||!w.name)throw new Error("Missing package name");if(!jn(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 Vn(f,w.piWebapp.client),P=w.piWebapp.style?await Vn(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 $n(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 $n(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 Gl}from"node:fs/promises";import{SessionManager as Jl}from"@earendil-works/pi-coding-agent";async function ft(s,e){let t=await Ae(s),i=e??await Jl.listAll(),r=await Promise.all(i.map(async n=>n.cwd!==""&&await Gl(n.cwd).catch(()=>null)===t));return i.filter((n,o)=>r[o])}var Ze=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))}},Un=new WeakMap;function Ln(s,e,t,i=5e3,r=()=>{}){let n=Un.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 Un.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:
|
|
34
|
+
`),bt=await Promise.all(be.filter(z=>["image/png","image/jpeg","image/webp","image/gif"].includes(z.mediaType)).map(ln));se.operationId??=Zr(),y.setHeader("X-Operation-ID",se.operationId),t.breadcrumb("send",{...se,attachmentCount:be.length}),await p.coordinateStart(V.cwd,async()=>s.send(g.sessionId,Ue,bt,se,S));for(let z of _)h.delete(z)}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){P(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!S.idle){P(y,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!S.paused){P(y,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(S.interactions?.length){P(y,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??=Zr(),y.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);P(y,202,{accepted:!0})}catch(g){if(g instanceof oe){P(y,g.status,{error:g.message});return}let S=p.requestFailure(g);if(S){P(y,S.status,S.body);return}let _=g instanceof Error?g.message:"\u8BF7\u6C42\u5931\u8D25";ce(g,_==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,_)}return}P(y,404,{error:"\u672A\u627E\u5230"})}catch(le){y.headersSent?(t.capture(le,{...se,route:x,stage:"http_stream"}),y.end()):ce(le,500,"\u8BF7\u6C42\u5931\u8D25")}}),T=Number(process.env.PI_WEBAPP_RESTART_PORT),Y;try{Y=await xl(H,Number.isInteger(T)&&T>0&&T<65536&&i===n?T:0)}catch(b){throw t.capture(b,{stage:"listen"}),await t.close(),b}return I=`http://127.0.0.1:${Y}`,{protocolVersion:7,buildId:Pe,runPluginTool:(b,y,j,me,we)=>p.runAgentAction(b,y,j,me,we),reportError(b,y){return t.capture(b,y)},breadcrumb(b,y){t.breadcrumb(b,y)},url:`${I}/#${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[j,me]of h)me.sessionId!==b.session.sessionId&&h.delete(j);let y=`${JSON.stringify(b)}
|
|
35
|
+
`;for(let j of a)j.write(y)},async close(b){m.close(),await p.close();for(let j of a)j.end(`${JSON.stringify({type:"shutdown",reconnect:b?.reconnect??E})}
|
|
36
|
+
`);a.clear();let y;try{await new Promise((j,me)=>{H.close(we=>we?me(we):j()),y=setTimeout(()=>H.closeAllConnections(),50).unref()})}finally{clearTimeout(y),await t.close()}}}}import{getSupportedThinkingLevels as _l}from"@earendil-works/pi-ai";var At="pi-webapp/paused",ti="pi-webapp/resume";function ot(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="custom_message"&&t.customType===ti)return!1;if(t.type==="custom"&&t.customType===At)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 ri(s,e){let t=[],r;for(let i of s){if(i.type==="message"&&(r=i.id),i.type!=="custom")continue;let n=e.find(o=>i.customType.startsWith(`${o}/`));if(n){try{if(JSON.stringify(i.data).length>128*1024)continue}catch{continue}t.push({id:i.id,pluginId:n,kind:i.customType,data:i.data,timestamp:i.timestamp,...r?{afterMessageId:r}:{}})}}return t}function ze(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 Tt(s){if(s.type==="custom_message")return s.display?{id:s.id,role:"notice",timestamp:s.timestamp,blocks:ze(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:ze(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:ze(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function or(s,e){let t=s?.trim();if(t)return t;let r=e.find(n=>n.role==="user");return xt(r?.blocks.find(n=>n.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function Rn(s,e,t=[]){let r=s.sessionManager.getBranch().flatMap(i=>{let n=Tt(i);return n?[n]:[]});return{schemaVersion:1,sessionId:s.sessionManager.getSessionId(),cwd:s.cwd,name:or(e,r),model:s.model?`${s.model.provider}/${s.model.id}`:null,thinkingLevel:s.thinkingLevel??null,thinkingLevels:s.model?_l(s.model):["off"],idle:s.isIdle(),paused:ot(s.sessionManager.getBranch()),contextUsage:s.getContextUsage()??null,messages:r,pluginEntries:ri(s.sessionManager.getBranch(),t)}}import{randomUUID as ii}from"node:crypto";import{mkdir as Cn,readFile as Al,realpath as si,rename as Tl,rm as Rl,stat as ni,writeFile as Cl}from"node:fs/promises";import{basename as Nn,dirname as Nl,isAbsolute as Dn,join as Dl}from"node:path";var Rt=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 qe(s){try{let e=await si(s);return(await ni(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function xe(s){let e=await qe(s);if(e===null)throw new Rt;return e}var ar=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Al(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(!Dn(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await Cn(e,{recursive:!0});let r=await si(e);if(!(await ni(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let i=this.hiddenPaths.filter(a=>a!==r),n=this.items.find(a=>a.path===r);if(n)return i.length!==this.hiddenPaths.length&&(await this.save(this.items,i),this.hiddenPaths=i),n;let o={id:ii(),path:r,title:Nn(r)||r},c=[o,...this.items];return await this.save(c,i),this.items=c,this.hiddenPaths=i,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter(Dn).map(async r=>{try{let i=await si(r);return(await ni(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:ii(),path:o,title:Nn(o)||o}));if(i.length===0)return;let n=[...this.items,...i];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 r=this.items.filter(n=>n.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 Cn(Nl(this.file),{recursive:!0});let r=`${this.file}.${ii()}.tmp`;try{await Cl(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await Tl(r,this.file)}catch(i){throw await Rl(r,{force:!0}),i}}};function On(s){return Dl(s,"pi-web","workspaces.json")}import{createAgentSession as Pd,createEventBus as Id,DefaultResourceLoader as Sd,getAgentDir as Ed,SessionManager as Nt,VERSION as pr}from"@earendil-works/pi-coding-agent";var Ol="pi-webapp:interaction-open:v1",Hl="pi-webapp:interaction-accept:v1",Hn="pi-webapp:interaction-settle:v1",Ml="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(Ol,i=>{!jl(i)||!t(i)||this.requests.has(i.requestId)||(this.requests.set(i.requestId,i),e.emit(Hl,{requestId:i.requestId}),r())}),e.on(Ml,i=>{let n=i,o=this.requests.get(n?.requestId);o&&o.sessionId===n.sessionId&&o.pluginId===n.pluginId&&(this.requests.delete(n.requestId),r())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,r,i){let n=this.requests.get(r);if(!n||n.sessionId!==e||n.pluginId!==t||!this.accepts(n))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(Hn,{requestId:r,value:i}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(Hn,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function jl(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 Ge(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 je(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&&Ge(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Ge(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Ge(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Ge(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 Wl=1,$l="pi-webapp:action:v1",Vl="pi-webapp:action-response:v1",cr="pi-webapp:plugin-changed:v1";function Mn(s){if(!s||typeof s!="object")return!1;let e=s;return e.apiVersion===Wl&&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 lr(s,e,t=15e3,r){return new Promise((i,n)=>{let o=!1,c=(u,v)=>{o||(o=!0,clearTimeout(l),a(),r?.removeEventListener("abort",p),u?n(u):i(v))},a=s.on(Vl,u=>{let v=u;v?.requestId===e.requestId&&c(v.ok?null:new Error(v.error??"Plugin action failed"),v.value)}),l=setTimeout(()=>c(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),t),p=()=>c(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{s.emit($l,e)}catch(u){c(u instanceof Error?u:new Error(String(u)))}})}import{realpath as xd}from"node:fs/promises";import{readFile as oi,realpath as Vn,stat as Fn}from"node:fs/promises";import{createHash as Fl}from"node:crypto";import{dirname as jn,isAbsolute as Ul,join as ai,parse as Bl,resolve as Ll,sep as zl,delimiter as ql}from"node:path";import{DefaultPackageManager as Gl,getAgentDir as Jl,SettingsManager as Kl}from"@earendil-works/pi-coding-agent";async function Wn(s,e){let t=await oi(s),r=e?await oi(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=Fl("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:i}}function Xl(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(ql).filter(Boolean).map(s=>Ll(s))}async function Yl(s){let e=jn(s);for(;e!==Bl(e).root;)try{return await Fn(ai(e,"package.json")),e}catch{e=jn(e)}return null}async function $n(s,e){let t=await Vn(ai(s,e));if(!t.startsWith(s+zl))throw new Error("Asset escapes package root");let r=await Fn(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 Je=class s{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=Xl()){let i=Kl.create(e,void 0,{projectTrusted:t}),n=new Gl({cwd:e,agentDir:Jl(),settingsManager:i}),o=await n.resolve(async()=>"skip"),c=r.length?await n.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},a=new Set;for(let w of[...o.extensions,...c.extensions]){if(!w.enabled)continue;let h=await Yl(w.path);h&&a.add(h)}for(let w of r)Ul(w)&&a.add(w);let l=[],p=[],u=[],v=new Set;for(let w of a)try{let h=await Vn(w),m=JSON.parse(await oi(ai(h,"package.json"),"utf8"));if(m.piWebapp===void 0)continue;if(typeof m.name!="string"||!m.name)throw new Error("Missing package name");if(!Mn(m.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(v.has(m.name))throw new Error(`Duplicate plugin id: ${m.name}`);let k=await $n(h,m.piWebapp.client),I=m.piWebapp.style?await $n(h,m.piWebapp.style):void 0;v.add(m.name),l.push({id:m.name,root:h,manifest:m.piWebapp,clientPath:k,stylePath:I,...await Wn(k,I)}),u.push(h)}catch(h){p.push(`${w}: ${h instanceof Error?h.message:String(h)}`)}return l.sort((w,h)=>w.id.localeCompare(h.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 Wn(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 n=this.plugins.find(c=>c.id===i);if(!n||t.searchParams.has("v")&&t.searchParams.get("v")!==n.revision)return null;let o=r[2]==="client.js"?n.clientBytes:n.styleBytes;return o?{bytes:o,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as Ql}from"node:fs/promises";import{SessionManager as Zl}from"@earendil-works/pi-coding-agent";async function ct(s,e){let t=await xe(s),r=e??await Zl.listAll(),i=await Promise.all(r.map(async n=>n.cwd!==""&&await Ql(n.cwd).catch(()=>null)===t));return r.filter((n,o)=>i[o])}var Ke=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))}},Un=new WeakMap;function Bn(s,e,t,r=5e3,i=()=>{}){let n=Un.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")),r)})])}catch(a){t(a instanceof Error?a.message:String(a))}finally{clearTimeout(c);try{i()}finally{s.dispose()}}})();return Un.set(s,o),o}function dr(s){let t=[...s].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
|
|
37
|
+
`);return{customType:ti,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 ed}from"node:crypto";import{readFile as td,writeFile as rd,unlink as id}from"node:fs/promises";import{basename as sd,dirname as nd,extname as od,join as ad}from"node:path";import{DefaultPackageManager as cd,getAgentDir as ld,SettingsManager as dd}from"@earendil-works/pi-coding-agent";var Ct=new Map;async function Ln(s,e){let r=await new cd({cwd:s,agentDir:ld(),settingsManager:dd.create(s)}).resolveExtensionSources([...e],{temporary:!0}),i=[],n=[],o=async()=>{for(let c of i.splice(0)){let a=(Ct.get(c)??1)-1;a?Ct.set(c,a):(Ct.delete(c),await id(c).catch(()=>{}))}};try{for(let c of r.extensions){if(!c.enabled)continue;let a=od(c.path);if(![".js",".mjs"].includes(a)){n.push(c.path);continue}let l=await td(c.path),p=ed("sha256").update(l).digest("hex"),u=ad(nd(c.path),`.pi-web-runtime-${sd(c.path,a)}-${p}${a}`);await rd(u,l,{flag:"wx"}).catch(v=>{if(v.code!=="EEXIST")throw v}),Ct.set(u,(Ct.get(u)??0)+1),i.push(u),n.push(u)}return{paths:n,release:o}}catch(c){throw await o(),c}}import{createHash as pd}from"node:crypto";var ci={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"}},We=s=>s!==null&&typeof s=="object"?s:void 0,ud=[{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 qn(s,e){let t=s instanceof Error?s:We(s)?.error instanceof Error?We(s).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},i=(p,u,v)=>{Object.assign(r,{failureKind:p,errorCode:u,errorSummary:v.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete r.summaryOmittedReason},n=We(t)?.code;if(typeof n=="string"&&ci[n]){let p=ci[n];return i(p.kind,n,`${n}: ${p.summary}`),r}let o=t?.message??"";if(!t){let p=We(s)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(u=>{let v=We(u);return v?.type==="text"&&typeof v.text=="string"?[v.text.length>16384?`${v.text.slice(0,8192)}
|
|
40
40
|
[truncated]
|
|
41
|
-
${
|
|
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
|
|
43
|
-
`)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=
|
|
41
|
+
${v.text.slice(-8192)}`:v.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 i("process_exit","nonzero_exit",a),r.exitCode=Number(p[1]),r;if(u&&Number.isFinite(Number(u[1]))&&Number(u[1])>0)return i("timeout","timeout",a),r.timeoutMs=Number(u[1])*1e3,r;if(a==="Command aborted")return i("cancelled","cancelled",a),r}let l=o.slice(0,8192).split(/\r?\n/,1)[0]??"";if(o==="Operation aborted"||t?.name==="AbortError")i("cancelled","cancelled","Operation aborted");else if(o==="Tool execution was blocked")i("blocked","blocked",o);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(o))i("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=ci[p[1]],v=l.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);i(u.kind,p[1],`${p[1]}: ${u.summary}${v?`; operation=${v[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))i("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))i("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))i("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=ud.find(v=>v.pattern.test(o));u&&i("validation",u.code,u.summary)}}return r}var fd=256;function zn(s,e,t){s.delete(e),s.set(e,t),s.size>fd&&s.delete(s.keys().next().value)}var lt=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:Jt.has(e.toolName)?e.toolName:"custom",...Jt.has(e.toolName)?{}:{toolId:pd("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 r=e.toolName==="bash"||e.toolName==="powershell"?We(e.args)?.timeout:void 0,i=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,n={...ke(t),...this.identity(e),stage:"tool"};zn(this.pending,e.toolCallId,{context:n,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:i}),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,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let i=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),zn(this.completed,e.toolCallId,!0);let n={...i?.context??{...ke(t),...this.identity(e),stage:"tool"},diagnosticSource:r};if(i&&(n.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-i.started)),i.timeoutMs!==void 0&&(n.timeoutMs=i.timeoutMs)),!e.isError){this.breadcrumb("tool_end",n);return}let o=e.result instanceof Error?e.result:We(e.result)?.error instanceof Error?We(e.result).error:void 0,c=i?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:qn(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=Gn(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 Gn(s,e,t=0){let r=qn(s,e),i=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return i.name=s.name,i.stack=s.stack?`${i.name}: ${i.message}
|
|
44
44
|
${s.stack.split(`
|
|
45
45
|
`).slice(1).join(`
|
|
46
|
-
`)}`:void 0,t<3&&s.cause instanceof Error&&(r.cause=Jn(s.cause,e,t+1)),dt(r)}import{randomUUID as Yn}from"node:crypto";import{randomUUID as ld}from"node:crypto";import{EnvHttpProxyAgent as dd,getGlobalDispatcher as Xm,setGlobalDispatcher as Ym}from"undici";var Kn=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 pd(s,e){let t=Kn(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 ud(s){let e=Kn(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 dd(e)}function gr({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:ld(),phase:"headers",proxied:o&&pd(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??=ud(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 Q=await _.read();Q.done?(T.close(),_.releaseLock(),P()):T.enqueue(Q.value)}catch(Q){c(Q,{...y,phase:"body"}),T.error(Q),_.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 Xn=(s,e)=>gr({autoClose:!0}).fetch(s,e);var hd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),fd=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 mr(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=fd(a.code);if(t.push({name:hd.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:Yn(),requestId:c(e.requestId)??Yn(),...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 gr({env:s,fetchRequest:t,onFailure:(i,r)=>e(mr(i,{...r,stage:r.phase==="body"?"model_stream":"model_headers"}))})}function gd(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 md=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Zn(s,e,t=()=>{}){let i=s.agent.streamFunction;s.agent.streamFunction=async(r,n,o)=>{if(!md.has(r.api))return i(r,n,o);let c=t(),a=Qn({env:gd(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 mt(s,e,t){try{s()}catch(i){let r=mr(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 Pd=["read","grep","find","ls"],eo=200,wi=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Ze;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=jt.create(i);else if(t==="continue"){let c=(await ft(i))[0];n=c?jt.open(c.path):jt.create(i)}else n="sessionManager"in t?t.sessionManager:jt.open(t.sessionFile);if(await kd(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=Ht(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=>Ht(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 Qe.discover(e,this.isProjectTrusted(e)),c=yd(),a=await zn(e,o.extensionRoots),l=new vd({cwd:e,agentDir:bd(),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 wd({cwd:e,sessionManager:t,model:y,resourceLoader:l,customTools:this.customTools}),f=new gt({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,Zn(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>eo&&P.events.splice(0,P.events.length-eo))};w.interactions=new ht(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:Ke(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=[],Q=!0;if(await m.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Q&&T.push(b.error),this.diagnostic(w,o.plugins.find(v=>b.extensionPath.startsWith(v.root+"/"))?.id??b.extensionPath,b.event??"runtime",b.error)}}),Q=!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(Pd)),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 Ln(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=Ht(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:ut(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:cr(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");mt(()=>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&&!ut(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(Nt),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");mt(()=>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(!ut(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(!ut(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=jt.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 Id,mkdir as Sd,rename as Ed,unlink as xd}from"node:fs/promises";import{basename as _d,join as to}from"node:path";var Ad=s=>to(s,"pi-web","trash");async function io(s,e){let t=Ad(e);await Sd(t,{recursive:!0});let i=to(t,`${Date.now()}_${_d(s)}`);try{await Ed(s,i)}catch(r){let n=r.code;if(n==="ENOENT")return null;if(n!=="EXDEV")throw r;await Id(s,i),await xd(s)}return i}import{basename as wr,dirname as Td}from"node:path";function ro(s,e){let t=i=>e[i].map(r=>({name:i==="skills"&&wr(r.path).toLowerCase()==="skill.md"?wr(Td(r.path)):wr(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 Rd}from"node:child_process";var Cd=(s,e)=>new Promise((t,i)=>{Rd(s,[...e],{windowsHide:!0},r=>{r?i(r):t()})});async function yr(s,e=process.platform,t=process.env,i=Cd){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 dp}from"node:child_process";import{randomUUID as Pi}from"node:crypto";import{existsSync as ko}from"node:fs";import{access as Tr,mkdir as Ii,mkdtemp as pp,readFile as ge,realpath as up,rename as Rr,rm as Vt,writeFile as Si}from"node:fs/promises";import{dirname as Po,join as M}from"node:path";import{createHash as kr,randomUUID as $d}from"node:crypto";import{mkdir as Vd,readFile as Fd,readdir as Bd,realpath as lo,rename as Ud}from"node:fs/promises";import{join as Re}from"node:path";import{constants as vr}from"node:fs";import{DatabaseSync as Dd}from"node:sqlite";import{lstat as oo,mkdir as Nd,open as Wt,rename as Hd,unlink as ao}from"node:fs/promises";import{dirname as Od,join as so,resolve as Md}from"node:path";import{randomUUID as jd}from"node:crypto";import{setTimeout as Wd}from"node:timers/promises";async function ee(s){await Nd(s,{recursive:!0,mode:448});let e=await oo(s);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function Y(s,e){let t;try{t=await Wt(s,vr.O_RDONLY|vr.O_NONBLOCK|(vr.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 te(s,e=2*1024*1024){let t=await Y(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 Y(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}.${jd()}.tmp`,i=await Wt(t,"wx",384);try{try{await i.writeFile(JSON.stringify(e)),await i.sync()}finally{await i.close()}await Hd(t,s);let r;try{r=await Wt(Od(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 ao(t).catch(()=>{})}}var co='{"version":2,"mechanism":"sqlite-exclusive"}',no=s=>s.toString("utf8")===co,yi=new Set;async function br(s,e,t=0){await ee(s);let i=so(s,`${e}.lock`),r=so(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 Wt(r,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await oo(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 Dd(r,{allowExtension:!1}),p=Md(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 Wd(10)}let f=await Y(i,4096);if(f===null){let w;try{w=await Wt(i,"wx",384),await w.writeFile(co),await w.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await w?.close()}f=await Y(i,4096)}if(f===null||!no(f))throw o()}catch(f){throw l.close(),y&&yi.delete(p),f}let m=!1;return async()=>{if(m)return;let f=await Y(i,4096);if(f===null||!no(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await ao(i),l.close(),yi.delete(p),m=!0}}async function W(s,e,t=2e3){let i=await br(s,"transaction",t);try{return await e()}finally{await i()}}var Ee=s=>Re(s,"host-pair"),ie=s=>kr("sha256").update(JSON.stringify(s)).digest("hex");async function Ld(s){let e=kr("sha256"),t=0,i=0;async function r(n){let o=(await Bd(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 Y(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,kr("sha256").update(l).digest("hex")]))}}return await r(""),e.digest("hex")}async function et(s,e){let t=await lo(e),i=Re(e,"dist","hosted-worker.js");if(await lo(i)!==Re(t,"dist","hosted-worker.js"))throw new h("host_pair_required","Candidate worker must remain inside the staged host");let r=await Y(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 Y(i,32*1024*1024);if(!c)throw new h("host_pair_required","Candidate worker missing");return ie([r.toString("base64"),c.toString("base64"),await Ld(e)])}async function vi(s){await Ud(s,`${s}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var zd=s=>s.schema===1&&/^[a-f0-9-]{36}$/.test(s.id)&&typeof s.version=="string"&&typeof s.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(s.hostDigest)&&/^[a-f0-9]{64}$/.test(s.fingerprint)&&Array.isArray(s.selections)&&!s.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(s.selection&&(typeof s.selection.path!="string"||!/^[a-f0-9]{64}$/.test(s.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(s.phase);async function Oe(s){let e=Re(Ee(s),"intent.json"),t,i=!0;try{t=await ce(e)}catch{t=null,i=!1}if(!i||t&&!zd(t))return await vi(e),null;if(t){let{lifecyclePhase:r,...n}=t;t={...n,phase:n.phase==="selected"&&r==="restart-requested"?"restart-requested":n.phase==="reconciled"&&r==="cancelled"?"cancelled":n.phase}}return t}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 bi=s=>s&&!["prepared","reconciled","cancelled"].includes(s.phase),Pr=s=>s&&["selecting","selected","restart-requested"].includes(s.phase);async function $t(s){let e=await Oe(s);if(e&&Pr(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 po(s,e,t,i=async()=>{}){let r=async o=>{let c=Re(Ee(s),"history");await Vd(c,{recursive:!0,mode:448}),await j(Re(c,`${o.id}.json`),o)},n=async(o,c,a)=>{let l=await et(o,c),p=ie(await t()),u=await e(o,a);if(a?.throwIfAborted(),ie(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:$d(),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 $t(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.phase==="required-action"?{...l,message:`Superseded by a new update; ${l.message??"no message"}`}: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(bi(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 $t(s);let l=await Oe(s),p=l?.phase==="prepared"&&l.version===o&&l.packageRoot===c&&l.fingerprint===ie(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 et(o,c)!==u||ie(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 et(o,c)||l.fingerprint!==ie(await t()))throw new h("host_pair_changed","Selected pair changed; restart refused, inspect pair journal");if(l.selection&&ie((await Fd(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 et(o,c)||l.fingerprint!==ie(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 hp}from"node:util";import{realpathSync as fo,statSync as qd}from"node:fs";import{basename as Gd,delimiter as Jd,dirname as uo,join as Ir,resolve as Kd}from"node:path";function ho(s){if(!s)return null;try{let e=fo(s);return Gd(e)==="npm-cli.js"&&qd(e).isFile()?e:null}catch{return null}}function Xd({execPath:s=process.execPath,env:e=process.env}={}){let t=ho(e.npm_execpath);if(t)return t;let i=new Set([uo(s)]);try{i.add(uo(fo(s)))}catch{}let r=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of r.split(Jd).filter(Boolean))i.add(Kd(n));for(let n of i)for(let o of[Ir(n,"node_modules","npm","bin","npm-cli.js"),Ir(n,"..","lib","node_modules","npm","bin","npm-cli.js"),Ir(n,"npm")]){let c=ho(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 go(s){return{file:process.execPath,args:[Xd(),...s]}}import{readFile as Yd,rename as Qd,writeFile as Zd,unlink as ep}from"node:fs/promises";import{join as tp}from"node:path";import{randomUUID as ip}from"node:crypto";var Sr=1,mo=s=>tp(s,"pi-web","launcher-handoff.json");function wo(s){return s?.protocol===Sr&&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 Er(s){try{let e=JSON.parse(await Yd(mo(s),"utf8"));if(!wo(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 rp(s,e){let t=`${s}.${ip()}.tmp`;try{await Zd(t,JSON.stringify(e),{mode:384}),await Qd(t,s)}finally{await ep(t).catch(()=>{})}}async function yo(s,e){if(!wo(e))throw new Error("Invalid launcher handoff receipt");await rp(mo(s),e)}import{execFile as sp}from"node:child_process";import{cp as np,readFile as xr,realpath as op,rm as ap}from"node:fs/promises";import{join as wt,sep as cp}from"node:path";import{promisify as lp}from"node:util";var vo=lp(sp),_r=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Ar(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 _r.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 ki(s){return Promise.all(_r.map(async e=>{let t=await pt(s,e),i=JSON.parse(await xr(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 bo(s,e){let t=JSON.parse(await xr(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 ki(s):Ar(t.peerDependencies);if(JSON.stringify(await ki(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 pt(s,"node-pty"),n=await pt(e,"node-pty"),o=await op(wt(e,"../.."));if(r===n||!n.startsWith(o+cp))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 xr(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 ap(n,{recursive:!0,force:!0}),await np(r,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await vo(process.execPath,[wt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await pt(e,_r[0]),{stdout:p}=await vo(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 fp=hp(dp);function Io(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 gp(s,e){try{let t=go(s),{stdout:i}=await fp(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 Ei=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??gp,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 ki(this.packageRoot);let r=JSON.parse(i),n=Array.isArray(r)&&r.length===1?r[0]:r;return Ar(n)},this.verifyPackage=e.verifyPackage??bo,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"?Sr: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 Er(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 yo(this.agentDir,p),l=!0}catch(u){let y=await Er(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(){let e;try{e=await ce(this.transactionPath)}catch{return await vi(this.transactionPath),null}try{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");return e}catch{return await vi(this.transactionPath),null}}async record(e){if(await Ii(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 Ii(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 Tr(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(ie(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 Tr(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||ie(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 Vt(t.selectionPath);else if(typeof t.before=="string"){let n=`${t.selectionPath}.${Pi()}.tmp`;try{await Si(n,Buffer.from(t.before,"base64"),{mode:384}),await Rr(n,t.selectionPath)}finally{await Vt(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}.${Pi()}.tmp`;try{await Ii(M(this.agentDir,"pi-web"),{recursive:!0}),await Si(t,JSON.stringify({channel:e}),{mode:384}),await Rr(t,this.preferencePath)}finally{this.savingPreference=!1,await Vt(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),i=ko(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","required-action"].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");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||!In(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"),this.desktopManaged&&this.desktopPackageUpdates&&r.available&&r.canRestart&&(r.reason="\u5347\u7EA7\u4F1A\u91CD\u542F\u540E\u53F0\uFF0C\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\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(ko(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 Ii(i,{recursive:!0});let r=await pp(M(await up(i),`${t.latest}-`)),n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Pi(),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&&Io(p)!==Io(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=>Tr(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 xn(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:ie(Buffer.from(JSON.stringify(N)).toString("base64"))},await this.record(o),await _n(this.agentDir,N)}else{let P=M(this.agentDir,"pi-web"),E=M(P,`update.${Pi()}.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:ie(Buffer.from(JSON.stringify(T)).toString("base64"))},await this.record(o),await Si(E,JSON.stringify(T),{mode:384}),await Rr(E,M(P,"update.json"))}finally{await Vt(E,{force:!0})}}let k=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");return{path:k,digest:ie((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 Vt(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,{force:t=!1}={}){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 i,r=!1;try{i=await this.beforeRestart?.(t),await this.preparedUpdate?.select();let n=async()=>{let o=M(this.agentDir,"pi-web","launcher.restart"),c=await this.transaction();c&&await this.record({...c,phase:"restart-requested"});try{await Si(o,JSON.stringify({nonce:this.launcherNonce,launcher:e.launcher}),{mode:384,flag:"wx"}),r=!0}catch(a){try{let l=JSON.parse(await ge(o,"utf8"));r=l.nonce===this.launcherNonce&&l.launcher===e.launcher}catch{}if(!r)throw a}};this.hostedPair?await this.hostedPair.restart(e.version,Po(Po(e.launcher)),n):await n(),this.restartPending=!0}catch(n){if(r){this.restartPending=!0;return}this.restartPending=!1;let o=await this.transaction();o?.phase==="restart-requested"&&await this.record({...o,phase:"selected",message:"Restart marker was not accepted; reverting owned selection"});let c=this.preparedUpdate;try{await this.cancel(),this.preparedUpdate=c}finally{i&&await i()}throw n}}};import{createHash as aa,randomUUID as yh}from"node:crypto";import{randomUUID as qu}from"node:crypto";import{access as Gu}from"node:fs/promises";import{join as $i}from"node:path";import{randomUUID as xo}from"node:crypto";import{randomUUID as mp}from"node:crypto";function So(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_${mp().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 wp;function Eo(){return wp??=yp().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function yp(){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,Q)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:T,parameters:{type:"object",properties:{}},execute:Q}),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,Q,b,v,$)=>{let ye=await $.executeTool("__contract_hidden",{}),ve=await $.executeTool("__contract_model_only",{}),ne=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!ye.isError||!ve.isError)&&p.push("nested-tool-exposure"),(ne.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,Q={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:Q}),b.push({type:"done",reason:T?"toolUse":"stop",message:Q}),b.end(Q),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 xi=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??=Eo().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=So(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:xo(),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:vp};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:xo(),scope:t,kind:"action",action:i,input:r},n)}};async function vp(){throw new Error("Hosted tool unavailable")}import{randomBytes as vu,randomUUID as bu,timingSafeEqual as ku}from"node:crypto";import{join as ke}from"node:path";var bp=30,_o=/^[a-z][a-z0-9-]{0,63}$/,kp=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Ft=s=>{throw new h("invalid_package",s)},Cr=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?Ft(`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")?Cr(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&_o.test(a)?a:Ft("Invalid secret name")}):[],r=e.network,n=t.has("network")?Cr(r?.hosts,"network").map(c=>typeof c=="string"&&kp.test(c)?c:Ft("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Cr(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!_o.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<bp||a.intervalSec>86400?Ft("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&Ft("Duplicate schedule id"),{secrets:i,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as Pp}from"node:dns/promises";import{isIP as Ip}from"node:net";var Sp=new Set(["GET","POST","PATCH","PUT","DELETE"]),Ep=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),xp=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),_i=(s,e)=>{throw new h("network_denied",s,{status:403,reason:e})};function _p(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if(Ip(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 Ao(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")&&_i("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||_i("Host is not declared by the plugin","host");let c=(n.method??"GET").toUpperCase();if(!Sp.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"||Ep.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)||_i("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 Pp(E,{all:!0})).map(_=>_.address)))(o.hostname);(!p.length||p.some(_p))&&_i("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,_)=>{xp.has(_.toLowerCase())&&(P[_.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:m.status,headers:P,body:k}}var Ai=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new h("invalid_input",`Invalid ${t}`);return s};async function To(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:Ai(o.title,200,"title"),prompt:Ai(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=Ai(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,Ai(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 Ap=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),Ti=class{options;constructor(e){this.options=e}handles(e){return Ap.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 Ao(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 To(this.options.sessions,e,i.scope.cwd,r,n,this.options.maxActiveSessions??3)}};var Ri=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 Wr,timingSafeEqual as Xp}from"node:crypto";import{lstat as Vo,mkdtemp as jr,readdir as Yp,readFile as Qp,realpath as Zp,rename as eu,rm as ze,writeFile as tu}from"node:fs/promises";import{tmpdir as iu}from"node:os";import{join as L}from"node:path";import{gunzipSync as Op}from"node:zlib";import{mkdir as Mp,writeFile as jp}from"node:fs/promises";import{dirname as Wp,join as $p}from"node:path";import{constants as Dr}from"node:fs";import{lstat as Do,open as Tp,readdir as Ro,realpath as No}from"node:fs/promises";import{createHash as Rp}from"node:crypto";import{join as Ho,relative as Cp,resolve as Dp,sep as Np}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},Hp={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"]},U=s=>Rp("sha256").update(s).digest("hex");function F(s){throw new h("invalid_package",s)}async function tt(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=Ho(r,i[c]);let a=await Do(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 No(r);(n!==Dp(s,e)||Cp(s,n).startsWith(`..${Np}`))&&F("Resource escapes package root");let o=await Tp(r,Dr.O_RDONLY|Dr.O_NONBLOCK|(Dr.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 Co(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return F("Invalid package JSON")}}async function it(s,e){let t=await No(s);(await Do(s)).isSymbolicLink()&&F("Package root cannot be a symlink");let i=Co(await tt(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 Ro(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=Co(await tt(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};(!Ye(`./${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);Hp[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 tt(t,m.path,w);(k.length!==m.bytes||U(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 Ro(Ho(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=U(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 Oo(s,e,t){if(t!==s.digest||e.length>1536)return null;let i;try{i=decodeURIComponent(e)}catch{return null}if(!Ye(`./${i}`))return null;let r=s.resources.get(i);if(!r||i===s.manifest.backend.entry.slice(2))return null;let n=await tt(s.root,i,r.bytes);if(n.length!==r.bytes||U(n)!==r.sha256)throw new h("resource_changed","Installed resource integrity mismatch");return{bytes:n,mime:r.mime}}var Ci=64*1024*1024,Vp=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 Mo(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 Fp(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 Bp(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 Up(s){if(!s.length||s.length>Ci)return V("Compressed archive exceeds budget");let e;try{e=Op(s,{maxOutputLength:Vp})}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(Mo(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=Mo(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=Bp(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=Fp(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 Nr(s,e){let t=Up(s);for(let i of t){if(!i.path)continue;let r=$p(e,i.path);await Mp(i.directory?r:Wp(r),{recursive:!0,mode:448}),i.directory||await jp(r,i.data,{flag:"wx",mode:384})}}import{lstat as Lp,mkdir as zp,readdir as qp,realpath as Gp,writeFile as Jp}from"node:fs/promises";import{dirname as Kp,join as Hr}from"node:path";async function jo(s,e){let t=await Gp(s),i=await tt(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 qp(Hr(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 tt(t,w,K.js);if((c+=k.length)>K.total)throw new h("invalid_package","Resource budget exceeded");let P=Hr(e,w);await zp(Kp(P),{recursive:!0,mode:448}),await Jp(P,k,{flag:"wx",mode:384}),n.push([w,U(k)])}}let l;try{l=await Lp(Hr(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:U(JSON.stringify({package:u,files:n})),packageJson:r}}function be(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=be(s),i=be(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 Wo(s){let e=be(s);if(e)return e;if(!ai(s))return null;let[t,i]=s.split("-alpha."),r=be(t),n=Number(i);return r&&Number.isSafeInteger(n)?{...r,alpha:n}:null}function Or(s){return!!Wo(s)}function bt(s,e){if(!Or(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&&Wo(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 Mr(s,e,t){let i=s.piWebapp;return s.name===e.id&&!!be(s.version)&&!s.deprecated&&Ue(i)&&bt(t,i.hostRange)&&e.requiredCapabilities.every(r=>i.capabilities.includes(r))}function $o(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&&Mr(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 ru(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=Wr("sha512").update(s).digest();if(i.length!==r.length||!Xp(i,r))throw new h("integrity_mismatch","Downloaded package failed integrity verification")}var rt=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Or(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??Xn}async index(){let e=await te(L(this.root,"installed.json"));if(!e){if(await Y(L(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||!be(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${U(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 L(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await ce(L(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(L(this.root,"install-journal.json"))}await this.recoverCollection(e);let i=L(this.root,"staging");await ee(i);for(let r of await Yp(i)){if(!/^stage-[A-Za-z0-9]+$/.test(r)||(await Vo(L(i,r))).isSymbolicLink())throw new h("invalid_storage","Invalid abandoned staging directory");await ze(L(i,r),{recursive:!0})}return e}async recoverCollection(e){let t=L(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 ee(L(this.root,"versions")),await ee(L(this.root,"versions",U(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 ee(L(this.root,"versions")),await ee(L(this.root,"versions",U(e))),await j(L(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(L(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&&!be(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 $o(c,n,this.hostVersion,t,i)}async install(e,t,i){let r=me(e,this.catalog);if(!Mr(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),Ci,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(!be(r))throw new h("invalid_version","Choose an exact stable version");if(t.length>Ci)throw new h("download_too_large","Package archive exceeds budget");return ru(t,i),W(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await jr(L(this.root,"staging","stage-"));try{await Nr(t,a),n?.throwIfAborted();let l=await it(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:`${U(e)}/${r.version}-${r.digest}`,installedAt:new Date().toISOString()};if(await ee(L(this.root,"versions",U(e))),!c&&(t.versions[e]?.length??0)>=16)throw new h("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await j(L(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await Vo(l),p=!0}catch(u){if(!Ve(u))throw u}if(p){if((await it(l,e)).digest!==r.digest)throw new h("resource_changed","Installed package content was modified")}else await eu(i,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await j(L(this.root,"installed.json"),t)),await ze(L(this.root,"install-journal.json")),{...r,root:await Zp(l)}}async installDevArchive(e,t,i){me(e,this.catalog);let r=await Qp(t),n="sha512-"+Wr("sha512").update(r).digest("base64"),o=await jr(L(iu(),"pi-dev-archive-"));try{await Nr(r,o);let c=(await it(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 jr(L(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await jo(t,o);i?.throwIfAborted();let l=L(this.root,"dev-sources.json"),p=await te(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 it(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"?be(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=>be(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 tu(L(o,"package.json"),JSON.stringify({...a,version:P},null,2),{flag:"wx",mode:384});let E=await it(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-"+Wr("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 it(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 Di,mkdir as su,open as Fo,realpath as Bo,readdir as $r,link as nu,rename as ou,unlink as st,copyFile as au,rm as cu}from"node:fs/promises";import{dirname as lu,isAbsolute as Uo,join as O,relative as Lo,resolve as du,sep as Vr,win32 as pu}from"node:path";import{randomUUID as Fr}from"node:crypto";var Bt=192*1024*1024,Ut=512*1024,qo=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function uu(s){if(!s||typeof s!="object"||Array.isArray(s))throw new h("invalid_input","Expected object input");return s}function zo(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new h("invalid_input","Invalid state key");return s}function Lt(s){if(s&&(!qo(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 nt=class{root;pluginId;legacy;checkpoint;constructor(e,t,i,r){this.root=O(e,U(t)),this.pluginId=t,this.legacy=i,this.checkpoint=r}active(){return te(O(this.root,"active.json")).then(Lt)}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");Lt(t.next),Lt(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 st(O(this.root,"fork.json"))}return await st(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=Lt({...t,generation:e+1,operationId:Fr()});await ee(O(this.root,"states")),await ee(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 st(O(this.root,"transition.json")),await st(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=Fr(),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 ee(r);let n=O(this.root,"states",t.stateRef);for(let o of await $r(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await Y(O(n,o),Bt))throw new h("invalid_storage","Missing state file");await au(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 Y(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=Lt(await ce(O(this.root,"previous.json")));if(!t&&await Y(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 ee(n);let o=await $r(n),c=new Set(r.map(l=>l.stateRef));for(let l of o){if(!qo(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(n,l),u=await Di(p);if(!u.isDirectory()||u.isSymbolicLink())throw new h("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let y of await $r(p)){let m=await Di(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 te(O(p,y),Bt);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 cu(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,`${U(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=uu(i);return W(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await te(this.statePath(n,e,zo(r.key),r.scope),Bt);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(n,e,zo(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)>Bt)throw new h("state_too_large","Plugin state exceeds limit");let a=await te(o,Bt);a&&this.validateState(a);let l=U(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?Ut:r.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>Ut)throw new h("invalid_input","Invalid workspace read limit");let a=await Y(o,c);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash:U(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")||Uo(t)||pu.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let r=await Bo(e),n=du(r,t),o=Lo(r,n);if(!o||o===".."||o.startsWith(`..${Vr}`)||Uo(o))throw new h("invalid_path","Workspace path escapes root");let c=r,a=o.split(Vr);for(let p=0;p<a.length;p++){c=O(c,a[p]);let u;try{u=await Di(c)}catch(y){if(!Ve(y))throw y;if(p<a.length-1){if(!i||Lo(r,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await su(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Di(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 Bo(lu(n));if(l!==r&&!l.startsWith(r+Vr))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)>Ut||!(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,`${U(this.scopeKey(t)+":file:"+t.requestId+":"+String(i.path))}.json`),c=U(JSON.stringify(i)),a=U(i.text),l=await te(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 Fo(`${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 Y(r,Ut),m=y?U(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-${Fr()}.tmp`);let f=await Fo(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 Y(r,Ut);if((k?U(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 nu(u,r)}catch(P){throw P.code==="EEXIST"?new h("file_conflict","Workspace file was created concurrently"):P}await st(u),u=void 0}else await ou(u,r),u=void 0;return await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await st(u).catch(()=>{}),await p.close(),await st(`${r}.lock`)}}};import{randomUUID as wu}from"node:crypto";import{fork as hu}from"node:child_process";import{randomUUID as fu}from"node:crypto";import{join as gu}from"node:path";import{EventEmitter as mu}from"node:events";var Go=192*1024*1024,zt=class s{child;pending=new Map;events=new mu;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=hu(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:gu(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>Go){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:X(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??fu();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))>Go?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 yu={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ni=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,i=yu,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 br(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 zt.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):wu(),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,t=!1){return this.serialize(async()=>{let i=this.worker,r=this.phaseValue,n=await this.broker.active(),o=async()=>{if(!(!i||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(n))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 zt.start(i.package,i.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{let a=async l=>{try{await l()}catch(p){if(!t)throw p}};await a(async()=>{if(i&&!await i.waitForIdle(e))throw new h("drain_pending","Plugin work is still draining; current host retained")}),await a(()=>this.hooks.freeze()),await a(async()=>{if(i&&!await i.waitForIdle(e))throw new h("drain_pending","Checkpoint work is still draining; current host retained")}),await i?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(a){try{await o(),this.phaseValue=r,await this.hooks.resume()}catch(l){throw this.phaseValue="failed",l}throw a}let c=!1;return()=>this.serialize(async()=>{c||(await o(),this.phaseValue=r,await this.hooks.resume(),c=!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 Jo}from"node:fs/promises";var Hi=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 rt({root:ke(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new Ti(e.capabilities):void 0;this.scheduler=new Ri({invoke:async(i,r)=>{let n=this.closing?null:e.scheduledScope?.(i)??null;n&&await this.supervisor(i).invoke({requestId:bu(),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 nt(ke(e.root,"data"),i.id,e.legacy?.(i.id)),n=e.hooks(i.id);this.supervisors.set(i.id,new Ni(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,vu(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,X(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 $t(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,X(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 te(ke(this.options.root,"policies","policies.json"));if(!e){if(await Y(ke(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 te(ke(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await W(ke(this.options.root,"policies"),async()=>{let i=await this.diagnostics();i[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await j(ke(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:X(n).code,message:X(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 $t(this.options.root),await W(ke(this.options.root,"policies"),async()=>{let i=await this.policies();i[e]={updatePolicy:"notify"},await j(ke(this.options.root,"policies","policies.json"),i)})})}async start(){await W(Ee(this.options.root),()=>this.startLocked())}async startLocked(){await W(ke(this.options.root,"policies"),async()=>{let n=await this.policies();await j(ke(this.options.root,"policies","policies.json"),n)});let e=await Oe(this.options.root),t=bi(e),i=!0;if(t&&e){try{if(e.version!==this.options.hostVersion||e.hostDigest!==await et(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await et(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Jo(this.options.workerEntry)).equals(await Jo(ke(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(n){let o=`Selected host not running; current host and plugins retained. ${X(n).message}; data retained`;await Te(this.options.root,{...e,phase:"required-action",message:o}),t=!1}if(t)try{await this.validatePairPackages(e.version,e.selections)}catch{i=!1}}await this.installer.inventory();let r=ie(await this.pairSnapshot());for(let n of this.installer.catalog){let o=this.supervisor(n.id),c=await o.broker.active();if(c?.enabled)try{let a=t&&i?e?.selections.find(u=>u.id===n.id):void 0,l=a&&ie(c)===ie(a.before)&&e?.fingerprint===r,p=await this.installer.load(n.id,l?a.version:c.version);if(l&&p.digest!==a.digest)throw new Error("Staged plugin digest changed");await this.lifecycle(n.id,()=>o.replace(p)),this.packages.set(n.id,p),bi(e)||await this.collectSettled(n.id)}catch(a){let l=X(a),p=["runtime_owned","storage_busy"].includes(l.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(n.id,{...l,message:`Plugin unavailable: startup failed (${l.code}): ${l.message}; data retained. ${p}`})}}t&&e&&(await Te(this.options.root,{...e,phase:"reconciled",message:this.errors.size?`Host admitted; unavailable plugins retained with their data: ${[...this.errors].map(([n,o])=>`${n}: ${o.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=X(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 Oo(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)||!ku(n,Buffer.from(r))?null:this.asset(i,t[3],t[4])}async reconcileHostUpgrade(){if(Pr(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(X(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=X(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 po(this.options.root,(e,t)=>this.prepareHostPair(e,t),()=>this.pairSnapshot(),(e,t)=>this.validatePairPackages(e,t))}async validatePairPackages(e,t){let i=new rt({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 rt({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=null;try{u=await i.load(c.id,l?.enabled?l.version:p)}catch(y){let m=X(y);if(m.code==="incompatible_plugin")try{let f=await i.check(c.id,p,void 0,t);u=f.version===p?await i.load(c.id,p):await i.install(c.id,f,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(f){t?.throwIfAborted();let w=X(f);p!==l?.version&&(u=await i.load(c.id,p).catch(()=>null)),u||await this.recordCheck(c.id,{status:"failed",code:w.code,message:`${w.message}; plugin will be unavailable after the software update until a compatible release is installed`})}else await this.recordCheck(c.id,{status:"failed",code:m.code,message:`${m.message}; plugin will be unavailable after the software update`})}u&&o.push({id:c.id,version:u.version,digest:u.digest,before:l})}return o}async validateHostUpdate(e){let t=new rt({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}: ${X(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(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],i=async()=>{let r=await Promise.allSettled(t.map(o=>o()));this.closing=!1;let n=r.find(o=>o.status==="rejected");if(n?.status==="rejected")throw n.reason};try{for(let r of this.supervisors.values())t.push(await r.suspendForRestart(void 0,e));return i}catch(r){throw await i(),r}}};import{randomUUID as Pu}from"node:crypto";var D=s=>Object.assign(new Error(s),{status:409,code:"view_barrier"}),qt=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;staleMs;constructor(e,t,i=2e4,r=15e3,n=12e4){this.pluginId=e,this.generation=t,this.pollMs=i,this.freezeMs=r,this.staleMs=n}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??Pu();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:[],seenAt:Date.now()}),{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==="status"){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{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let o=!i.waiter&&Date.now()-i.seenAt>this.staleMs;return{viewToken:i.token,commands:[],recovery:{...this.recovery(i,this.switching||i.activeActions?"active":"unconfirmed"),stale:o}}}if(i&&this.sameScope(i,e,t)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(i.seenAt=Date.now()),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 Iu="@chengzhiyi/pi-excalidraw",Su={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"}}},Eu="@chengzhiyi/pi-github",xu={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"}}},Ko=new Map([[Iu,Su],[Eu,xu]]);function Br(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 _u}from"node:crypto";var Au="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"}),Tu="Ov23limJmKiuu8cOP83E";function Ur(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||Tu,scope:"repo",createUrl:Au}}var Ru="https://github.com/login/device/code",Cu="https://github.com/login/oauth/access_token",Du=8,Oi=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>=Du)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let r=await this.post(Ru,{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=_u();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(Cu,{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 Yo,readFileSync as Qo,statSync as Nu}from"node:fs";import{lstat as Hu,readdir as Ou,writeFile as Mu,mkdir as ju,rename as Wu}from"node:fs/promises";import{delimiter as $u,dirname as Vu,isAbsolute as Fu,join as ot,resolve as Gt}from"node:path";var Xo="@chengzhiyi/pi-github",Wi={[Xo]:{id:Xo,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"]}},Zo=()=>Object.keys(Wi).join(", ");function Bu(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=Wi[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?Yo(Gt(a))?null:`archive not found: ${Gt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Zo()})`;if(p){i.push({level:"error",source:r,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,Gt(a))}return{catalog:e,archives:t,notices:i}}var ea=s=>ot(s,"pi-web","hosted-dev.json"),ta=s=>ot(s,"pi-web","hosted-dev-status.json");function Uu(s,e,t=process.cwd()){let i=[],r=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split($u).map(c=>c.trim()).filter(Boolean);for(let c of n)i.push({path:Gt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&Yo(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"||!Fu(l)?r.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):i.push({path:Gt(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 Lu(s){let e=(r,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${r}`}}),t;try{t=Nu(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(ot(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"):Wi[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: ${Zo()})`)}var Mi=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=Bu(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=Uu(this.env,this.configPath,this.cwd),i=[],r=new Map,n=new Map;for(let o of t.specs){let c=Lu(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(Wi[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]}},ji=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: ${X(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 zu(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=X(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 ju(Vu(i),{recursive:!0}),await Mu(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await Wu(o,i)}catch{}}};async function zu(s){let e=[],t=async(i,r)=>{let n=await Hu(i);e.push(`${r}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(ot(s,"package.json"),"package.json");let i=async(r,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await Ou(r,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await i(ot(r,c.name),`${n}/${c.name}`,o+1):await t(ot(r,c.name),`${n}/${c.name}`)};if(await i(ot(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 Ju(s){try{return[...yt(s).secrets]}catch{return[]}}var Vi=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Oi;restartPreparation;restartResume;closing=!1;started=!1;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Ko,e.dev?.enabled&&(this.devWatcher=new ji({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 xi({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 Hi({...e,lifecycle:(t,i,r)=>this.lifecycle(t,i,r),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:i=>{if(i.length!==Object.keys(Br(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:Ju(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)?Ur(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=Br(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 nt($i(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 nt($i(this.options.root,"data"),e.id).active();this.views.set(e.id,new qt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new qt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=$i(this.options.root,"host-version.json");(await te(e))?.version!==this.options.hostVersion&&(this.manager.pairAdmitted?!(await this.manager.inventory()).plugins.some(i=>i.updateDiagnostic?.status==="failed"):await this.manager.reconcileHostUpgrade())&&(await ee(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 Gu($i(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=Ur(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:qu(),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(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let n of this.views.values())n.allowImmediateReopen(!0);let t=await this.manager.suspendForRestart(e),i=!1,r=async()=>{if(!i)try{await t(),i=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=r,r}catch(t){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),t}finally{for(let t of this.views.values())t.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 Ku,readdir as Xu,unlink as Yu}from"node:fs/promises";import{join as kt}from"node:path";import{randomUUID as Qu}from"node:crypto";var Lr="hosted-migration.json";function ia(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:i,sessionId:r}=t.scope,n=kt(s,U(JSON.stringify([i,r])));await ee(s),await ee(n);let o=kt(n,"scope.lock"),c;try{c=await Ku(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:Qu()}));let a=await te(kt(n,Lr));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Xu(n),p=[];for(let y of l){if(y==="scope.lock"||y==="focus.json"||y===Lr||/^[\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 te(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 te(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,Lr),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Yu(o)}}}import{join as ah}from"node:path";import{randomUUID as Zu}from"node:crypto";var eh=6e4,Fi=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<eh?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:Zu(),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 th,readFile as ih,rename as rh,writeFile as sh}from"node:fs/promises";import{randomUUID as nh,createHash as oh}from"node:crypto";import{join as ra}from"node:path";var Bi=class{dir;queue=Promise.resolve();constructor(e){this.dir=ra(e,"secrets")}file=e=>ra(this.dir,`${oh("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await ih(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 th(this.dir,{recursive:!0,mode:448});let r=`${this.file(e)}.${nh()}.tmp`;await sh(r,JSON.stringify(i),{mode:384}),await rh(r,this.file(e))})}};function sa(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 ch="scheduler";function na(s){let e=new Fi({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 Bi(ah(s.root,"capability-secrets")),sessions:sa(i,(r,n)=>e.authorize(r,n))},scheduledScope:()=>{let r=s.activeWorkspace();if(!r)return null;try{return s.trustedScope(r,ch)}catch{return null}}}}async function lh(){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:Rt,buildId:Se,browser:ni({}).browser}}async function oa(){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:Rt,buildId:Se}}finally{await s.close()}}var Jt=St(ph(fh(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),vh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[vh]??={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()}),re()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Ze,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Ze;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()}),re()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function Ui(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var bh=null;function kh(){return bh??=gh.create({refreshOnCreate:!1})}var Li=new Map;async function It(){let s=await kh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let i of Li.keys())t.has(i)||(s.unregisterProvider(i),Li.delete(i));for(let i of t){let r=e?.getRegisteredNativeProvider(i),n=e?.getRegisteredProviderConfig(i),o=r??n;!o||Li.get(i)===o||(r?s.registerNativeProvider(r):n&&s.registerProvider(i,n),Li.set(i,o))}return await s.refresh({allowNetwork:!1}),s}function se(){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{...Cn(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 Xr(s,e,t,i,r){let n=he(s);We({...je(),idle:n.isIdle()},e,r);let o=n.isIdle();o&&mt(()=>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 Gr(){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)=>Xr(s,i,r,n))}function oe(s){if(se().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function pa(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=se(),r=d.current?je():null,n=await Xe(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=r?await Xe(r.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await Kr.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 ft(p.path,c).catch(m=>(m instanceof Ot?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 ca=0;async function re(){if(!d.bridge)return;let s=++ca;try{let e=await pa();s===ca&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function Jr(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 Xe(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:se()});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:se()})}await re()}async function la(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 Xe(d.current.cwd)===r)return i;if(!(await ft(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:se()})}function ua(){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 mh.create(s,void 0,{projectTrusted:e})}async function ha(){let s=ua(),e=r=>({packages:(r.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:r.extensions??[],skills:r.skills??[]}),t=new da({cwd:se().cwd,agentDir:we(),settingsManager:s}),i=ro(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:i}}async function Ph(s){oe(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=ua();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 da({cwd:se().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 ha()}function zi(s,e=yr){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=zr(a);return{cwd:p,sessionId:l,workspaceId:aa("sha256").update(p).digest("hex")}},i=Pt(we(),"pi-web","hosted"),r=new Mi({configPath:ea(we())});d.hosted??=new Vi({root:i,...r.enabled?{dev:r,devStatusPath:ta(we())}:{},...r.catalog.length?{catalog:[...Me,...r.catalog],devArchives:r.archives,devRoots:r.roots}:{},...na({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(uh(St(Jt,"../../package.json"),"utf8")).version,packageRoot:St(Jt,"../.."),workerEntry:St(Jt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${aa("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:()=>ia(Pt(we(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Gr),d.pi=s,d.tools?.clear(),d.tools=new gt({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:qr,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new ht(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()}),re()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Qe.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 re())}).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),re()}),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,Gr(),le(l),re()}),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:qr});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),re()}),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:Ke(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 Qe.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ui(On(we())),await d.workspaces.load());try{await d.workspaces.discover((await Kr.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&&zr(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"},()=>{re()},[],{adapter:d.hosted.adapter,scope:t}),y&&await d.workspaceSessions.open(y.path,{sessionManager:y.sessionManager});let m={hosted:d.hosted?.handlers,selfUpdate:new Ei({agentDir:we(),packageRoot:St(Jt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,hostedPair:d.hosted.manager.hostPair,beforeRestart:f=>d.hosted.prepareRestart(f)}),snapshot:se,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(zr(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=Ui();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Ui()?.asset(f)??null,async invokePluginAction(f,w,k,P){if(oe(f),!Ui()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,_=d.tuiGeneration,H=d.workspaceSessions?.session,N={requestId:yh(),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(oe(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(oe(f),!Ui()?.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){oe(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 pa()},async addWorkspace(f,w){let k=await d.workspaces.add(f,w);try{await Jr(k.id,!0)}catch(P){throw await re(),P}},async selectWorkspace(f){await Jr(f)},async newSessionInWorkspace(f){await Jr(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 re()},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 Xe(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:se()});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 ft(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:se()})}await re()},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 la(f,w,k),d.current?.sessionManager.getSessionId()===w&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(w,E)||Kr.open(k).appendSessionInfo(E),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===w&&d.bridge?.publish({type:"snapshot",session:se()}),await re()},async deleteSession(f,w,k){let P=await la(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 io(_,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:se()})),await re()},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 gn(Pt(we(),"models.json"),f,w)},async updateProviderModel(f,w,k){if(oe(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=se().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 mn(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(oe(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,ln(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(oe(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 dn(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(oe(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:se()});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(oe(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(oe(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:se()});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||!wh(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:ha,updateConfig:Ph,async send(f,w,k=[],P,E){if(oe(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),Gr();return}if(_.isIdle()&&d.tuiPrompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Xr(f,w,k,P,E)},async updateQueuedPrompt(f,w,k,P){if(oe(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)=>Xr(f,E,_,H,"steer"))},async abort(f){if(oe(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(Nt),w.abort()}},async resume(f,w){if(oe(f),d.selected==="sdk"){await d.workspaceSessions.resume(w);return}let k=he(f);if(mt(()=>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(se().messages),{triggerTurn:!0})}catch(P){throw d.operation=void 0,P}},async newSession(f){if(oe(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 re();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:se()}),await re();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 re()}};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 Rn(m,Jt,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(dh).filter(Boolean))try{u.push(hh(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:qr}),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 Wk=zi;export{Wk as default,lh as verifySentryDisabledRelease,oa as verifySentryNodeRelease};
|
|
46
|
+
`)}`:void 0,t<3&&s.cause instanceof Error&&(i.cause=Gn(s.cause,e,t+1)),st(i)}import{randomUUID as Xn}from"node:crypto";import{randomUUID as hd}from"node:crypto";import{EnvHttpProxyAgent as gd,getGlobalDispatcher as fw,setGlobalDispatcher as hw}from"undici";var Jn=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 md(s,e){let t=Jn(s),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 n=Number(r.port)||(r.protocol==="https:"?443:80),o=r.hostname.toLowerCase();return!i.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 wd(s){let e=Jn(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 gd(e)}function li({env:s=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:r=!1}={}){let i,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 v={requestId:hd(),phase:"headers",proxied:o&&md(s,p)},w=r?void 0:i,h=!1,m=u?.signal??(p instanceof Request?p.signal:void 0),k=()=>I(),I=()=>{m?.removeEventListener("abort",k),!h&&r&&(h=!0,a(w).catch(()=>{}))},E;try{o?(w??=wd(s),n.add(w),r||(i=w),E=await t(p,{...u,dispatcher:w})):E=await t(p,u)}catch(T){throw c(T,v),I(),T}if(E.ok||c(void 0,{...v,status:E.status}),!E.body)return I(),E;let A=E.body.getReader();m?.addEventListener("abort",k,{once:!0}),m?.aborted&&I();let O=new ReadableStream({async pull(T){try{let Y=await A.read();Y.done?(T.close(),A.releaseLock(),I()):T.enqueue(Y.value)}catch(Y){c(Y,{...v,phase:"body"}),T.error(Y),A.releaseLock(),I()}},async cancel(T){try{await A.cancel(T)}finally{A.releaseLock(),I()}}}),H=new Response(O,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(H,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),H},close:async()=>{await Promise.all([...n].map(a))}}}var Kn=(s,e)=>li({autoClose:!0}).fetch(s,e);var yd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),vd=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 di(s,e={}){let t=[],r=new Set,i=(a,l=0)=>{if(!a||l>4||r.has(a)||t.length>=8)return;r.add(a);let p=vd(a.code);if(t.push({name:yd.has(a.name)?a.name:"Error",...p?{code:p}:{}}),i(a.cause,l+1),a instanceof AggregateError)for(let u of a.errors.slice(0,4))i(u,l+1)};i(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:Xn(),requestId:c(e.requestId)??Xn(),...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 Yn({env:s=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return li({env:s,fetchRequest:t,onFailure:(r,i)=>e(di(r,{...i,stage:i.phase==="body"?"model_stream":"model_headers"}))})}function bd(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 kd=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Qn(s,e,t=()=>{}){let r=s.agent.streamFunction;s.agent.streamFunction=async(i,n,o)=>{if(!kd.has(i.api))return r(i,n,o);let c=t(),a=Yn({env:bd(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 r(i,n,{...o,fetch:a.fetch});return l.result().finally(()=>a.close()).catch(()=>{}),l}catch(l){throw await a.close(),l}}}function dt(s,e,t){try{s()}catch(r){let i=di(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(n=>n.code?[n.code]:[]).join(",")})}catch{}throw r}}var _d=["read","grep","find","ls"],Zn=200,ur=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Ke;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,r=()=>!1,i=()=>{},n={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},c=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=r,this.reportError=i,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 r=await xe(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 n;if(t==="new")n=Nt.create(r);else if(t==="continue"){let c=(await ct(r))[0];n=c?Nt.open(c.path):Nt.create(r)}else n="sessionManager"in t?t.sessionManager:Nt.open(t.sessionFile);if(await xd(n.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(n.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,n,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await xe(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:r,prompts:i}=e,n=t.sessionManager.getBranch(),o=n.flatMap(c=>{let a=Tt(c);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:r,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!i.sending,name:or(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=>Tt(t)?.role==="user")}rename(e,t){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.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 r=this.active===t,i=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),r&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:i,cwd:t.cwd,wasActive:r}})}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 n=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${i}`;console.error(n),this.publishFor(e,{type:"error",message:n})}async replace(e,t,r,i){let n=this.runtimes.get(t.getSessionId()),o=await Je.discover(e,this.isProjectTrusted(e)),c=Id(),a=await Ln(e,o.extensionRoots),l=new Sd({cwd:e,agentDir:Ed(),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 v=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:w}=await Pd({cwd:e,sessionManager:t,model:v,resourceLoader:l,customTools:this.customTools}),h=new lt({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(b,y)=>this.telemetry.breadcrumb(b,y),anonymize:b=>this.telemetry.anonymize(b)}),m={session:w,cwd:e,catalog:o,bus:c,generation:++this.generation,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:h,streaming:null,prompts:null,detached:i?{owner:i,events:[],seq:0,lastText:"",restoreTools:null}:void 0};m.prompts=n?.prompts??new Oe(()=>{let b=this.runtimes.get(t.getSessionId())??m;this.publishFor(b,{type:"snapshot",session:this.snapshotOf(b)}),!this.disposed&&!b.closing&&this.onSessionsChanged()}),p=m,Qn(w,b=>{m.networkDiagnostic=b},()=>m.operation?.operationId);let k=b=>this.publishFor(m,b),I=m.detached,E=(b,y)=>{I&&(I.events.push({seq:++I.seq,type:b,...y===void 0?{}:{text:y}}),I.events.length>Zn&&I.events.splice(0,I.events.length-Zn))};m.interactions=new at(c,b=>!m.closing&&b.sessionId===w.sessionManager.getSessionId()&&o.has(b.pluginId),()=>k({type:"snapshot",session:this.snapshotOf(m)}));let A=0,O=c.on(cr,()=>k({type:"snapshot",session:this.snapshotOf(m)})),H=w.subscribe(b=>{if(I&&!m.closing&&(b.type==="message_end"&&b.message.role==="assistant"&&(b.message.stopReason==="error"?E("error",b.message.errorMessage??"Agent response failed"):I.lastText=b.message.content.flatMap(y=>y.type==="text"?[y.text]:[]).join(`
|
|
47
|
+
`)),b.type==="agent_settled"&&E("turn_end",I.lastText)),!this.disposed&&!m.closing){let y={...m.operation,session:this.telemetry.anonymize(w.sessionManager.getSessionId()),piVersion:pr,model:w.model?`${w.model.provider}/${w.model.id}`:null,thinkingLevel:w.thinkingLevel};if(b.type==="agent_start"&&this.telemetry.breadcrumb("agent_start",y),b.type==="tool_execution_start"&&h.start(b,y),b.type==="tool_execution_end"&&h.end(b,y),b.type==="message_end"&&b.message.role==="assistant"&&b.message.stopReason==="error"){m.agentErrorReported=!0;let j=m.networkDiagnostic,me=this.reportError(new Error("Agent response failed"),{...m.operation,stage:"agent",code:"agent_failed",piVersion:pr,...j?{networkKind:j.kind,networkStage:j.stage,causeCodes:j.causes.flatMap(we=>we.code?[we.code]:[]).join(","),requestId:j.requestId}:{}})??j?.errorId;k({type:"error",message:b.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:me,...m.operation})}b.type==="message_end"&&b.message.role==="toolResult"&&h.message(b.message,y),b.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",y),h.clear(),m.operation=void 0)}b.type==="message_update"&&b.message.role==="assistant"&&(m.streaming={id:"stream",role:"assistant",timestamp:new Date(b.message.timestamp).toISOString(),blocks:ze(b.message.content)},Date.now()-A>=60&&(A=Date.now(),k({type:"stream",message:m.streaming}))),b.type==="agent_settled"&&this.scheduleQueued(m),["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")&&(m.streaming=null,k({type:"stream",message:null})),k({type:"snapshot",session:this.snapshotOf(m)}),!this.disposed&&!m.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(b.type)&&this.onSessionsChanged())});m.detach=()=>{O(),H()},m.releaseHosted=this.hosted?.adapter.attach(w);let T=[],Y=!0;if(await w.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Y&&T.push(b.error),this.diagnostic(m,o.plugins.find(y=>b.extensionPath.startsWith(y.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,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");m.detached&&(m.detached.restoreTools=w.getActiveToolNames(),w.setActiveToolsByName(_d)),this.runtimes.set(w.sessionManager.getSessionId(),m),p=null,m.detached?this.onSessionsChanged():this.activate(m)}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 Bn(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,n=t.sessionManager.getBranch().flatMap(o=>{let c=Tt(o);return c?[c]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:or(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:ot(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:ri(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 lr(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 n=this.active;if(De(this.snapshot(),e,i),i==="followUp"&&(!n.session.isIdle||n.prompts.length>0)){n.prompts.enqueue(e,t,r),this.scheduleQueued(n);return}if(n.session.isIdle&&n.prompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(n,e,t,r,i)}async prompt(e,t,r,i,n){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),i,this.reportError),De({...this.snapshotOf(e),idle:e.session.isIdle},t,n);let o=e.session,c=o.isIdle;c&&(e.operation=i,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...i,piVersion:pr});let a=!1,l,p,u=new Promise((v,w)=>{l=v,p=w});o.prompt(t,{images:r,streamingBehavior:n,preflightResult:v=>{v&&(a=!0,l())}}).then(()=>{a||l()}).catch(v=>{if(!a)p(v);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let w=this.reportError(Ae(v,"Agent response failed"),{...i,stage:"agent",code:"agent_failed",piVersion:pr});this.publishFor(e,{type:"error",message:v instanceof Error?v.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:w,...i})}});try{await u}catch(v){throw c&&(e.operation=void 0),v}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!ot(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 oe("\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,(n,o,c)=>this.prompt(i,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(At),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(!ot(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(!ot(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let n=dr(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(n,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let c=this.reportError(Ae(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 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)})}createDetached(e,t,r){return this.queue.run(async()=>{this.ensureAvailable();let i=await xe(e),n=Nt.create(i);return await this.replace(i,n,"new",t),this.runtimes.get(n.getSessionId()).session.setSessionName(r),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,r){let i=this.detachedRuntime(e);if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&i.detached.restoreTools&&(i.session.setActiveToolsByName(i.detached.restoreTools),i.detached.restoreTools=null),!i.session.isIdle||i.prompts.length>0){i.prompts.enqueue(t,[],void 0),this.scheduleQueued(i);return}await this.prompt(i,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 r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(i=>i.seq>t),next:r.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 Ad,mkdir as Td,rename as Rd,unlink as Cd}from"node:fs/promises";import{basename as Nd,join as eo}from"node:path";var Dd=s=>eo(s,"pi-web","trash");async function to(s,e){let t=Dd(e);await Td(t,{recursive:!0});let r=eo(t,`${Date.now()}_${Nd(s)}`);try{await Rd(s,r)}catch(i){let n=i.code;if(n==="ENOENT")return null;if(n!=="EXDEV")throw i;await Ad(s,r),await Cd(s)}return r}import{basename as pi,dirname as Od}from"node:path";function ro(s,e){let t=r=>e[r].map(i=>({name:r==="skills"&&pi(i.path).toLowerCase()==="skill.md"?pi(Od(i.path)):pi(i.path),path:i.path,source:i.metadata.source,scope:i.metadata.scope,enabled:i.enabled}));return{packages:s.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 Hd}from"node:child_process";var Md=(s,e)=>new Promise((t,r)=>{Hd(s,[...e],{windowsHide:!0},i=>{i?r(i):t()})});async function ui(s,e=process.platform,t=process.env,r=Md){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,[s]),!0)}import{execFile as Ep}from"node:child_process";import{randomUUID as Ri}from"node:crypto";import{existsSync as Ao}from"node:fs";import{access as xp,mkdir as Ht,mkdtemp as _p,readFile as Ve,realpath as Ap,rename as To,rm as Ro,writeFile as Co}from"node:fs/promises";import{join as q}from"node:path";import{createHash as gi}from"node:crypto";import{readdir as Ld,realpath as co,rename as zd,stat as qd}from"node:fs/promises";import{join as $e}from"node:path";import{constants as fi}from"node:fs";import{DatabaseSync as jd}from"node:sqlite";import{lstat as no,mkdir as Wd,open as Dt,rename as $d,unlink as oo}from"node:fs/promises";import{dirname as Vd,join as io,resolve as Fd}from"node:path";import{randomUUID as Ud}from"node:crypto";import{setTimeout as Bd}from"node:timers/promises";async function Z(s){await Wd(s,{recursive:!0,mode:448});let e=await no(s);if(!e.isDirectory()||e.isSymbolicLink())throw new f("invalid_storage","Plugin storage must be a real directory")}async function X(s,e){let t;try{t=await Dt(s,fi.O_RDONLY|fi.O_NONBLOCK|(fi.O_NOFOLLOW??0))}catch(r){if(He(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new f("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(r.size+1,e+1)),n=0;for(;n<i.length;){let o=await t.read(i,n,i.length-n,n);if(!o.bytesRead)break;n+=o.bytesRead}if(n>e||n!==r.size)throw new f("invalid_storage","Storage record changed during read");return i.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 f("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function fe(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 f("gc_recovery_required",`Invalid journal ${s}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new f("gc_recovery_required",`Invalid journal ${s}; original bytes preserved`);return t}async function M(s,e){let t=`${s}.${Ud()}.tmp`,r=await Dt(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await $d(t,s);let i;try{i=await Dt(Vd(s),"r"),await i.sync()}catch(n){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(n.code??""))throw n}finally{await i?.close()}}finally{await oo(t).catch(()=>{})}}var ao='{"version":2,"mechanism":"sqlite-exclusive"}',so=s=>s.toString("utf8")===ao,fr=new Set;async function hi(s,e,t=0){await Z(s);let r=io(s,`${e}.lock`),i=io(s,`${e}.ownership.sqlite`),n=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new f(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 Dt(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let a=await no(i);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new f("invalid_storage","Ownership database must be a small, single-link regular file");let l=new jd(i,{allowExtension:!1}),p=Fd(i),u=Date.now()+t,v=!1;try{for(;;){if(!fr.has(p))try{l.exec("BEGIN EXCLUSIVE"),fr.add(p),v=!0;break}catch(m){if(m.errcode!==5)throw m}if(Date.now()>=u)throw new f(n,"Another host owns this plugin storage; wait for it to stop before retrying");await Bd(10)}let h=await X(r,4096);if(h===null){let m;try{m=await Dt(r,"wx",384),await m.writeFile(ao),await m.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await m?.close()}h=await X(r,4096)}if(h===null||!so(h))throw o()}catch(h){throw l.close(),v&&fr.delete(p),h}let w=!1;return async()=>{if(w)return;let h=await X(r,4096);if(h===null||!so(h))throw new f("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await oo(r),l.close(),fr.delete(p),w=!0}}async function te(s,e,t=2e3){let r=await hi(s,"transaction",t);try{return await e()}finally{await r()}}var hr=s=>$e(s,"host-pair"),Gd=s=>gi("sha256").update(JSON.stringify(s)).digest("hex"),Jd=10*6e4;async function Kd(s){let e=gi("sha256"),t=0,r=0;async function i(n){let o=(await Ld($e(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 f("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new f("host_pair_required","Candidate package resource budget exceeded");if(c.isDirectory()){await i(a);continue}let l=await X($e(s,a),64*1024*1024);if(!l||(r+=l.length)>256*1024*1024)throw new f("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,gi("sha256").update(l).digest("hex")]))}}return await i(""),e.digest("hex")}async function mi(s,e){let t=await co(e),r=$e(e,"dist","hosted-worker.js");if(await co(r)!==$e(t,"dist","hosted-worker.js"))throw new f("host_pair_required","Candidate worker must remain inside the staged host");let i=await X($e(e,"package.json"),512*1024);if(!i)throw new f("host_pair_required","Candidate package metadata missing");let n=JSON.parse(i.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 f("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(r,32*1024*1024);if(!c)throw new f("host_pair_required","Candidate worker missing");return Gd([i.toString("base64"),c.toString("base64"),await Kd(e)])}async function gr(s){await zd(s,`${s}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Xd=s=>s.schema===1&&/^[a-f0-9-]{36}$/.test(s.id)&&typeof s.version=="string"&&typeof s.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(s.hostDigest)&&/^[a-f0-9]{64}$/.test(s.fingerprint)&&Array.isArray(s.selections)&&!s.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(s.selection&&(typeof s.selection.path!="string"||!/^[a-f0-9]{64}$/.test(s.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(s.phase);async function wi(s){let e=$e(hr(s),"intent.json"),t,r=!0;try{t=await fe(e)}catch{t=null,r=!1}if(!r||t&&!Xd(t))return await gr(e),null;if(t){let{lifecyclePhase:i,...n}=t,o=typeof n.updatedAt=="string"&&!Number.isNaN(Date.parse(n.updatedAt))?n.updatedAt:await qd(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());t={...n,updatedAt:o,phase:n.phase==="selected"&&i==="restart-requested"?"restart-requested":n.phase==="reconciled"&&i==="cancelled"?"cancelled":n.phase==="reconciled"&&i==="required-action"?"required-action":n.phase}}return t}async function mr(s,e){let{lifecyclePhase:t,...r}={...e,selections:[],updatedAt:new Date().toISOString()},i=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await M($e(hr(s),"intent.json"),i)}var yi=s=>s&&["selecting","selected","restart-requested"].includes(s.phase),lo=(s,e=Date.now())=>!!s&&!!yi(s)&&e-Date.parse(s.updatedAt??"")<Jd;import{promisify as Tp}from"node:util";import{realpathSync as fo,statSync as Yd}from"node:fs";import{basename as Qd,delimiter as Zd,dirname as po,join as vi,resolve as ep}from"node:path";function uo(s){if(!s)return null;try{let e=fo(s);return Qd(e)==="npm-cli.js"&&Yd(e).isFile()?e:null}catch{return null}}function tp({execPath:s=process.execPath,env:e=process.env}={}){let t=uo(e.npm_execpath);if(t)return t;let r=new Set([po(s)]);try{r.add(po(fo(s)))}catch{}let i=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of i.split(Zd).filter(Boolean))r.add(ep(n));for(let n of r)for(let o of[vi(n,"node_modules","npm","bin","npm-cli.js"),vi(n,"..","lib","node_modules","npm","bin","npm-cli.js"),vi(n,"npm")]){let c=uo(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 ho(s){return{file:process.execPath,args:[tp(),...s]}}import{randomUUID as rp}from"node:crypto";import{mkdir as wo,readFile as ip,rename as ki,rm as sp,unlink as gy,writeFile as np}from"node:fs/promises";import{isAbsolute as go,join as Ot}from"node:path";var Pi=1,op=1440*6e4,wr=s=>Ot(s,"pi-web","upgrade"),Ii=s=>Ot(wr(s),"candidate.json"),ap=s=>Ot(wr(s),"transaction.json"),mo=s=>Ot(wr(s),"history"),yo=/^[a-f0-9-]{36}$/i;async function cp(s,e){let t=`${s}.${rp()}.tmp`;try{await np(t,e,{mode:384}),await ki(t,s)}finally{await sp(t,{force:!0})}}var lp=(s,e)=>cp(s,JSON.stringify(e));async function bi(s,e){await ki(s,`${s}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function vo(s,e,t=()=>!1){let r;try{r=JSON.parse(await ip(s,"utf8"))}catch(i){return i?.code==="ENOENT"||await bi(s,"invalid"),null}return e(r)?t(r)?(await bi(s,"expired"),null):r:(await bi(s,"invalid"),null)}function bo(s){if(!s||typeof s!="object"||s.schema!==Pi||!yo.test(s.id??""))return!1;try{Ee(s.version)}catch{return!1}return typeof s.launcher=="string"&&go(s.launcher)&&typeof s.packageRoot=="string"&&go(s.packageRoot)&&["stable","alpha"].includes(s.channel)&&typeof s.downgrade=="boolean"&&!Number.isNaN(Date.parse(s.createdAt??""))}async function yr(s,e=Date.now()){return vo(Ii(s),bo,t=>e-Date.parse(t.createdAt)>op)}async function ko(s,e){let t={schema:Pi,createdAt:new Date().toISOString(),...e};if(!bo(t))throw new Error("Invalid upgrade candidate");return await wo(wr(s),{recursive:!0,mode:448}),await lp(Ii(s),t),t}async function Si(s,e,t){let r=await yr(s);!r||e&&r.id!==e||(await wo(mo(s),{recursive:!0,mode:448}),await ki(Ii(s),Ot(mo(s),`${r.id}-candidate-${t}.json`)).catch(i=>{if(i?.code!=="ENOENT")throw i}))}var dp=["selected","committed","rolled-back"];function pp(s){return!!s&&typeof s=="object"&&s.schema===Pi&&yo.test(s.id??"")&&dp.includes(s.phase)&&typeof s.version=="string"&&typeof s.from=="string"&&!Number.isNaN(Date.parse(s.updatedAt??""))}async function Po(s){return vo(ap(s),pp)}import{readFile as up,rename as fp,writeFile as hp,unlink as gp}from"node:fs/promises";import{join as mp}from"node:path";import{randomUUID as wp}from"node:crypto";var Ei=1,Io=s=>mp(s,"pi-web","launcher-handoff.json");function So(s){return s?.protocol===Ei&&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 xi(s){try{let e=JSON.parse(await up(Io(s),"utf8"));if(!So(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 yp(s,e){let t=`${s}.${wp()}.tmp`;try{await hp(t,JSON.stringify(e),{mode:384}),await fp(t,s)}finally{await gp(t).catch(()=>{})}}async function Eo(s,e){if(!So(e))throw new Error("Invalid launcher handoff receipt");await yp(Io(s),e)}import{execFile as vp}from"node:child_process";import{cp as bp,readFile as _i,realpath as kp,rm as Pp}from"node:fs/promises";import{join as pt,sep as Ip}from"node:path";import{promisify as Sp}from"node:util";var xo=Sp(vp),Ai=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Ti(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 Ai.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 vr(s){return Promise.all(Ai.map(async e=>{let t=await nt(s,e),r=JSON.parse(await _i(pt(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 _o(s,e){let t=JSON.parse(await _i(pt(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 vr(s):Ti(t.peerDependencies);if(JSON.stringify(await vr(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(s,"node-pty"),n=await nt(e,"node-pty"),o=await kp(pt(e,"../.."));if(i===n||!n.startsWith(o+Ip))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 _i(pt(u,"package.json"),"utf8")).version;if(await c(i)!==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 Pp(n,{recursive:!0,force:!0}),await bp(i,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await xo(process.execPath,[pt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await nt(e,Ai[0]),{stdout:p}=await xo(process.execPath,[pt(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:a,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 Rp=Tp(Ep),Mt=s=>["committed","cancelled","failed"].includes(s);function No(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=ho(s),{stdout:r}=await Rp(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 br=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;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 r=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return vr(this.packageRoot);let i=JSON.parse(r),n=Array.isArray(i)&&i.length===1?i[0]:i;return Ti(n)},this.verifyPackage=e.verifyPackage??_o,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,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"?Ei: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&&!Mt(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=q(this.agentDir,"pi-web","launcher.json"),n=JSON.parse(await Ve(i,"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 xi(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 Ve(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:n.pid,phase:"requested"};try{await Eo(this.agentDir,p),l=!0}catch(u){let v=await xi(this.agentDir).catch(()=>null);if(l=v?.nonce===e&&v?.requestId===t&&["requested","draining","stopped"].includes(v.phase),!l)throw u}this.restartPending=!0}finally{!l&&a&&await a()}}async current(){let e=JSON.parse(await Ve(q(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Ee(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();if(!t||Mt(t.phase)||t.id===this.ownTransaction)return e;if(t.version===e&&["selecting","selected","restart-requested"].includes(t.phase))await this.record({...t,phase:"committed",message:"Selected version is running"});else if(t.phase==="restart-requested"){let r=await Po(this.agentDir);await this.record({...t,phase:"failed",message:r?.id===t.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Si(this.agentDir,t.id,"superseded"),await this.record({...t,phase:"failed",message:`Interrupted while ${t.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return q(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await fe(this.transactionPath)}catch{return await gr(this.transactionPath),null}return e?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)||typeof e.selectionPath!="string"?(await gr(this.transactionPath),null):e:null}async record(e){if(await Ht(q(this.agentDir,"pi-web"),{recursive:!0}),await M(this.transactionPath,e),Mt(e.phase)){let t=q(this.agentDir,"pi-web","update-history");await Ht(t,{recursive:!0}),await M(q(t,`${e.id}-${e.phase}.json`),e)}}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");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),t=await yr(this.agentDir);t&&(!e||t.id===e.id)&&await Si(this.agentDir,t.id,"cancelled"),e&&!Mt(e.phase)&&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}get preferencePath(){return q(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await Ve(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}.${Ri()}.tmp`;try{await Ht(q(this.agentDir,"pi-web"),{recursive:!0}),await Co(t,JSON.stringify({channel:e}),{mode:384}),await To(t,this.preferencePath)}finally{this.savingPreference=!1,await Ro(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=Ao(q(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 n=await this.transaction();if(n&&!Mt(n.phase)?i.recovery={version:n.version,phase:n.phase,canCancel:n.phase!=="restart-requested"}:n?.phase==="failed"&&n.message&&(i.lastFailure={version:n.version,message:n.message}),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 o=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),c=Array.isArray(o)&&o.length===1?o[0]:o,a=t==="alpha"?c:{latest:c};if(!a||!Sn(a.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let l=a.latest;if(t==="alpha"&&a.alpha!==void 0){if(!ir(a.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ue(a.alpha,l)>0&&(l=a.alpha)}if(i.latest=l,i.downgrade=ue(l,e)<0,i.available=t==="stable"?ue(l,e)!==0:ue(l,e)>0,i.available&&this.pluginWarnings){let p=await this.pluginWarnings(l).catch(()=>[]);p.length&&(i.pluginWarnings=p)}this.desktopManaged&&i.downgrade&&!this.desktopReleaseChannels&&ue(l,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(o){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`)}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(Ao(q(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=q(this.agentDir,"pi-web","releases");await Ht(r,{recursive:!0});let i=await _p(q(await Ap(r),`${t.latest}-`)),n=q(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Ri(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:n,ownerNonce:this.launcherNonce};this.ownTransaction=o.id,await this.record(o);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 a=q(i,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:a},await this.record(o);let l=JSON.parse(await Ve(q(a,"package.json"),"utf8"));if(l.name!=="pi-webapp"||l.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await Ve(q(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&No(l)!==No(p))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=q(a,"bin","pi-webapp.mjs");return await Promise.all([u,q(a,"dist","extension.js"),q(a,"web","dist","index.html")].map(v=>xp(v))),this.desktopManaged&&(await Qr(this.agentDir,{version:t.latest,launcher:u,desktopProtocolVersion:Me}),await this.verifyPackage(this.packageRoot,a)),await this.prefetchPlugins?.(t.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await ko(this.agentDir,{id:o.id,version:t.latest,launcher:u,packageRoot:a,channel:t.channel??"stable",downgrade:!!t.downgrade}),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={id:o.id,update:{version:t.latest,launcher:u},channel:t.channel??"stable"},{version:t.latest,launcher:u}}catch(c){await Ro(i,{recursive:!0,force:!0});let a=(c instanceof Error?c.message:String(c)).slice(0,500);throw 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\uFF1A${a}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),c}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:t=!1}={}){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 r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let i,n=!1,o=q(this.agentDir,"pi-web","launcher.restart");try{if(i=await this.beforeRestart?.(t),(await yr(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let c=await this.transaction();c?.id===r.id&&await this.record({...c,phase:"restart-requested"});try{if(JSON.parse(await Ve(o,"utf8"))?.nonce!==this.launcherNonce){let l=q(this.agentDir,"pi-web","restart-history");await Ht(l,{recursive:!0,mode:448}),await To(o,q(l,`stale-${Ri()}.json`))}}catch{}try{await Co(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),n=!0}catch(a){try{let l=JSON.parse(await Ve(o,"utf8"));n=l.nonce===this.launcherNonce&&l.candidate===r.id}catch{}if(!n)throw a}this.restartPending=!0}catch(c){if(n){this.restartPending=!0;return}let a=await this.transaction();throw a?.id===r.id&&a.phase==="restart-requested"&&await this.record({...a,phase:"prepared"}),i&&await i(),c}}};import{createHash as ma,randomUUID as Of}from"node:crypto";import{randomUUID as lf}from"node:crypto";import{join as Li}from"node:path";import{randomUUID as Ho}from"node:crypto";import{randomUUID as Np}from"node:crypto";function Do(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 r=`__pi_web_contract_${Np().replaceAll("-","")}`,i;try{if(i=s.getActiveTools(),!Array.isArray(i))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let n={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{s.registerTool(n),s.setActiveTools([...i,r]),(s.getAllTools().find(c=>c.name===r)?.exposure!=="hidden"||s.getActiveTools().includes(r))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};s.registerTool({...n,parameters:o}),s.getAllTools().find(c=>c.name===r)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{s.setActiveTools(i)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var Dp;function Oo(){return Dp??=Op().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function Op(){let{createAgentSession:s,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:i,rm:n}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:c}=await import("node:path"),a=await i(c(o(),"pi-sdk-contract-")),l,p=[],u=0,v=0,w=!1,h=!1;try{let m=(H,T,Y)=>({name:H,label:H,description:"Inert host SDK contract check",exposure:T,parameters:{type:"object",properties:{}},execute:Y}),k=()=>({content:[],details:void 0}),I=new e({cwd:a,agentDir:a,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[H=>{H.on("tool_call",T=>{if(T.toolName==="__contract_direct"&&(w=!!T.parentToolCallId),T.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let T of["hidden","model-only"])H.registerTool(m(`__contract_${T.replace("-","_")}`,T,async()=>(v++,k())));H.registerTool(m("__contract_protected","direct",async()=>(v++,k()))),H.registerTool(m("__contract_direct","direct",async()=>(u++,k()))),H.registerTool(m("__contract_driver","direct",async(T,Y,b,y,j)=>{let me=await j.executeTool("__contract_hidden",{}),we=await j.executeTool("__contract_model_only",{}),se=await j.executeTool("__contract_direct",{}),x=await j.executeTool("__contract_protected",{});return(!me.isError||!we.isError)&&p.push("nested-tool-exposure"),(se.isError||u!==1)&&p.push("nested-tool-execution"),(!x.isError||v!==0)&&p.push("nested-tool-permission-guard"),w||p.push("nested-parent-identity"),h=!0,k()}))}]});await I.reload(),{session:l}=await s({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:I}),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 A=0;l.agent.streamFunction=async H=>{let T=A++===0,Y={role:"assistant",api:H.api,provider:H.provider,model:H.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=r();return b.push({type:"start",partial:Y}),b.push({type:"done",reason:T?"toolUse":"stop",message:Y}),b.end(Y),b};let O;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((H,T)=>{O=setTimeout(()=>T(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(O)}return h||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await n(a,{recursive:!0,force:!0})}}var kr=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??=Oo().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=n=>{if(typeof n!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(n)};try{i(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(n=>this.waiters.add(n));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",n=>{let o=r.owned.get(n.toolName);if(!o)return;let c=this.descriptors.get(o)?.find(a=>a.name===n.toolName);if(!c||!this.allowed(r,o,c,!!n.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 n of r.handlers)try{n()}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 n=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&n.enabled&&(!n.allowlist||n.allowlist.includes(r.name))&&(!n.planMode||r.readonly===!0)&&(!i||n.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[n,o]of i.owned)this.assertOwner(i,o,n);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[n,o]of this.descriptors)if(n!==e&&o.some(c=>c.name===i.name))throw new Error(`Hosted tool ownership conflict: ${i.name}`);for(let n of this.bindings)n.compatible!==!1&&this.assertOwner(n,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 n=e.pi.getAllTools().find(o=>o.name===r);if(n&&(!i||n.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=Do(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 n of i)this.assertOwner(e,r,n.name);let t=new Set;for(let[r,i]of this.descriptors)for(let n of i){if(e.owned.set(n.name,r),!this.allowed(e,r,n))continue;t.add(n.name);let o=this.service.policy(r,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,v)=>{if(!this.allowed(e,r,n))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:Ho(),scope:{...e.scope},kind:"tool",action:n.action,input:u},v)}};e.pi.registerTool(l),e.definitions.set(n.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:Hp};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,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:Ho(),scope:t,kind:"action",action:r,input:i},n)}};async function Hp(){throw new Error("Hosted tool unavailable")}import{randomBytes as Hu,randomUUID as Mu,timingSafeEqual as ju}from"node:crypto";import{join as ve}from"node:path";var Mp=30,Mo=/^[a-z][a-z0-9-]{0,63}$/,jp=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,jt=s=>{throw new f("invalid_package",s)},Ci=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?jt(`Invalid ${e} declaration`):s;function ut(s){let e=s&&typeof s=="object"?s:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),r=t.has("secrets")?Ci(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&Mo.test(a)?a:jt("Invalid secret name")}):[],i=e.network,n=t.has("network")?Ci(i?.hosts,"network").map(c=>typeof c=="string"&&jp.test(c)?c:jt("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Ci(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!Mo.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<Mp||a.intervalSec>86400?jt("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&jt("Duplicate schedule id"),{secrets:r,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as Wp}from"node:dns/promises";import{isIP as $p}from"node:net";var Vp=new Set(["GET","POST","PATCH","PUT","DELETE"]),Fp=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),Up=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Pr=(s,e)=>{throw new f("network_denied",s,{status:403,reason:e})};function Bp(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if($p(e)===4){let[t,r]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&r===254||t===172&&r>=16&&r<=31||t===192&&r===168||t===100&&r>=64&&r<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function jo(s,e,t,r,i){let n=r;if(!n||typeof n!="object"||typeof n.url!="string")throw new f("invalid_input","Invalid network request");let o;try{o=new URL(n.url)}catch{throw new f("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Pr("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Pr("Host is not declared by the plugin","host");let c=(n.method??"GET").toUpperCase();if(!Vp.has(c))throw new f("invalid_input","Unsupported method");if(n.body!==void 0&&(typeof n.body!="string"||n.body.length>1024*1024))throw new f("invalid_input","Invalid body");let a={};for(let[E,A]of Object.entries(n.headers??{})){if(typeof A!="string"||Fp.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(A))throw new f("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=A}let l=null;if(n.secret!==void 0){if(t.includes(n.secret)||Pr("Secret is not declared by the plugin","secret"),l=await i.secrets.get(s,n.secret),!l)throw new f("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(i.resolve??(async E=>(await Wp(E,{all:!0})).map(A=>A.address)))(o.hostname);(!p.length||p.some(Bp))&&Pr("Host resolves to a non-public address","address");let u=i.timeoutMs??2e4,v=i.maxResponseBytes??2*1024*1024,w=await(i.fetch??fetch)(o,{method:c,headers:a,body:n.body,redirect:"manual",signal:AbortSignal.timeout(u)}),h=[],m=0;if(w.body)for await(let E of w.body){if(m+=E.byteLength,m>v)throw new f("response_too_large","Network response exceeds limit",{status:502});h.push(Buffer.from(E))}let k=Buffer.concat(h).toString("utf8"),I={};return w.headers.forEach((E,A)=>{Up.has(A.toLowerCase())&&(I[A.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:w.status,headers:I,body:k}}var Ir=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new f("invalid_input",`Invalid ${t}`);return s};async function Wo(s,e,t,r,i,n){let o=i&&typeof i=="object"&&!Array.isArray(i)?i:{};if(r==="sessions.create"){if(o.mode!=="plan")throw new f("invalid_input","Plugin sessions must start in plan mode");if(s.activeCount(e)>=n)throw new f("quota_exceeded","Too many active plugin sessions",{status:429});return s.create({pluginId:e,cwd:t,title:Ir(o.title,200,"title"),prompt:Ir(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=Ir(o.sessionId,200,"sessionId");if(s.ownerOf(c)!==e)throw new f("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new f("invalid_input","Invalid mode");return await s.send(c,Ir(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 f("method_denied","Unknown sessions method")}}var Lp=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),Sr=class{options;constructor(e){this.options=e}handles(e){return Lp.has(e)}async call(e,t,r,i,n){let o=ut(t);if(i==="network.fetch"){if(!o.networkHosts.length)throw new f("capability_denied","Plugin did not declare network access",{status:403});return jo(e,o.networkHosts,o.secrets,n,this.options)}if(!o.sessions||!this.options.sessions)throw new f("capability_denied","Sessions capability is unavailable",{status:403});return Wo(this.options.sessions,e,r.scope.cwd,i,n,this.options.maxActiveSessions??3)}};var Er=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let r=this.deps.setInterval??((i,n)=>{let o=setInterval(i,n);return o.unref(),o});this.timers.set(e,t.map(i=>r(()=>{this.tick(e,i)},i.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])t(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let r=`${e}\0${t.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,t),!0}catch(i){return this.deps.onError?.(e,t,i),!1}finally{this.running.delete(r)}}};import{createHash as Wi,timingSafeEqual as uu}from"node:crypto";import{lstat as Ko,mkdtemp as ji,readdir as fu,readFile as hu,realpath as gu,rename as mu,rm as Fe,writeFile as wu}from"node:fs/promises";import{tmpdir as yu}from"node:os";import{join as U}from"node:path";import{gunzipSync as Yp}from"node:zlib";import{mkdir as Qp,writeFile as Zp}from"node:fs/promises";import{dirname as eu,join as tu}from"node:path";import{constants as Ni}from"node:fs";import{lstat as Fo,open as zp,readdir as $o,realpath as Uo}from"node:fs/promises";import{createHash as qp}from"node:crypto";import{join as Bo,relative as Gp,resolve as Jp,sep as Kp}from"node:path";var J={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},Xp={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"]},F=s=>qp("sha256").update(s).digest("hex");function $(s){throw new f("invalid_package",s)}async function Xe(s,e,t){let r=e.split("/");(!r.length||r.some(c=>!c||c==="."||c===".."||!/^[\w.-]+$/.test(c)))&&$("Invalid resource path");let i=s;for(let c=0;c<r.length;c++){i=Bo(i,r[c]);let a=await Fo(i);(a.isSymbolicLink()||(c<r.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&$("Links and non-regular package files are forbidden")}let n=await Uo(i);(n!==Jp(s,e)||Gp(s,n).startsWith(`..${Kp}`))&&$("Resource escapes package root");let o=await zp(i,Ni.O_RDONLY|Ni.O_NONBLOCK|(Ni.O_NOFOLLOW??0));try{let c=await o.stat();(!c.isFile()||c.nlink!==1||c.size>t)&&$("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)&&$("Package resource changed during read"),a.subarray(0,l)}finally{await o.close()}}function Vo(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return $("Invalid package JSON")}}async function Ye(s,e){let t=await Uo(s);(await Fo(s)).isSymbolicLink()&&$("Package root cannot be a symlink");let r=Vo(await Xe(t,"package.json",J.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"),je(r.piWebapp)||$("Unsupported hosted manifest"),r.type!=="module"&&$("Hosted package must declare ESM module type");for(let u of await $o(t,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&$("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&$("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let v=r[u];v&&(typeof v!="object"||Object.keys(v).length>0)&&$("Hosted packages must contain all runtime dependencies")}let i=r.piWebapp,n=Vo(await Xe(t,i.resourcesManifest.slice(2),J.other));(!n||n.version!==1||!Array.isArray(n.files)||!n.files.length||n.files.length>J.files)&&$("Invalid resource manifest");let o=new Map,c=0;for(let u of n.files){(!u||typeof u!="object")&&$("Invalid resource entry");let v=u,w={...v,path:typeof v.path=="string"&&v.path.startsWith("./")?v.path.slice(2):v.path};(!Ge(`./${w.path}`)||typeof w.sha256!="string"||!/^[a-f0-9]{64}$/.test(w.sha256)||!Number.isSafeInteger(w.bytes)||w.bytes<0||o.has(w.path))&&$("Invalid or duplicate resource");let h=w.path.split(".").at(-1);Xp[h]?.includes(w.mime)||$("Unsupported resource MIME");let m=h==="js"||h==="mjs"?J.js:h==="css"?J.css:h==="woff"||h==="woff2"?J.font:J.other;(w.bytes>m||(c+=w.bytes)>J.total)&&$("Resource budget exceeded");let k=await Xe(t,w.path,m);(k.length!==w.bytes||F(k)!==w.sha256)&&$("Resource integrity mismatch"),o.set(w.path,Object.freeze({...w}))}for(let u of[i.backend.entry,i.frontend.document,i.frontend.controller])o.has(u.slice(2))||$("Entrypoint is absent from resource manifest");let a=0;async function l(u,v=0){v>16&&$("Package directory nesting limit exceeded");for(let w of await $o(Bo(t,u),{withFileTypes:!0})){++a>J.files*2&&$("Too many package entries");let h=`${u}/${w.name}`;(w.isSymbolicLink()||!w.isDirectory()&&!w.isFile())&&$("Invalid archive member"),w.isDirectory()?await l(h,v+1):h!==i.resourcesManifest.slice(2)&&!o.has(h)&&$("Undeclared distribution asset")}}await l("dist");let p=F(JSON.stringify({id:r.name,version:r.version,manifest:i,resources:[...o.values()].sort((u,v)=>u.path.localeCompare(v.path))}));return{id:r.name,version:r.version,root:t,manifest:i,resources:o,digest:p}}async function Lo(s,e,t){if(t!==s.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Ge(`./${r}`))return null;let i=s.resources.get(r);if(!i||r===s.manifest.backend.entry.slice(2))return null;let n=await Xe(s.root,r,i.bytes);if(n.length!==i.bytes||F(n)!==i.sha256)throw new f("resource_changed","Installed resource integrity mismatch");return{bytes:n,mime:i.mime}}var xr=64*1024*1024,ru=J.total+J.files*2048,W=s=>{throw new f("invalid_archive",s)};function ft(s){let e=s.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?s:s.subarray(0,e))}catch{return W("Archive has invalid UTF-8 paths")}}function zo(s){let e=ft(s).trim();if(!/^[0-7]+$/.test(e))return W("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:W("Archive number exceeds limits")}function iu(s){let e=s.endsWith("/")?s.slice(0,-1):s;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return W("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))?W("Archive path is not a safe relative package path"):t}function su(s){let e={},t=0;for(;t<s.length;){let r=s.indexOf(32,t);if(r<0)return W("Invalid PAX header");let i=s.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(i))return W("Invalid PAX record length");let n=Number(i),o=t+n;if(o>s.length||o<=r+2||s[o-1]!==10)return W("Truncated PAX record");let c=ft(s.subarray(r+1,o-1)),a=c.indexOf("=");if(a<1)return W("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 W("Unsupported PAX feature");e[l]=p,t=o}return e}function nu(s){if(!s.length||s.length>xr)return W("Compressed archive exceeds budget");let e;try{e=Yp(s,{maxOutputLength:ru})}catch{return W("Invalid or oversized gzip archive")}let t=[],r=new Set,i=0,n=0,o=0,c=0,a=null,l=!1;for(;i+512<=e.length;){let u=e.subarray(i,i+512);if(i+=512,u.every(O=>O===0)){if(a||e.subarray(i).some(O=>O!==0))return W("Unexpected archive data after end marker");l=!0;break}if(++c>J.files*2)return W("Too many archive headers");let v=0;for(let O=0;O<512;O++)v+=O>=148&&O<156?32:u[O];if(zo(u.subarray(148,156))!==v)return W("Invalid tar header checksum");let w=ft(u.subarray(257,263));if(w&&w!=="ustar"&&w!=="ustar ")return W("Unsupported tar format");let h=u[156],m=ft(u.subarray(345,500)),k=(m?m+"/":"")+ft(u.subarray(0,100)),I=zo(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 W("Invalid PAX size");I=Number(a.size)}if(!Number.isSafeInteger(I)||I<0||I>J.total||i+I>e.length)return W("Truncated or oversized tar member");let E=e.subarray(i,i+I);if(i+=Math.ceil(I/512)*512,h===120){if(a||I>8192)return W("Oversized or chained PAX header");a=su(E);continue}if(a=null,h!==0&&h!==48&&h!==53)return W("Links and special archive members are forbidden");let A=h===53;if(A&&I!==0||ft(u.subarray(157,257)))return W("Invalid archive link or directory");if(k=iu(k),!k&&!A)return W("Invalid package root member");if(r.has(k))return W("Duplicate archive member");if(r.add(k),++n>J.files||(o+=I)>J.total)return W("Unpacked archive exceeds budget");t.push({path:k,data:E,directory:A})}if(!l||!r.has("package.json"))return W("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 v=u.path.split("/");for(let w=1;w<v.length;w++)if(p.has(v.slice(0,w).join("/")))return W("Archive file/directory collision")}return t}async function Di(s,e){let t=nu(s);for(let r of t){if(!r.path)continue;let i=tu(e,r.path);await Qp(r.directory?i:eu(i),{recursive:!0,mode:448}),r.directory||await Zp(i,r.data,{flag:"wx",mode:384})}}import{lstat as ou,mkdir as au,readdir as cu,realpath as lu,writeFile as du}from"node:fs/promises";import{dirname as pu,join as Oi}from"node:path";async function qo(s,e){let t=await lu(s),r=await Xe(t,"package.json",J.other),i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new f("invalid_package","package.json is not valid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw new f("invalid_package","package.json must be an object");let n=[],o=0,c=0;async function a(v,w){if(w>16)throw new f("invalid_package","Package directory nesting limit exceeded");for(let h of await cu(Oi(t,v),{withFileTypes:!0})){let m=`${v}/${h.name}`;if(++o>J.files)throw new f("invalid_package","Too many package entries");if(h.isDirectory()){await a(m,w+1);continue}if(!h.isFile())throw new f("invalid_package",`Links and non-regular files are forbidden: ${m}`);let k=await Xe(t,m,J.js);if((c+=k.length)>J.total)throw new f("invalid_package","Resource budget exceeded");let I=Oi(e,m);await au(pu(I),{recursive:!0,mode:448}),await du(I,k,{flag:"wx",mode:384}),n.push([m,F(k)])}}let l;try{l=await ou(Oi(t,"dist"))}catch(v){throw v.code==="ENOENT"?new f("dist_missing","dist/ does not exist yet; build the plugin first"):v}if(!l.isDirectory())throw new f("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...u}=i;return n.sort((v,w)=>v[0].localeCompare(w[0])),{contentHash:F(JSON.stringify({package:u,files:n})),packageJson:i}}function ye(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 Ie(s,e){let t=ye(s),r=ye(e);if(!t||!r)throw new f("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function Go(s){let e=ye(s);if(e)return e;if(!ir(s))return null;let[t,r]=s.split("-alpha."),i=ye(t),n=Number(r);return i&&Number.isSafeInteger(n)?{...i,alpha:n}:null}function Hi(s){return!!Go(s)}function ht(s,e){if(!Hi(s)||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 n=i.trim().split(/\s+/),o=!0;for(let c of n){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&Go(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 v=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&ue(s,`${v}-0`)<0;break}}}r.push(o)}return r.some(Boolean)}var Ce=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 he(s,e=Ce){let t=e.find(r=>r.id===s);if(!t)throw new f("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Mi(s,e,t){let r=s.piWebapp;return s.name===e.id&&!!ye(s.version)&&!s.deprecated&&je(r)&&ht(t,r.hostRange)&&e.requiredCapabilities.every(i=>r.capabilities.includes(i))}function Jo(s,e,t,r,i){if(!s||typeof s!="object"||!("versions"in s)||!s.versions||typeof s.versions!="object"||Array.isArray(s.versions))throw new f("registry_invalid","Invalid registry version catalog");let n=Object.entries(s.versions);if(n.length>1e4)throw new f("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&&Mi(p,e,t)&&(!i||a===i)&&(!r||Ie(a,r)>=0)?[p]:[]}).sort((a,l)=>Ie(l.version,a.version))[0];if(!c)throw new f("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 f("registry_invalid","Release is missing its immutable tarball integrity");return c}function vu(s,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new f("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),i=Wi("sha512").update(s).digest();if(r.length!==i.length||!uu(r,i))throw new f("integrity_mismatch","Downloaded package failed integrity verification")}var gt=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Hi(e.hostVersion))throw new f("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Ce,this.fetcher=e.fetch??Kn}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 f("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 f("invalid_storage","Invalid plugin installation index");for(let[t,r]of Object.entries(e.versions))if(this.catalog.some(i=>i.id===t)){if(!Array.isArray(r)||r.length>16||new Set(r.map(i=>i.version)).size!==r.length)throw new f("invalid_storage","Invalid installed version list");for(let i of r)this.validateRecord(t,i)}return e}validateRecord(e,t){if(!t||!ye(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${F(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new f("invalid_storage","Invalid installed plugin record")}path(e){return U(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await fe(U(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(n=>!["schema","pluginId","next"].includes(n)))throw new f("invalid_storage","Invalid install journal");he(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let i=e.versions[t.pluginId]?.find(n=>n.version===t.next.version);if(i&&i.digest!==t.next.digest)throw new f("invalid_storage","Conflicting installation journal");await Fe(U(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=U(this.root,"staging");await Z(r);for(let i of await fu(r)){if(!/^stage-[A-Za-z0-9]+$/.test(i)||(await Ko(U(r,i))).isSymbolicLink())throw new f("invalid_storage","Invalid abandoned staging directory");await Fe(U(r,i),{recursive:!0})}return e}async recoverCollection(e){let t=U(this.root,"gc-journal.json"),r=await fe(t);if(!r)return;if(r.schema!==1||Object.keys(r).some(n=>!["schema","pluginId","records"].includes(n))||!Array.isArray(r.records)||!r.records.length)throw new f("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");he(r.pluginId,this.catalog);for(let n of r.records)this.validateRecord(r.pluginId,n);let i=r.records.filter(n=>e.versions[r.pluginId]?.some(o=>o.directory===n.directory));if(i.length&&i.length!==r.records.length)throw new f("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!i.length){await Z(U(this.root,"versions")),await Z(U(this.root,"versions",F(r.pluginId)));for(let n of r.records)await Fe(this.path(n),{recursive:!0,force:!0})}await Fe(t)}async collect(e,t){return he(e,this.catalog),te(this.root,async()=>{let r=await this.recoverLocked(),i=r.versions[e]??[],n=new Set(await t()),o=i.at(-1);o&&n.add(o.version);let c=i.filter(a=>!n.has(a.version));return await this.removeLocked(e,r,c),c.map(a=>a.version)})}async removeLocked(e,t,r){r.length&&(await Z(U(this.root,"versions")),await Z(U(this.root,"versions",F(e))),await M(U(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),t.versions[e]=(t.versions[e]??[]).filter(i=>!r.some(n=>n.directory===i.directory)),t.revision++,await M(U(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return te(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 f("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 f("registry_denied","Only the official registry origin is permitted");return r}async download(e,t,r,i="tarball"){let n=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:n,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw r?.aborted?r.reason:new f("registry_unreachable",u instanceof Error?u.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new f(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 f("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 f("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 f("download_too_large","Registry response exceeds budget");a.push(Buffer.from(u.value))}return n.throwIfAborted(),Buffer.concat(a)}catch(u){throw r?.aborted?r.reason:u instanceof f?u:new f("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,r,i){let n=he(e,this.catalog);if(r&&!ye(r))throw new f("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,i,"metadata");try{c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{throw new f("registry_invalid","Invalid registry metadata JSON")}return Jo(c,n,this.hostVersion,t,r)}async install(e,t,r){let i=he(e,this.catalog);if(!Mi(t,i,this.hostVersion))throw new f("incompatible_plugin","Plugin release is incompatible with this host");let n=await this.download(this.trustedUrl(t.dist.tarball,i),xr,r);return this.installArchive(e,n,t.dist.integrity,t.version,r)}async installArchive(e,t,r,i,n){let o=he(e,this.catalog);if(!ye(i))throw new f("invalid_version","Choose an exact stable version");if(t.length>xr)throw new f("download_too_large","Package archive exceeds budget");return vu(t,r),te(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await ji(U(this.root,"staging","stage-"));try{await Di(t,a),n?.throwIfAborted();let l=await Ye(a,e);if(l.version!==i||!je(l.manifest)||!ht(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(p=>l.manifest.capabilities.includes(p)))throw new f("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,c,a,l,r,n)}finally{await Fe(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,r,i,n,o){let c=t.versions[e]?.find(u=>u.version===i.version);if(c&&c.digest!==i.digest)throw new f("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:i.version,digest:i.digest,integrity:n,directory:`${F(e)}/${i.version}-${i.digest}`,installedAt:new Date().toISOString()};if(await Z(U(this.root,"versions",F(e))),!c&&(t.versions[e]?.length??0)>=16)throw new f("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await M(U(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await Ko(l),p=!0}catch(u){if(!He(u))throw u}if(p){if((await Ye(l,e)).digest!==i.digest)throw new f("resource_changed","Installed package content was modified")}else await mu(r,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await M(U(this.root,"installed.json"),t)),await Fe(U(this.root,"install-journal.json")),{...i,root:await gu(l)}}async installDevArchive(e,t,r){he(e,this.catalog);let i=await hu(t),n="sha512-"+Wi("sha512").update(i).digest("base64"),o=await ji(U(yu(),"pi-dev-archive-"));try{await Di(i,o);let c=(await Ye(o,e)).version;return await this.installArchive(e,i,n,c,r)}finally{await Fe(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,r){let i=he(e,this.catalog);return te(this.root,async()=>{let n=await this.recoverLocked();r?.throwIfAborted();let o=await ji(U(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await qo(t,o);r?.throwIfAborted();let l=U(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],v=n.versions[e]??[],w=u?.contentHash===c?v.find(T=>T.version===u.version):void 0;if(w){let T=await Ye(this.path(w),e);if(T.digest!==w.digest)throw new f("resource_changed","Installed package integrity changed");return T}let h=typeof a.version=="string"?ye(a.version):null;if(!h)throw new f("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let m=Math.max(-1,...v.map(T=>ye(T.version)).filter(T=>T&&T.major===h.major&&T.minor===h.minor).map(T=>T.patch)),k=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),m+1),I=`${h.major}.${h.minor}.${k}`;await wu(U(o,"package.json"),JSON.stringify({...a,version:I},null,2),{flag:"wx",mode:384});let E=await Ye(o,e);if(!ht(this.hostVersion,E.manifest.hostRange))throw new f("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let A=i.requiredCapabilities.filter(T=>!E.manifest.capabilities.includes(T));if(A.length)throw new f("incompatible_plugin",`Package lacks required capabilities: ${A.join(", ")}`);let O="sha512-"+Wi("sha512").update(c).digest("base64"),H=await this.commitStaged(e,n,o,E,O,r);return p[e]={contentHash:c,version:I},await M(l,p),H}finally{await Fe(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=he(e,this.catalog);return te(this.root,async()=>{let i=await this.recoverLocked(),n=i.versions[e]?.find(c=>c.version===t);if(!n)throw new f("not_installed","Plugin version is not installed");let o=await Ye(this.path(n),e);if(o.digest!==n.digest)throw new f("resource_changed","Installed package integrity changed");if(!ht(this.hostVersion,o.manifest.hostRange)||!r.requiredCapabilities.every(c=>o.manifest.capabilities.includes(c)))throw new f("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){he(e,this.catalog),await te(this.root,async()=>{let r=await this.recoverLocked(),n=(r.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,r,n)})}};import{lstat as _r,mkdir as bu,open as Xo,realpath as Yo,readdir as $i,link as ku,rename as Pu,unlink as Qe,copyFile as Iu,rm as Su}from"node:fs/promises";import{dirname as Eu,isAbsolute as Qo,join as D,relative as Zo,resolve as xu,sep as Vi,win32 as _u}from"node:path";import{randomUUID as Fi}from"node:crypto";var Wt=192*1024*1024,$t=512*1024,ta=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function Au(s){if(!s||typeof s!="object"||Array.isArray(s))throw new f("invalid_input","Expected object input");return s}function ea(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new f("invalid_input","Invalid state key");return s}function Vt(s){if(s&&(!ta(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 f("invalid_storage","Invalid active plugin record");return s}var Ze=class{root;pluginId;legacy;checkpoint;constructor(e,t,r,i){this.root=D(e,F(t)),this.pluginId=t,this.legacy=r,this.checkpoint=i}active(){return ee(D(this.root,"active.json")).then(Vt)}async recover(){return te(this.root,async()=>{let e=await this.active(),t=await fe(D(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 f("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Vt(t.next),Vt(t.before);let r=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,r==="committed"?t.next:t.before))throw new f("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let n=t.before;if(r==="committed"&&n&&n.stateRef!==e.stateRef&&await M(D(this.root,"previous.json"),n),r==="committed"){let o=await fe(D(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(c=>["version","stateRef"].includes(c))&&await Qe(D(this.root,"fork.json"))}return await Qe(D(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return te(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new f("stale_generation","Plugin activation changed concurrently");let i=await fe(D(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(o=>!["version","stateRef"].includes(o))))throw new f("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let n=Vt({...t,generation:e+1,operationId:Fi()});await Z(D(this.root,"states")),await Z(D(this.root,"states",n.stateRef)),await M(D(this.root,"transition.json"),{version:1,before:r,next:n}),await this.checkpoint?.("prepared");try{await M(D(this.root,"active.json"),n)}catch(o){if((await this.active())?.operationId!==n.operationId)throw o}await this.checkpoint?.("committed");try{r&&r.stateRef!==n.stateRef&&await M(D(this.root,"previous.json"),r),await Qe(D(this.root,"transition.json")),await Qe(D(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),n})}async forkState(e){return te(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=Fi(),i=D(this.root,"states",r);if(await fe(D(this.root,"fork.json")))throw new f("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await M(D(this.root,"fork.json"),{version:1,stateRef:r}),await Z(i);let n=D(this.root,"states",t.stateRef);for(let o of await $i(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new f("invalid_storage","Unexpected state file");if(!await X(D(n,o),Wt))throw new f("invalid_storage","Missing state file");await Iu(D(n,o),D(i,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return te(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await X(D(this.root,l),2*1024*1024))throw new f("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),r=Vt(await fe(D(this.root,"previous.json")));if(!t&&await X(D(this.root,"active.json"),2*1024*1024))throw new f("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,r].filter(l=>!!l),n=D(this.root,"states");await Z(n);let o=await $i(n),c=new Set(i.map(l=>l.stateRef));for(let l of o){if(!ta(l))throw new f("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=D(n,l),u=await _r(p);if(!u.isDirectory()||u.isSymbolicLink())throw new f("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let v of await $i(p)){let w=await _r(D(p,v));if(!/^[a-f0-9]{64}\.json$/.test(v)||!w.isFile()||w.isSymbolicLink()||w.nlink!==1)throw new f("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await ee(D(p,v),Wt);if(!h)throw new f("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let m=h;if(Object.keys(m).some(k=>!["requestId","inputHash","nextHash","committed"].includes(k))||m.committed!==!0||!/^[a-f0-9]{64}$/.test(m.inputHash)||!/^[a-f0-9]{64}$/.test(m.nextHash)||typeof m.requestId!="string")throw new f("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(m=>!["revision","schema","value","requestId","inputHash"].includes(m)))throw new f("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let l of c)if(!o.includes(l))throw new f("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let a=await e(i);for(let l of o)c.has(l)||await Su(D(n,l),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let r=await this.active();if(!r||r.generation!==e||t&&!r.enabled)throw new f("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 f("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,r,i="session"){if(i!=="session"&&i!=="workspace")throw new f("invalid_input","Invalid state scope");let n=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return D(this.root,"states",e.stateRef,`${F(n+":state:"+r)}.json`)}async call(e,t,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new f("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=Au(r);return te(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(n,e,ea(i.key),i.scope),Wt);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(n,e,ea(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==n.schema||!Object.hasOwn(i,"value"))throw new f("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new f("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>Wt)throw new f("state_too_large","Plugin state exceeds limit");let a=await ee(o,Wt);a&&this.validateState(a);let l=F(c);if(a?.requestId===e.requestId&&a.inputHash===l)return{revision:a.revision,schema:a.schema,value:a.value};if((a?.revision??0)!==i.expectedRevision)throw new f("revision_conflict","Plugin state changed concurrently");let p={revision:i.expectedRevision+1,schema:n.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),c=i.maxBytes===void 0?$t:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>$t)throw new f("invalid_input","Invalid workspace read limit");let a=await X(o,c);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash:F(a)}:null}case"workspace.commit":return this.commitFile(n,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new f("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 f("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")||Qo(t)||_u.isAbsolute(t))throw new f("invalid_path","Use a workspace-relative .excalidraw path");let i=await Yo(e),n=xu(i,t),o=Zo(i,n);if(!o||o===".."||o.startsWith(`..${Vi}`)||Qo(o))throw new f("invalid_path","Workspace path escapes root");let c=i,a=o.split(Vi);for(let p=0;p<a.length;p++){c=D(c,a[p]);let u;try{u=await _r(c)}catch(v){if(!He(v))throw v;if(p<a.length-1){if(!r||Zo(i,c)!=="diagrams")throw new f("invalid_path","Workspace directory does not exist");try{await bu(c,{mode:448})}catch(w){if(w.code!=="EEXIST")throw w}u=await _r(c)}}if(u&&(u.isSymbolicLink()||(p<a.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new f("invalid_path","Workspace path contains a link or non-regular file")}let l=await Yo(Eu(n));if(l!==i&&!l.startsWith(i+Vi))throw new f("invalid_path","Workspace directory changed");return{target:n,parent:l}}async commitFile(e,t,r){if(typeof r.text!="string"||Buffer.byteLength(r.text)>$t||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new f("invalid_input","Invalid file content or expected hash");let{target:i,parent:n}=await this.fileTarget(t.scope.cwd,r.path,!0),o=D(this.root,"states",e.stateRef,`${F(this.scopeKey(t)+":file:"+t.requestId+":"+String(r.path))}.json`),c=F(JSON.stringify(r)),a=F(r.text),l=await ee(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==a))throw new f("duplicate_request","Request ID was reused with different content");let p;try{p=await Xo(`${i}.lock`,"wx",384)}catch(v){throw v.code==="EEXIST"?new f("file_busy","Workspace file is locked; original file preserved"):v}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let v=await X(i,$t),w=v?F(v):null;if(l&&w===a)return{hash:a};if(l?.committed||w!==r.expectedHash)throw new f("file_conflict","Workspace file already exists or changed externally");await M(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=D(n,`.plugin-${Fi()}.tmp`);let h=await Xo(u,"wx",384);try{await h.writeFile(r.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,r.path)).parent!==n)throw new f("file_conflict","Workspace directory changed during save");let k=await X(i,$t);if((k?F(k):null)!==r.expectedHash)throw new f("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await ku(u,i)}catch(I){throw I.code==="EEXIST"?new f("file_conflict","Workspace file was created concurrently"):I}await Qe(u),u=void 0}else await Pu(u,i),u=void 0;return await M(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await Qe(u).catch(()=>{}),await p.close(),await Qe(`${i}.lock`)}}};import{randomUUID as Du}from"node:crypto";import{fork as Tu}from"node:child_process";import{randomUUID as Ru}from"node:crypto";import{join as Cu}from"node:path";import{EventEmitter as Nu}from"node:events";var ra=192*1024*1024,Ft=class s{child;pending=new Map;events=new Nu;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 n={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(n[o]=process.env[o]);this.child=Tu(r,[],{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 f("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,n=1e4){let o=new s(e,t,r,i);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 f("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 f("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>ra){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 n=r.error;r.ok===!0?i.resolve(r.value):i.reject(new f(n?.code??"plugin_failed",n?.message??"Plugin request failed",n))}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 f("invalid_lease","Plugin invocation lease is no longer writable");let n=await this.broker(i.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:n})}catch(n){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:K(n)})}}}request(e,t,r=3e4,i){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new f("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new f("worker_busy","Too many plugin requests"));let n=i?.requestId??Ru();if(this.pending.has(n))return Promise.reject(new f("duplicate_request","An identical request is still running"));let o={type:"request",id:n,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>ra?Promise.reject(new f("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 f("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(n,{resolve:c,reject:a,timer:l,invocation:i,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 f("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 f("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 Ou={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ar=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,r=Ou,i){this.broker=e,this.workerEntry=t,this.hooks=r,this.capabilities=i}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 hi(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,r)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new f("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,r):this.broker.call(e,t,r);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new f("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 f("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 f("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 f("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,n=this.worker;n||(this.phaseValue="starting");let o=null,c=!1,a=!1;try{if(o=await Ft.start(e,i+1,this.workerEntry,this.callBroker),this.phaseValue="draining",n&&!await n.waitForIdle(t))throw new f("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 f("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new f("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):Du(),p=await this.broker.activate(i,{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,t=!1){return this.serialize(async()=>{let r=this.worker,i=this.phaseValue,n=await this.broker.active(),o=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(n))throw await this.releaseOwnership?.(),this.phaseValue="failed",new f("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Ft.start(r.package,r.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{let a=async l=>{try{await l()}catch(p){if(!t)throw p}};await a(async()=>{if(r&&!await r.waitForIdle(e))throw new f("drain_pending","Plugin work is still draining; current host retained")}),await a(()=>this.hooks.freeze()),await a(async()=>{if(r&&!await r.waitForIdle(e))throw new f("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(a){try{await o(),this.phaseValue=i,await this.hooks.resume()}catch(l){throw this.phaseValue="failed",l}throw a}let c=!1;return()=>this.serialize(async()=>{c||(await o(),this.phaseValue=i,await this.hooks.resume(),c=!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 f("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 n=!1;try{if(t&&!await t.waitForIdle(e))throw new f("drain_pending","Plugin still has in-flight work; not killed");if(n=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new f("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,n&&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 f("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new f("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 ia}from"node:fs/promises";var Tr=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;constructor(e){this.options=e,this.installer=new gt({root:ve(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new Sr(e.capabilities):void 0;this.scheduler=new Er({invoke:async(r,i)=>{let n=this.closing?null:e.scheduledScope?.(r)??null;n&&await this.supervisor(r).invoke({requestId:Mu(),scope:n,kind:"action",action:i.action,input:{schedule:i.id}})},onError:(r,i,n)=>e.onScheduleError?.(r,i.id,n),...e.scheduleTimers});for(let r of this.installer.catalog){let i=new Ze(ve(e.root,"data"),r.id,e.legacy?.(r.id)),n=e.hooks(r.id);this.supervisors.set(r.id,new Ar(i,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(r.id,o.version);this.packages.set(r.id,c),this.assetTokens.set(r.id,Hu(24).toString("base64url"));try{this.scheduler.start(r.id,ut(c.manifest).schedules)}catch(a){this.scheduler.stop(r.id),this.errors.set(r.id,K(a))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await n.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return t?i=>this.installer.installDevDirectory(e,t,i):r?i=>this.installer.installDevArchive(e,r,i):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){he(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new f("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new f("manager_closed","Plugin manager is shutting down"));let r=(this.operations.get(e)??Promise.resolve()).then(t,t);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),i=>{this.errors.set(e,K(i))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,r=!1){return this.options.lifecycle?this.options.lifecycle(e,t,r):t()}async policies(){let e=await ee(ve(this.options.root,"policies","policies.json"));if(!e){if(await X(ve(this.options.root,"policies","policies.json"),2*1024*1024))throw new f("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,r]of Object.entries(e))if(this.installer.catalog.some(i=>i.id===t)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new f("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await ee(ve(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await te(ve(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await M(ve(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,r,i){try{let n=await this.installer.check(e,t,r,i),o=!t||Ie(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:K(n).code,message:K(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 f("invalid_input","Invalid plugin update policy");await te(ve(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await M(ve(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return te(hr(this.options.root),async()=>{let e=await wi(this.options.root);if(!e)return{intent:e,admitted:!1};if(!yi(e))return e.phase==="required-action"&&await mr(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await mi(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await mi(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await ia(this.options.workerEntry)).equals(await ia(ve(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(t){return await mr(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${K(t).message}; data retained`}),{intent:e,admitted:!1}}return await mr(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await te(ve(this.options.root,"policies"),async()=>{let t=await this.policies();await M(ve(this.options.root,"policies","policies.json"),t)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let t of this.installer.catalog){let r=this.supervisor(t.id),i=await r.broker.active();if(i?.enabled)try{let n=await this.compatiblePackage(t.id,i.version);await this.lifecycle(t.id,()=>r.replace(n)),this.packages.set(t.id,n),e||await this.collectSettled(t.id)}catch(n){let o=K(n),c=["runtime_owned","storage_busy"].includes(o.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(t.id,{...o,message:`Plugin unavailable: startup failed (${o.code}): ${o.message}; data retained. ${c}`})}}}async compatiblePackage(e,t){try{return await this.installer.load(e,t)}catch(r){if(K(r).code!=="incompatible_plugin")throw r;let i=((await this.installer.inventory()).versions[e]??[]).map(n=>n.version).filter(n=>n!==t).sort((n,o)=>Ie(o,n));for(let n of i)try{return await this.installer.load(e,n)}catch{}throw r}}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 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)=>Ie(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:r[n.id],availableVersion:this.available.get(n.id)?.version??(r[n.id]?.status==="available"?r[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,r,i){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)=>Ie(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,i)).version};case"install":{let l=this.devSource(e);if(l){let v=await l(i);return await this.recordDevSync(e,v.version),{installed:!0,version:v.version}}let p=await this.check(e,c,r,i),u=await this.installer.install(e,p,i);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=r??c;if(!l)throw new f("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 f("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let h=await l(i),m=await n.broker.active();if(await this.recordDevSync(e,h.version),!m?.enabled)return{installed:!0,enabled:!1,version:h.version};if(m.version===h.version&&!n.pendingVersion)return{unchanged:!0,version:h.version};let k=await this.lifecycle(e,()=>n.replace(h));return k.pending||this.packages.set(e,h),k}let p=await this.check(e,c,r,i),u=await n.broker.active();if(p.version===c&&(!u?.enabled||u.version===c)&&!n.pendingVersion)return{unchanged:!0,version:c};let v=p.version===c?await this.installer.load(e,c):await this.installer.install(e,p,i);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:v.version,message:"Selected compatible release installed; activation may wait for editors"}),!u?.enabled)return{installed:!0,enabled:!1,version:v.version};let w=await this.lifecycle(e,()=>n.replace(v));return w.pending||this.packages.set(e,v),w}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 f("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=K(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 r=>this.installer.collect(e,async()=>{let i=(await this.policies())[e];return[...r.map(n=>n.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 f("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 f("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 n=this.assetLeases.get(e);n||(n=new Map,this.assetLeases.set(e,n)),n.set(i.version,(n.get(i.version)??0)+1);try{return await Lo(i,r,t)}finally{let o=n.get(i.version)-1;o?n.set(i.version,o):n.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),n=Buffer.from(t[2]);return!i||n.length!==Buffer.byteLength(i)||!ju(n,Buffer.from(i))?null:this.asset(r,t[3],t[4])}async reconcileHostUpgrade(){if(lo(await wi(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 n=e.versions[i.id];if(n?.length)try{let o=await this.supervisor(i.id).broker.active(),c=o?.enabled?o.version:n.map(l=>l.version).sort((l,p)=>Ie(p,l))[0];try{await this.installer.load(i.id,c);continue}catch(l){if(K(l).code!=="incompatible_plugin")throw l}let a=await this.manage(i.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(r=!1)}catch(o){r=!1;let c=K(o);this.errors.set(i.id,c),await this.recordCheck(i.id,{status:"failed",code:c.code,message:c.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()]))}}async prefetchForHost(e,t){let r=new gt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),i=await this.installer.inventory();for(let n of this.installer.catalog){let o=(i.versions[n.id]??[]).map(l=>l.version).sort((l,p)=>Ie(p,l)),c=await this.supervisor(n.id).broker.active();if(!o.length||this.isDevPlugin(n.id))continue;let a=!1;for(let l of new Set([...c?.enabled?[c.version]:[],...o]))try{await r.load(n.id,l),a=!0;break}catch{}if(!a)try{let l=await r.check(n.id,o[0],void 0,t),p=await r.install(n.id,l,t);await this.recordCheck(n.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(l){t?.throwIfAborted();let p=K(l);await this.recordCheck(n.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let t=new gt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),i=[];for(let n of this.installer.catalog){let o=r.versions[n.id],c=await this.supervisor(n.id).broker.active();if(!c?.enabled)continue;if(!o?.length){i.push({pluginId:n.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let a=[c.version,...o.map(u=>u.version).sort((u,v)=>Ie(v,u))],l=!1,p="";for(let u of new Set(a))try{await t.load(n.id,u),l=!0;break}catch(v){p||=K(v).message}l||i.push({pluginId:n.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return i}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(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],r=async()=>{let i=await Promise.allSettled(t.map(o=>o()));this.closing=!1;let n=i.find(o=>o.status==="rejected");if(n?.status==="rejected")throw n.reason};try{for(let i of this.supervisors.values())t.push(await i.suspendForRestart(void 0,e));return r}catch(i){throw await r(),i}}};import{randomUUID as Wu}from"node:crypto";var N=s=>Object.assign(new Error(s),{status:409,code:"view_barrier"}),Ut=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;staleMs;constructor(e,t,r=2e4,i=15e3,n=12e4){this.pluginId=e,this.generation=t,this.pollMs=r,this.freezeMs=i,this.staleMs=n}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,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??Wu();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw N("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 N("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.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:[],seenAt:Date.now()}),{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),n=this.retired.get(e.viewToken);if(n&&!this.sameScope(n,e,t))throw N("Unknown or stale view capability");if(e.operation==="status"){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(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let o=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:o}}}if(r&&this.sameScope(r,e,t)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),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(n)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(c=>c.id===e.commandId);if(!o)throw N("Unknown command acknowledgement");r.commands=r.commands.filter(c=>c.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 c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),r.waiter=void 0,o()}r.waiter=a}),{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}${r.activeActions?` (action in flight x${r.activeActions})`:r.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let i=n=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,n?r(n):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(n=>n.token)),resolve:()=>i(),reject:n=>i(n),timer:setTimeout(()=>{let n=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));i(N(`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||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 $u="@chengzhiyi/pi-excalidraw",Vu={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"}}},Fu="@chengzhiyi/pi-github",Uu={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"}}},sa=new Map([[$u,Vu],[Fu,Uu]]);function Ui(s,e){let t=s.get(e);if(!t)throw new f("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as Bu}from"node:crypto";var Lu="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"}),zu="Ov23limJmKiuu8cOP83E";function Bi(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||zu,scope:"repo",createUrl:Lu}}var qu="https://github.com/login/device/code",Gu="https://github.com/login/oauth/access_token",Ju=8,Rr=class{flows=new Map;fetcher;now;constructor(e=(r,i)=>fetch(r,{...i,signal:i.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let r;try{r=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 f("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let i=await r.json().catch(()=>null);if(!i||typeof i!="object"||!r.ok&&!("error"in i))throw new f("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return i}async start(e,t,r){if(!r.clientId)throw new f("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[u,v]of this.flows)v.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=Ju)throw new f("oauth_busy","Too many sign-ins in progress",{status:429});let i=await this.post(qu,{client_id:r.clientId,scope:r.scope}),{device_code:n,user_code:o,verification_uri:c}=i,a=Number(i.expires_in),l=Math.max(Number(i.interval)||5,1);if(typeof n!="string"||typeof o!="string"||typeof c!="string"||!c.startsWith("https://github.com/")||!Number.isFinite(a))throw new f("oauth_failed",typeof i.error_description=="string"?i.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:r.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 r=await this.post(Gu,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:t.pluginId,name:t.name};switch(r.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 oa,readFileSync as aa,statSync as Ku}from"node:fs";import{lstat as Xu,readdir as Yu,writeFile as Qu,mkdir as Zu,rename as ef}from"node:fs/promises";import{delimiter as tf,dirname as rf,isAbsolute as sf,join as et,resolve as Bt}from"node:path";var na="@chengzhiyi/pi-github",Dr={[na]:{id:na,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"]}},ca=()=>Object.keys(Dr).join(", ");function nf(s=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,r=[],i="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=Dr[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?oa(Bt(a))?null:`archive not found: ${Bt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${ca()})`;if(p){r.push({level:"error",source:i,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,Bt(a))}return{catalog:e,archives:t,notices:r}}var la=s=>et(s,"pi-web","hosted-dev.json"),da=s=>et(s,"pi-web","hosted-dev-status.json");function of(s,e,t=process.cwd()){let r=[],i=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(tf).map(c=>c.trim()).filter(Boolean);for(let c of n)r.push({path:Bt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&oa(e)){o=!0;try{let c=JSON.parse(aa(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"||!sf(l)?i.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):r.push({path:Bt(l),source:e})}catch(c){i.push({level:"error",source:e,message:`cannot read dev configuration: ${c instanceof Error?c.message:String(c)}`})}}return{specs:r,notices:i,configured:o}}function af(s){let e=(i,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${i}`}}),t;try{t=Ku(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 r;try{r=JSON.parse(aa(et(s.path,"package.json"),"utf8"))}catch(i){return e(i.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof r.name!="string"?e("package.json has no name"):Dr[r.name]?je(r.piWebapp)?{pluginId:r.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name):e(`unknown plugin id "${r.name}" (known: ${ca()})`)}var Cr=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=nf(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 r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let t=of(this.env,this.configPath,this.cwd),r=[],i=new Map,n=new Map;for(let o of t.specs){let c=af(o);if(c.notice){r.push(c.notice);continue}let a=c.pluginId;if(i.has(a)){r.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${i.get(a)}`});continue}if(this.archives.has(a)&&r.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){r.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(Dr[a])}i.set(a,o.path),n.set(a,o.source)}for(let o of[...this.roots.keys()])i.has(o)||this.roots.delete(o);for(let[o,c]of i)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=r,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Nr=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: ${K(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,r]of e){let i=this.roots.get(t);(!i||i.root!==r)&&(i={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,i));let n=await cf(r);if(n===null){this.set(t,i,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),i.seen=void 0;continue}if(n!==i.seen){i.seen=n;continue}n===i.applied||this.stopped||await this.apply(t,i,n)}await this.publish()}set(e,t,r,i={}){let n=t.state!==r||t.message!==i.message||t.version!==i.version;t.state=r,t.message=i.message,t.code=i.code,t.version=i.version??t.version,n&&(t.at=new Date().toISOString(),this.log(`${e}: ${r}${i.version?` ${i.version}`:""}${i.message?` \u2014 ${i.message}`:""}`))}async apply(e,t,r){this.set(e,t,"switching");try{let n=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=r,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(i){let n=K(i);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(n.code)||(t.applied=r),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 r=this.options.statusPath;if(!r)return;let i=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:i,notices:e.notices});if(n===this.lastStatus)return;this.lastStatus=n;let o=`${r}.${process.pid}.tmp`;try{await Zu(rf(r),{recursive:!0}),await Qu(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await ef(o,r)}catch{}}};async function cf(s){let e=[],t=async(r,i)=>{let n=await Xu(r);e.push(`${i}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(et(s,"package.json"),"package.json");let r=async(i,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await Yu(i,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await r(et(i,c.name),`${n}/${c.name}`,o+1):await t(et(i,c.name),`${n}/${c.name}`)};if(await r(et(s,"dist"),"dist",0),!e.some(i=>i.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function df(s){try{return[...ut(s).secrets]}catch{return[]}}var Or=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Rr;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??sa,e.dev?.enabled&&(this.devWatcher=new Nr({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let r=await this.inventory();return r.plugins.find(i=>i.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):r}}})),this.adapter=new kr({policy:(t,r)=>{let i=e.policy?.(t,r);return{...i,enabled:!this.recovery.has(t)&&this.manager.tools.some(n=>n.pluginId===t)&&i?.enabled!==!1}},invoke:async(t,r,i)=>{i?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let n=this.manager.tools.find(c=>c.pluginId===t);if(!n)throw new f("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,n.generation,r);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Tr({...e,lifecycle:(t,r,i)=>this.lifecycle(t,r,i),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(Ui(this.trusted,t).tools).length)throw new f("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(n=>n.pluginId===t)?.descriptors:[];if(!i)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,i),r.enabled){let n=await this.manager.installer.load(t,r.version);this.documents.set(t,{document:n.manifest.frontend.document.replace(/^\.\//,""),controller:n.manifest.frontend.controller.replace(/^\.\//,""),secrets:df(n.manifest)})}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),secret:async(t,r,i)=>{let n=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!n)throw new f("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(r))throw new f("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return i===null?await n.delete(t,r):await n.set(t,r,i),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let r=this.options.capabilities?.secrets;if(!r)throw new f("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)?Bi(t.pluginId,t.name):void 0;if(!n)throw new f("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 i=await this.deviceFlows.poll(t.deviceId);return i.status!=="granted"?{status:i.status}:(await r.set(i.pluginId,i.name,i.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,r)=>{if(!this.options.approvals)throw new f("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,r),this.inventory()},action:(t,r)=>this.action(t,r?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new f("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}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){let r=Ui(this.trusted,e);for(let i of t)if(!Object.hasOwn(r.tools,i.name)||r.tools[i.name]!==i.action||i.readonly!==r.readonlyActions.includes(i.action))throw new f("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new f("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 f("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 f("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 f("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 f("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 Ze(Li(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new f("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return n}finally{if(!r)for(let n of this.views.values())n.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=i.catch(()=>{}),i.catch(n=>{throw r&&this.adapter.thaw(),n})}async admit(e){let t,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(i=>{t=setTimeout(()=>i(!1),e),t.unref?.()})])}finally{clearTimeout(t)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Ce)try{let t=await new Ze(Li(this.options.root,"data"),e.id).active();this.views.set(e.id,new Ut(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new Ut(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Li(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await Z(this.options.root),await M(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Ce)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,r=new Map;for(let i of e.plugins){let n=i.enabled?this.documents.get(i.id)?.secrets??[]:[];t&&n.length&&r.set(i.id,await Promise.all(n.map(async o=>{let c=Bi(i.id,o);return{name:o,configured:await t.has(i.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(i=>({pluginId:i.id,name:i.name,official:i.official,installed:i.installed,enabled:i.enabled,description:i.description,...r.has(i.id)?{secrets:r.get(i.id)}:{},icon:(this.options.catalog??Ce).find(n=>n.id===i.id)?.icon,hasRetainedData:i.activeVersion!==null,phase:this.recovery.has(i.id)?"reconnect-required":i.phase,updatePolicy:i.updatePolicy,pinnedVersion:i.pinnedVersion,updateDiagnostic:i.updateDiagnostic,...i.enabled&&i.activeVersion?{version:i.activeVersion}:i.version?{version:i.version}:{},...i.availableVersion?{availableVersion:i.availableVersion}:{},...i.pendingVersion?{pendingVersion:i.pendingVersion}:{},...i.generation!==null?{generation:i.generation}:{},...this.recovery.has(i.id)||i.error?{error:this.recovery.get(i.id)instanceof Error?this.recovery.get(i.id).message:i.error?.message??"Recovery required",errorCode:this.recovery.has(i.id)?"reconnect_required":i.error?.code}:{},...i.enabled&&i.assetBase&&this.documents.has(i.id)&&this.trusted.has(i.id)?{documentUrl:i.assetBase+this.documents.get(i.id).document,controllerUrl:i.assetBase+this.documents.get(i.id).controller,contribution:structuredClone(this.trusted.get(i.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}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 f("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new f("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 f("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 f("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 f("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.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 r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new f("action_denied","Action is not reviewed by this host",{status:403});let i=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let n={requestId:lf(),scope:r,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(r)))return await this.manager.flush(e.pluginId,e.generation,n);throw new f("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new f("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{i()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let n of this.views.values())n.allowImmediateReopen(!0);let t=await this.manager.suspendForRestart(e),r=!1,i=async()=>{if(!r)try{await t(),r=!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(t){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),t}finally{for(let t of this.views.values())t.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 pf,readdir as uf,unlink as ff}from"node:fs/promises";import{join as mt}from"node:path";import{randomUUID as hf}from"node:crypto";var zi="hosted-migration.json";function pa(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:i}=t.scope,n=mt(s,F(JSON.stringify([r,i])));await Z(s),await Z(n);let o=mt(n,"scope.lock"),c;try{c=await pf(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new f("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:hf()}));let a=await ee(mt(n,zi));if(a&&(a.version!==1||a.pluginId!==e))throw new f("invalid_storage","Legacy scope belongs to another migration");let l=await uf(n),p=[];for(let v of l){if(v==="scope.lock"||v==="focus.json"||v===zi||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(v))continue;if(!/^[\w-]{1,80}\.json$/.test(v))throw new f("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new f("invalid_storage","Too many legacy checkpoints");let w=await ee(mt(n,v),3*512*1024);if(!w||w.version!==1||w.cwd!==r||w.sessionId!==i||!w.draft||v!==`${w.draft.id}.json`)throw new f("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(w.draft)}let u=await ee(mt(n,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(v=>v.id===u)))throw new f("invalid_storage","Invalid legacy focused drawing");return a||await M(mt(n,zi),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await ff(o)}}}import{join as If}from"node:path";import{randomUUID as gf}from"node:crypto";var mf=6e4,Hr=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:r,title:i})=>({id:e,pluginId:t,sessionId:r,title:i}))}async authorize(e,t){let r=this.entries.get(t);if(r&&r.pluginId!==e)throw new f("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new f("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<mf?new f("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:gf(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new f("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,t){let r=[...this.entries.values()].find(i=>i.id===e&&i.status==="pending");if(!r)throw new f("unknown_approval","No such pending approval",{status:404});r.status=t?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as wf,readFile as yf,rename as vf,writeFile as bf}from"node:fs/promises";import{randomUUID as kf,createHash as Pf}from"node:crypto";import{join as ua}from"node:path";var Mr=class{dir;queue=Promise.resolve();constructor(e){this.dir=ua(e,"secrets")}file=e=>ua(this.dir,`${Pf("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await yf(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!He(t))throw new f("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(r=>r!==null)}set(e,t,r){return this.mutate(e,i=>{i[t]=r})}delete(e,t){return this.mutate(e,r=>{delete r[t]})}mutate(e,t){return this.serialize(async()=>{let r=await this.read(e);t(r),await wf(this.dir,{recursive:!0,mode:448});let i=`${this.file(e)}.${kf()}.tmp`;await bf(i,JSON.stringify(r),{mode:384}),await vf(i,this.file(e))})}};function fa(s,e){let t=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:i,title:n,prompt:o}){let c=await s.createDetached(i,r,n);try{await s.sendDetached(c,o,!1)}catch(a){throw await s.releaseDetached(c),a}return{sessionId:c}},ownerOf:r=>s.detachedOwner(r),activeCount:r=>s.detachedCount(r),async send(r,i,n){let o=s.detachedOwner(r);if(n==="execute"&&(!o||!await e(o,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await s.sendDetached(r,i,n==="execute")},abort:r=>s.abortDetached(r),release:r=>s.releaseDetached(r),async events(r,i){let n=s.detachedEvents(r,i);return{events:n.events.map(t),next:n.next}}}}var Sf="scheduler";function ha(s){let e=new Hr({describe:s.sessionTitle,changed:s.changed}),t=()=>{let i=s.sessions();if(!i)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return i},r={createDetached:(...i)=>t().createDetached(...i),detachedOwner:i=>s.sessions()?.detachedOwner(i)??null,detachedCount:i=>s.sessions()?.detachedCount(i)??0,sendDetached:(...i)=>t().sendDetached(...i),abortDetached:i=>t().abortDetached(i),releaseDetached:async i=>{e.forget(i),await t().releaseDetached(i)},detachedEvents:(...i)=>t().detachedEvents(...i)};return{approvals:e,capabilities:{secrets:new Mr(If(s.root,"capability-secrets")),sessions:fa(r,(i,n)=>e.authorize(i,n))},scheduledScope:()=>{let i=s.activeWorkspace();if(!i)return null;try{return s.trustedScope(i,Sf)}catch{return null}}}}async function Ef(){for(let s of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=tr(s),t=new Se({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:Et,buildId:Pe,browser:tr({}).browser}}async function ga(){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 Se({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:Et,buildId:Pe}}finally{await s.close()}}var Lt=vt(_f(Rf(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),Hf=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[Hf]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Oe(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:Ne()}),re()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Ke,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Ke;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new Oe(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:Ne()}),re()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function jr(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var Mf=null;function jf(){return Mf??=Cf.create({refreshOnCreate:!1})}var Wr=new Map;async function yt(){let s=await jf(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Wr.keys())t.has(r)||(s.unregisterProvider(r),Wr.delete(r));for(let r of t){let i=e?.getRegisteredNativeProvider(r),n=e?.getRegisteredProviderConfig(r),o=i??n;!o||Wr.get(r)===o||(i?s.registerNativeProvider(i):n&&s.registerProvider(r,n),Wr.set(r,o))}return await s.refresh({allowNetwork:!1}),s}function ie(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():Ne()}function Ne(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...Rn(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 Yi(s,e,t,r,i){let n=de(s);De({...Ne(),idle:n.isIdle()},e,i);let o=n.isIdle();o&&dt(()=>d.hosted?.adapter.assertAdmission(),r,(c,a)=>d.bridge?.reportError?.(c,a)),o&&(d.operation=r);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:i});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:i})}d.current?.sessionManager.getSessionId()===s&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:Ne()})}catch(c){throw o&&(d.operation=void 0),c}}function Ji(){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 r=Ne();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!r.paused&&!r.interactions.length};d.tuiPrompts.schedule(t,(r,i,n)=>Yi(s,r,i,n))}function ne(s){if(ie().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function ba(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=ie(),i=d.current?Ne():null,n=await qe(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=i?await qe(i.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await Xi.listAll(),a=d.workspaceSessions?.retainedSessions()??[];i&&o&&a.push({sessionId:i.sessionId,cwd:o,path:null,name:i.name,modified:i.messages.at(-1)?.timestamp??new Date().toISOString(),idle:i.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&i.idle&&d.tuiPrompts.length===0&&!i.messages.some(p=>p.role==="user")});let l=(await Promise.all(s.map(async p=>{let v=(await ct(p.path,c).catch(w=>(w instanceof Rt?p.available=!1:d.bridge?.reportError?.(w,{stage:"workspace_sessions"}),[]))).map(w=>({id:w.id,workspaceId:p.id,path:w.path,name:w.name||w.firstMessage?.slice(0,50)||"",modified:w.modified.toISOString(),idle:!0}));for(let w of a.filter(h=>h.cwd===p.path)){if(w.blank&&w.sessionId!==t.sessionId)continue;let h=v.findIndex(k=>k.id===w.sessionId),m={id:w.sessionId,workspaceId:p.id,path:w.path??v[h]?.path??null,name:w.name,modified:w.modified,idle:w.idle};h<0?v.unshift(m):v[h]=m}return p.path===n&&!v.some(w=>w.id===t.sessionId)&&v.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),v}))).flat();return{items:s,activeId:e,sessions:l}}var wa=0;async function re(){if(!d.bridge)return;let s=++wa;try{let e=await ba();s===wa&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function Ki(s,e=!1){let t=d.workspaces?.get(s);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await xe(t.path),!e&&d.current&&t.path===await qe(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:ie()});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:ie()})}await re()}async function ya(s,e,t){let r=d.workspaces?.get(s);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let i=await xe(r.path);if(d.workspaceSessions?.hasSession(i,e)||d.current?.sessionManager.getSessionId()===e&&await qe(d.current.cwd)===i)return r;if(!(await ct(i)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function de(s){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function ae(s){d.current=s,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:ie()})}function ka(){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 Nf.create(s,void 0,{projectTrusted:e})}async function Pa(){let s=ka(),e=i=>({packages:(i.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:i.extensions??[],skills:i.skills??[]}),t=new va({cwd:ie().cwd,agentDir:ge(),settingsManager:s}),r=ro(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:r}}async function Wf(s){ne(s.sessionId);let e=d.selected==="tui"?de(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=ka();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 r=s.value.trim(),i=s.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(s.kind==="packages"){let n=new va({cwd:ie().cwd,agentDir:ge(),settingsManager:t});s.action==="add"?await n.installAndPersist(r,{local:s.scope==="project"}):await n.removeAndPersist(r,{local:s.scope==="project"})}else if(s.kind==="extensions"){let n=i.extensions??[],o=s.action==="add"?[...new Set([...n,r])]:n.filter(c=>c!==r);s.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let n=i.skills??[],o=s.action==="add"?[...new Set([...n,r])]:n.filter(c=>c!==r);s.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 Pa()}function $r(s,e=ui){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=qi(a);return{cwd:p,sessionId:l,workspaceId:ma("sha256").update(p).digest("hex")}},r=wt(ge(),"pi-web","hosted"),i=new Cr({configPath:la(ge())});d.hosted??=new Or({root:r,...i.enabled?{dev:i,devStatusPath:da(ge())}:{},...i.catalog.length?{catalog:[...Ce,...i.catalog],devArchives:i.archives,devRoots:i.roots}:{},...ha({root:r,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(Af(vt(Lt,"../../package.json"),"utf8")).version,packageRoot:vt(Lt,"../.."),workerEntry:vt(Lt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${ma("sha256").update(ge()).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:()=>pa(wt(ge(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Ji),d.pi=s,d.tools?.clear(),d.tools=new lt({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:Gi,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new at(s.events,a=>!!d.bridge&&a.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(a.pluginId),()=>{d.current&&d.selected==="tui"&&ae(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=s.events.on(cr,()=>{d.selected==="tui"&&d.current&&ae(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())),d.hosted&&!await d.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new Oe(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:Ne()}),re()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Je.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),ae(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 re())}).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)),ae(l),re()}),s.on("agent_end",(a,l)=>ae(l)),s.on("agent_settled",(a,l)=>{d.bridge?.breadcrumb?.("agent_end",n(l)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Ji(),ae(l),re()}),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)=>ae(l)),s.on("thinking_level_select",(a,l)=>ae(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:Gi});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}),ae(l),re()}),s.on("session_info_changed",(a,l)=>ae(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:ze(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 Se;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=s,d.tuiCatalog=await Je.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ar(On(ge())),await d.workspaces.load());try{await d.workspaces.discover((await Xi.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!==Pe||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 Se}if(d.bridge===null){let u=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,v=u?.session&&u.path?{path:u.path,sessionManager:u.session.sessionManager}:null;u&&(await u.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new ur(h=>{d.selected==="sdk"&&d.bridge?.publish(h)},()=>d.current?.model,h=>{try{return!!d.current&&qi(d.current.cwd)===h&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(h,m)=>d.bridge?.reportError?.(h,m),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(h,m)=>d.bridge?.breadcrumb?.(h,m),anonymize:h=>d.telemetry?.session(h)??"unavailable"},()=>{re()},[],{adapter:d.hosted.adapter,scope:t}),v&&await d.workspaceSessions.open(v.path,{sessionManager:v.sessionManager});let w={hosted:d.hosted?.handlers,selfUpdate:new br({agentDir:ge(),packageRoot:vt(Lt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:h=>d.hosted.manager.hostUpdateWarnings(h),prefetchPlugins:(h,m)=>d.hosted.manager.prefetchForHost(h,m),beforeRestart:h=>d.hosted.prepareRestart(h)}),snapshot:ie,busyGitWorkspaces:()=>{let h=(d.workspaceSessions?.retainedSessions()??[]).filter(m=>!m.idle).map(m=>m.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{h.push(qi(d.current.cwd))}catch{h.push(d.current.cwd)}return h},plugins:async()=>{let h=jr();return await h?.refreshAssets(),h?.view()??{plugins:[],errors:[]}},pluginAsset:async h=>jr()?.asset(h)??null,async invokePluginAction(h,m,k,I){if(ne(h),!jr()?.has(m))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,A=d.tuiGeneration,O=d.workspaceSessions?.session,H={requestId:Of(),sessionId:h,pluginId:m,action:k,input:I},T=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(H):await lr(d.pi.events,H,15e3,d.tuiWaitController.signal);if(ne(h),E!==d.selected||(E==="tui"?A!==d.tuiGeneration:O!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&ae(d.current),T},async resolvePluginInteraction(h,m,k,I){if(ne(h),!jr()?.has(m))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(h,m,k,I):d.interactions.resolve(h,m,k,I)},image(h,m,k){ne(h);let E=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(O=>O.id===m);if(E?.type!=="message"||E.message.role!=="user"||!Array.isArray(E.message.content))return null;let A=E.message.content[k];return A?.type!=="image"?null:{data:Buffer.from(A.data,"base64"),mimeType:A.mimeType}},async workspaces(){return ba()},async addWorkspace(h,m){let k=await d.workspaces.add(h,m);try{await Ki(k.id,!0)}catch(I){throw await re(),I}},async selectWorkspace(h){await Ki(h)},async newSessionInWorkspace(h){await Ki(h,!0)},async removeWorkspace(h){if(h===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(h),await re()},async selectSession(h,m,k){let I=d.workspaces?.get(h);if(!I)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await xe(I.path),m===d.current?.sessionManager.getSessionId()&&I.path===await qe(d.current.cwd))d.selected="tui",d.activeWorkspaceId=h,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:ie()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===m&&d.workspaceSessions.path===I.path)return;if(d.workspaceSessions?.hasSession(I.path,m))await d.workspaceSessions.open(I.path,{sessionId:m});else{if(!(await ct(I.path)).some(A=>A.id===m&&A.path===k))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(I.path,{sessionFile:k})}d.selected="sdk",d.activeWorkspaceId=h,d.bridge?.publish({type:"snapshot",session:ie()})}await re()},async renameSession(h,m,k,I){let E=I.replace(/\s+/g," ").trim();if(E.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await ya(h,m,k),d.current?.sessionManager.getSessionId()===m&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(m,E)||Xi.open(k).appendSessionInfo(E),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===m&&d.bridge?.publish({type:"snapshot",session:ie()}),await re()},async deleteSession(h,m,k){let I=await ya(h,m,k);if(d.current?.sessionManager.getSessionId()===m)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(m)??null,A=E?.path??(k||null);A&&await to(A,ge()),E?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(I.path,"new"),d.selected="sdk",d.activeWorkspaceId=h,d.bridge?.publish({type:"snapshot",session:ie()})),await re()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let h=d.current;if(!h)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let m=h.scopedModels?.map(k=>`${k.model.provider}/${k.model.id}`)??[];return h.modelRegistry.getAvailable().filter(k=>m.length===0||m.includes(`${k.provider}/${k.id}`)).map(k=>({provider:k.provider,id:k.id,name:k.name}))},async providers(){let h=await yt(),m=new Set((await h.listCredentials()).map(k=>k.providerId));return h.getProviders().map(k=>({id:k.id,name:k.name,configured:h.getProviderAuthStatus(k.id).configured,storedCredential:m.has(k.id),methods:[k.auth.apiKey?.login?"api_key":null,k.auth.oauth?"oauth":null].filter(I=>I!==null)}))},async providerModels(h){let m=await yt();return mn(wt(ge(),"models.json"),h,m)},async updateProviderModel(h,m,k){if(ne(h),d.selected==="tui"?!de(h).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let I=ie().model;if(k.action==="remove"&&I===`${m}/${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&&I===`${m}/${k.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let E=await yt();await wn(wt(ge(),"models.json"),m,k,E),await E.refresh({providers:[m],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[m],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[m],allowNetwork:!1});let A=k.action==="save"?k.model.id:k.action==="base_url"&&I?.startsWith(`${m}/`)?I.slice(m.length+1):null;if(A&&I===`${m}/${A}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(m,A)}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 O=de(h),H=O.modelRegistry.find(m,A);if(!H||!d.pi||!await d.pi.setModel(H))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");ae(O)}},async logoutProvider(h,m){if(ne(h),d.selected==="tui"?!de(h).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 yt();if(!(await k.listCredentials()).some(I=>I.providerId===m))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await k.logout(m),await d.current?.modelRegistry.refresh({providers:[m],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[m],allowNetwork:!1})},async loginProvider(h,m,k){let I=await yt();await I.login(h,m,dn(h,m,k)),await I.refresh({providers:[h],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[h],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[h],allowNetwork:!1})},async addCustomProvider(h,m){if(ne(h),d.selected==="tui"?!de(h).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 yt();if(k.getProvider(m.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await pn(wt(ge(),"models.json"),m),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(h=>h.name!=="web"&&h.name!=="web-dev-reload").map(h=>({name:h.name,description:h.description})):[]},async compact(h){if(ne(h),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:ie()});return}let m=de(h);if(!m.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");m.compact()},async setModel(h,m,k){if(ne(h),d.selected==="sdk"){await d.workspaceSessions.setModel(m,k);return}let I=de(h);if(!I.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=I.modelRegistry.find(m,k);if(!E||!I.modelRegistry.getAvailable().some(A=>A.provider===m&&A.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");ae(I)},async setThinkingLevel(h,m){if(ne(h),!["off","minimal","low","medium","high","xhigh"].includes(m))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(m))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");E.setThinkingLevel(m),d.bridge?.publish({type:"snapshot",session:ie()});return}let I=de(h);if(!I.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!I.model||!Df(I.model).includes(m))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(m),ae(I)},config:Pa,updateConfig:Wf,async send(h,m,k=[],I,E){if(ne(h),d.selected==="sdk"){await d.workspaceSessions.send(m,k,I,E);return}let A=de(h);if(De(Ne(),m,E),E==="followUp"&&(!A.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(m,k,I),Ji();return}if(A.isIdle()&&d.tuiPrompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Yi(h,m,k,I,E)},async updateQueuedPrompt(h,m,k,I){if(ne(h),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(m,k,I);return}if(I.kind==="steer"&&de(h).isIdle())throw new oe("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(m,k,I,(E,A,O)=>Yi(h,E,A,O,"steer"))},async abort(h){if(ne(h),d.selected==="sdk")await d.workspaceSessions.stop();else{let m=de(h);if(m.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(At),m.abort()}},async resume(h,m){if(ne(h),d.selected==="sdk"){await d.workspaceSessions.resume(m);return}let k=de(h);if(dt(()=>d.hosted?.adapter.assertAdmission(),m,(I,E)=>d.bridge?.reportError?.(I,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=m;try{d.pi.sendMessage(dr(ie().messages),{triggerTurn:!0})}catch(I){throw d.operation=void 0,I}},async newSession(h){if(ne(h),d.selected==="sdk"){let I=d.workspaces?.get(d.activeWorkspaceId??"");if(!I)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(I.path)||await d.workspaceSessions.open(I.path,"new"),await re();return}let m=de(h);if(!m.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(m.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:ie()}),await re();return}if((await d.commandContext.newSession({withSession:async I=>{d.commandContext=I,d.replacementContext=I,d.replacementSessionId=I.sessionManager.getSessionId(),d.current=I}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await re()}};w.addWorkspace=d.lifecycle.wrap(w.addWorkspace),w.selectWorkspace=d.lifecycle.wrap(w.selectWorkspace),w.newSessionInWorkspace=d.lifecycle.wrap(w.newSessionInWorkspace),w.removeWorkspace=d.lifecycle.wrap(w.removeWorkspace),w.selectSession=d.lifecycle.wrap(w.selectSession),w.renameSession=d.lifecycle.wrap(w.renameSession),w.deleteSession=d.lifecycle.wrap(w.deleteSession),w.newSession=d.lifecycle.wrap(w.newSession),w.updateConfig=d.lifecycle.wrap(w.updateConfig),d.bridge=await Tn(w,Lt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let u=[],v=null;for(let w of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(xf).filter(Boolean))try{u.push(Tf(wt(vt(w),"dist"),(h,m)=>{let k=String(m??"");["client.js","client.css"].includes(k)&&(v&&clearTimeout(v),v=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(h){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${w}: ${String(h)}`})}d.stopPluginWatch=()=>{for(let w of u)w.close();v&&clearTimeout(v)}}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:Gi}),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 pP=$r;export{pP as default,Ef as verifySentryDisabledRelease,ga as verifySentryNodeRelease};
|
|
48
48
|
|
|
49
|
-
//# debugId=
|
|
49
|
+
//# debugId=9e20e653-5bbf-464a-a434-24bf112c8a35
|