pi-webapp 0.1.50-alpha.3 → 0.1.50-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/extension.js CHANGED
@@ -1,49 +1,49 @@
1
- (function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="fbbcbd4a-0bea-4e92-adf3-88783db8ace0",s._sentryDebugIdIdentifier="sentry-dbid-fbbcbd4a-0bea-4e92-adf3-88783db8ace0")}catch{}})();import{delimiter as Ju,dirname as Ku,join as kt,resolve as It}from"node:path";import{readFileSync as Xu,realpathSync as Ur,watch as Yu}from"node:fs";import{fileURLToPath as Qu}from"node:url";import{DefaultPackageManager as ea,getAgentDir as Pe,ModelRuntime as Zu,SessionManager as ta,SettingsManager as eh,VERSION as Br}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as th}from"@earendil-works/pi-ai";import{randomBytes as kn,randomUUID as rr,timingSafeEqual as sl}from"node:crypto";import{readFile as nl,readdir as ol}from"node:fs/promises";import{createServer as al}from"node:http";import{join as sr}from"node:path";import{getAgentDir as cl}from"@earendil-works/pi-coding-agent";import{isAbsolute as Oa,relative as Ma}from"node:path";var nt={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Gr={id:nt.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 aa}from"node:child_process";import{realpath as ca}from"node:fs/promises";import{isAbsolute as Jr,relative as la,sep as da,win32 as pa}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function L(s,e,t=2*1024*1024,i={}){let r=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=aa("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 w=l.code;w==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):w==="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 Ce(s){let e=await ca(s),t;try{t=(await L(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(r){if(r instanceof R&&r.status===404)return{kind:"not-repository"};if(r instanceof R&&r.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw r}let i=la(t,e).split(da).join("/");if(i===".."||i.startsWith("../")||Jr(i))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function qe(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||Jr(s)||pa.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 Ia}from"node:crypto";import{lstat as Gi,realpath as ls}from"node:fs/promises";import{dirname as cs,isAbsolute as Sa,relative as Ea,resolve as Et}from"node:path";import{lstat as ba}from"node:fs/promises";import{resolve as ka}from"node:path";import{constants as ot}from"node:fs";import{open as Qr,opendir as ua,realpath as Kr,stat as Li}from"node:fs/promises";import{isAbsolute as Zr,relative as ha,resolve as fa,sep as ga,win32 as ma}from"node:path";var wa=1e3,ya=512*1024,es=8*1024*1024,Xr=1e4,va=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 Yr(s,e){let t=ha(s,e);return t!==".."&&!t.startsWith(`..${ga}`)&&!Zr(t)}async function Jt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||Zr(e)||ma.isAbsolute(e))throw new J("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Kr(s),i=fa(t,e);if(!Yr(t,i))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let r=await Kr(i);if(!Yr(t,r))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return r}async function zi(s){try{return await s()}catch(e){if(e instanceof J)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new J("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new J("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function ts(s,e){return zi(async()=>{let t=await Jt(s,e),i=[],r=!1;for await(let n of await ua(t)){if(i.length===wa){r=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await Li(await Jt(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")||va.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:i,truncated:r}})}function is(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 St(s,e){return zi(async()=>{let t=await Jt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Qr(t,ot.O_RDONLY|ot.O_NONBLOCK|(ot.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=is(o),a=c?es:ya;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 w=1;for(let m=0;m<u.length-1;m++)if(u[m]===10&&++w>Xr)return{...n,kind:"too-large",limit:Xr,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 rs(s,e){return zi(async()=>{let t=await Jt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Qr(t,ot.O_RDONLY|ot.O_NONBLOCK|(ot.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>es)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=is(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 Pa=1e3,ss=512*1024,ns=1e4;function os(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function at(s){let e=await Ce(s);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,r=await L(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=r.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let k=a.slice(13);n.head=k==="(initial)"?null:k;continue}if(a.startsWith("# branch.head ")){let k=a.slice(14);n.branch=k==="(detached)"?null:k;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let k=a.match(/\+(\d+) -(\d+)/);k&&(n.ahead=Number(k[1]),n.behind=Number(k[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 k=0;k<p;k++)u=a.indexOf(" ",u)+1;let w=os(i,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!w)continue;if(n.entries.length===Pa){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),y={path:w,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},P=m===void 0?void 0:os(i,m);P&&(y.originalPath=P),n.entries.push(y)}return n}async function as(s,e,t){if(qe(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await at(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 ba(ka(s,e))).isFile())return{...r,kind:"unsupported"};let c=await St(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 window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="21797faa-38d4-4a0e-a037-226896d3ebe4",s._sentryDebugIdIdentifier="sentry-dbid-21797faa-38d4-4a0e-a037-226896d3ebe4")}catch{}})();import{delimiter as rh,dirname as sh,join as Pt,resolve as St}from"node:path";import{readFileSync as nh,realpathSync as Br,watch as oh}from"node:fs";import{fileURLToPath as ah}from"node:url";import{DefaultPackageManager as sa,getAgentDir as we,ModelRuntime as ch,SessionManager as qr,SettingsManager as lh,VERSION as Ur}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as dh}from"@earendil-works/pi-ai";import{randomBytes as Pn,randomUUID as rr,timingSafeEqual as al}from"node:crypto";import{readFile as cl,readdir as ll}from"node:fs/promises";import{createServer as dl}from"node:http";import{join as sr}from"node:path";import{getAgentDir as pl}from"@earendil-works/pi-coding-agent";import{isAbsolute as Wa,relative as $a}from"node:path";var ot={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Jr={id:ot.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as da}from"node:child_process";import{realpath as pa}from"node:fs/promises";import{isAbsolute as Kr,relative as ua,sep as ha,win32 as fa}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function L(s,e,t=2*1024*1024,i={}){let r=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=da("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,env:{...r,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:i.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new R("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,i.write?"outcome_unknown":"git_failed"));return}n(p);return}if(i.write){let m=l.killed||l.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(u)?"index_locked":/already exists/i.test(u)?"branch_exists":/already checked out|used by worktree/i.test(u)?"branch_in_use":/would be overwritten|local changes/i.test(u)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(u)?"identity_missing":"git_failed";o(new R("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",m==="outcome_unknown"?503:409,m));return}let y=l.code;y==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):y==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new R("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new R("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new R(l.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});a.stdin?.on("error",l=>{c=l}),i.input!==void 0&&a.stdin?.end(i.input)})}async function De(s){let e=await pa(s),t;try{t=(await L(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(r){if(r instanceof R&&r.status===404)return{kind:"not-repository"};if(r instanceof R&&r.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw r}let i=ua(t,e).split(ha).join("/");if(i===".."||i.startsWith("../")||Kr(i))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function qe(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||Kr(s)||fa.isAbsolute(s)||s.split("/").some(e=>!e||e==="."||e===".."))throw new R("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as xa}from"node:crypto";import{lstat as Gi,realpath as ds}from"node:fs/promises";import{dirname as ls,isAbsolute as _a,relative as Aa,resolve as xt}from"node:path";import{lstat as Ia}from"node:fs/promises";import{resolve as Sa}from"node:path";import{constants as at}from"node:fs";import{open as Zr,opendir as ga,realpath as Xr,stat as Li}from"node:fs/promises";import{isAbsolute as es,relative as ma,resolve as wa,sep as ya,win32 as va}from"node:path";var ba=1e3,ka=512*1024,ts=8*1024*1024,Yr=1e4,Pa=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),J=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function Qr(s,e){let t=ma(s,e);return t!==".."&&!t.startsWith(`..${ya}`)&&!es(t)}async function Kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||es(e)||va.isAbsolute(e))throw new J("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Xr(s),i=wa(t,e);if(!Qr(t,i))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let r=await Xr(i);if(!Qr(t,r))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return r}async function zi(s){try{return await s()}catch(e){if(e instanceof J)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new J("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new J("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function is(s,e){return zi(async()=>{let t=await Kt(s,e),i=[],r=!1;for await(let n of await ga(t)){if(i.length===ba){r=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await Li(await Kt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}i.push({name:n.name,path:o,kind:c})}return i.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Pa.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:i,truncated:r}})}function rs(s){if(s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(s.subarray(0,6).toString("ascii")))return"image/gif";if(s.subarray(0,4).toString("ascii")==="RIFF"&&s.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Et(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n={path:e,size:r.size},o=Buffer.alloc(16);await i.read(o,0,o.length,0);let c=rs(o),a=c?ts:ka;if(r.size>a)return{...n,kind:"too-large",limit:a,unit:"bytes"};let l=Buffer.alloc(Math.min(r.size+1,a+1)),p=0;for(;p<l.length;){let{bytesRead:m}=await i.read(l,p,l.length-p,p);if(!m)break;p+=m}if(p>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let u=l.subarray(0,p);if(c)return{...n,kind:"image",mimeType:c,data:u.toString("base64")};if(u.some(m=>m===0||m<32&&![9,10,12,13,27].includes(m)))return{...n,kind:"unsupported"};let y=1;for(let m=0;m<u.length-1;m++)if(u[m]===10&&++y>Yr)return{...n,kind:"too-large",limit:Yr,unit:"lines"};try{return{...n,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(u)}}catch{return{...n,kind:"unsupported"}}}finally{await i.close()}})}async function ss(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(r.size>ts)throw new J("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(r.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await i.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=rs(c);if(!a)throw new J("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:c}}finally{await i.close()}})}var Ea=1e3,ns=512*1024,os=1e4;function as(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function ct(s){let e=await De(s);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,r=await L(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=r.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);n.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);n.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(n.ahead=Number(P[1]),n.behind=Number(P[2]));continue}let l=a[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,u=0;for(let P=0;P<p;P++)u=a.indexOf(" ",u)+1;let y=as(i,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!y)continue;if(n.entries.length===Ea){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),w={path:y,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},k=m===void 0?void 0:as(i,m);k&&(w.originalPath=k),n.entries.push(w)}return n}async function cs(s,e,t){if(qe(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await ct(s);if(i.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r={path:e,area:t},n=i.entries.find(c=>c.path===e);if(!n)return{...r,kind:"empty"};if(n.conflict)return{...r,kind:"conflict"};if(n.submodule)return{...r,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...r,kind:"empty"};if(!(await Ia(Sa(s,e))).isFile())return{...r,kind:"unsupported"};let c=await Et(s,e);if(c.kind==="too-large")return{...r,kind:"too-large"};if(c.kind!=="text")return{...r,kind:"binary"};if(!c.text)return{...r,kind:"empty"};let a=c.text.split(`
2
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)>ss||a.length>ns?{...r,kind:"too-large"}:{...r,kind:"text",patch:p}}if(n.untracked||(t==="staged"?n.index:n.worktree)===".")return{...r,kind:"empty"};let o=t==="staged"&&n.originalPath?[e,n.originalPath]:[e];try{let c=await L(s,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],ss);return c?c.split(`
9
- `).length>ns?{...r,kind:"too-large"}:/^Binary files /m.test(c)?{...r,kind:"binary"}:{...r,kind:"text",patch:c}:{...r,kind:"empty"}}catch(c){if(c instanceof R&&c.status===413)return{...r,kind:"too-large"};throw c}}var qi=new Set,z=(s,e=409)=>{throw new R("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,s)};async function xa(s){return ls(Et(s,(await L(s,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Ji(s,e,t=!1){let i=null;try{let r=await Ce(s);r.kind==="repository"&&(i=await xa(r.cwd))}catch(r){if(!t)throw r}if(!i)return e();if(qi.has(i))return z("busy");qi.add(i);try{return await e()}finally{qi.delete(i)}}async function Kt(s){let e=await Ce(s),t={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return t;let i=await at(e.root);if(i.kind!=="repository")return t;let[r,n,o]=await Promise.all([L(e.cwd,["ls-files","--stage","-z"]),L(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),L(e.cwd,["rev-parse","--absolute-git-dir"])]),c=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],a=(await Promise.all(c.map(async m=>{try{return await Gi(Et(o.replace(/\n$/,""),m)),m}catch(f){if(f.code==="ENOENT")return null;throw f}}))).filter(Boolean),l=await Promise.all(i.entries.map(async m=>{try{let f=await Gi(Et(e.root,m.path));return[m.path,f.size,f.mtimeMs,f.ctimeMs,f.ino,f.mode]}catch(f){if(["ENOENT","ENOTDIR"].includes(f.code??""))return[m.path,"missing"];throw f}})),p=n.split(`
10
- `).filter(Boolean).map(m=>{let[f,,y]=m.split("\0");return{name:f,current:f===i.branch,occupied:!!y&&f!==i.branch}}),u=i.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||i.entries.some(m=>m.conflict)?"operation_in_progress":null,w=Ia("sha256").update(JSON.stringify({head:i.head,branch:i.branch,index:r,refs:n,entries:i.entries,files:l,present:a})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:i.head,branch:i.branch,version:w,staged:i.entries.filter(m=>!m.untracked&&m.index!==".").length,dirty:i.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function _a(s,e){qe(e);let t=cs(Et(s.cwd,e));for(;;)try{let n=await ls(t),o=Ea(s.cwd,n);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||Sa(o))return z("invalid_path",403);break}catch(n){if(n.code!=="ENOENT")throw n;t=cs(t)}let i=await at(s.cwd),r=i.kind==="repository"?i.entries.find(n=>n.path===e):void 0;if(!r||r.submodule||r.conflict)return z("invalid_path",400);try{let n=await Gi(Et(s.cwd,e));if(!n.isFile()&&!n.isSymbolicLink())return z("invalid_path",400)}catch(n){if(n.code!=="ENOENT")throw n}return r}async function ds(s,e,t){let i=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(i)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new R("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Ji(s,async()=>{let r=await Ce(s);if(r.kind!=="repository")return z("invalid_path",404);t(r.root);let n=await Kt(r.cwd);if(n.version!==e.expected)return z("state_changed");if(n.blocked)return z(n.blocked);let o,c;if(i==="stage"||i==="unstage"){if(typeof e.path!="string")return z("invalid_path",400);let p=await _a(r,e.path);if(i==="stage"&&!p.untracked&&p.worktree==="."||i==="unstage"&&(p.untracked||p.index==="."))return z("state_changed");let u=[e.path];i==="unstage"&&p.originalPath&&(qe(p.originalPath),u.push(p.originalPath)),o=i==="stage"?["add","--",...u]:n.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(i==="commit"){if(r.scope)return z("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return z("invalid_message",400);if(!n.staged)return z("nothing_staged",400);c=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!n.head)return z("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return z("invalid_branch",400);try{await L(r.cwd,["check-ref-format","--branch",e.branch])}catch{return z("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return z("invalid_branch",400);let p=n.branches.find(w=>w.name===e.branch),u=i==="switch-branch"||e.checkout===!0;if(i==="create-branch"&&p)return z("branch_exists");if(i==="switch-branch"&&(!p||p.current))return z("invalid_branch",400);if(u&&r.scope)return z("root_required",400);if(u&&n.dirty)return z("dirty_worktree");if(p?.occupied)return z("branch_in_use");o=i==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:u?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let a=await Kt(r.cwd);if(a.version!==e.expected||a.blocked)return z(a.blocked??"state_changed");t(r.root),await L(r.cwd,o,2*1024*1024,{write:!0,input:c});let l=(await L(r.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:i,head:l}})}import{createHash as Aa}from"node:crypto";var xt=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ps="%H%x00%P%x00%an%x00%aI%x00%s",us=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function hs(s){let[e,t,i]=await Promise.all([L(s,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),L(s,["rev-parse","--verify","--quiet","HEAD"]).then(c=>c.trim(),()=>null),L(s,["symbolic-ref","-q","HEAD"]).then(c=>c.trim(),()=>null)]),r=[];for(let c of e.split(`
11
- `).filter(Boolean)){let[a,l,p,u,w]=c.split("\0"),m=l==="commit"?p:u==="commit"?w:void 0;if(!m||!xt.test(m))continue;let f=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";r.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:m,kind:f})}if(r.length>512)throw new R("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let n=[...new Set([...r.map(c=>c.hash),...t&&xt.test(t)?[t]:[]])].sort(),o=Aa("sha256").update(JSON.stringify({refs:r,head:t,symbolic:i})).digest("hex");return{refs:r,tips:n,head:t,snapshot:o}}function fs(s){let[e,t,i,r,n]=s;if(!e||!xt.test(e)||!t?.split(" ").filter(Boolean).every(o=>xt.test(o)))throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:i,authoredAt:r,subject:n}}async function gs(s,e={}){let t=e.limit??50;if(!Number.isInteger(t)||t<1||t>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let i=await Ce(s),r={kind:i.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(i.kind!=="repository")return r;let n=await hs(i.cwd),o=0;if(e.cursor!==void 0){let u;try{u=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!u||typeof u.snapshot!="string"||!/^[a-f0-9]{64}$/.test(u.snapshot)||!Number.isInteger(u.offset)||u.offset<1||u.offset>1e4)throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(u.snapshot!==n.snapshot)throw new R("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);o=u.offset}let c={...r,root:i.root,scope:i.scope,head:n.head,snapshot:n.snapshot,refs:n.refs};if(!n.tips.length)return c;let l=(await L(i.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${ps}`,`--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(fs(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 ms(s,e){if(typeof e!="string"||!xt.test(e))throw new R("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await Ce(s);if(t.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i=await hs(t.cwd);if(!i.tips.length)throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await L(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await L(t.cwd,["rev-list","--max-count=1",e,"--not",...i.tips,"--"])).trim())throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function ws(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 ys(s,e,t){let r=(await L(s.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${ps}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(r.at(-1)===""&&r.pop(),r.length!==10)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let n=fs(r.slice(0,5)),o=ws(e,n.parents,t),c=["diff-tree","--root","-r","--no-commit-id",...us],[a,l]=await Promise.all([L(s.cwd,[...c,"--name-status","-z",...o,"--","."]),L(s.cwd,[...c,"--numstat","-z",...o,"--","."])]),p=new Map;for(let m of l.split("\0").filter(Boolean)){let f=m.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);f&&p.set(f[3],[f[1]==="-"?null:Number(f[1]),f[2]==="-"?null:Number(f[2])])}let u=a.split("\0");if(u.at(-1)===""&&u.pop(),u.length%2)throw new R("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let w=[];for(let m=0;m<u.length&&w.length<1e3;m+=2){let f=u[m+1],[y,P]=p.get(f)??[null,null];w.push({path:f,status:u[m],additions:y,deletions:P})}return{...n,email:r[5],committer:r[6],committerEmail:r[7],committedAt:r[8],message:r[9],root:s.root,scope:s.scope,parentIndex:t,files:w,truncated:u.length>2e3}}async function vs(s,e,t=0){return ys(await ms(s,e),e,t)}async function bs(s,e,t,i=0){qe(t);let r=await ms(s,e),n=await ys(r,e,i),o=n.files.find(a=>a.path===t);if(!o)throw new R("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let c={hash:e,path:t,parentIndex:i,parentHash:n.parents[i]??null};if(o.additions===null)return{...c,kind:"binary"};try{let a=await L(r.cwd,["diff-tree","--root","-r","--no-commit-id",...us,"--src-prefix=a/","--dst-prefix=b/","-p",...ws(e,n.parents,i),"--",t],524288);return a.split(`
12
- `).length>1e4?{...c,kind:"too-large"}:a?{...c,kind:"text",patch:a}:{...c,kind:"empty"}}catch(a){if(a instanceof R&&a.status===413)return{...c,kind:"too-large"};throw a}}var ks=["/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 Ps(s,e,t){if(s.endsWith("/control"))return Kt(e);if(s.endsWith("/status"))return at(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 gs(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 as(e,t.path,t.area)}if(typeof t.hash!="string"||t.parentIndex!==void 0&&(!Number.isInteger(t.parentIndex)||t.parentIndex<0))throw new R("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let i=t.parentIndex;if(s.endsWith("/commit-detail"))return vs(e,t.hash,i);if(s.endsWith("/commit-diff")&&typeof t.path=="string")return bs(e,t.hash,t.path,i);throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Yt=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),Ta=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Is={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},Ra=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"]),Ca=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 Ss(s){return s==="/api/message"||s==="/api/prompt-queue"||s.startsWith("/api/provider/")||s.startsWith("/api/workspace/files/")||s.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(s)}function fe(s){return s.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function Ie(s){let e={};for(let t of Ra){let i=s[t];t==="toolName"?typeof i=="string"&&(Yt.has(i)||i==="custom")&&(e[t]=i):t==="failureKind"?Ta.has(i)&&(e[t]=i):t==="level"?(i==="warning"||i==="error")&&(e[t]=i):t==="diagnosticSource"?(i==="tool_execution_end"||i==="message_end")&&(e[t]=i):t==="errorCode"?typeof i=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(i)&&(e[t]=i):t==="toolId"?typeof i=="string"&&/^[a-f0-9]{16}$/.test(i)&&(e[t]=i):t==="route"&&typeof i=="string"?e[t]=Ca.has(i.split("?")[0])?i.split("?")[0]:"[route]":t==="model"&&typeof i=="string"&&/^[\w.-]+\/[\w.-]+$/.test(i)?e[t]=i.split("/").map(fe).join("/"):typeof i=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(i)?i:fe(i).slice(0,t==="errorSummary"?512:1024):(typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)||i===null)&&(e[t]=i)}return e}function Ki(s){let e=s.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function ct(s,e=0){let t=s instanceof Error?s:new Error(typeof s=="string"?s:"Non-Error rejection"),i=new Error(fe(t.message));if(i.name=fe(t.name).slice(0,100),t.stack){let r=t.stack.split(`
8
+ `}`;return Buffer.byteLength(p)>ns||a.length>os?{...r,kind:"too-large"}:{...r,kind:"text",patch:p}}if(n.untracked||(t==="staged"?n.index:n.worktree)===".")return{...r,kind:"empty"};let o=t==="staged"&&n.originalPath?[e,n.originalPath]:[e];try{let c=await L(s,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],ns);return c?c.split(`
9
+ `).length>os?{...r,kind:"too-large"}:/^Binary files /m.test(c)?{...r,kind:"binary"}:{...r,kind:"text",patch:c}:{...r,kind:"empty"}}catch(c){if(c instanceof R&&c.status===413)return{...r,kind:"too-large"};throw c}}var qi=new Set,z=(s,e=409)=>{throw new R("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,s)};async function Ta(s){return ds(xt(s,(await L(s,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Ji(s,e,t=!1){let i=null;try{let r=await De(s);r.kind==="repository"&&(i=await Ta(r.cwd))}catch(r){if(!t)throw r}if(!i)return e();if(qi.has(i))return z("busy");qi.add(i);try{return await e()}finally{qi.delete(i)}}async function Xt(s){let e=await De(s),t={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return t;let i=await ct(e.root);if(i.kind!=="repository")return t;let[r,n,o]=await Promise.all([L(e.cwd,["ls-files","--stage","-z"]),L(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),L(e.cwd,["rev-parse","--absolute-git-dir"])]),c=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],a=(await Promise.all(c.map(async m=>{try{return await Gi(xt(o.replace(/\n$/,""),m)),m}catch(f){if(f.code==="ENOENT")return null;throw f}}))).filter(Boolean),l=await Promise.all(i.entries.map(async m=>{try{let f=await Gi(xt(e.root,m.path));return[m.path,f.size,f.mtimeMs,f.ctimeMs,f.ino,f.mode]}catch(f){if(["ENOENT","ENOTDIR"].includes(f.code??""))return[m.path,"missing"];throw f}})),p=n.split(`
10
+ `).filter(Boolean).map(m=>{let[f,,w]=m.split("\0");return{name:f,current:f===i.branch,occupied:!!w&&f!==i.branch}}),u=i.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||i.entries.some(m=>m.conflict)?"operation_in_progress":null,y=xa("sha256").update(JSON.stringify({head:i.head,branch:i.branch,index:r,refs:n,entries:i.entries,files:l,present:a})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:i.head,branch:i.branch,version:y,staged:i.entries.filter(m=>!m.untracked&&m.index!==".").length,dirty:i.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function Ra(s,e){qe(e);let t=ls(xt(s.cwd,e));for(;;)try{let n=await ds(t),o=Aa(s.cwd,n);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||_a(o))return z("invalid_path",403);break}catch(n){if(n.code!=="ENOENT")throw n;t=ls(t)}let i=await ct(s.cwd),r=i.kind==="repository"?i.entries.find(n=>n.path===e):void 0;if(!r||r.submodule||r.conflict)return z("invalid_path",400);try{let n=await Gi(xt(s.cwd,e));if(!n.isFile()&&!n.isSymbolicLink())return z("invalid_path",400)}catch(n){if(n.code!=="ENOENT")throw n}return r}async function ps(s,e,t){let i=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(i)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new R("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Ji(s,async()=>{let r=await De(s);if(r.kind!=="repository")return z("invalid_path",404);t(r.root);let n=await Xt(r.cwd);if(n.version!==e.expected)return z("state_changed");if(n.blocked)return z(n.blocked);let o,c;if(i==="stage"||i==="unstage"){if(typeof e.path!="string")return z("invalid_path",400);let p=await Ra(r,e.path);if(i==="stage"&&!p.untracked&&p.worktree==="."||i==="unstage"&&(p.untracked||p.index==="."))return z("state_changed");let u=[e.path];i==="unstage"&&p.originalPath&&(qe(p.originalPath),u.push(p.originalPath)),o=i==="stage"?["add","--",...u]:n.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(i==="commit"){if(r.scope)return z("root_required",400);if(typeof e.message!="string"||!e.message.trim()||e.message.includes("\0")||Buffer.byteLength(e.message)>8192)return z("invalid_message",400);if(!n.staged)return z("nothing_staged",400);c=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!n.head)return z("no_commits",400);if(typeof e.branch!="string"||!e.branch||e.branch.length>256||e.branch.startsWith("-")||e.branch.startsWith("refs/")||["HEAD","@"].includes(e.branch)||/[\0\r\n]|@\{/.test(e.branch))return z("invalid_branch",400);try{await L(r.cwd,["check-ref-format","--branch",e.branch])}catch{return z("invalid_branch",400)}if(e.checkout!==void 0&&typeof e.checkout!="boolean")return z("invalid_branch",400);let p=n.branches.find(y=>y.name===e.branch),u=i==="switch-branch"||e.checkout===!0;if(i==="create-branch"&&p)return z("branch_exists");if(i==="switch-branch"&&(!p||p.current))return z("invalid_branch",400);if(u&&r.scope)return z("root_required",400);if(u&&n.dirty)return z("dirty_worktree");if(p?.occupied)return z("branch_in_use");o=i==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:u?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let a=await Xt(r.cwd);if(a.version!==e.expected||a.blocked)return z(a.blocked??"state_changed");t(r.root),await L(r.cwd,o,2*1024*1024,{write:!0,input:c});let l=(await L(r.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:i,head:l}})}import{createHash as Ca}from"node:crypto";var _t=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,us="%H%x00%P%x00%an%x00%aI%x00%s",hs=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function fs(s){let[e,t,i]=await Promise.all([L(s,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),L(s,["rev-parse","--verify","--quiet","HEAD"]).then(c=>c.trim(),()=>null),L(s,["symbolic-ref","-q","HEAD"]).then(c=>c.trim(),()=>null)]),r=[];for(let c of e.split(`
11
+ `).filter(Boolean)){let[a,l,p,u,y]=c.split("\0"),m=l==="commit"?p:u==="commit"?y:void 0;if(!m||!_t.test(m))continue;let f=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";r.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:m,kind:f})}if(r.length>512)throw new R("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let n=[...new Set([...r.map(c=>c.hash),...t&&_t.test(t)?[t]:[]])].sort(),o=Ca("sha256").update(JSON.stringify({refs:r,head:t,symbolic:i})).digest("hex");return{refs:r,tips:n,head:t,snapshot:o}}function gs(s){let[e,t,i,r,n]=s;if(!e||!_t.test(e)||!t?.split(" ").filter(Boolean).every(o=>_t.test(o)))throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:i,authoredAt:r,subject:n}}async function ms(s,e={}){let t=e.limit??50;if(!Number.isInteger(t)||t<1||t>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let i=await De(s),r={kind:i.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(i.kind!=="repository")return r;let n=await fs(i.cwd),o=0;if(e.cursor!==void 0){let u;try{u=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!u||typeof u.snapshot!="string"||!/^[a-f0-9]{64}$/.test(u.snapshot)||!Number.isInteger(u.offset)||u.offset<1||u.offset>1e4)throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(u.snapshot!==n.snapshot)throw new R("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);o=u.offset}let c={...r,root:i.root,scope:i.scope,head:n.head,snapshot:n.snapshot,refs:n.refs};if(!n.tips.length)return c;let l=(await L(i.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${us}`,`--max-count=${t+1}`,`--skip=${o}`,...n.tips,"--"])).split("\0");if(l.at(-1)===""&&l.pop(),l.length%5)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let u=0;u<l.length;u+=5)p.push(gs(l.slice(u,u+5)));return c.commits=p.slice(0,t),p.length>t&&o+t<=1e4&&(c.nextCursor=Buffer.from(JSON.stringify({snapshot:n.snapshot,offset:o+t})).toString("base64url")),c}async function ws(s,e){if(typeof e!="string"||!_t.test(e))throw new R("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await De(s);if(t.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i=await fs(t.cwd);if(!i.tips.length)throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await L(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await L(t.cwd,["rev-list","--max-count=1",e,"--not",...i.tips,"--"])).trim())throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function ys(s,e,t){if(!Number.isInteger(t)||t<0||t>=Math.max(1,e.length))throw new R("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[t],s]:[s]}async function vs(s,e,t){let r=(await L(s.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${us}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(r.at(-1)===""&&r.pop(),r.length!==10)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let n=gs(r.slice(0,5)),o=ys(e,n.parents,t),c=["diff-tree","--root","-r","--no-commit-id",...hs],[a,l]=await Promise.all([L(s.cwd,[...c,"--name-status","-z",...o,"--","."]),L(s.cwd,[...c,"--numstat","-z",...o,"--","."])]),p=new Map;for(let m of l.split("\0").filter(Boolean)){let f=m.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);f&&p.set(f[3],[f[1]==="-"?null:Number(f[1]),f[2]==="-"?null:Number(f[2])])}let u=a.split("\0");if(u.at(-1)===""&&u.pop(),u.length%2)throw new R("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let y=[];for(let m=0;m<u.length&&y.length<1e3;m+=2){let f=u[m+1],[w,k]=p.get(f)??[null,null];y.push({path:f,status:u[m],additions:w,deletions:k})}return{...n,email:r[5],committer:r[6],committerEmail:r[7],committedAt:r[8],message:r[9],root:s.root,scope:s.scope,parentIndex:t,files:y,truncated:u.length>2e3}}async function bs(s,e,t=0){return vs(await ws(s,e),e,t)}async function ks(s,e,t,i=0){qe(t);let r=await ws(s,e),n=await vs(r,e,i),o=n.files.find(a=>a.path===t);if(!o)throw new R("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let c={hash:e,path:t,parentIndex:i,parentHash:n.parents[i]??null};if(o.additions===null)return{...c,kind:"binary"};try{let a=await L(r.cwd,["diff-tree","--root","-r","--no-commit-id",...hs,"--src-prefix=a/","--dst-prefix=b/","-p",...ys(e,n.parents,i),"--",t],524288);return a.split(`
12
+ `).length>1e4?{...c,kind:"too-large"}:a?{...c,kind:"text",patch:a}:{...c,kind:"empty"}}catch(a){if(a instanceof R&&a.status===413)return{...c,kind:"too-large"};throw a}}var Ps=["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff"];function Is(s,e,t){if(s.endsWith("/control"))return Xt(e);if(s.endsWith("/status"))return ct(e);if(s.endsWith("/history")){if(t.limit!==void 0&&typeof t.limit!="number"||t.cursor!==void 0&&typeof t.cursor!="string")throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return ms(e,{limit:t.limit,cursor:t.cursor})}if(s.endsWith("/diff")){if(typeof t.path!="string"||!["staged","unstaged","untracked"].includes(t.area))throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return cs(e,t.path,t.area)}if(typeof t.hash!="string"||t.parentIndex!==void 0&&(!Number.isInteger(t.parentIndex)||t.parentIndex<0))throw new R("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let i=t.parentIndex;if(s.endsWith("/commit-detail"))return bs(e,t.hash,i);if(s.endsWith("/commit-diff")&&typeof t.path=="string")return ks(e,t.hash,t.path,i);throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Qt=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),Da=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Ss={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},Na=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),Ha=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function Es(s){return s==="/api/message"||s==="/api/prompt-queue"||s.startsWith("/api/provider/")||s.startsWith("/api/workspace/files/")||s.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(s)}function fe(s){return s.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function Ie(s){let e={};for(let t of Na){let i=s[t];t==="toolName"?typeof i=="string"&&(Qt.has(i)||i==="custom")&&(e[t]=i):t==="failureKind"?Da.has(i)&&(e[t]=i):t==="level"?(i==="warning"||i==="error")&&(e[t]=i):t==="diagnosticSource"?(i==="tool_execution_end"||i==="message_end")&&(e[t]=i):t==="errorCode"?typeof i=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(i)&&(e[t]=i):t==="toolId"?typeof i=="string"&&/^[a-f0-9]{16}$/.test(i)&&(e[t]=i):t==="route"&&typeof i=="string"?e[t]=Ha.has(i.split("?")[0])?i.split("?")[0]:"[route]":t==="model"&&typeof i=="string"&&/^[\w.-]+\/[\w.-]+$/.test(i)?e[t]=i.split("/").map(fe).join("/"):typeof i=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(i)?i:fe(i).slice(0,t==="errorSummary"?512:1024):(typeof i=="boolean"||typeof i=="number"&&Number.isFinite(i)||i===null)&&(e[t]=i)}return e}function Ki(s){let e=s.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function lt(s,e=0){let t=s instanceof Error?s:new Error(typeof s=="string"?s:"Non-Error rejection"),i=new Error(fe(t.message));if(i.name=fe(t.name).slice(0,100),t.stack){let r=t.stack.split(`
13
13
  `).slice(1,31).map(n=>{let o=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${fe(n.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:fe(n)});i.stack=`${i.name}: ${i.message}
14
14
  ${r.join(`
15
- `)}`}else i.stack=void 0;return e<3&&t.cause!==void 0&&(i.cause=ct(t.cause,e+1)),i}function De(s,e){let t=new Error(e);return s instanceof Error&&(t.name=s.name,s.stack&&(t.stack=`${t.name}: ${e}
15
+ `)}`}else i.stack=void 0;return e<3&&t.cause!==void 0&&(i.cause=lt(t.cause,e+1)),i}function Ne(s,e){let t=new Error(e);return s instanceof Error&&(t.name=s.name,s.stack&&(t.stack=`${t.name}: ${e}
16
16
  ${s.stack.split(`
17
17
  `).slice(1).join(`
18
- `)}`)),t}function Da(s){return{...s.filename?{filename:Ki(s.filename)}:{},...s.abs_path?{abs_path:Ki(s.abs_path)}:{},...s.function?{function:fe(s.function)}:{},lineno:s.lineno,colno:s.colno,in_app:s.in_app}}function Na(s){let e=Ie(s.contexts?.diagnostic??{}),t=Es(e);return{event_id:s.event_id,timestamp:s.timestamp,platform:s.platform,level:s.level,release:s.release,dist:s.dist,environment:fe(s.environment??"production"),...s.message?{message:fe(s.message)}:{},exception:s.exception?{values:s.exception.values?.slice(0,4).map(i=>({type:fe(i.type??"Error"),value:fe(i.value??""),...i.stacktrace?{stacktrace:{frames:i.stacktrace.frames?.slice(-30).map(Da)}}:{},...i.mechanism?{mechanism:{type:i.mechanism.type,handled:i.mechanism.handled}}:{}}))}:void 0,tags:{side:s.tags?.side,buildId:s.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...t?{fingerprint:t}:{},contexts:{diagnostic:e},breadcrumbs:s.breadcrumbs?.slice(-100).map(i=>({timestamp:i.timestamp,category:fe(i.category??"app"),data:Ie(i.data??{})})),debug_meta:s.debug_meta?{images:s.debug_meta.images?.slice(0,10).map(i=>({type:i.type,debug_id:i.debug_id,...i.code_file?{code_file:Ki(i.code_file)}:{}}))}:void 0}}function Es(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 xs(s,e){return e.attachments=[],Na(s)}var _t=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let i={timestamp:Date.now()/1e3,category:fe(e),data:Ie(t)},r=this.encoder.encode(JSON.stringify(i)).byteLength+1;for(this.items.push({item:i,size:r}),this.bytes+=r;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},Xi=class{windowAt=-1;total=0;seen=new Map;take(e,t=Date.now()){(this.windowAt<0||t-this.windowAt>=6e4)&&(this.windowAt=t,this.total=0);let i=this.seen.get(e);if(i&&t-i.at<6e4){i.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!i&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:i?.repeats??0}}},Ha=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"]);function Ge(s){return s instanceof Error&&(s.name==="AbortError"||Ha.has(s.message))}var Xt=class{budget=new Xi;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,i,r,n=new _t){this.client=e,this.side=t,this.buildId=i,this.scopeClass=r.Scope,this.breadcrumbs=n,e.addIntegration(r.linkedErrorsIntegration({limit:4}))}setState(e){this.state=Ie(e)}capture(e,t={},i){try{if(Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let r=ct(e),n=Ie({...this.state,...t}),o=Es(n),c=o?JSON.stringify(o):`${r.name}:${r.message}:${r.stack?.split(`
19
- `)[1]??""}:${t.stage??""}`,a=this.budget.take(c);if(!a)return;let l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),n.level==="warning"&&l.setLevel("warning"),o&&l.setFingerprint(o),l.setContext("diagnostic",{...n,repeats:a.repeats});for(let p of this.breadcrumbs.snapshot())l.addBreadcrumb(p,100);return l.captureException(r,i?{event_id:i}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function _s(s,e){return s({...e,bufferSize:20},async({body:t})=>{let i=await fetch(e.url,{method:"POST",body:t,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:i.status,headers:{"x-sentry-rate-limits":i.headers.get("x-sentry-rate-limits"),"retry-after":i.headers.get("retry-after")}}})}var As={metadata:Gr,routes:ks,coordinateStart:(s,e)=>Ji(s,e,!0),requestFailure:s=>s instanceof R?{status:s.status,body:{error:s.message,errorCode:"validation_error",reason:s.reason}}:null,async handle({path:s,body:e,snapshot:t,busyWorkspaces:i,json:r}){let n=t();if(e.sessionId!==n.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||i().some(u=>{let w=(m,f)=>{let y=Ma(m,f);return y!==".."&&!y.startsWith("../")&&!y.startsWith("..\\")&&!Oa(y)};return w(p,u)||w(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 ds(n.cwd,e,c):await Ps(s,n.cwd,e);if(!a){let p=t();if(p.sessionId!==n.sessionId||p.cwd!==n.cwd){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(s.endsWith("/control")){let u=l;u.root&&o(u.root)&&(u.blocked??="agent_busy")}}r(200,l)}catch(o){if(o instanceof R||o instanceof J)r(o.status,{error:o.message,errorCode:"validation_error",...o instanceof R?{reason:o.reason}:{}});else throw De(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var Ts={id:nt.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 Rs={metadata:Ts,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw"],async handle({path:s,body:e,snapshot:t,json:i,res:r}){let n=t();if(e.sessionId!==n.sessionId){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(typeof e.path!="string"||e.path.length>4096){i(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}try{if(s.endsWith("/raw")){let a=await rs(n.cwd,e.path),l=t();if(l.sessionId!==n.sessionId||l.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r.writeHead(200,{"Content-Type":a.mimeType,"Content-Length":a.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),r.end(a.bytes);return}let o=s.endsWith("/list")?await ts(n.cwd,e.path):await St(n.cwd,e.path),c=t();if(c.sessionId!==n.sessionId||c.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}i(200,o)}catch(o){if(o instanceof J)i(o.status,{error:o.message,errorCode:"validation_error"});else throw De(o,"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var Cs={id:nt.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 Hs,constants as Yi,statSync as Os}from"node:fs";import{createRequire as za}from"node:module";import{execFile as Ms}from"node:child_process";import{accessSync as ja,chmodSync as Wa,constants as $a,statSync as Va}from"node:fs";import{createRequire as Fa}from"node:module";import{dirname as Ua,join as Ba}from"node:path";var Ds=Fa(import.meta.url);function La(s){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=Ba(s,e,"spawn-helper"),i;try{i=Va(t).mode}catch(r){if(r.code==="ENOENT")continue;throw r}try{ja(t,$a.X_OK)}catch{Wa(t,i|73)}}}function Ns(...s){return La(Ua(Ds.resolve("node-pty/package.json"))),Ds("node-pty").spawn(...s)}var Ne=class extends Error{reason;constructor(e,t,i){super(t,{cause:i}),this.reason=e}},js=za(import.meta.url),Qi=class{pid;pty;screen;serializer;followers=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,i,r,n,o,c,a){this.sessionId=e,this.abandoned=c,this.graceMs=a;let{Terminal:l}=js("@xterm/headless"),{SerializeAddon:p}=js("@xterm/addon-serialize");this.screen=new l({cols:i,rows:r,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([w,m])=>m!==void 0&&!/^PI_WEBAPP_RESTART_/.test(w)));try{this.pty=Ns(n,o,{name:"xterm-256color",cwd:t,cols:i,rows:r,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(w){throw this.screen.dispose(),new Ne("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",w)}this.pid=this.pty.pid,this.screen.onData(w=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(w)}),this.pty.onData(w=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(m=>{if(this.disposed){m();return}this.screen.write(w,()=>{this.broadcast({type:"output",data:w}),m()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(w=>this.pty.onExit(({exitCode:m,signal:f})=>{this.exit={type:"exit",exitCode:m,signal:f},this.pending.then(()=>{this.broadcast(this.exit),w()})})),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=>Ms("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(r=>Ms("ps",["-axo","pid=,ppid="],(n,o)=>r(n?"":o)))).trim().split(`
20
- `).map(r=>r.trim().split(/\s+/).map(Number)),i=r=>t.filter(([,n])=>n===r).flatMap(([n])=>[...i(n),n]);for(let r of[...i(this.pid),this.pid])try{process.kill(r,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending,this.followers.clear(),this.screen.dispose()}},Qt=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,i,r,n){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,t);if(this.terminals.size>=32||[...this.terminals.values()].filter(l=>l.sessionId===t).length>=8)throw new Ne("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(Hs(o,Yi.X_OK),!Os(o).isFile())throw new Error("Not a shell file")}catch(l){throw new Ne("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(!Os(i).isDirectory())throw new Error("Not a directory");Hs(i,Yi.R_OK|Yi.X_OK)}catch(l){throw new Ne("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",l)}let c=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),a=new Qi(t,i,r,n,o,c,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,a),a}get(e,t){let i=this.terminals.get(e);if(!i||i.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return i}async remove(e,t){let i=this.terminals.get(e);if(i){if(i.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await i.close(),this.terminals.get(e)===i&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var Ws=(s,e)=>Number.isInteger(s)&&Number.isInteger(e)&&Number(s)>=2&&Number(s)<=500&&Number(e)>=1&&Number(e)<=300;async function $s(s,e,t,i,r,n){let o=(l,p)=>{t.writeHead(l,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){o(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let c=s.slice(14),a=i();if(c!=="close"&&e.sessionId!==a.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((c==="create"||c==="resize")&&!Ws(e.cols,e.rows)){o(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(c==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){o(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(c==="create"){r.create(e.id,e.sessionId,a.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(c==="close"){await r.remove(e.id,e.sessionId),o(200,{closed:!0});return}let l=r.get(e.id,e.sessionId);if(c==="attach"){let p=!1,u;t.once("close",()=>{p=!0,u?.(),n.delete(t)}),u=await l.attach(w=>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(w)}
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 Ne?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 Ne?l.reason:c==="create"?"terminal_runtime_unavailable":void 0})}}function Vs(){let s=new Qt,e=new Set,t=async()=>{for(let i of e)i.end();e.clear(),await s.clear()};return{metadata:Cs,routes:["create","attach","input","resize","close"].map(i=>`/api/terminal/${i}`),handle:i=>$s(i.path,i.body,i.res,i.snapshot,s,e),restartBlocker:()=>s.size?"\u8BF7\u5148\u5173\u95ED\u6240\u6709\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0":null,disable:t,async close(){await t(),await s.close()}}}function Fs(){return[Rs,Vs(),As]}import{createHash as qa,randomUUID as Ga}from"node:crypto";import{mkdir as Ja,open as Ka,readFile as Xa,rename as Ya,rm as Us,writeFile as Qa}from"node:fs/promises";import{dirname as Za}from"node:path";var Q=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},Zt=class s{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Xa(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 qa("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,i,r){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let n=`${this.file}.${Ga()}.tmp`,o=`${this.file}.lock`,c;try{if(i!==this.revision())throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");r();let a=new Set(this.disabled);t?a.delete(e):a.add(e),await Ja(Za(this.file),{recursive:!0});try{c=await Ka(o,"wx",384)}catch(p){throw p.code==="EEXIST"?new Q("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await c.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
22
- `);let l=new s(this.file);if(await l.load(),l.revision()!==i)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await Qa(n,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
23
- `,{mode:384}),r(),await Ya(n,this.file),this.disabled=a}finally{this.changing=!1;try{await Us(n,{force:!0})}finally{c&&(await c.close(),await Us(o,{force:!0}))}}}};var ei=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(i=>[...i.routes]),new Set(e.map(i=>i.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(i=>i.metadata.id===e)?.routes.find(i=>i.split("/").at(-1)===t&&!i.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(i=>i.metadata.id));return{plugins:e.plugins.filter(i=>!t.has(i.id)),errors:[...e.errors,...e.plugins.filter(i=>t.has(i.id)).map(i=>`Plugin ID reserved by host: ${i.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(i=>this.preferences.enabled(i.metadata.id)).map(i=>({id:i.metadata.id,client:`builtin:${i.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,i,r){if(!this.plugins.some(n=>n.metadata.id===e))throw new Q("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(n=>n>0))throw new Q("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,i,r),t||await this.plugins.find(n=>n.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(r=>r.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let i=t.metadata.id;this.running.set(i,(this.running.get(i)??0)+1);try{await t.handle(e)}finally{this.running.set(i,this.running.get(i)-1)}return!0}async runAgentAction(e,t,i,r,n){let o=this.plugins.find(c=>c.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new Q("\u7ED8\u56FE\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(t,i,r,n)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let i="@host/start";this.running.set(i,(this.running.get(i)??0)+1);let r=t;for(let n of this.plugins)if(n.coordinateStart&&this.preferences.enabled(n.metadata.id)){let o=r;r=()=>n.coordinateStart(e,o)}try{return await r()}finally{this.running.set(i,this.running.get(i)-1)}}requestFailure(e){if(e instanceof Q)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let i=t.requestFailure?.(e);if(i)return i}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":this.plugins.map(e=>e.restartBlocker?.()).find(Boolean)??null}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as ec,opendir as tc,stat as ic}from"node:fs/promises";import{homedir as rc}from"node:os";import{basename as sc,dirname as Bs,join as Ls,posix as nc,resolve as zs,win32 as oc}from"node:path";function qs(s){return process.platform==="win32"?oc.isAbsolute(s)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(s):nc.isAbsolute(s)}function ac(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 Gs(s){if(s!==void 0&&!qs(s))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=rc(),t=zs(s??e),i=[];for(let a=t;;a=Bs(a)){let l=Bs(a);if(i.unshift({name:l===a?a:sc(a),path:a,hidden:!1}),l===a)break}let r=[],n=!1,o=await tc(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||ac(r,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(n=!0);let c=[];for(let a of r){let l=Ls(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await ic(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 Js(s,e){if(!qs(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=Ls(zs(s),e);return await ec(t),t}import{execFile as cc}from"node:child_process";import{accessSync as lc,constants as dc}from"node:fs";import{delimiter as pc,join as uc}from"node:path";var hc=(s,e,t)=>new Promise((i,r)=>{cc(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 fc(s){for(let e of(s??"").split(pc))if(e)for(let t of["zenity","kdialog"])try{return lc(uc(e,t),dc.X_OK),!0}catch{}return!1}function Ks(s=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":s==="darwin"||s==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&fc(e.PATH)?"native":"browse"}function ti(s){if(!(typeof s!="object"||s===null||!("code"in s)))return typeof s.code=="string"||typeof s.code=="number"?s.code:void 0}function gc(s){return typeof s=="object"&&s!==null&&"stderr"in s&&typeof s.stderr=="string"?s.stderr:""}function Zi(s){return s.replace(/[\r\n]+$/,"")||null}async function Xs(s,e=process.platform,t=hc){if(e==="darwin")try{let i=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],s);return Zi(i.stdout)}catch(i){if(!s.aborted&&ti(i)===1&&/(?:User canceled|-128)/i.test(gc(i)))return null;throw i}if(e==="linux"){try{return Zi((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],s)).stdout)}catch(i){if(s.aborted)throw i;if(ti(i)===1)return null;if(ti(i)!=="ENOENT")throw i}try{return Zi((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],s)).stdout)}catch(i){if(s.aborted)throw i;if(ti(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 mc,randomUUID as wc}from"node:crypto";import{mkdir as yc,readFile as vc,writeFile as bc}from"node:fs/promises";import{join as Ys}from"node:path";import{getAgentDir as kc}from"@earendil-works/pi-coding-agent";var ii=20*1024*1024,Qs=20,Pc=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function Ic(s){let e=s.indexOf("."),t=(e<0?s:s.slice(0,e)).replace(/[. ]+$/u,"");return Pc.test(t)}function Sc(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 Ec(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 Ic(t)&&(t=`_${t}`),t=Sc(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function xc(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 Zs(s,e,t,i){if(i.byteLength===0||i.byteLength>ii)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let r=Ec(e),n=mc("sha256").update(i).digest("hex"),o=Ys(kc(),"pi-web","attachments",n);await yc(o,{recursive:!0});let c=Ys(o,r);try{await bc(c,i,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:wc(),name:r,bytes:i.byteLength,path:c,mediaType:xc(i)??t.replace(/^image\//,"application/"),sessionId:s}}async function en(s){return{type:"image",data:(await vc(s.path)).toString("base64"),mimeType:s.mediaType}}import{randomBytes as _c}from"node:crypto";function tn(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 ri=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=_c(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:w,...m}=l;a.answer=p,a.reject=u,a.view={...a.view,status:"waiting",prompt:m},w?.aborted?u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):w?.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 Oa(s){return{...s.filename?{filename:Ki(s.filename)}:{},...s.abs_path?{abs_path:Ki(s.abs_path)}:{},...s.function?{function:fe(s.function)}:{},lineno:s.lineno,colno:s.colno,in_app:s.in_app}}function Ma(s){let e=Ie(s.contexts?.diagnostic??{}),t=xs(e);return{event_id:s.event_id,timestamp:s.timestamp,platform:s.platform,level:s.level,release:s.release,dist:s.dist,environment:fe(s.environment??"production"),...s.message?{message:fe(s.message)}:{},exception:s.exception?{values:s.exception.values?.slice(0,4).map(i=>({type:fe(i.type??"Error"),value:fe(i.value??""),...i.stacktrace?{stacktrace:{frames:i.stacktrace.frames?.slice(-30).map(Oa)}}:{},...i.mechanism?{mechanism:{type:i.mechanism.type,handled:i.mechanism.handled}}:{}}))}:void 0,tags:{side:s.tags?.side,buildId:s.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...t?{fingerprint:t}:{},contexts:{diagnostic:e},breadcrumbs:s.breadcrumbs?.slice(-100).map(i=>({timestamp:i.timestamp,category:fe(i.category??"app"),data:Ie(i.data??{})})),debug_meta:s.debug_meta?{images:s.debug_meta.images?.slice(0,10).map(i=>({type:i.type,debug_id:i.debug_id,...i.code_file?{code_file:Ki(i.code_file)}:{}}))}:void 0}}function xs(s){if(!(s.stage!=="tool"||s.originalStackAvailable!==!1||!s.toolName||!s.failureKind))return["pi-webapp-tool-result",String(s.toolName),String(s.toolId??"builtin"),String(s.failureKind),String(s.errorCode??"unknown")]}function _s(s,e){return e.attachments=[],Ma(s)}var At=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let i={timestamp:Date.now()/1e3,category:fe(e),data:Ie(t)},r=this.encoder.encode(JSON.stringify(i)).byteLength+1;for(this.items.push({item:i,size:r}),this.bytes+=r;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},Xi=class{windowAt=-1;total=0;seen=new Map;take(e,t=Date.now()){(this.windowAt<0||t-this.windowAt>=6e4)&&(this.windowAt=t,this.total=0);let i=this.seen.get(e);if(i&&t-i.at<6e4){i.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!i&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:i?.repeats??0}}},ja=new Set(["\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84","\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0","\u4F1A\u8BDD\u5DF2\u5207\u6362","Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A","\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u4F1A\u8BDD","\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A","\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88","\u5DF2\u6709\u767B\u5F55\u6B63\u5728\u8FDB\u884C","\u6A21\u578B\u4E0D\u53EF\u7528","\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1","\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6","\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55","\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279","\u8BF7\u5148\u9009\u62E9\u6A21\u578B","\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B","\u63D2\u4EF6\u672A\u542F\u7528","\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362","\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728","\u6587\u4EF6\u8D85\u8FC7 20 MB","\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927","\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A","\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548","\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F","\u4F1A\u8BDD\u4E0D\u5B58\u5728","\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664","\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664"]);function Ge(s){return s instanceof Error&&(s.name==="AbortError"||ja.has(s.message))}var Yt=class{budget=new Xi;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,i,r,n=new At){this.client=e,this.side=t,this.buildId=i,this.scopeClass=r.Scope,this.breadcrumbs=n,e.addIntegration(r.linkedErrorsIntegration({limit:4}))}setState(e){this.state=Ie(e)}capture(e,t={},i){try{if(Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let r=lt(e),n=Ie({...this.state,...t}),o=xs(n),c=o?JSON.stringify(o):`${r.name}:${r.message}:${r.stack?.split(`
19
+ `)[1]??""}:${t.stage??""}`,a=this.budget.take(c);if(!a)return;let l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),n.level==="warning"&&l.setLevel("warning"),o&&l.setFingerprint(o),l.setContext("diagnostic",{...n,repeats:a.repeats});for(let p of this.breadcrumbs.snapshot())l.addBreadcrumb(p,100);return l.captureException(r,i?{event_id:i}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function As(s,e){return s({...e,bufferSize:20},async({body:t})=>{let i=await fetch(e.url,{method:"POST",body:t,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:i.status,headers:{"x-sentry-rate-limits":i.headers.get("x-sentry-rate-limits"),"retry-after":i.headers.get("retry-after")}}})}var Ts={metadata:Jr,routes:Ps,coordinateStart:(s,e)=>Ji(s,e,!0),requestFailure:s=>s instanceof R?{status:s.status,body:{error:s.message,errorCode:"validation_error",reason:s.reason}}:null,async handle({path:s,body:e,snapshot:t,busyWorkspaces:i,json:r}){let n=t();if(e.sessionId!==n.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||i().some(u=>{let y=(m,f)=>{let w=$a(m,f);return w!==".."&&!w.startsWith("../")&&!w.startsWith("..\\")&&!Wa(w)};return y(p,u)||y(u,p)}),c=p=>{let u=t();if(u.sessionId!==n.sessionId||u.cwd!==n.cwd)throw new R("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(o(p))throw new R("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},a=s.endsWith("/write"),l=a?await ps(n.cwd,e,c):await Is(s,n.cwd,e);if(!a){let p=t();if(p.sessionId!==n.sessionId||p.cwd!==n.cwd){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(s.endsWith("/control")){let u=l;u.root&&o(u.root)&&(u.blocked??="agent_busy")}}r(200,l)}catch(o){if(o instanceof R||o instanceof J)r(o.status,{error:o.message,errorCode:"validation_error",...o instanceof R?{reason:o.reason}:{}});else throw Ne(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var Rs={id:ot.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u5DE5\u4F5C\u533A\u76EE\u5F55\uFF0C\u53EA\u8BFB\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\u3002",en:"Browse workspace directories and preview code, Markdown and images read-only."}};var Cs={metadata:Rs,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw"],async handle({path:s,body:e,snapshot:t,json:i,res:r}){let n=t();if(e.sessionId!==n.sessionId){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(typeof e.path!="string"||e.path.length>4096){i(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}try{if(s.endsWith("/raw")){let a=await ss(n.cwd,e.path),l=t();if(l.sessionId!==n.sessionId||l.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r.writeHead(200,{"Content-Type":a.mimeType,"Content-Length":a.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),r.end(a.bytes);return}let o=s.endsWith("/list")?await is(n.cwd,e.path):await Et(n.cwd,e.path),c=t();if(c.sessionId!==n.sessionId||c.cwd!==n.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}i(200,o)}catch(o){if(o instanceof J)i(o.status,{error:o.message,errorCode:"validation_error"});else throw Ne(o,"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var Ds={id:ot.terminal,kind:"builtin",version:"1.0.0",name:{zh:"\u7EC8\u7AEF",en:"Terminal"},description:{zh:"\u5728\u5DE5\u4F5C\u533A\u8FD0\u884C\u4EA4\u4E92\u5F0F Shell\u3002\u505C\u7528\u4F1A\u7ED3\u675F\u6B64\u670D\u52A1\u7684\u6240\u6709\u7EC8\u7AEF\u8FDB\u7A0B\u3002",en:"Run an interactive shell in the workspace. Disabling ends all terminals on this service."}};import{accessSync as Os,constants as Yi,statSync as Ms}from"node:fs";import{createRequire as Ja}from"node:module";import{execFile as js}from"node:child_process";import{accessSync as Va,chmodSync as Fa,constants as Ba,statSync as Ua}from"node:fs";import{createRequire as La}from"node:module";import{dirname as za,join as qa}from"node:path";var Ns=La(import.meta.url);function Ga(s){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=qa(s,e,"spawn-helper"),i;try{i=Ua(t).mode}catch(r){if(r.code==="ENOENT")continue;throw r}try{Va(t,Ba.X_OK)}catch{Fa(t,i|73)}}}function Hs(...s){return Ga(za(Ns.resolve("node-pty/package.json"))),Ns("node-pty").spawn(...s)}var He=class extends Error{reason;constructor(e,t,i){super(t,{cause:i}),this.reason=e}},Ws=Ja(import.meta.url),Qi=class{pid;pty;screen;serializer;followers=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,i,r,n,o,c,a){this.sessionId=e,this.abandoned=c,this.graceMs=a;let{Terminal:l}=Ws("@xterm/headless"),{SerializeAddon:p}=Ws("@xterm/addon-serialize");this.screen=new l({cols:i,rows:r,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([y,m])=>m!==void 0&&!/^PI_WEBAPP_RESTART_/.test(y)));try{this.pty=Hs(n,o,{name:"xterm-256color",cwd:t,cols:i,rows:r,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(y){throw this.screen.dispose(),new He("terminal_runtime_unavailable","\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684 node-pty \u4F9D\u8D56",y)}this.pid=this.pty.pid,this.screen.onData(y=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(y)}),this.pty.onData(y=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(m=>{if(this.disposed){m();return}this.screen.write(y,()=>{this.broadcast({type:"output",data:y}),m()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(y=>this.pty.onExit(({exitCode:m,signal:f})=>{this.exit={type:"exit",exitCode:m,signal:f},this.pending.then(()=>{this.broadcast(this.exit),y()})})),this.scheduleExpiry()}broadcast(e){for(let t of this.followers)t(e)||this.followers.delete(t);this.followers.size||this.scheduleExpiry()}scheduleExpiry(){this.expire||this.disposed||(this.expire=setTimeout(this.abandoned,this.graceMs).unref())}async attach(e){if(await this.pending,this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u5173\u95ED");return clearTimeout(this.expire),this.expire=void 0,e({type:"snapshot",screen:this.serializer.serialize(),cols:this.screen.cols,rows:this.screen.rows})?(this.exit&&e(this.exit),this.followers.add(e)):this.scheduleExpiry(),()=>{this.followers.delete(e),this.followers.size||this.scheduleExpiry()}}write(e){if(this.exit||this.disposed)throw new Error("\u7EC8\u7AEF\u5DF2\u9000\u51FA");this.pty.write(e)}resize(e,t){this.exit||this.disposed||(this.pty.resize(e,t),this.pending=this.pending.then(()=>{this.disposed||(this.screen.resize(e,t),this.broadcast({type:"resize",cols:e,rows:t}))}))}close(){return this.closing??=this.dispose()}async dispose(){if(this.disposed=!0,clearTimeout(this.expire),!this.exit){if(process.platform==="win32")await new Promise(e=>js("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(r=>js("ps",["-axo","pid=,ppid="],(n,o)=>r(n?"":o)))).trim().split(`
20
+ `).map(r=>r.trim().split(/\s+/).map(Number)),i=r=>t.filter(([,n])=>n===r).flatMap(([n])=>[...i(n),n]);for(let r of[...i(this.pid),this.pid])try{process.kill(r,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending,this.followers.clear(),this.screen.dispose()}},Zt=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,i,r,n){if(this.stopped)throw new Error("\u7EC8\u7AEF\u670D\u52A1\u5DF2\u505C\u6B62");if(this.terminals.has(e))return this.get(e,t);if(this.terminals.size>=32||[...this.terminals.values()].filter(l=>l.sessionId===t).length>=8)throw new He("terminal_limit","\u7EC8\u7AEF\u6570\u91CF\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u5173\u95ED\u4E0D\u7528\u7684\u7EC8\u7AEF");let o=this.options.shell??(process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/sh");try{if(Os(o,Yi.X_OK),!Ms(o).isFile())throw new Error("Not a shell file")}catch(l){throw new He("terminal_shell_unavailable","\u9ED8\u8BA4 shell \u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u6267\u884C\uFF0C\u8BF7\u4FEE\u6B63 SHELL\uFF08Windows \u4E3A COMSPEC\uFF09\u540E\u91CD\u542F\u5E94\u7528",l)}try{if(!Ms(i).isDirectory())throw new Error("Not a directory");Os(i,Yi.R_OK|Yi.X_OK)}catch(l){throw new He("terminal_workspace_unavailable","\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8BF7\u5207\u6362\u5230\u6709\u6548\u5DE5\u4F5C\u533A\u540E\u65B0\u5EFA\u7EC8\u7AEF",l)}let c=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),a=new Qi(t,i,r,n,o,c,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,a),a}get(e,t){let i=this.terminals.get(e);if(!i||i.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return i}async remove(e,t){let i=this.terminals.get(e);if(i){if(i.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await i.close(),this.terminals.get(e)===i&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var $s=(s,e)=>Number.isInteger(s)&&Number.isInteger(e)&&Number(s)>=2&&Number(s)<=500&&Number(e)>=1&&Number(e)<=300;async function Vs(s,e,t,i,r,n){let o=(l,p)=>{t.writeHead(l,{"Content-Type":"application/json","Cache-Control":"no-store"}),t.end(JSON.stringify(p))};if(typeof e.id!="string"||!/^[a-f0-9-]{36}$/i.test(e.id)){o(400,{error:"\u7EC8\u7AEF\u6807\u8BC6\u65E0\u6548"});return}let c=s.slice(14),a=i();if(c!=="close"&&e.sessionId!==a.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((c==="create"||c==="resize")&&!$s(e.cols,e.rows)){o(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(c==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){o(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(c==="create"){r.create(e.id,e.sessionId,a.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(c==="close"){await r.remove(e.id,e.sessionId),o(200,{closed:!0});return}let l=r.get(e.id,e.sessionId);if(c==="attach"){let p=!1,u;t.once("close",()=>{p=!0,u?.(),n.delete(t)}),u=await l.attach(y=>p?!1:(t.headersSent||t.writeHead(200,{"Content-Type":"application/x-ndjson","Cache-Control":"no-store","X-Accel-Buffering":"no"}),t.writableLength>1024*1024?(t.destroy(),!1):(t.write(`${JSON.stringify(y)}
21
+ `),!0))),p?u():n.add(t);return}if(c==="input")l.write(e.data);else if(c==="resize")l.resize(e.cols,e.rows);else{o(404,{error:"\u672A\u77E5\u7EC8\u7AEF\u64CD\u4F5C"});return}o(200,{accepted:!0})}catch(l){t.headersSent?t.end():o(400,{error:l instanceof He?l.message:c==="create"?"\u672C\u673A\u7EC8\u7AEF\u7EC4\u4EF6\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u4FEE\u590D\u5E94\u7528\u7684\u7EC8\u7AEF\u4F9D\u8D56":"\u7EC8\u7AEF\u4E0D\u53EF\u7528\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u6253\u5F00\u7EC8\u7AEF",reason:l instanceof He?l.reason:c==="create"?"terminal_runtime_unavailable":void 0})}}function Fs(){let s=new Zt,e=new Set,t=async()=>{for(let i of e)i.end();e.clear(),await s.clear()};return{metadata:Ds,routes:["create","attach","input","resize","close"].map(i=>`/api/terminal/${i}`),handle:i=>Vs(i.path,i.body,i.res,i.snapshot,s,e),restartBlocker:()=>s.size?"\u8BF7\u5148\u5173\u95ED\u6240\u6709\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0":null,disable:t,async close(){await t(),await s.close()}}}function Bs(){return[Cs,Fs(),Ts]}import{createHash as Ka,randomUUID as Xa}from"node:crypto";import{mkdir as Ya,open as Qa,readFile as Za,rename as ec,rm as Us,writeFile as tc}from"node:fs/promises";import{dirname as ic}from"node:path";var Q=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},ei=class s{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Za(this.file,"utf8"));if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("disabled"in e)||!Array.isArray(e.disabled)||!e.disabled.every(t=>typeof t=="string"&&t.length>0&&t.length<=200))throw new Q("\u63D2\u4EF6\u914D\u7F6E\u65E0\u6548\uFF0C\u8BF7\u4FEE\u590D\u914D\u7F6E\u540E\u91CD\u542F",503);this.disabled=new Set(e.disabled)}catch(e){if(e.code!=="ENOENT")throw e}}enabled(e){return!this.disabled.has(e)}revision(){return Ka("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,i,r){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let n=`${this.file}.${Xa()}.tmp`,o=`${this.file}.lock`,c;try{if(i!==this.revision())throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");r();let a=new Set(this.disabled);t?a.delete(e):a.add(e),await Ya(ic(this.file),{recursive:!0});try{c=await Qa(o,"wx",384)}catch(p){throw p.code==="EEXIST"?new Q("\u63D2\u4EF6\u914D\u7F6E\u9501\u5B9A\u6587\u4EF6\u4ECD\u5B58\u5728\uFF0C\u5237\u65B0\u4E0D\u4F1A\u89E3\u9664\u3002\u8BF7\u5148\u505C\u6B62\u4F7F\u7528\u6B64\u914D\u7F6E\u7684\u5168\u90E8 Pi \u670D\u52A1\uFF0C\u518D\u5220\u9664 pi-web/plugins.json.lock \u540E\u91CD\u542F\uFF1B\u4E0D\u8981\u5220\u9664\u6D3B\u8DC3\u670D\u52A1\u7684\u9501"):p}await c.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
22
+ `);let l=new s(this.file);if(await l.load(),l.revision()!==i)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await tc(n,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
23
+ `,{mode:384}),r(),await ec(n,this.file),this.disabled=a}finally{this.changing=!1;try{await Us(n,{force:!0})}finally{c&&(await c.close(),await Us(o,{force:!0}))}}}};var ti=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(i=>[...i.routes]),new Set(e.map(i=>i.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(i=>i.metadata.id===e)?.routes.find(i=>i.split("/").at(-1)===t&&!i.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(i=>i.metadata.id));return{plugins:e.plugins.filter(i=>!t.has(i.id)),errors:[...e.errors,...e.plugins.filter(i=>t.has(i.id)).map(i=>`Plugin ID reserved by host: ${i.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(i=>this.preferences.enabled(i.metadata.id)).map(i=>({id:i.metadata.id,client:`builtin:${i.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,i,r){if(!this.plugins.some(n=>n.metadata.id===e))throw new Q("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(n=>n>0))throw new Q("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,i,r),t||await this.plugins.find(n=>n.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(r=>r.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let i=t.metadata.id;this.running.set(i,(this.running.get(i)??0)+1);try{await t.handle(e)}finally{this.running.set(i,this.running.get(i)-1)}return!0}async runAgentAction(e,t,i,r,n){let o=this.plugins.find(c=>c.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new Q("\u7ED8\u56FE\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(t,i,r,n)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let i="@host/start";this.running.set(i,(this.running.get(i)??0)+1);let r=t;for(let n of this.plugins)if(n.coordinateStart&&this.preferences.enabled(n.metadata.id)){let o=r;r=()=>n.coordinateStart(e,o)}try{return await r()}finally{this.running.set(i,this.running.get(i)-1)}}requestFailure(e){if(e instanceof Q)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let i=t.requestFailure?.(e);if(i)return i}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":this.plugins.map(e=>e.restartBlocker?.()).find(Boolean)??null}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as rc,opendir as sc,stat as nc}from"node:fs/promises";import{homedir as oc}from"node:os";import{basename as ac,dirname as Ls,join as zs,posix as cc,resolve as qs,win32 as lc}from"node:path";function Gs(s){return process.platform==="win32"?lc.isAbsolute(s)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(s):cc.isAbsolute(s)}function dc(s,e,t){if(s.length===t&&e.name.localeCompare(s[s.length-1].name)>=0)return!0;let i=0,r=s.length;for(;i<r;){let n=i+r>>>1;e.name.localeCompare(s[n].name)<0?r=n:i=n+1}return s.splice(i,0,e),s.length<=t?!1:(s.pop(),!0)}async function Js(s){if(s!==void 0&&!Gs(s))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=oc(),t=qs(s??e),i=[];for(let a=t;;a=Ls(a)){let l=Ls(a);if(i.unshift({name:l===a?a:ac(a),path:a,hidden:!1}),l===a)break}let r=[],n=!1,o=await sc(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||dc(r,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(n=!0);let c=[];for(let a of r){let l=zs(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await nc(l)).isDirectory())continue}catch{continue}if(c.length===1e3){n=!0;break}c.push({name:a.name,path:l,hidden:a.name.startsWith(".")})}return{path:t,home:e,crumbs:i,entries:c,truncated:n}}async function Ks(s,e){if(!Gs(s))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let t=zs(qs(s),e);return await rc(t),t}import{execFile as pc}from"node:child_process";import{accessSync as uc,constants as hc}from"node:fs";import{delimiter as fc,join as gc}from"node:path";var mc=(s,e,t)=>new Promise((i,r)=>{pc(s,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(n,o,c)=>{n?r(Object.assign(new Error(n.message,{cause:n}),{code:n.code,stdout:o,stderr:c})):i({stdout:o,stderr:c})})});function wc(s){for(let e of(s??"").split(fc))if(e)for(let t of["zenity","kdialog"])try{return uc(gc(e,t),hc.X_OK),!0}catch{}return!1}function Xs(s=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":s==="darwin"||s==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&wc(e.PATH)?"native":"browse"}function ii(s){if(!(typeof s!="object"||s===null||!("code"in s)))return typeof s.code=="string"||typeof s.code=="number"?s.code:void 0}function yc(s){return typeof s=="object"&&s!==null&&"stderr"in s&&typeof s.stderr=="string"?s.stderr:""}function Zi(s){return s.replace(/[\r\n]+$/,"")||null}async function Ys(s,e=process.platform,t=mc){if(e==="darwin")try{let i=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],s);return Zi(i.stdout)}catch(i){if(!s.aborted&&ii(i)===1&&/(?:User canceled|-128)/i.test(yc(i)))return null;throw i}if(e==="linux"){try{return Zi((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],s)).stdout)}catch(i){if(s.aborted)throw i;if(ii(i)===1)return null;if(ii(i)!=="ENOENT")throw i}try{return Zi((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],s)).stdout)}catch(i){if(s.aborted)throw i;if(ii(i)===1)return null;throw i}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as vc,randomUUID as bc}from"node:crypto";import{mkdir as kc,readFile as Pc,writeFile as Ic}from"node:fs/promises";import{join as Qs}from"node:path";import{getAgentDir as Sc}from"@earendil-works/pi-coding-agent";var ri=20*1024*1024,Zs=20,Ec=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function xc(s){let e=s.indexOf("."),t=(e<0?s:s.slice(0,e)).replace(/[. ]+$/u,"");return Ec.test(t)}function _c(s,e){let t=0,i="";for(let r of Buffer.from(s).toString("utf8")){let n=Buffer.byteLength(r);if(t+n>e)break;i+=r,t+=n}return i}function Ac(s){if(s===void 0)return"file";let t=s.slice(Math.max(s.lastIndexOf("/"),s.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return xc(t)&&(t=`_${t}`),t=_c(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function Tc(s){return s.length>=8&&s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":s.length>=3&&s.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":s.length>=6&&["GIF87a","GIF89a"].includes(s.toString("ascii",0,6))?"image/gif":s.length>=12&&s.toString("ascii",0,4)==="RIFF"&&s.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function en(s,e,t,i){if(i.byteLength===0||i.byteLength>ri)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let r=Ac(e),n=vc("sha256").update(i).digest("hex"),o=Qs(Sc(),"pi-web","attachments",n);await kc(o,{recursive:!0});let c=Qs(o,r);try{await Ic(c,i,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:bc(),name:r,bytes:i.byteLength,path:c,mediaType:Tc(i)??t.replace(/^image\//,"application/"),sessionId:s}}async function tn(s){return{type:"image",data:(await Pc(s.path)).toString("base64"),mimeType:s.mediaType}}import{randomBytes as Rc}from"node:crypto";function rn(s,e,t){return s!=="openai-codex"||e!=="oauth"?t:{...t,prompt:i=>i.type==="select"&&i.options.some(r=>r.id==="browser")&&i.options.some(r=>r.id==="device_code")?Promise.resolve("browser"):t.prompt(i)}}var si=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,i,r,n){let o=this.getActive();if(o){if(o.providerId===e&&o.method===t&&r===void 0)return o;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let c=Rc(18).toString("base64url"),a={view:{id:c,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(c,a),i(e,t,{signal:a.controller.signal,notify:l=>{a.view={...a.view,event:l,...l.type==="auth_url"||l.type==="device_code"?{authorization:l}:{}}},prompt:l=>{if(l.type==="secret"&&r!==void 0){let p=r;return r=void 0,Promise.resolve(p)}return new Promise((p,u)=>{let{signal:y,...m}=l;a.answer=p,a.reject=u,a.view={...a.view,status:"waiting",prompt:m},y?.aborted?u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):y?.addEventListener("abort",()=>u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{a.view.status!=="cancelled"&&(a.view={id:c,providerId:e,method:t,status:"done"})}).catch(l=>{if(a.view.status!=="cancelled"){let p=new Error("Provider login failed");l instanceof Error&&l.stack&&(p.stack=`${p.message}
24
24
  ${l.stack.split(`
25
25
  `).slice(1).join(`
26
- `)}`);let u=this.reportError(p,{...n,stage:"provider_login"});a.view={id:c,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:u}}}),{...a.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let i=this.flows.get(e);if(!i?.answer||i.view.status!=="waiting"||i.view.prompt?.type==="select"&&!i.view.prompt.options.some(n=>n.id===t))return!1;let r=i.answer;return i.answer=void 0,i.reject=void 0,i.view={...i.view,status:"running",prompt:void 0},r(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as Ac}from"node:crypto";import{readFile as Tc,rename as Rc,rm as Cc,stat as Dc,writeFile as Nc,mkdir as Hc}from"node:fs/promises";import{dirname as Oc}from"node:path";var Mc=["openai-completions","openai-responses","anthropic-messages"];function er(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!Mc.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 rn(s,e){if(!er(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let t;try{t=await Tc(s,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let i;if(t===void 0)i={providers:{}};else{try{i=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(i.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let r={...i,providers:{...i.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await Hc(Oc(s),{recursive:!0});let n=t===void 0?384:(await Dc(s)).mode&511,o=`${s}.pi-web-${Ac(6).toString("hex")}.tmp`;try{await Nc(o,`${JSON.stringify(r,null,2)}
27
- `,{mode:n,flag:"wx"}),await Rc(o,s)}finally{await Cc(o,{force:!0})}}import{randomBytes as jc}from"node:crypto";import{mkdir as Wc,readFile as $c,rename as Vc,rm as Fc,stat as Uc,writeFile as Bc}from"node:fs/promises";import{dirname as Lc}from"node:path";function sn(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 nn(s){if(!s||typeof s!="object")return!1;let e=s;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&on(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&sn(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function on(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 an(s){let e;try{e=await $c(s,"utf8")}catch(i){if(i.code!=="ENOENT")throw i}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function zc(s,e,t){await Wc(Lc(s),{recursive:!0});let i=t===void 0?384:(await Uc(s)).mode&511,r=`${s}.pi-web-${jc(6).toString("hex")}.tmp`;try{await Bc(r,`${JSON.stringify(e,null,2)}
28
- `,{mode:i,flag:"wx"}),await Vc(r,s)}finally{await Fc(r,{force:!0})}}async function cn(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await an(s),r=i.providers[e],n=new Set(r?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:r?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!r?.modelOverrides?.[o.id]}))}}async function ln(s,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r,existing:n}=await an(s),o={...r.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!sn(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(!on(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(w=>w.id===p);if(p===void 0&&(c.some(w=>w.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(c.some(m=>m.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let w={...c[u],...l};for(let m of["name","contextWindow","maxTokens","input"])l[m]===void 0&&delete w[m];c[u]=w}else if(p!==void 0&&i.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:w,...m}=l;a[p]={...a[p],...m};for(let f of["name","contextWindow","maxTokens","input"])l[f]===void 0&&delete a[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(l)}}else{let l=c.findIndex(p=>p.id===t.id);if(l>=0)c.splice(l,1);else if(Object.hasOwn(a,t.id))delete a[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(a).length?o.modelOverrides=a:delete o.modelOverrides,Object.keys(o).length?r.providers[e]=o:delete r.providers[e],await zc(s,r,n)}function dn(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as pn,createHash as qc}from"node:crypto";import{fileURLToPath as Gc}from"node:url";var At="pi-webapp@0.1.50-alpha.3+6fa461bac0923ef2a88d",Se="6fa461bac0923ef2a88d";var Jc="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function si(s=process.env,e=console.warn){let t=i=>{let r={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:At,buildId:Se},n=s[`PI_WEB_SENTRY_${i}_DSN`]??s.PI_WEB_SENTRY_DSN??Jc;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return r;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...r,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),r}};return{browser:t("BROWSER"),node:t("NODE")}}var xe=class{config;ready;reporter;client;salt=pn(16);breadcrumbs=new _t;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=si(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Gc(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),r=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:r)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Se,integrations:[],transport:e.transport??(i=>_s(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:xs,sendClientReports:!1,dataCollection:{...Is,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Xt(this.client,"node",Se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=pn(16).toString("hex");return this.early.push({error:ct(e),context:Ie(t),eventId:i}),i}catch{return}}setState(e){this.state=Ie({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return qc("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as ll}from"@earendil-works/pi-coding-agent";function je(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 Kc}from"node:crypto";function Tt(s){let e=[],t=s;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let r;try{r=JSON.parse(i[2])}catch{break}e.unshift({name:r,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(r)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Rt=s=>Buffer.byteLength(s.text)+s.images.reduce((e,t)=>e+t.data.length,0),ne=class extends Error{status=409},We=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,...Tt(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((r,n)=>r+Rt(n),Rt({text:e,images:t}))>64*1024*1024)throw new ne("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Kc(),revision:1,text:e,images:t.map(r=>({...r})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new ne("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(r=>r.id===e);if(!i||i.revision!==t)throw new ne("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new ne("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,r){let n=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(i.kind==="edit"){let o=Tt(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[i.text.trim(),c].filter(Boolean).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 i=this.flows.get(e);if(!i?.answer||i.view.status!=="waiting"||i.view.prompt?.type==="select"&&!i.view.prompt.options.some(n=>n.id===t))return!1;let r=i.answer;return i.answer=void 0,i.reject=void 0,i.view={...i.view,status:"running",prompt:void 0},r(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as Cc}from"node:crypto";import{readFile as Dc,rename as Nc,rm as Hc,stat as Oc,writeFile as Mc,mkdir as jc}from"node:fs/promises";import{dirname as Wc}from"node:path";var $c=["openai-completions","openai-responses","anthropic-messages"];function er(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!$c.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let t=new URL(e.baseUrl);return(t.protocol==="https:"||t.protocol==="http:")&&!!t.hostname&&!t.username&&!t.password&&!t.hash}catch{return!1}}async function sn(s,e){if(!er(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let t;try{t=await Dc(s,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let i;if(t===void 0)i={providers:{}};else{try{i=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(i.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let r={...i,providers:{...i.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await jc(Wc(s),{recursive:!0});let n=t===void 0?384:(await Oc(s)).mode&511,o=`${s}.pi-web-${Cc(6).toString("hex")}.tmp`;try{await Mc(o,`${JSON.stringify(r,null,2)}
27
+ `,{mode:n,flag:"wx"}),await Nc(o,s)}finally{await Hc(o,{force:!0})}}import{randomBytes as Vc}from"node:crypto";import{mkdir as Fc,readFile as Bc,rename as Uc,rm as Lc,stat as zc,writeFile as qc}from"node:fs/promises";import{dirname as Gc}from"node:path";function nn(s){if(!s||s.length>2048)return!1;try{let e=new URL(s);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function on(s){if(!s||typeof s!="object")return!1;let e=s;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&an(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&nn(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function an(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let t of[e.contextWindow,e.maxTokens])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(t=>t==="text"||t==="image")&&new Set(e.input).size===e.input.length}async function cn(s){let e;try{e=await Bc(s,"utf8")}catch(i){if(i.code!=="ENOENT")throw i}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function Jc(s,e,t){await Fc(Gc(s),{recursive:!0});let i=t===void 0?384:(await zc(s)).mode&511,r=`${s}.pi-web-${Vc(6).toString("hex")}.tmp`;try{await qc(r,`${JSON.stringify(e,null,2)}
28
+ `,{mode:i,flag:"wx"}),await Uc(r,s)}finally{await Lc(r,{force:!0})}}async function ln(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await cn(s),r=i.providers[e],n=new Set(r?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:r?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!r?.modelOverrides?.[o.id]}))}}async function dn(s,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r,existing:n}=await cn(s),o={...r.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!nn(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!an(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let l={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},p=t.originalId,u=p===void 0?-1:c.findIndex(y=>y.id===p);if(p===void 0&&(c.some(y=>y.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(c.some(m=>m.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let y={...c[u],...l};for(let m of["name","contextWindow","maxTokens","input"])l[m]===void 0&&delete y[m];c[u]=y}else if(p!==void 0&&i.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:y,...m}=l;a[p]={...a[p],...m};for(let f of["name","contextWindow","maxTokens","input"])l[f]===void 0&&delete a[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(l)}}else{let l=c.findIndex(p=>p.id===t.id);if(l>=0)c.splice(l,1);else if(Object.hasOwn(a,t.id))delete a[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(a).length?o.modelOverrides=a:delete o.modelOverrides,Object.keys(o).length?r.providers[e]=o:delete r.providers[e],await Jc(s,r,n)}function pn(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as un,createHash as Kc}from"node:crypto";import{fileURLToPath as Xc}from"node:url";var Tt="pi-webapp@0.1.50-alpha.4+6f276aca4a67bf831236",Se="6f276aca4a67bf831236";var Yc="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ni(s=process.env,e=console.warn){let t=i=>{let r={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Tt,buildId:Se},n=s[`PI_WEB_SENTRY_${i}_DSN`]??s.PI_WEB_SENTRY_DSN??Yc;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return r;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...r,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),r}};return{browser:t("BROWSER"),node:t("NODE")}}var xe=class{config;ready;reporter;client;salt=un(16);breadcrumbs=new At;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=ni(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Xc(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),r=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:r)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Se,integrations:[],transport:e.transport??(i=>As(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:_s,sendClientReports:!1,dataCollection:{...Ss,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Yt(this.client,"node",Se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=un(16).toString("hex");return this.early.push({error:lt(e),context:Ie(t),eventId:i}),i}catch{return}}setState(e){this.state=Ie({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return Kc("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as ul}from"@earendil-works/pi-coding-agent";function We(s,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(s.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!s.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Qc}from"node:crypto";function Rt(s){let e=[],t=s;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let r;try{r=JSON.parse(i[2])}catch{break}e.unshift({name:r,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(r)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Ct=s=>Buffer.byteLength(s.text)+s.images.reduce((e,t)=>e+t.data.length,0),ae=class extends Error{status=409},$e=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...Rt(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((r,n)=>r+Ct(n),Ct({text:e,images:t}))>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Qc(),revision:1,text:e,images:t.map(r=>({...r})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new ae("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(r=>r.id===e);if(!i||i.revision!==t)throw new ae("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new ae("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,r){let n=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(i.kind==="edit"){let o=Rt(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[i.text.trim(),c].filter(Boolean).join(`
29
29
 
30
- `);if(this.validateText(a),this.entries.reduce((l,p)=>l+Rt(p),0)-Rt(n)+Rt({text:a,images:n.images})>64*1024*1024)throw new ne("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");n.text=a,n.revision++,delete n.error,this.changed();return}await this.deliver(n,r)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(i=>i!==e)}catch(i){throw e.status="queued",e.revision++,e.error=i instanceof Error?i.message:"\u53D1\u9001\u5931\u8D25",i}finally{this.changed()}}schedule(e,t){let i=this.entries[0];this.pumping||!i||i.status!=="queued"||i.error||!e()||(this.pumping=!0,i.status="sending",i.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){i.status="queued",i.revision++,this.changed();return}await this.deliver(i,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var h=class extends Error{code;status;reason;constructor(e,t,i={}){super(t),this.name="HostedPluginError",this.code=e,this.status=i.status,this.reason=i.reason}};function G(s){let e=s&&typeof s=="object"?s:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:s instanceof Error?s.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var $e=s=>s.code==="ENOENT";var un=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function tr(s,e,t,i){if(!s)throw new h("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return s.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new h("invalid_input","Expected plugin request object",{status:400});let r=t;if(e==="/api/hosted-plugins/views"){if(i?.draining&&!["poll","pollMany","change","ack","close","reconcile","cancel-initialization"].includes(String(r.operation)))throw new h("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(r.operation!=="pollMany")return s.views(r);if(!Array.isArray(r.views)||!r.views.length||r.views.length>64||r.views.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.operation!=="poll"))throw new h("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(r.views.map(async n=>{try{return{reply:await s.views({...n,operation:"poll",immediate:!0})}}catch(o){return{failure:ni(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 ni(s){let e=G(s);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as hn}from"node:fs/promises";import{join as fn}from"node:path";async function gn(s){try{let e=JSON.parse(await hn(fn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,i=await hn(fn(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 Yc,readFile as ir,realpath as ci,rename as Qc,rm as Zc,writeFile as el}from"node:fs/promises";import{randomUUID as tl}from"node:crypto";import{dirname as ai,join as _e,resolve as il,sep as wn}from"node:path";import{createRequire as rl}from"node:module";var Xc=/^(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 Ve(s){let e=typeof s=="string"&&Xc.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=Ve(s),i=Ve(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 mn(s){try{return Ve(s).prerelease.length===0}catch{return!1}}function oi(s){try{return Ve(s),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(s)}catch{return!1}}var Fe=1,yn=s=>_e(s,"pi-web","desktop-update.json");async function lt(s,e){let t=rl(_e(s,"package.json"));for(let i of t.resolve.paths(e)??[]){let r=_e(i,e);try{if(JSON.parse(await ir(_e(r,"package.json"),"utf8")).name===e)return await ci(r)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function li(s,e){if(ue(e?.version,e?.version),e.desktopProtocolVersion!==Fe||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await ci(il(ai(e.launcher),"..")),i=await ci(_e(s,"pi-web","releases")),r=ai(ai(t));if(await ci(e.launcher)!==_e(t,"bin","pi-webapp.mjs")||ai(r)!==i||!r.startsWith(i+wn)||!r.slice(i.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(r.slice(i.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let n=JSON.parse(await ir(_e(t,"package.json"),"utf8"));if(n.name!=="pi-webapp"||n.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(n.piWebappDesktopProtocol!==Fe)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 lt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(r+wn))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=>Yc(a))),e.fallbackVersion!==void 0&&Ve(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:Fe,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}async function vn(s,e,t=e){try{let i=JSON.parse(await ir(yn(s),"utf8"));return ue(i.version,e)<0&&i.fallbackVersion!==t?null:await li(s,i)}catch{return null}}async function bn(s,e){let t=yn(s),i=`${t}.${tl()}.tmp`;try{await el(i,JSON.stringify(e),{mode:384}),await Qc(i,t)}finally{await Zc(i,{force:!0})}}var dl={"/":{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 pl(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&&sl(i,e)}async function Pn(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 ul(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>ii)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(r)}return Buffer.concat(t)}async function hl(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 In(s,e,t=new xe,i={}){t.setState({piVersion:ll});let r=process.env.PI_WEBAPP_RESTART_TOKEN,n=r&&/^[A-Za-z0-9_-]{32}$/.test(r)?r:kn(24).toString("base64url"),o=Buffer.from(n),c=Ks(),a=new Set,l=new Zt(i.pluginSettingsFile??sr(cl(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new ei(Fs(),l),u=async()=>await s.plugins?.()??{plugins:[],errors:[]},w=()=>({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(w())}
31
- `)},f=new Map,y=new ri((b,v)=>t.capture(b,v)),P=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}),k="",E=!1,_=!1,H={...dl,...await gn(e)};for(let b of await ol(sr(e,"assets")).catch(()=>[])){let v=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(b);if(!v)continue;let $={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};H[`/assets/${b}`]={path:`assets/${b}`,type:$[v[1]]}}let N=al(async(b,v)=>{let $=kn(18).toString("base64"),we=pe=>typeof pe=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(pe),ye=we(b.headers["x-request-id"])?b.headers["x-request-id"]:rr(),ie={requestId:ye,operationId:we(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",ye),ie.operationId&&v.setHeader("X-Operation-ID",ie.operationId);let x="/",na=performance.now(),de=(pe,g,S)=>{let C=!Ge(pe)&&Ss(x)?De(pe,"Agent or provider operation failed"):pe,q=t.capture(C,{...ie,route:x,method:b.method,status:g,stage:"http"});I(v,g,{error:S,errorId:q,errorReported:t.enabled,errorCode:Ge(pe)?"validation_error":"unexpected_error"})};v.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...ie,route:x,method:b.method,status:v.statusCode,durationMs:Math.round(performance.now()-na)})});try{v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${$}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${t.config.browser.dsn?` ${new URL(t.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{x=new URL(b.url??"/",k).pathname}catch{I(v,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let pe=H[x];if(b.method==="GET"&&pe){try{let g=await nl(sr(e,pe.path));v.writeHead(200,{"Content-Type":pe.type,"Cache-Control":"no-store"}),v.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${$}">`):g)}catch(g){de(g,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let g=await s.hosted?.asset(x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),v.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),v.end(g.bytes)}catch{I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(b.method==="GET"&&x.startsWith("/plugins/")){try{let g=await s.pluginAsset?.(b.url??x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),v.end(g.bytes)}catch(g){de(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(v,404,{error:"\u672A\u627E\u5230"});return}if(!pl(b,o)){I(v,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(b.method==="GET"&&x==="/api/hosted-plugins"){try{I(v,200,await tr(s.hosted,x,void 0))}catch(g){let S=ni(g);I(v,S.status,S.body)}return}if(b.method==="POST"&&un.includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==k){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){I(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let g;try{g=await Pn(b,2*1024*1024)}catch(S){I(v,S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{I(v,200,await tr(s.hosted,x,g,{draining:E}))}catch(S){let A=ni(S);I(v,A.status,A.body)}return}if(b.method==="GET"&&x==="/api/telemetry/config"){I(v,200,t.config.browser);return}if(b.method==="GET"&&x==="/api/update/version"){try{I(v,200,{current:await s.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Fe,...s.selfUpdate?.launcherIdentity?{launcher:s.selfUpdate.launcherIdentity(),desktopHandoffProtocol:s.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){de(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{I(v,200,await s.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){de(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/image"){let g=new URL(b.url??x,k),S=g.searchParams.get("sessionId")??"",A=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==s.snapshot().sessionId||!A||!Number.isInteger(C)||C<0||C>100){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let q=s.image?.(S,A,C);if(!q||!["image/png","image/jpeg","image/webp","image/gif"].includes(q.mimeType)){I(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":q.mimeType,"Cache-Control":"private, no-store"}),v.end(q.data);return}if(b.method==="POST"&&x==="/api/attachment"){if(b.headers.origin!==void 0&&b.headers.origin!==k){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let g=new URL(b.url??x,k),S=g.searchParams.get("sessionId"),A=g.searchParams.get("name");try{if(!S||!A||A.length>1024||S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(b.headers["content-length"]??0)>ii){I(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await Zs(S,A,b.headers["content-type"]??"application/octet-stream",await ul(b));if(S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}f.set(C.id,C),I(v,201,{id:C.id,name:C.name,bytes:C.bytes})}catch(C){de(C,400,C instanceof Error?C.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/session"){try{let g=s.snapshot();P(g),I(v,200,g)}catch(g){de(g,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugin-management"){try{I(v,200,p.inventory(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugins"){try{I(v,200,p.catalog(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/providers"){try{I(v,200,await s.providers?.()??[])}catch(g){de(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/models"){let g=new URL(b.url??x,k).searchParams.get("providerId")??"";try{if(!g||!s.providerModels){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(v,200,await s.providerModels(g))}catch(S){de(S,400,S instanceof Error?S.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/login/active"){I(v,200,{active:y.getActive()??null});return}if(b.method==="GET"&&x==="/api/provider/login"){let g=new URL(b.url??x,k).searchParams.get("id")??"",S=y.get(g);I(v,S?200:404,S??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(b.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{I(v,200,x==="/api/models"?await s.models():x==="/api/config"?await s.config():x==="/api/commands"?s.commands?.()??[]:await s.workspaces())}catch(g){de(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/directory/capability"){I(v,200,{kind:c});return}if(b.method==="GET"&&x==="/api/events"){let g;try{g=s.snapshot(),P(g)}catch(S){de(S,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}v.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),a.add(v),v.write(`${JSON.stringify({type:"snapshot",session:g})}
32
- `),v.on("close",()=>a.delete(v));return}if(b.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==k){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 Pn(b,x==="/api/plugin-action"?544*1024:64*1024)}catch(S){if(S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){I(v,413,{error:S.message});return}if(S instanceof SyntaxError||Ge(S)){I(v,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw S}if(x==="/api/desktop/handoff"){let S=g;if(!S||typeof S.nonce!="string"||typeof S.requestId!="string"){I(v,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!s.selfUpdate?.requestLauncherHandoff){I(v,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(E||_||y.getActive()){I(v,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let A=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||A){I(v,409,{error:A??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}E=!0;try{await s.selfUpdate.requestLauncherHandoff(S.nonce,S.requestId)}catch(C){throw E=!1,C}I(v,202,{accepted:!0,protocol:1,requestId:S.requestId});return}if(typeof g!="object"||g===null||!("sessionId"in g)||typeof g.sessionId!="string"){I(v,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(E&&x!=="/api/update/cancel"){I(v,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(x==="/api/plugin-management"){let S=g;if(typeof S.id!="string"||S.id.length>200||typeof S.enabled!="boolean"||typeof S.expected!="string"){I(v,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let A=()=>{if(s.snapshot().sessionId!==g.sessionId)throw new Q("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length)throw new Q("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(S.id,S.enabled,S.expected,A),I(v,200,p.inventory(await u()))}catch(C){if(C instanceof Q)I(v,C.status,{error:C.message});else throw C}finally{m()}return}if(p.mutating&&x!=="/api/abort"){I(v,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:x,body:g,res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(S,A)=>I(v,S,A)}))return;if(x==="/api/plugin-interaction"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("requestId"in g)||typeof g.requestId!="string"||g.requestId.length>200||!s.resolvePluginInteraction||!("value"in g)){I(v,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(s.snapshot().cwd,async()=>s.resolvePluginInteraction(g.sessionId,g.pluginId,g.requestId,g.value)),I(v,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("action"in g)||typeof g.action!="string"||g.action.length>100){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(C=>C.metadata.id===g.pluginId)){let C=p.actionRoute(g.pluginId,g.action);if(!C){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let q="input"in g?g.input:{};if(!q||typeof q!="object"||Array.isArray(q)){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...q,sessionId:g.sessionId},res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(ve,Gt)=>I(v,ve,ve>=200&&ve<300?{value:Gt}:Gt)});return}if(!s.invokePluginAction){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let A=await p.coordinateStart(s.snapshot().cwd,async()=>s.invokePluginAction(g.sessionId,g.pluginId,g.action,"input"in g?g.input:void 0));I(v,200,{value:A});return}if(x==="/api/update/channel"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in g)||g.channel!=="stable"&&g.channel!=="alpha"){I(v,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!s.selfUpdate?.setChannel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}I(v,200,await s.selfUpdate.setChannel(g.channel));return}if(x==="/api/update/cancel"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.selfUpdate?.cancel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await s.selfUpdate.cancel(),I(v,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(_){I(v,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.snapshot().idle){I(v,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!s.selfUpdate){I(v,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let S=p.restartBlocker();if((s.busyGitWorkspaces?.()??[]).length||S){I(v,409,{error:S??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let A=g,C="channel"in A||"version"in A||"allowDowngrade"in A;if(C&&(A.channel!=="stable"&&A.channel!=="alpha"||typeof A.version!="string"||A.allowDowngrade!==void 0&&typeof A.allowDowngrade!="boolean")){I(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}_=!0;let q;try{q=await s.selfUpdate.prepare(C?{channel:A.channel,version:A.version,allowDowngrade:A.allowDowngrade}:void 0);let ve=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||ve)throw new Error(ve??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");E=!0,await s.selfUpdate.requestRestart(q)}catch(ve){throw E=!1,ve}finally{_=!1}I(v,202,{accepted:!0,version:q.version});return}if(x==="/api/provider/custom"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in g)||!er(g.provider)||!s.addCustomProvider){I(v,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await s.addCustomProvider(g.sessionId,g.provider),I(v,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in g)||typeof g.providerId!="string"){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(x==="/api/provider/models"){if(!("change"in g)||!nn(g.change)||!s.updateProviderModel){I(v,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await s.updateProviderModel(g.sessionId,g.providerId,g.change)}else{if(!s.logoutProvider){I(v,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await s.logoutProvider(g.sessionId,g.providerId)}I(v,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(x==="/api/provider/login"){if(!("providerId"in g)||typeof g.providerId!="string"||!("method"in g)||g.method!=="api_key"&&g.method!=="oauth"||!s.loginProvider||!s.providers){I(v,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await s.providers()).some(q=>q.id===g.providerId&&q.methods.includes(g.method))){I(v,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let A="initialSecret"in g?g.initialSecret:void 0;if(A!==void 0&&(g.method!=="api_key"||typeof A!="string"||!A.trim()||A.length>16384)){I(v,400,{error:"API Key \u65E0\u6548"});return}let C=y.start(g.providerId,g.method,s.loginProvider,A,ie);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,y.cancel(g.id)?202:404,{accepted:!0});return}if(!("value"in g)||typeof g.value!="string"||g.value.length>16384||!y.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 Xs(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 Gs("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 Js(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/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"&&dn(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>Qs||A.some(se=>typeof se!="string")||new Set(A).size!==A.length){I(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=A.map(se=>f.get(se));if(C.some(se=>!se||se.sessionId!==g.sessionId)){I(v,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in g)||typeof g.text!="string"||!g.text.trim()&&A.length===0||g.text.length>32e3){I(v,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let q=s.snapshot();if(g.sessionId!==q.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{je(q,g.text,S)}catch(se){I(v,409,{error:se.message});return}let ve=C,Gt=[g.text.trim(),...ve.map(se=>`\u9644\u4EF6 ${JSON.stringify(se.name)}\uFF1A${se.path}`)].filter(Boolean).join(`
30
+ `);if(this.validateText(a),this.entries.reduce((l,p)=>l+Ct(p),0)-Ct(n)+Ct({text:a,images:n.images})>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");n.text=a,n.revision++,delete n.error,this.changed();return}await this.deliver(n,r)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(i=>i!==e)}catch(i){throw e.status="queued",e.revision++,e.error=i instanceof Error?i.message:"\u53D1\u9001\u5931\u8D25",i}finally{this.changed()}}schedule(e,t){let i=this.entries[0];this.pumping||!i||i.status!=="queued"||i.error||!e()||(this.pumping=!0,i.status="sending",i.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){i.status="queued",i.revision++,this.changed();return}await this.deliver(i,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var h=class extends Error{code;status;reason;constructor(e,t,i={}){super(t),this.name="HostedPluginError",this.code=e,this.status=i.status,this.reason=i.reason}};function G(s){let e=s&&typeof s=="object"?s:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:s instanceof Error?s.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Ve=s=>s.code==="ENOENT";var hn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function tr(s,e,t,i){if(!s)throw new h("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return s.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new h("invalid_input","Expected plugin request object",{status:400});let r=t;if(e==="/api/hosted-plugins/views"){if(i?.draining&&!["poll","pollMany","change","ack","close","reconcile","cancel-initialization"].includes(String(r.operation)))throw new h("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(r.operation!=="pollMany")return s.views(r);if(!Array.isArray(r.views)||!r.views.length||r.views.length>64||r.views.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.operation!=="poll"))throw new h("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(r.views.map(async n=>{try{return{reply:await s.views({...n,operation:"poll",immediate:!0})}}catch(o){return{failure:oi(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(i?.draining)throw new h("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof r.id!="string"||!/^[a-f0-9-]{36}$/.test(r.id)||r.decision!=="allow"&&r.decision!=="deny")throw new h("invalid_input","Invalid approval decision",{status:400});if(!s.decide)throw new h("hosted_unavailable","Approvals are not available in this runtime",{status:503});return s.decide(r.id,r.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(i?.draining)throw new h("host_restarting","Host is updating; secret changes are fenced",{status:409});if(r.auth!==void 0){if(!s.secretAuth)throw new h("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(r.auth==="start"&&typeof r.pluginId=="string"&&r.pluginId.length<=214&&typeof r.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(r.name))return s.secretAuth({phase:"start",pluginId:r.pluginId,name:r.name});if((r.auth==="poll"||r.auth==="cancel")&&typeof r.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(r.deviceId))return s.secretAuth({phase:r.auth,deviceId:r.deviceId});throw new h("invalid_input","Invalid sign-in request",{status:400})}if(typeof r.pluginId!="string"||r.pluginId.length>214||typeof r.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(r.name)||!(r.value===null||typeof r.value=="string"&&r.value.length>=1&&r.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(r.value)))throw new h("invalid_input","Invalid secret request",{status:400});if(!s.secret)throw new h("hosted_unavailable","Secrets are not available in this runtime",{status:503});return s.secret(r.pluginId,r.name,r.value)}if(typeof r.pluginId!="string"||r.pluginId.length>214)throw new h("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(i?.draining)throw new h("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof r.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(r.operation)||r.version!==void 0&&(typeof r.version!="string"||!/^\d+\.\d+\.\d+$/.test(r.version)))throw new h("invalid_input","Invalid plugin management request",{status:400});if(r.downloadId!==void 0&&(typeof r.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(r.downloadId))||r.operation==="cancel-download"&&!r.downloadId)throw new h("invalid_input","Exact download identity required",{status:400});if(r.reopenEditors!==void 0&&typeof r.reopenEditors!="boolean")throw new h("invalid_input","Invalid editor reopen consent",{status:400});if(r.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(r.updatePolicy)||r.operation==="policy"&&(typeof r.updatePolicy!="string"||r.updatePolicy==="pinned"&&!r.version))throw new h("invalid_input","Invalid update policy or missing exact pin",{status:400});return s.manage({pluginId:r.pluginId,operation:r.operation,...typeof r.downloadId=="string"?{downloadId:r.downloadId}:{},...typeof r.updatePolicy=="string"?{updatePolicy:r.updatePolicy}:{},...typeof r.version=="string"?{version:r.version}:{},...typeof r.reopenEditors=="boolean"?{reopenEditors:r.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof r.sessionId!="string"||!r.sessionId||r.sessionId.length>200||!Number.isSafeInteger(r.generation)||Number(r.generation)<1||typeof r.action!="string"||!/^[\w.-]{1,80}$/.test(r.action))throw new h("invalid_input","Invalid plugin action request",{status:400});if(r.viewToken!==void 0&&(typeof r.viewToken!="string"||r.viewToken.length>200)||r.mountId!==void 0&&(typeof r.mountId!="string"||r.mountId.length>200))throw new h("invalid_input","Invalid view flush capability",{status:400});return s.action({sessionId:r.sessionId,pluginId:r.pluginId,generation:Number(r.generation),action:r.action,input:r.input??{},...typeof r.viewToken=="string"?{viewToken:r.viewToken}:{},...typeof r.mountId=="string"?{mountId:r.mountId}:{}},i?.draining?{checkpointOnly:!0}:void 0)}throw new h("invalid_route","Unknown hosted plugin route",{status:404})}function oi(s){let e=G(s);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as fn}from"node:fs/promises";import{join as gn}from"node:path";async function mn(s){try{let e=JSON.parse(await fn(gn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,i=await fn(gn(s,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let n of[...Object.values(e),{assets:Array.isArray(i)?i:[]}])if(!(!n||typeof n!="object"))for(let o of[n.file,...Array.isArray(n.css)?n.css:[],...Array.isArray(n.assets)?n.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let r={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(n=>[`/${n}`,{path:n,type:r[n.split(".").pop()]}]))}catch{return{}}}import{access as el,readFile as ir,realpath as li,rename as tl,rm as il,writeFile as rl}from"node:fs/promises";import{randomUUID as sl}from"node:crypto";import{dirname as ci,join as _e,resolve as nl,sep as yn}from"node:path";import{createRequire as ol}from"node:module";var Zc=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function Fe(s){let e=typeof s=="string"&&Zc.exec(s);if(!e||e[0]!==s)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),i=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||i.some(r=>/^\d+$/.test(r)&&r.length>1&&r[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:i}}function ue(s,e){let t=Fe(s),i=Fe(e);for(let r=0;r<3;r++)if(t.core[r]!==i.core[r])return t.core[r]>i.core[r]?1:-1;if(!t.prerelease.length||!i.prerelease.length)return+!t.prerelease.length-+!i.prerelease.length;for(let r=0;r<Math.max(t.prerelease.length,i.prerelease.length);r++){let n=t.prerelease[r],o=i.prerelease[r];if(n===void 0||o===void 0)return n===void 0?-1:1;if(n===o)continue;let c=/^\d+$/.test(n),a=/^\d+$/.test(o);return c!==a?c?-1:1:c&&n.length!==o.length?n.length>o.length?1:-1:n>o?1:-1}return 0}function wn(s){try{return Fe(s).prerelease.length===0}catch{return!1}}function ai(s){try{return Fe(s),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(s)}catch{return!1}}var Be=1,vn=s=>_e(s,"pi-web","desktop-update.json");async function dt(s,e){let t=ol(_e(s,"package.json"));for(let i of t.resolve.paths(e)??[]){let r=_e(i,e);try{if(JSON.parse(await ir(_e(r,"package.json"),"utf8")).name===e)return await li(r)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function di(s,e){if(ue(e?.version,e?.version),e.desktopProtocolVersion!==Be||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await li(nl(ci(e.launcher),"..")),i=await li(_e(s,"pi-web","releases")),r=ci(ci(t));if(await li(e.launcher)!==_e(t,"bin","pi-webapp.mjs")||ci(r)!==i||!r.startsWith(i+yn)||!r.slice(i.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(r.slice(i.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let n=JSON.parse(await ir(_e(t,"package.json"),"utf8"));if(n.name!=="pi-webapp"||n.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(n.piWebappDesktopProtocol!==Be)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await dt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(r+yn))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let c=_e(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,c,_e(t,"dist","extension.js"),_e(t,"web","dist","index.html")].map(a=>el(a))),e.fallbackVersion!==void 0&&Fe(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:Be,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}async function bn(s,e,t=e){try{let i=JSON.parse(await ir(vn(s),"utf8"));return ue(i.version,e)<0&&i.fallbackVersion!==t?null:await di(s,i)}catch{return null}}async function kn(s,e){let t=vn(s),i=`${t}.${sl()}.tmp`;try{await rl(i,JSON.stringify(e),{mode:384}),await tl(i,t)}finally{await il(i,{force:!0})}}var hl={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function I(s,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:s.getHeader("X-Request-ID"),operationId:s.getHeader("X-Operation-ID")}),s.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),s.end(JSON.stringify(t))}function fl(s,e){let t=s.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let i=Buffer.from(t.slice(7),"utf8");return i.length===e.length&&al(i,e)}async function In(s,e=64*1024){let t=0,i=[];for await(let r of s){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(t+=n.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");i.push(n)}return JSON.parse(Buffer.concat(i).toString("utf8"))}async function gl(s){let e=0,t=[];for await(let i of s){let r=Buffer.isBuffer(i)?i:Buffer.from(i);if(e+=r.length,e>ri)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(r)}return Buffer.concat(t)}async function ml(s,e=0){await new Promise((i,r)=>{s.once("error",r),s.listen(e,"127.0.0.1",()=>{s.off("error",r),i()})});let t=s.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function Sn(s,e,t=new xe,i={}){t.setState({piVersion:ul});let r=process.env.PI_WEBAPP_RESTART_TOKEN,n=r&&/^[A-Za-z0-9_-]{32}$/.test(r)?r:Pn(24).toString("base64url"),o=Buffer.from(n),c=Xs(),a=new Set,l=new ei(i.pluginSettingsFile??sr(pl(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new ti(Bs(),l),u=async()=>await s.plugins?.()??{plugins:[],errors:[]},y=()=>({type:"plugin_state",disabled:p.plugins.filter(b=>!l.enabled(b.metadata.id)).map(b=>b.metadata.id)}),m=()=>{for(let b of a)b.write(`${JSON.stringify(y())}
31
+ `)},f=new Map,w=new si((b,v)=>t.capture(b,v)),k=b=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(b.sessionId),idle:b.idle,model:b.model,thinkingLevel:b.thinkingLevel,messageCount:b.messages.length}),P="",E=!1,_=!1,H={...hl,...await mn(e)};for(let b of await ll(sr(e,"assets")).catch(()=>[])){let v=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(b);if(!v)continue;let $={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};H[`/assets/${b}`]={path:`assets/${b}`,type:$[v[1]]}}let N=dl(async(b,v)=>{let $=Pn(18).toString("base64"),ye=pe=>typeof pe=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(pe),ve=ye(b.headers["x-request-id"])?b.headers["x-request-id"]:rr(),se={requestId:ve,operationId:ye(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",ve),se.operationId&&v.setHeader("X-Operation-ID",se.operationId);let x="/",ca=performance.now(),de=(pe,g,S)=>{let C=!Ge(pe)&&Es(x)?Ne(pe,"Agent or provider operation failed"):pe,q=t.capture(C,{...se,route:x,method:b.method,status:g,stage:"http"});I(v,g,{error:S,errorId:q,errorReported:t.enabled,errorCode:Ge(pe)?"validation_error":"unexpected_error"})};v.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...se,route:x,method:b.method,status:v.statusCode,durationMs:Math.round(performance.now()-ca)})});try{v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${$}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${t.config.browser.dsn?` ${new URL(t.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{x=new URL(b.url??"/",P).pathname}catch{I(v,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let pe=H[x];if(b.method==="GET"&&pe){try{let g=await cl(sr(e,pe.path));v.writeHead(200,{"Content-Type":pe.type,"Cache-Control":"no-store"}),v.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${$}">`):g)}catch(g){de(g,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let g=await s.hosted?.asset(x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),v.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),v.end(g.bytes)}catch{I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(b.method==="GET"&&x.startsWith("/plugins/")){try{let g=await s.pluginAsset?.(b.url??x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),v.end(g.bytes)}catch(g){de(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(v,404,{error:"\u672A\u627E\u5230"});return}if(!fl(b,o)){I(v,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(b.method==="GET"&&x==="/api/hosted-plugins"){try{I(v,200,await tr(s.hosted,x,void 0))}catch(g){let S=oi(g);I(v,S.status,S.body)}return}if(b.method==="POST"&&hn.includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){I(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let g;try{g=await In(b,2*1024*1024)}catch(S){I(v,S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{I(v,200,await tr(s.hosted,x,g,{draining:E}))}catch(S){let A=oi(S);I(v,A.status,A.body)}return}if(b.method==="GET"&&x==="/api/telemetry/config"){I(v,200,t.config.browser);return}if(b.method==="GET"&&x==="/api/update/version"){try{I(v,200,{current:await s.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Be,...s.selfUpdate?.launcherIdentity?{launcher:s.selfUpdate.launcherIdentity(),desktopHandoffProtocol:s.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){de(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{I(v,200,await s.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){de(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/image"){let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId")??"",A=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==s.snapshot().sessionId||!A||!Number.isInteger(C)||C<0||C>100){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let q=s.image?.(S,A,C);if(!q||!["image/png","image/jpeg","image/webp","image/gif"].includes(q.mimeType)){I(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":q.mimeType,"Cache-Control":"private, no-store"}),v.end(q.data);return}if(b.method==="POST"&&x==="/api/attachment"){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId"),A=g.searchParams.get("name");try{if(!S||!A||A.length>1024||S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(b.headers["content-length"]??0)>ri){I(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await en(S,A,b.headers["content-type"]??"application/octet-stream",await gl(b));if(S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}f.set(C.id,C),I(v,201,{id:C.id,name:C.name,bytes:C.bytes})}catch(C){de(C,400,C instanceof Error?C.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/session"){try{let g=s.snapshot();k(g),I(v,200,g)}catch(g){de(g,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugin-management"){try{I(v,200,p.inventory(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugins"){try{I(v,200,p.catalog(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/providers"){try{I(v,200,await s.providers?.()??[])}catch(g){de(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/models"){let g=new URL(b.url??x,P).searchParams.get("providerId")??"";try{if(!g||!s.providerModels){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(v,200,await s.providerModels(g))}catch(S){de(S,400,S instanceof Error?S.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/login/active"){I(v,200,{active:w.getActive()??null});return}if(b.method==="GET"&&x==="/api/provider/login"){let g=new URL(b.url??x,P).searchParams.get("id")??"",S=w.get(g);I(v,S?200:404,S??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(b.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{I(v,200,x==="/api/models"?await s.models():x==="/api/config"?await s.config():x==="/api/commands"?s.commands?.()??[]:await s.workspaces())}catch(g){de(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/directory/capability"){I(v,200,{kind:c});return}if(b.method==="GET"&&x==="/api/events"){let g;try{g=s.snapshot(),k(g)}catch(S){de(S,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}v.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),a.add(v),v.write(`${JSON.stringify({type:"snapshot",session:g})}
32
+ `),v.on("close",()=>a.delete(v));return}if(b.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){I(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let g;try{g=await In(b,x==="/api/plugin-action"?544*1024:64*1024)}catch(S){if(S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){I(v,413,{error:S.message});return}if(S instanceof SyntaxError||Ge(S)){I(v,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw S}if(x==="/api/desktop/handoff"){let S=g;if(!S||typeof S.nonce!="string"||typeof S.requestId!="string"){I(v,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!s.selfUpdate?.requestLauncherHandoff){I(v,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(E||_||w.getActive()){I(v,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let A=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||A){I(v,409,{error:A??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}E=!0;try{await s.selfUpdate.requestLauncherHandoff(S.nonce,S.requestId)}catch(C){throw E=!1,C}I(v,202,{accepted:!0,protocol:1,requestId:S.requestId});return}if(typeof g!="object"||g===null||!("sessionId"in g)||typeof g.sessionId!="string"){I(v,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(E&&x!=="/api/update/cancel"){I(v,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(x==="/api/plugin-management"){let S=g;if(typeof S.id!="string"||S.id.length>200||typeof S.enabled!="boolean"||typeof S.expected!="string"){I(v,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let A=()=>{if(s.snapshot().sessionId!==g.sessionId)throw new Q("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length)throw new Q("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(S.id,S.enabled,S.expected,A),I(v,200,p.inventory(await u()))}catch(C){if(C instanceof Q)I(v,C.status,{error:C.message});else throw C}finally{m()}return}if(p.mutating&&x!=="/api/abort"){I(v,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:x,body:g,res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(S,A)=>I(v,S,A)}))return;if(x==="/api/plugin-interaction"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("requestId"in g)||typeof g.requestId!="string"||g.requestId.length>200||!s.resolvePluginInteraction||!("value"in g)){I(v,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(s.snapshot().cwd,async()=>s.resolvePluginInteraction(g.sessionId,g.pluginId,g.requestId,g.value)),I(v,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("action"in g)||typeof g.action!="string"||g.action.length>100){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(C=>C.metadata.id===g.pluginId)){let C=p.actionRoute(g.pluginId,g.action);if(!C){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let q="input"in g?g.input:{};if(!q||typeof q!="object"||Array.isArray(q)){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...q,sessionId:g.sessionId},res:v,snapshot:()=>s.snapshot(),busyWorkspaces:()=>s.busyGitWorkspaces?.()??[],json:(be,Jt)=>I(v,be,be>=200&&be<300?{value:Jt}:Jt)});return}if(!s.invokePluginAction){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let A=await p.coordinateStart(s.snapshot().cwd,async()=>s.invokePluginAction(g.sessionId,g.pluginId,g.action,"input"in g?g.input:void 0));I(v,200,{value:A});return}if(x==="/api/update/channel"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in g)||g.channel!=="stable"&&g.channel!=="alpha"){I(v,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!s.selfUpdate?.setChannel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}I(v,200,await s.selfUpdate.setChannel(g.channel));return}if(x==="/api/update/cancel"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.selfUpdate?.cancel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await s.selfUpdate.cancel(),I(v,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(_){I(v,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!s.snapshot().idle){I(v,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!s.selfUpdate){I(v,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let S=p.restartBlocker();if((s.busyGitWorkspaces?.()??[]).length||S){I(v,409,{error:S??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let A=g,C="channel"in A||"version"in A||"allowDowngrade"in A;if(C&&(A.channel!=="stable"&&A.channel!=="alpha"||typeof A.version!="string"||A.allowDowngrade!==void 0&&typeof A.allowDowngrade!="boolean")){I(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}_=!0;let q;try{q=await s.selfUpdate.prepare(C?{channel:A.channel,version:A.version,allowDowngrade:A.allowDowngrade}:void 0);let be=p.restartBlocker();if(!s.snapshot().idle||(s.busyGitWorkspaces?.()??[]).length||be)throw new Error(be??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");E=!0,await s.selfUpdate.requestRestart(q)}catch(be){throw E=!1,be}finally{_=!1}I(v,202,{accepted:!0,version:q.version});return}if(x==="/api/provider/custom"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in g)||!er(g.provider)||!s.addCustomProvider){I(v,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await s.addCustomProvider(g.sessionId,g.provider),I(v,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in g)||typeof g.providerId!="string"){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(x==="/api/provider/models"){if(!("change"in g)||!on(g.change)||!s.updateProviderModel){I(v,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await s.updateProviderModel(g.sessionId,g.providerId,g.change)}else{if(!s.logoutProvider){I(v,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await s.logoutProvider(g.sessionId,g.providerId)}I(v,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(x==="/api/provider/login"){if(!("providerId"in g)||typeof g.providerId!="string"||!("method"in g)||g.method!=="api_key"&&g.method!=="oauth"||!s.loginProvider||!s.providers){I(v,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await s.providers()).some(q=>q.id===g.providerId&&q.methods.includes(g.method))){I(v,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let A="initialSecret"in g?g.initialSecret:void 0;if(A!==void 0&&(g.method!=="api_key"||typeof A!="string"||!A.trim()||A.length>16384)){I(v,400,{error:"API Key \u65E0\u6548"});return}let C=w.start(g.providerId,g.method,s.loginProvider,A,se);I(v,202,{id:C.id});return}if(!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(x==="/api/provider/login/cancel"){I(v,w.cancel(g.id)?202:404,{accepted:!0});return}if(!("value"in g)||typeof g.value!="string"||g.value.length>16384||!w.respond(g.id,g.value)){I(v,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}I(v,202,{accepted:!0});return}if(x==="/api/attachment/remove"){if(!("id"in g)||typeof g.id!="string"||g.sessionId!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}f.get(g.id)?.sessionId===g.sessionId&&f.delete(g.id),I(v,202,{accepted:!0});return}if(x==="/api/directory/pick"){if(c!=="native"){I(v,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let S=new AbortController;v.once("close",()=>S.abort()),I(v,200,{path:await Ys(S.signal)});return}if(x==="/api/directory/list"){if("path"in g&&(typeof g.path!="string"||g.path.length>4096)){I(v,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}I(v,200,await Js("path"in g?g.path:void 0));return}if(x==="/api/directory/create"){if(!("path"in g)||typeof g.path!="string"||g.path.length>4096||!("name"in g)||typeof g.name!="string"||g.name.length>255){I(v,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}I(v,200,{path:await Ks(g.path,g.name)});return}if(x==="/api/workspace/add"){if(!("path"in g)||typeof g.path!="string"||g.path.length>4096||!("create"in g)||typeof g.create!="boolean"){I(v,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await s.addWorkspace(g.path,g.create),I(v,202,{accepted:!0});return}if(x==="/api/workspace/select"||x==="/api/workspace/remove"||x==="/api/workspace/new-session"){if(!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}x==="/api/workspace/select"?await s.selectWorkspace(g.id):x==="/api/workspace/new-session"?await s.newSessionInWorkspace(g.id):await s.removeWorkspace(g.id),I(v,202,{accepted:!0});return}if(x==="/api/session/select"){if(!("workspaceId"in g)||typeof g.workspaceId!="string"||!("id"in g)||typeof g.id!="string"||!("path"in g)||typeof g.path!="string"){I(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await s.selectSession(g.workspaceId,g.id,g.path),I(v,202,{accepted:!0});return}if(x==="/api/session/rename"||x==="/api/session/delete"){if(!("workspaceId"in g)||typeof g.workspaceId!="string"||!("id"in g)||typeof g.id!="string"||!("path"in g)||typeof g.path!="string"||g.path.length>4096){I(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(x==="/api/session/rename"){if(!("name"in g)||typeof g.name!="string"){I(v,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!s.renameSession){I(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await s.renameSession(g.workspaceId,g.id,g.path,g.name)}else{if(!s.deleteSession){I(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await s.deleteSession(g.workspaceId,g.id,g.path)}I(v,202,{accepted:!0});return}if(x==="/api/thinking-level"){if(!("level"in g)||typeof g.level!="string"){I(v,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await s.setThinkingLevel(g.sessionId,g.level)}else if(x==="/api/model"){if(!("provider"in g)||typeof g.provider!="string"||!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await s.setModel(g.sessionId,g.provider,g.id)}else if(x==="/api/config"){let S=g;if(!["packages","extensions","skills"].includes(S.kind)||!["global","project"].includes(S.scope)||!["add","remove"].includes(S.action)||typeof S.value!="string"||!S.value.trim()||S.value.length>2048){I(v,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(S.action==="add"&&S.kind!=="packages"&&pn(S.value)){I(v,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}I(v,200,await s.updateConfig(S));return}else if(x==="/api/prompt-queue"){let S=g,A=S.action;if(typeof S.id!="string"||S.id.length>100||!Number.isSafeInteger(S.revision)||S.revision<1||!A||typeof A!="object"||!["edit","remove","steer"].includes(A.kind)||A.kind==="edit"&&(typeof A.text!="string"||A.text.length>32e3)){I(v,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let C=s.snapshot();if(S.sessionId!==C.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(A.kind==="steer"&&C.idle){I(v,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(A.kind==="steer"&&C.interactions?.length){I(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!s.updateQueuedPrompt){I(v,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(C.cwd,async()=>s.updateQueuedPrompt(g.sessionId,S.id,S.revision,A))}else if(x==="/api/message"){let S="delivery"in g?g.delivery:void 0;if(S!==void 0&&S!=="steer"&&S!=="followUp"){I(v,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let A="attachments"in g?g.attachments:[];if(!Array.isArray(A)||A.length>Zs||A.some(oe=>typeof oe!="string")||new Set(A).size!==A.length){I(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=A.map(oe=>f.get(oe));if(C.some(oe=>!oe||oe.sessionId!==g.sessionId)){I(v,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in g)||typeof g.text!="string"||!g.text.trim()&&A.length===0||g.text.length>32e3){I(v,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let q=s.snapshot();if(g.sessionId!==q.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{We(q,g.text,S)}catch(oe){I(v,409,{error:oe.message});return}let be=C,Jt=[g.text.trim(),...be.map(oe=>`\u9644\u4EF6 ${JSON.stringify(oe.name)}\uFF1A${oe.path}`)].filter(Boolean).join(`
33
33
 
34
- `),oa=await Promise.all(ve.filter(se=>["image/png","image/jpeg","image/webp","image/gif"].includes(se.mediaType)).map(en));ie.operationId??=rr(),v.setHeader("X-Operation-ID",ie.operationId),t.breadcrumb("send",{...ie,attachmentCount:ve.length}),await p.coordinateStart(q.cwd,async()=>s.send(g.sessionId,Gt,oa,ie,S));for(let se of A)f.delete(se)}else if(x==="/api/compact"){if(!s.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await s.compact(g.sessionId)}else if(x==="/api/resume"){let S=s.snapshot();if(g.sessionId!==S.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!S.idle){I(v,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!S.paused){I(v,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(S.interactions?.length){I(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!s.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");ie.operationId??=rr(),v.setHeader("X-Operation-ID",ie.operationId),t.breadcrumb("resume",{...ie}),await p.coordinateStart(S.cwd,async()=>s.resume(g.sessionId,ie))}else x==="/api/abort"?await s.abort(g.sessionId):await s.newSession(g.sessionId);I(v,202,{accepted:!0})}catch(g){if(g instanceof ne){I(v,g.status,{error:g.message});return}let S=p.requestFailure(g);if(S){I(v,S.status,S.body);return}let A=g instanceof Error?g.message:"\u8BF7\u6C42\u5931\u8D25";de(g,A==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,A)}return}I(v,404,{error:"\u672A\u627E\u5230"})}catch(pe){v.headersSent?(t.capture(pe,{...ie,route:x,stage:"http_stream"}),v.end()):de(pe,500,"\u8BF7\u6C42\u5931\u8D25")}}),T=Number(process.env.PI_WEBAPP_RESTART_PORT),Y;try{Y=await hl(N,Number.isInteger(T)&&T>0&&T<65536&&r===n?T:0)}catch(b){throw t.capture(b,{stage:"listen"}),await t.close(),b}return k=`http://127.0.0.1:${Y}`,{protocolVersion:7,buildId:Se,runPluginTool:(b,v,$,we,ye)=>p.runAgentAction(b,v,$,we,ye),reportError(b,v){return t.capture(b,v)},breadcrumb(b,v){t.breadcrumb(b,v)},url:`${k}/#${n}`,publish(b){if(b.type==="snapshot"&&P(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[$,we]of f)we.sessionId!==b.session.sessionId&&f.delete($);let v=`${JSON.stringify(b)}
35
- `;for(let $ of a)$.write(v)},async close(b){y.close(),await p.close();for(let $ of a)$.end(`${JSON.stringify({type:"shutdown",reconnect:b?.reconnect??E})}
36
- `);a.clear();let v;try{await new Promise(($,we)=>{N.close(ye=>ye?we(ye):$()),v=setTimeout(()=>N.closeAllConnections(),50).unref()})}finally{clearTimeout(v),await t.close()}}}}import{getSupportedThinkingLevels as fl}from"@earendil-works/pi-ai";var Ct="pi-webapp/paused",nr="pi-webapp/resume";function dt(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="custom_message"&&t.customType===nr)return!1;if(t.type==="custom"&&t.customType===Ct)return!0;if(t.type==="message"){if(t.message.role==="user")return!1;if(t.message.role==="assistant"){if(t.message.stopReason==="aborted")return!0;if(t.message.stopReason==="stop"||t.message.stopReason==="length"||t.message.stopReason==="error")return!1}}}return!1}function or(s,e){let t=[],i;for(let r of s){if(r.type==="message"&&(i=r.id),r.type!=="custom")continue;let n=e.find(o=>r.customType.startsWith(`${o}/`));if(n){try{if(JSON.stringify(r.data).length>128*1024)continue}catch{continue}t.push({id:r.id,pluginId:n,kind:r.customType,data:r.data,timestamp:r.timestamp,...i?{afterMessageId:i}:{}})}}return t}function Je(s){return typeof s=="string"?[{kind:"text",text:s}]:s.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function di(s){if(s.type==="custom_message")return s.display?{id:s.id,role:"notice",timestamp:s.timestamp,blocks:Je(s.content)}:null;if(s.type!=="message")return null;let{message:e}=s;return e.role==="user"||e.role==="assistant"?{id:s.id,role:e.role,timestamp:s.timestamp,blocks:Je(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:s.id,role:"tool",timestamp:s.timestamp,blocks:Je(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function pi(s,e){let t=s?.trim();if(t)return t;let i=e.find(n=>n.role==="user"),r=Tt(i?.blocks.find(n=>n.kind==="text")?.text??"").text.replace(/\s+/g," ").trim();return r?r.slice(0,50):"\u5F53\u524D\u4F1A\u8BDD"}function Sn(s,e,t=[]){let i=s.sessionManager.getBranch().flatMap(r=>{let n=di(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?fl(s.model):["off"],idle:s.isIdle(),paused:dt(s.sessionManager.getBranch()),contextUsage:s.getContextUsage()??null,messages:i,pluginEntries:or(s.sessionManager.getBranch(),t)}}import{randomUUID as ar}from"node:crypto";import{mkdir as En,readFile as gl,realpath as cr,rename as ml,rm as wl,stat as lr,writeFile as yl}from"node:fs/promises";import{basename as xn,dirname as vl,isAbsolute as _n,join as bl}from"node:path";var Dt=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 pt(s){try{let e=await cr(s);return(await lr(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Ue(s){let e=await pt(s);if(e===null)throw new Dt;return e}var ui=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await gl(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(!_n(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await En(e,{recursive:!0});let i=await cr(e);if(!(await lr(i)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let r=this.hiddenPaths.filter(a=>a!==i),n=this.items.find(a=>a.path===i);if(n)return r.length!==this.hiddenPaths.length&&(await this.save(this.items,r),this.hiddenPaths=r),n;let o={id:ar(),path:i,title:xn(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(_n).map(async i=>{try{let r=await cr(i);return(await lr(r)).isDirectory()?r:null}catch{return null}}))).filter(i=>i!==null);await this.mutate(async()=>{let i=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),r=[];for(let o of t)i.has(o)||(i.add(o),r.push({id:ar(),path:o,title:xn(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 En(vl(this.file),{recursive:!0});let i=`${this.file}.${ar()}.tmp`;try{await yl(i,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await ml(i,this.file)}catch(r){throw await wl(i,{force:!0}),r}}};function An(s){return bl(s,"pi-web","workspaces.json")}import{createAgentSession as ld,createEventBus as dd,DefaultResourceLoader as pd,getAgentDir as ud,SessionManager as Ot,VERSION as mi}from"@earendil-works/pi-coding-agent";var kl="pi-webapp:interaction-open:v1",Pl="pi-webapp:interaction-accept:v1",Tn="pi-webapp:interaction-settle:v1",Il="pi-webapp:interaction-cancel:v1";var ut=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,i){this.bus=e,this.accepts=t,this.changed=i,this.detach=[e.on(kl,r=>{!Sl(r)||!t(r)||this.requests.has(r.requestId)||(this.requests.set(r.requestId,r),e.emit(Pl,{requestId:r.requestId}),i())}),e.on(Il,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(Tn,{requestId:i,value:r}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(Tn,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function Sl(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 Ke(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 Be(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&&Ke(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Ke(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Ke(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Ke(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 El=1,xl="pi-webapp:action:v1",_l="pi-webapp:action-response:v1",hi="pi-webapp:plugin-changed:v1";function Rn(s){if(!s||typeof s!="object")return!1;let e=s;return e.apiVersion===El&&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,w)=>{o||(o=!0,clearTimeout(l),a(),i?.removeEventListener("abort",p),u?n(u):r(w))},a=s.on(_l,u=>{let w=u;w?.requestId===e.requestId&&c(w.ok?null:new Error(w.error??"Plugin action failed"),w.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(xl,e)}catch(u){c(u instanceof Error?u:new Error(String(u)))}})}import{realpath as hd}from"node:fs/promises";import{readFile as dr,realpath as Hn,stat as On}from"node:fs/promises";import{createHash as Al}from"node:crypto";import{dirname as Cn,isAbsolute as Tl,join as pr,parse as Rl,resolve as Cl,sep as Dl,delimiter as Nl}from"node:path";import{DefaultPackageManager as Hl,getAgentDir as Ol,SettingsManager as Ml}from"@earendil-works/pi-coding-agent";async function Dn(s,e){let t=await dr(s),i=e?await dr(e):void 0;if(t.length>8*1024*1024||(i?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let r=Al("sha256").update(t).update("\0").update(i??"").digest("hex");return{clientBytes:t,styleBytes:i,revision:r}}function jl(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Nl).filter(Boolean).map(s=>Cl(s))}async function Wl(s){let e=Cn(s);for(;e!==Rl(e).root;)try{return await On(pr(e,"package.json")),e}catch{e=Cn(e)}return null}async function Nn(s,e){let t=await Hn(pr(s,e));if(!t.startsWith(s+Dl))throw new Error("Asset escapes package root");let i=await On(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 Xe=class s{plugins;errors;extensionRoots;constructor(e,t,i){this.plugins=e,this.errors=t,this.extensionRoots=i}static async discover(e,t,i=jl()){let r=Ml.create(e,void 0,{projectTrusted:t}),n=new Hl({cwd:e,agentDir:Ol(),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 Wl(m.path);f&&a.add(f)}for(let m of i)Tl(m)&&a.add(m);let l=[],p=[],u=[],w=new Set;for(let m of a)try{let f=await Hn(m),y=JSON.parse(await dr(pr(f,"package.json"),"utf8"));if(y.piWebapp===void 0)continue;if(typeof y.name!="string"||!y.name)throw new Error("Missing package name");if(!Rn(y.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(w.has(y.name))throw new Error(`Duplicate plugin id: ${y.name}`);let P=await Nn(f,y.piWebapp.client),k=y.piWebapp.style?await Nn(f,y.piWebapp.style):void 0;w.add(y.name),l.push({id:y.name,root:f,manifest:y.piWebapp,clientPath:P,stylePath:k,...await Dn(P,k)}),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 Dn(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 $l}from"node:fs/promises";import{SessionManager as Vl}from"@earendil-works/pi-coding-agent";async function Nt(s,e){let t=await Ue(s),i=e??await Vl.listAll(),r=await Promise.all(i.map(async n=>n.cwd!==""&&await $l(n.cwd).catch(()=>null)===t));return i.filter((n,o)=>r[o])}var Ye=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))}},Mn=new WeakMap;function jn(s,e,t,i=5e3,r=()=>{}){let n=Mn.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 Mn.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(`
34
+ `),la=await Promise.all(be.filter(oe=>["image/png","image/jpeg","image/webp","image/gif"].includes(oe.mediaType)).map(tn));se.operationId??=rr(),v.setHeader("X-Operation-ID",se.operationId),t.breadcrumb("send",{...se,attachmentCount:be.length}),await p.coordinateStart(q.cwd,async()=>s.send(g.sessionId,Jt,la,se,S));for(let oe of A)f.delete(oe)}else if(x==="/api/compact"){if(!s.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await s.compact(g.sessionId)}else if(x==="/api/resume"){let S=s.snapshot();if(g.sessionId!==S.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!S.idle){I(v,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!S.paused){I(v,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(S.interactions?.length){I(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!s.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");se.operationId??=rr(),v.setHeader("X-Operation-ID",se.operationId),t.breadcrumb("resume",{...se}),await p.coordinateStart(S.cwd,async()=>s.resume(g.sessionId,se))}else x==="/api/abort"?await s.abort(g.sessionId):await s.newSession(g.sessionId);I(v,202,{accepted:!0})}catch(g){if(g instanceof ae){I(v,g.status,{error:g.message});return}let S=p.requestFailure(g);if(S){I(v,S.status,S.body);return}let A=g instanceof Error?g.message:"\u8BF7\u6C42\u5931\u8D25";de(g,A==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,A)}return}I(v,404,{error:"\u672A\u627E\u5230"})}catch(pe){v.headersSent?(t.capture(pe,{...se,route:x,stage:"http_stream"}),v.end()):de(pe,500,"\u8BF7\u6C42\u5931\u8D25")}}),T=Number(process.env.PI_WEBAPP_RESTART_PORT),Y;try{Y=await ml(N,Number.isInteger(T)&&T>0&&T<65536&&r===n?T:0)}catch(b){throw t.capture(b,{stage:"listen"}),await t.close(),b}return P=`http://127.0.0.1:${Y}`,{protocolVersion:7,buildId:Se,runPluginTool:(b,v,$,ye,ve)=>p.runAgentAction(b,v,$,ye,ve),reportError(b,v){return t.capture(b,v)},breadcrumb(b,v){t.breadcrumb(b,v)},url:`${P}/#${n}`,publish(b){if(b.type==="snapshot"&&k(b.session),b.type==="error"&&!b.errorCode&&(b={...b,errorCode:"unexpected_error",errorId:t.capture(new Error("Agent execution failed"),{stage:"agent",requestId:b.requestId,operationId:b.operationId})}),b.type==="error"&&(b={...b,errorReported:b.errorReported??t.enabled}),b.type==="snapshot")for(let[$,ye]of f)ye.sessionId!==b.session.sessionId&&f.delete($);let v=`${JSON.stringify(b)}
35
+ `;for(let $ of a)$.write(v)},async close(b){w.close(),await p.close();for(let $ of a)$.end(`${JSON.stringify({type:"shutdown",reconnect:b?.reconnect??E})}
36
+ `);a.clear();let v;try{await new Promise(($,ye)=>{N.close(ve=>ve?ye(ve):$()),v=setTimeout(()=>N.closeAllConnections(),50).unref()})}finally{clearTimeout(v),await t.close()}}}}import{getSupportedThinkingLevels as wl}from"@earendil-works/pi-ai";var Dt="pi-webapp/paused",nr="pi-webapp/resume";function pt(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="custom_message"&&t.customType===nr)return!1;if(t.type==="custom"&&t.customType===Dt)return!0;if(t.type==="message"){if(t.message.role==="user")return!1;if(t.message.role==="assistant"){if(t.message.stopReason==="aborted")return!0;if(t.message.stopReason==="stop"||t.message.stopReason==="length"||t.message.stopReason==="error")return!1}}}return!1}function or(s,e){let t=[],i;for(let r of s){if(r.type==="message"&&(i=r.id),r.type!=="custom")continue;let n=e.find(o=>r.customType.startsWith(`${o}/`));if(n){try{if(JSON.stringify(r.data).length>128*1024)continue}catch{continue}t.push({id:r.id,pluginId:n,kind:r.customType,data:r.data,timestamp:r.timestamp,...i?{afterMessageId:i}:{}})}}return t}function Je(s){return typeof s=="string"?[{kind:"text",text:s}]:s.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function Nt(s){if(s.type==="custom_message")return s.display?{id:s.id,role:"notice",timestamp:s.timestamp,blocks:Je(s.content)}:null;if(s.type!=="message")return null;let{message:e}=s;return e.role==="user"||e.role==="assistant"?{id:s.id,role:e.role,timestamp:s.timestamp,blocks:Je(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:s.id,role:"tool",timestamp:s.timestamp,blocks:Je(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function pi(s,e){let t=s?.trim();if(t)return t;let i=e.find(n=>n.role==="user");return Rt(i?.blocks.find(n=>n.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function En(s,e,t=[]){let i=s.sessionManager.getBranch().flatMap(r=>{let n=Nt(r);return n?[n]:[]});return{schemaVersion:1,sessionId:s.sessionManager.getSessionId(),cwd:s.cwd,name:pi(e,i),model:s.model?`${s.model.provider}/${s.model.id}`:null,thinkingLevel:s.thinkingLevel??null,thinkingLevels:s.model?wl(s.model):["off"],idle:s.isIdle(),paused:pt(s.sessionManager.getBranch()),contextUsage:s.getContextUsage()??null,messages:i,pluginEntries:or(s.sessionManager.getBranch(),t)}}import{randomUUID as ar}from"node:crypto";import{mkdir as xn,readFile as yl,realpath as cr,rename as vl,rm as bl,stat as lr,writeFile as kl}from"node:fs/promises";import{basename as _n,dirname as Pl,isAbsolute as An,join as Il}from"node:path";var Ht=class extends Error{constructor(){super("\u5DE5\u4F5C\u533A\u76EE\u5F55\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6062\u590D\u76EE\u5F55\u6216\u4ECE\u5217\u8868\u79FB\u9664\u540E\u91CD\u65B0\u6DFB\u52A0")}};async function Ke(s){try{let e=await cr(s);return(await lr(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Ae(s){let e=await Ke(s);if(e===null)throw new Ht;return e}var ui=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await yl(this.file,"utf8")),t,i=[];if(Array.isArray(e)?t=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(t=e.items,i=e.hiddenPaths),!Array.isArray(t)||!Array.isArray(i))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=t.filter(r=>typeof r=="object"&&r!==null&&typeof r.id=="string"&&typeof r.path=="string"&&typeof r.title=="string"),this.hiddenPaths=i.filter(r=>typeof r=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(t=>t.id===e)}async add(e,t=!1){if(!An(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await xn(e,{recursive:!0});let i=await cr(e);if(!(await lr(i)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let r=this.hiddenPaths.filter(a=>a!==i),n=this.items.find(a=>a.path===i);if(n)return r.length!==this.hiddenPaths.length&&(await this.save(this.items,r),this.hiddenPaths=r),n;let o={id:ar(),path:i,title:_n(i)||i},c=[o,...this.items];return await this.save(c,r),this.items=c,this.hiddenPaths=r,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter(An).map(async i=>{try{let r=await cr(i);return(await lr(r)).isDirectory()?r:null}catch{return null}}))).filter(i=>i!==null);await this.mutate(async()=>{let i=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),r=[];for(let o of t)i.has(o)||(i.add(o),r.push({id:ar(),path:o,title:_n(o)||o}));if(r.length===0)return;let n=[...this.items,...r];await this.save(n,this.hiddenPaths),this.items=n})}async remove(e){await this.mutate(async()=>{let t=this.get(e);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let i=this.items.filter(n=>n.id!==e),r=[...new Set([...this.hiddenPaths,t.path])];await this.save(i,r),this.items=i,this.hiddenPaths=r})}mutate(e){let t=this.mutationChain.then(e,e);return this.mutationChain=t.then(()=>{},()=>{}),t}async save(e,t){await xn(Pl(this.file),{recursive:!0});let i=`${this.file}.${ar()}.tmp`;try{await kl(i,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await vl(i,this.file)}catch(r){throw await bl(i,{force:!0}),r}}};function Tn(s){return Il(s,"pi-web","workspaces.json")}import{createAgentSession as ud,createEventBus as hd,DefaultResourceLoader as fd,getAgentDir as gd,SessionManager as Mt,VERSION as mi}from"@earendil-works/pi-coding-agent";var Sl="pi-webapp:interaction-open:v1",El="pi-webapp:interaction-accept:v1",Rn="pi-webapp:interaction-settle:v1",xl="pi-webapp:interaction-cancel:v1";var ut=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,i){this.bus=e,this.accepts=t,this.changed=i,this.detach=[e.on(Sl,r=>{!_l(r)||!t(r)||this.requests.has(r.requestId)||(this.requests.set(r.requestId,r),e.emit(El,{requestId:r.requestId}),i())}),e.on(xl,r=>{let n=r,o=this.requests.get(n?.requestId);o&&o.sessionId===n.sessionId&&o.pluginId===n.pluginId&&(this.requests.delete(n.requestId),i())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,i,r){let n=this.requests.get(i);if(!n||n.sessionId!==e||n.pluginId!==t||!this.accepts(n))throw new Error("Interaction expired or session changed");this.requests.delete(i),this.bus.emit(Rn,{requestId:i,value:r}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(Rn,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function _l(s){if(!s||typeof s!="object")return!1;let e=s;for(let t of["requestId","sessionId","pluginId","kind"])if(typeof e[t]!="string"||!e[t]||e[t].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function Xe(s){return typeof s=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(s)&&s.length<=512&&!s.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function Ue(s){if(!s||typeof s!="object"||Array.isArray(s))return!1;let e=s;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&Xe(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Xe(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Xe(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Xe(e.resourcesManifest)&&/\.json$/.test(e.resourcesManifest)&&Number.isSafeInteger(e.dataSchemaVersion)&&e.dataSchemaVersion>0&&Array.isArray(e.supportedDataSchemas)&&e.supportedDataSchemas.length>0&&e.supportedDataSchemas.length<=32&&e.supportedDataSchemas.every(t=>Number.isSafeInteger(t)&&t>0)&&e.supportedDataSchemas.includes(e.dataSchemaVersion)&&Array.isArray(e.capabilities)&&e.capabilities.length<=64&&e.capabilities.every(t=>typeof t=="string"&&/^[a-z][a-z0-9.-]{0,79}$/.test(t))}var Al=1,Tl="pi-webapp:action:v1",Rl="pi-webapp:action-response:v1",hi="pi-webapp:plugin-changed:v1";function Cn(s){if(!s||typeof s!="object")return!1;let e=s;return e.apiVersion===Al&&typeof e.client=="string"&&/^\.\/dist\/[\w.-]+\.js$/.test(e.client)&&(e.style===void 0||typeof e.style=="string"&&/^\.\/dist\/[\w.-]+\.css$/.test(e.style))}function fi(s,e,t=15e3,i){return new Promise((r,n)=>{let o=!1,c=(u,y)=>{o||(o=!0,clearTimeout(l),a(),i?.removeEventListener("abort",p),u?n(u):r(y))},a=s.on(Rl,u=>{let y=u;y?.requestId===e.requestId&&c(y.ok?null:new Error(y.error??"Plugin action failed"),y.value)}),l=setTimeout(()=>c(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),t),p=()=>c(new Error("Plugin action runtime unloaded"));if(i?.addEventListener("abort",p,{once:!0}),i?.aborted)p();else try{s.emit(Tl,e)}catch(u){c(u instanceof Error?u:new Error(String(u)))}})}import{realpath as md}from"node:fs/promises";import{readFile as dr,realpath as On,stat as Mn}from"node:fs/promises";import{createHash as Cl}from"node:crypto";import{dirname as Dn,isAbsolute as Dl,join as pr,parse as Nl,resolve as Hl,sep as Ol,delimiter as Ml}from"node:path";import{DefaultPackageManager as jl,getAgentDir as Wl,SettingsManager as $l}from"@earendil-works/pi-coding-agent";async function Nn(s,e){let t=await dr(s),i=e?await dr(e):void 0;if(t.length>8*1024*1024||(i?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let r=Cl("sha256").update(t).update("\0").update(i??"").digest("hex");return{clientBytes:t,styleBytes:i,revision:r}}function Vl(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Ml).filter(Boolean).map(s=>Hl(s))}async function Fl(s){let e=Dn(s);for(;e!==Nl(e).root;)try{return await Mn(pr(e,"package.json")),e}catch{e=Dn(e)}return null}async function Hn(s,e){let t=await On(pr(s,e));if(!t.startsWith(s+Ol))throw new Error("Asset escapes package root");let i=await Mn(t);if(!i.isFile()||i.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return t}var Ye=class s{plugins;errors;extensionRoots;constructor(e,t,i){this.plugins=e,this.errors=t,this.extensionRoots=i}static async discover(e,t,i=Vl()){let r=$l.create(e,void 0,{projectTrusted:t}),n=new jl({cwd:e,agentDir:Wl(),settingsManager:r}),o=await n.resolve(async()=>"skip"),c=i.length?await n.resolveExtensionSources(i,{temporary:!0}):{extensions:[]},a=new Set;for(let m of[...o.extensions,...c.extensions]){if(!m.enabled)continue;let f=await Fl(m.path);f&&a.add(f)}for(let m of i)Dl(m)&&a.add(m);let l=[],p=[],u=[],y=new Set;for(let m of a)try{let f=await On(m),w=JSON.parse(await dr(pr(f,"package.json"),"utf8"));if(w.piWebapp===void 0)continue;if(typeof w.name!="string"||!w.name)throw new Error("Missing package name");if(!Cn(w.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(y.has(w.name))throw new Error(`Duplicate plugin id: ${w.name}`);let k=await Hn(f,w.piWebapp.client),P=w.piWebapp.style?await Hn(f,w.piWebapp.style):void 0;y.add(w.name),l.push({id:w.name,root:f,manifest:w.piWebapp,clientPath:k,stylePath:P,...await Nn(k,P)}),u.push(f)}catch(f){p.push(`${m}: ${f instanceof Error?f.message:String(f)}`)}return l.sort((m,f)=>m.id.localeCompare(f.id)),new s(l,p,u)}has(e){return this.plugins.some(t=>t.id===e)}ids(){return this.plugins.map(e=>e.id)}async refreshAssets(){for(let e of this.plugins)Object.assign(e,await Nn(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let t=new URL(e,"http://localhost"),i=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(t.pathname);if(!i)return null;let r;try{r=decodeURIComponent(i[1])}catch{return null}let n=this.plugins.find(c=>c.id===r);if(!n||t.searchParams.has("v")&&t.searchParams.get("v")!==n.revision)return null;let o=i[2]==="client.js"?n.clientBytes:n.styleBytes;return o?{bytes:o,type:i[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as Bl}from"node:fs/promises";import{SessionManager as Ul}from"@earendil-works/pi-coding-agent";async function ht(s,e){let t=await Ae(s),i=e??await Ul.listAll(),r=await Promise.all(i.map(async n=>n.cwd!==""&&await Bl(n.cwd).catch(()=>null)===t));return i.filter((n,o)=>r[o])}var Qe=class{tail=Promise.resolve();run(e){let t=this.tail.then(e);return this.tail=t.catch(()=>{}),t}wrap(e){return(...t)=>this.run(()=>e(...t))}},jn=new WeakMap;function Wn(s,e,t,i=5e3,r=()=>{}){let n=jn.get(s);if(n)return n;let o=(async()=>{let c;try{await Promise.race([s.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((a,l)=>{c=setTimeout(()=>l(new Error("Plugin shutdown timed out")),i)})])}catch(a){t(a instanceof Error?a.message:String(a))}finally{clearTimeout(c);try{r()}finally{s.dispose()}}})();return jn.set(s,o),o}function gi(s){let t=[...s].reverse().find(i=>i.role==="assistant")?.blocks.filter(i=>i.kind==="text").map(i=>i.text).join(`
37
37
  `);return{customType:nr,display:!1,details:{action:"resume"},content:"The user clicked Continue for the interrupted turn. Continue the response to the latest user request from the interrupted point. Preserve completed work and do not repeat text already delivered. Check existing task progress when needed."+(t?`
38
38
  Already displayed assistant text (reference data):
39
- ${JSON.stringify(t)}`:"")}}import{createHash as Fl}from"node:crypto";import{readFile as Ul,writeFile as Bl,unlink as Ll}from"node:fs/promises";import{basename as zl,dirname as ql,extname as Gl,join as Jl}from"node:path";import{DefaultPackageManager as Kl,getAgentDir as Xl,SettingsManager as Yl}from"@earendil-works/pi-coding-agent";var Ht=new Map;async function Wn(s,e){let i=await new Kl({cwd:s,agentDir:Xl(),settingsManager:Yl.create(s)}).resolveExtensionSources([...e],{temporary:!0}),r=[],n=[],o=async()=>{for(let c of r.splice(0)){let a=(Ht.get(c)??1)-1;a?Ht.set(c,a):(Ht.delete(c),await Ll(c).catch(()=>{}))}};try{for(let c of i.extensions){if(!c.enabled)continue;let a=Gl(c.path);if(![".js",".mjs"].includes(a)){n.push(c.path);continue}let l=await Ul(c.path),p=Fl("sha256").update(l).digest("hex"),u=Jl(ql(c.path),`.pi-web-runtime-${zl(c.path,a)}-${p}${a}`);await Bl(u,l,{flag:"wx"}).catch(w=>{if(w.code!=="EEXIST")throw w}),Ht.set(u,(Ht.get(u)??0)+1),r.push(u),n.push(u)}return{paths:n,release:o}}catch(c){throw await o(),c}}import{createHash as Ql}from"node:crypto";var ur={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},Le=s=>s!==null&&typeof s=="object"?s:void 0,Zl=[{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 Vn(s,e){let t=s instanceof Error?s:Le(s)?.error instanceof Error?Le(s).error:void 0,i={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},r=(p,u,w)=>{Object.assign(i,{failureKind:p,errorCode:u,errorSummary:w.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete i.summaryOmittedReason},n=Le(t)?.code;if(typeof n=="string"&&ur[n]){let p=ur[n];return r(p.kind,n,`${n}: ${p.summary}`),i}let o=t?.message??"";if(!t){let p=Le(s)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(u=>{let w=Le(u);return w?.type==="text"&&typeof w.text=="string"?[w.text.length>16384?`${w.text.slice(0,8192)}
39
+ ${JSON.stringify(t)}`:"")}}import{createHash as Ll}from"node:crypto";import{readFile as zl,writeFile as ql,unlink as Gl}from"node:fs/promises";import{basename as Jl,dirname as Kl,extname as Xl,join as Yl}from"node:path";import{DefaultPackageManager as Ql,getAgentDir as Zl,SettingsManager as ed}from"@earendil-works/pi-coding-agent";var Ot=new Map;async function $n(s,e){let i=await new Ql({cwd:s,agentDir:Zl(),settingsManager:ed.create(s)}).resolveExtensionSources([...e],{temporary:!0}),r=[],n=[],o=async()=>{for(let c of r.splice(0)){let a=(Ot.get(c)??1)-1;a?Ot.set(c,a):(Ot.delete(c),await Gl(c).catch(()=>{}))}};try{for(let c of i.extensions){if(!c.enabled)continue;let a=Xl(c.path);if(![".js",".mjs"].includes(a)){n.push(c.path);continue}let l=await zl(c.path),p=Ll("sha256").update(l).digest("hex"),u=Yl(Kl(c.path),`.pi-web-runtime-${Jl(c.path,a)}-${p}${a}`);await ql(u,l,{flag:"wx"}).catch(y=>{if(y.code!=="EEXIST")throw y}),Ot.set(u,(Ot.get(u)??0)+1),r.push(u),n.push(u)}return{paths:n,release:o}}catch(c){throw await o(),c}}import{createHash as td}from"node:crypto";var ur={ENOENT:{kind:"not_found",summary:"no such file or directory"},ENOTDIR:{kind:"not_found",summary:"not a directory"},EACCES:{kind:"permission",summary:"permission denied"},EPERM:{kind:"permission",summary:"operation not permitted"},ETIMEDOUT:{kind:"timeout",summary:"operation timed out"},EINVAL:{kind:"validation",summary:"invalid argument"}},Le=s=>s!==null&&typeof s=="object"?s:void 0,id=[{pattern:/^Could not find (?:the exact text in [^\r\n]+\. The old text|edits\[\d+\] in [^\r\n]+\. The oldText) must match exactly including all whitespace and newlines\.$/,code:"edit_text_not_found",summary:"Edit text does not match the file"},{pattern:/^Found \d+ occurrences of (?:the text in [^\r\n]+\. The text|edits\[\d+\] in [^\r\n]+\. Each oldText) must be unique\. Please provide more context to make it unique\.$/,code:"edit_text_ambiguous",summary:"Edit text matches multiple locations"},{pattern:/^(?:edits\[\d+\]\.)?oldText must not be empty in [^\r\n]+\.$/,code:"invalid_arguments",summary:"Edit oldText must not be empty"},{pattern:/^No changes made to [^\r\n]+\. (?:The replacement produced identical content\. This might indicate an issue with special characters or the text not existing as expected\.|The replacements produced identical content\.)$/,code:"edit_no_change",summary:"Edit replacement produced no changes"},{pattern:/^edits\[\d+\] and edits\[\d+\] overlap in [^\r\n]+\. Merge them into one edit or target disjoint regions\.$/,code:"edit_overlap",summary:"Edit replacements overlap"}];function Fn(s,e){let t=s instanceof Error?s:Le(s)?.error instanceof Error?Le(s).error:void 0,i={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},r=(p,u,y)=>{Object.assign(i,{failureKind:p,errorCode:u,errorSummary:y.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete i.summaryOmittedReason},n=Le(t)?.code;if(typeof n=="string"&&ur[n]){let p=ur[n];return r(p.kind,n,`${n}: ${p.summary}`),i}let o=t?.message??"";if(!t){let p=Le(s)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(u=>{let y=Le(u);return y?.type==="text"&&typeof y.text=="string"?[y.text.length>16384?`${y.text.slice(0,8192)}
40
40
  [truncated]
41
- ${w.text.slice(-8192)}`:w.text]:[]}).join(`
41
+ ${y.text.slice(-8192)}`:y.text]:[]}).join(`
42
42
  `))}let c=e==="bash"||e==="powershell",a=o.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(c){let p=a.match(/^Command exited with code (-?\d{1,10})$/),u=a.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return r("process_exit","nonzero_exit",a),i.exitCode=Number(p[1]),i;if(u&&Number.isFinite(Number(u[1]))&&Number(u[1])>0)return r("timeout","timeout",a),i.timeoutMs=Number(u[1])*1e3,i;if(a==="Command aborted")return r("cancelled","cancelled",a),i}let l=o.slice(0,8192).split(/\r?\n/,1)[0]??"";if(o==="Operation aborted"||t?.name==="AbortError")r("cancelled","cancelled","Operation aborted");else if(o==="Tool execution was blocked")r("blocked","blocked",o);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(o))r("not_found","ENOENT","Working directory does not exist");else if(!c||!o.includes(`
43
- `)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=ur[p[1]],w=l.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);r(u.kind,p[1],`${p[1]}: ${u.summary}${w?`; operation=${w[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))r("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(l)||l==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(l))r("validation","invalid_arguments",l.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(o))r("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=Zl.find(w=>w.pattern.test(o));u&&r("validation",u.code,u.summary)}}return i}var ed=256;function $n(s,e,t){s.delete(e),s.set(e,t),s.size>ed&&s.delete(s.keys().next().value)}var ht=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:Yt.has(e.toolName)?e.toolName:"custom",...Yt.has(e.toolName)?{}:{toolId:Ql("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,t){try{this.options.breadcrumb(e,t)}catch{}}start(e,t={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let i=e.toolName==="bash"||e.toolName==="powershell"?Le(e.args)?.timeout:void 0,r=typeof i=="number"&&i>0&&Number.isFinite(i*1e3)?i*1e3:void 0,n={...Ie(t),...this.identity(e),stage:"tool"};$n(this.pending,e.toolCallId,{context:n,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:r}),this.breadcrumb("tool_start",n)}catch{}}end(e,t={}){this.finish(e,t,"tool_execution_end")}message(e,t={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},t,"message_end")}catch{}}finish(e,t,i){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let r=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),$n(this.completed,e.toolCallId,!0);let n={...r?.context??{...Ie(t),...this.identity(e),stage:"tool"},diagnosticSource:i};if(r&&(n.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-r.started)),r.timeoutMs!==void 0&&(n.timeoutMs=r.timeoutMs)),!e.isError){this.breadcrumb("tool_end",n);return}let o=e.result instanceof Error?e.result:Le(e.result)?.error instanceof Error?Le(e.result).error:void 0,c=r?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:Vn(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=Fn(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 Fn(s,e,t=0){let i=Vn(s,e),r=new Error(i.errorSummary??"Tool exception (diagnostic text unavailable)");return r.name=s.name,r.stack=s.stack?`${r.name}: ${r.message}
43
+ `)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=ur[p[1]],y=l.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);r(u.kind,p[1],`${p[1]}: ${u.summary}${y?`; operation=${y[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))r("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(l)||l==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(l))r("validation","invalid_arguments",l.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(o))r("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=id.find(y=>y.pattern.test(o));u&&r("validation",u.code,u.summary)}}return i}var rd=256;function Vn(s,e,t){s.delete(e),s.set(e,t),s.size>rd&&s.delete(s.keys().next().value)}var ft=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:Qt.has(e.toolName)?e.toolName:"custom",...Qt.has(e.toolName)?{}:{toolId:td("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,t){try{this.options.breadcrumb(e,t)}catch{}}start(e,t={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let i=e.toolName==="bash"||e.toolName==="powershell"?Le(e.args)?.timeout:void 0,r=typeof i=="number"&&i>0&&Number.isFinite(i*1e3)?i*1e3:void 0,n={...Ie(t),...this.identity(e),stage:"tool"};Vn(this.pending,e.toolCallId,{context:n,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:r}),this.breadcrumb("tool_start",n)}catch{}}end(e,t={}){this.finish(e,t,"tool_execution_end")}message(e,t={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},t,"message_end")}catch{}}finish(e,t,i){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let r=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),Vn(this.completed,e.toolCallId,!0);let n={...r?.context??{...Ie(t),...this.identity(e),stage:"tool"},diagnosticSource:i};if(r&&(n.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-r.started)),r.timeoutMs!==void 0&&(n.timeoutMs=r.timeoutMs)),!e.isError){this.breadcrumb("tool_end",n);return}let o=e.result instanceof Error?e.result:Le(e.result)?.error instanceof Error?Le(e.result).error:void 0,c=r?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:Fn(e.result,e.toolName);if(Object.assign(n,c,{code:"tool_failed"}),this.breadcrumb(c.failureKind==="cancelled"?"tool_cancelled":c.failureKind==="blocked"?"tool_blocked":"tool_failed",n),c.failureKind==="cancelled"||c.failureKind==="blocked")return;let a;o?a=Bn(o,e.toolName):(a=new Error(`${n.toolName}: ${c.failureKind} (${c.errorCode??"unknown"})`),a.name="ToolResultFailure",a.stack=void 0),this.options.capture(a,n)}catch{}}cancel(){try{if(!this.enabled())return;for(let e of this.pending.values())e.cancelled=!0}catch{}}clear(){this.pending.clear(),this.completed.clear()}};function Bn(s,e,t=0){let i=Fn(s,e),r=new Error(i.errorSummary??"Tool exception (diagnostic text unavailable)");return r.name=s.name,r.stack=s.stack?`${r.name}: ${r.message}
44
44
  ${s.stack.split(`
45
45
  `).slice(1).join(`
46
- `)}`:void 0,t<3&&s.cause instanceof Error&&(r.cause=Fn(s.cause,e,t+1)),ct(r)}import{randomUUID as Ln}from"node:crypto";import{randomUUID as td}from"node:crypto";import{EnvHttpProxyAgent as id,getGlobalDispatcher as Hm,setGlobalDispatcher as Om}from"undici";var Un=s=>({httpProxy:s.http_proxy??s.HTTP_PROXY??s.all_proxy??s.ALL_PROXY??"",httpsProxy:s.https_proxy??s.HTTPS_PROXY??s.all_proxy??s.ALL_PROXY??"",noProxy:s.no_proxy??s.NO_PROXY??""});function rd(s,e){let t=Un(s),i;try{i=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(i.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let r=t.noProxy.toLowerCase();if(r==="*")return!1;let n=Number(i.port)||(i.protocol==="https:"?443:80),o=i.hostname.toLowerCase();return!r.split(/[,\s]/).filter(Boolean).some(c=>{let a=c.match(/^(.+):(\d+)$/),l=(a?.[1]??c).replace(/^\*?\./,"");return(!a||Number(a[2])===n)&&(o===l||o.endsWith("."+l))})}function sd(s){let e=Un(s);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new id(e)}function hr({env:s=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:i=!1}={}){let r,n=new Set,o=t===globalThis.fetch,c=(p,u)=>{try{e(p,u)}catch{}},a=p=>p?p.close().finally(()=>n.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let w={requestId:td(),phase:"headers",proxied:o&&rd(s,p)},m=i?void 0:r,f=!1,y=u?.signal??(p instanceof Request?p.signal:void 0),P=()=>k(),k=()=>{y?.removeEventListener("abort",P),!f&&i&&(f=!0,a(m).catch(()=>{}))},E;try{o?(m??=sd(s),n.add(m),i||(r=m),E=await t(p,{...u,dispatcher:m})):E=await t(p,u)}catch(T){throw c(T,w),k(),T}if(E.ok||c(void 0,{...w,status:E.status}),!E.body)return k(),E;let _=E.body.getReader();y?.addEventListener("abort",P,{once:!0}),y?.aborted&&k();let H=new ReadableStream({async pull(T){try{let Y=await _.read();Y.done?(T.close(),_.releaseLock(),k()):T.enqueue(Y.value)}catch(Y){c(Y,{...w,phase:"body"}),T.error(Y),_.releaseLock(),k()}},async cancel(T){try{await _.cancel(T)}finally{_.releaseLock(),k()}}}),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 Bn=(s,e)=>hr({autoClose:!0}).fetch(s,e);var nd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),od=s=>typeof s=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(s)?s:void 0;function fr(s,e={}){let t=[],i=new Set,r=(a,l=0)=>{if(!a||l>4||i.has(a)||t.length>=8)return;i.add(a);let p=od(a.code);if(t.push({name:nd.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:Ln(),requestId:c(e.requestId)??Ln(),...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 zn({env:s=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return hr({env:s,fetchRequest:t,onFailure:(i,r)=>e(fr(i,{...r,stage:r.phase==="body"?"model_stream":"model_headers"}))})}function ad(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 cd=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function qn(s,e,t=()=>{}){let i=s.agent.streamFunction;s.agent.streamFunction=async(r,n,o)=>{if(!cd.has(r.api))return i(r,n,o);let c=t(),a=zn({env:ad(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 ft(s,e,t){try{s()}catch(i){let r=fr(i,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...r})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:r.errorId,requestId:r.requestId,stage:r.stage,code:"hosted_admission_blocked",networkKind:r.kind,networkStage:r.stage,causeCodes:r.causes.flatMap(n=>n.code?[n.code]:[]).join(",")})}catch{}throw i}}var fd=["read","grep","find","ls"],Gn=200,wi=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Ye;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 Ue(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=Ot.create(i);else if(t==="continue"){let c=(await Nt(i))[0];n=c?Ot.open(c.path):Ot.create(i)}else n="sessionManager"in t?t.sessionManager:Ot.open(t.sessionFile);if(await hd(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")})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(({session:e,cwd:t,prompts:i})=>{let r=e.sessionManager.getBranch(),n=r.flatMap(o=>{let c=di(o);return c?[c]:[]});return{sessionId:e.sessionManager.getSessionId(),cwd:t,path:e.sessionManager.getSessionFile()??null,idle:e.isIdle&&!i.sending,name:pi(e.sessionManager.getSessionName(),n),modified:r.at(-1)?.timestamp??new Date().toISOString()}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,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 Xe.discover(e,this.isProjectTrusted(e)),c=dd(),a=await Wn(e,o.extensionRoots),l=new pd({cwd:e,agentDir:ud(),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 w=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:m}=await ld({cwd:e,sessionManager:t,model:w,resourceLoader:l,customTools:this.customTools}),f=new ht({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(b,v)=>this.telemetry.breadcrumb(b,v),anonymize:b=>this.telemetry.anonymize(b)}),y={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};y.prompts=n?.prompts??new We(()=>{let b=this.runtimes.get(t.getSessionId())??y;this.publishFor(b,{type:"snapshot",session:this.snapshotOf(b)}),!this.disposed&&!b.closing&&this.onSessionsChanged()}),p=y,qn(m,b=>{y.networkDiagnostic=b},()=>y.operation?.operationId);let P=b=>this.publishFor(y,b),k=y.detached,E=(b,v)=>{k&&(k.events.push({seq:++k.seq,type:b,...v===void 0?{}:{text:v}}),k.events.length>Gn&&k.events.splice(0,k.events.length-Gn))};y.interactions=new ut(c,b=>!y.closing&&b.sessionId===m.sessionManager.getSessionId()&&o.has(b.pluginId),()=>P({type:"snapshot",session:this.snapshotOf(y)}));let _=0,H=c.on(hi,()=>P({type:"snapshot",session:this.snapshotOf(y)})),N=m.subscribe(b=>{if(k&&!y.closing&&(b.type==="message_end"&&b.message.role==="assistant"&&(b.message.stopReason==="error"?E("error",b.message.errorMessage??"Agent response failed"):k.lastText=b.message.content.flatMap(v=>v.type==="text"?[v.text]:[]).join(`
47
- `)),b.type==="agent_settled"&&E("turn_end",k.lastText)),!this.disposed&&!y.closing){let v={...y.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"){y.agentErrorReported=!0;let $=y.networkDiagnostic,we=this.reportError(new Error("Agent response failed"),{...y.operation,stage:"agent",code:"agent_failed",piVersion:mi,...$?{networkKind:$.kind,networkStage:$.stage,causeCodes:$.causes.flatMap(ye=>ye.code?[ye.code]:[]).join(","),requestId:$.requestId}:{}})??$?.errorId;P({type:"error",message:b.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:we,...y.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(),y.operation=void 0)}b.type==="message_update"&&b.message.role==="assistant"&&(y.streaming={id:"stream",role:"assistant",timestamp:new Date(b.message.timestamp).toISOString(),blocks:Je(b.message.content)},Date.now()-_>=60&&(_=Date.now(),P({type:"stream",message:y.streaming}))),b.type==="agent_settled"&&this.scheduleQueued(y),["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")&&(y.streaming=null,P({type:"stream",message:null})),P({type:"snapshot",session:this.snapshotOf(y)}),!this.disposed&&!y.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(b.type)&&this.onSessionsChanged())});y.detach=()=>{H(),N()},y.releaseHosted=this.hosted?.adapter.attach(m);let T=[],Y=!0;if(await m.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Y&&T.push(b.error),this.diagnostic(y,o.plugins.find(v=>b.extensionPath.startsWith(v.root+"/"))?.id??b.extensionPath,b.event??"runtime",b.error)}}),Y=!1,T.length)throw new Error(T.join("; "));if(this.ensureAvailable(),n&&(!n.session.isIdle||n.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(n&&await this.close(n,i),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");y.detached&&(y.detached.restoreTools=m.getActiveToolNames(),m.setActiveToolsByName(fd)),this.runtimes.set(m.sessionManager.getSessionId(),y),p=null,y.detached?this.onSessionsChanged():this.activate(y)}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 jn(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=di(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:dt(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:n,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:or(t.sessionManager.getBranch(),r.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let i=t.session.extensionRunner,r=await fi(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||i!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),r}resolveInteraction(e,t,i,r){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,i,r)}async send(e,t=[],i,r){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let n=this.active;if(je(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 ne("\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");ft(()=>this.hosted?.adapter.assertAdmission(),r,this.reportError),je({...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((w,m)=>{l=w,p=m});o.prompt(t,{images:i,streamingBehavior:n,preflightResult:w=>{w&&(a=!0,l())}}).then(()=>{a||l()}).catch(w=>{if(!a)p(w);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let m=this.reportError(De(w,"Agent response failed"),{...r,stage:"agent",code:"agent_failed",piVersion:mi});this.publishFor(e,{type:"error",message:w instanceof Error?w.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:m,...r})}});try{await u}catch(w){throw c&&(e.operation=void 0),w}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!dt(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 ne("\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(Ct),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");ft(()=>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(!dt(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(!dt(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(De(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 Ue(e),n=Ot.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{basename as gr,dirname as gd}from"node:path";function Jn(s,e){let t=i=>e[i].map(r=>({name:i==="skills"&&gr(r.path).toLowerCase()==="skill.md"?gr(gd(r.path)):gr(r.path),path:r.path,source:r.metadata.source,scope:r.metadata.scope,enabled:r.enabled}));return{packages:s.map(i=>({name:i.source,path:i.installedPath??"",source:i.source,scope:i.scope,enabled:!!i.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as md}from"node:child_process";var wd=(s,e)=>new Promise((t,i)=>{md(s,[...e],{windowsHide:!0},r=>{r?i(r):t()})});async function mr(s,e=process.platform,t=process.env,i=wd){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 Jd}from"node:child_process";import{randomUUID as bi}from"node:crypto";import{existsSync as uo}from"node:fs";import{access as xr,mkdir as ki,mkdtemp as Kd,readFile as ge,realpath as Xd,rename as _r,rm as Wt,writeFile as Pi}from"node:fs/promises";import{dirname as ho,join as M}from"node:path";import{createHash as vr,randomUUID as Ed}from"node:crypto";import{mkdir as xd,readFile as _d,readdir as Ad,realpath as eo}from"node:fs/promises";import{join as Te}from"node:path";import{constants as wr}from"node:fs";import{DatabaseSync as yd}from"node:sqlite";import{lstat as Yn,mkdir as vd,open as Mt,rename as bd,unlink as Qn}from"node:fs/promises";import{dirname as kd,join as Kn,resolve as Pd}from"node:path";import{randomUUID as Id}from"node:crypto";import{setTimeout as Sd}from"node:timers/promises";async function Z(s){await vd(s,{recursive:!0,mode:448});let e=await Yn(s);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function X(s,e){let t;try{t=await Mt(s,wr.O_RDONLY|wr.O_NONBLOCK|(wr.O_NOFOLLOW??0))}catch(i){if($e(i))return null;throw i}try{let i=await t.stat();if(!i.isFile()||i.nlink>1||i.size>e)throw new h("invalid_storage","Invalid storage record size or type");let r=Buffer.alloc(Math.min(i.size+1,e+1)),n=0;for(;n<r.length;){let o=await t.read(r,n,r.length-n,n);if(!o.bytesRead)break;n+=o.bytesRead}if(n>e||n!==i.size)throw new h("invalid_storage","Storage record changed during read");return r.subarray(0,n)}finally{await t.close()}}async function ee(s,e=2*1024*1024){let t=await X(s,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new h("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function oe(s){let e=await X(s,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new h("gc_recovery_required",`Invalid journal ${s}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new h("gc_recovery_required",`Invalid journal ${s}; original bytes preserved`);return t}async function j(s,e){let t=`${s}.${Id()}.tmp`,i=await Mt(t,"wx",384);try{try{await i.writeFile(JSON.stringify(e)),await i.sync()}finally{await i.close()}await bd(t,s);let r;try{r=await Mt(kd(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 Qn(t).catch(()=>{})}}var Zn='{"version":2,"mechanism":"sqlite-exclusive"}',Xn=s=>s.toString("utf8")===Zn,yi=new Set;async function yr(s,e,t=0){await Z(s);let i=Kn(s,`${e}.lock`),r=Kn(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 Mt(r,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await Yn(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 yd(r,{allowExtension:!1}),p=Pd(r),u=Date.now()+t,w=!1;try{for(;;){if(!yi.has(p))try{l.exec("BEGIN EXCLUSIVE"),yi.add(p),w=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=u)throw new h(n,"Another host owns this plugin storage; wait for it to stop before retrying");await Sd(10)}let f=await X(i,4096);if(f===null){let y;try{y=await Mt(i,"wx",384),await y.writeFile(Zn),await y.sync()}catch(P){if(P.code!=="EEXIST")throw P}finally{await y?.close()}f=await X(i,4096)}if(f===null||!Xn(f))throw o()}catch(f){throw l.close(),w&&yi.delete(p),f}let m=!1;return async()=>{if(m)return;let f=await X(i,4096);if(f===null||!Xn(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Qn(i),l.close(),yi.delete(p),m=!0}}async function W(s,e,t=2e3){let i=await yr(s,"transaction",t);try{return await e()}finally{await i()}}var Ee=s=>Te(s,"host-pair"),te=s=>vr("sha256").update(JSON.stringify(s)).digest("hex");async function Td(s){let e=vr("sha256"),t=0,i=0;async function r(n){let o=(await Ad(Te(s,n),{withFileTypes:!0})).sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(let c of o){if(!n&&c.name==="node_modules")continue;let a=n?`${n}/${c.name}`:c.name;if(c.isSymbolicLink()||!c.isFile()&&!c.isDirectory())throw new h("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new h("host_pair_required","Candidate package resource budget exceeded");if(c.isDirectory()){await r(a);continue}let l=await X(Te(s,a),64*1024*1024);if(!l||(i+=l.length)>256*1024*1024)throw new h("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,vr("sha256").update(l).digest("hex")]))}}return await r(""),e.digest("hex")}async function Qe(s,e){let t=await eo(e),i=Te(e,"dist","hosted-worker.js");if(await eo(i)!==Te(t,"dist","hosted-worker.js"))throw new h("host_pair_required","Candidate worker must remain inside the staged host");let r=await X(Te(e,"package.json"),512*1024);if(!r)throw new h("host_pair_required","Candidate package metadata missing");let n=JSON.parse(r.toString("utf8")),o=n.piWebappHostedRuntime;if(n.name!=="pi-webapp"||n.version!==s||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(a=>o.capabilities.includes(a)))throw new h("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let c=await X(i,32*1024*1024);if(!c)throw new h("host_pair_required","Candidate worker missing");return te([r.toString("base64"),c.toString("base64"),await Td(e)])}async function He(s){let e=await oe(Te(Ee(s),"intent.json"));if(e&&(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||typeof e.packageRoot!="string"||!/^[a-f0-9]{64}$/.test(e.hostDigest)||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!Array.isArray(e.selections)||e.selections.some(t=>!t||typeof t.id!="string"||typeof t.version!="string"||!/^[a-f0-9]{64}$/.test(t.digest)||!Object.hasOwn(t,"before"))||e.selection&&(typeof e.selection.path!="string"||!/^[a-f0-9]{64}$/.test(e.selection.digest))||!["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(e.phase)))throw new h("host_pair_required","Invalid host pair journal; preserve data and inspect intent.json with all owners stopped");if(e){let{lifecyclePhase:t,...i}=e;e={...i,phase:i.phase==="selected"&&t==="restart-requested"?"restart-requested":i.phase==="reconciled"&&t==="cancelled"?"cancelled":i.phase}}return e}async function Ae(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(Te(Ee(s),"intent.json"),r)}var gt=s=>s&&!["prepared","reconciled","cancelled"].includes(s.phase);async function jt(s){let e=await He(s);if(e&&gt(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 to(s,e,t,i=async()=>{}){let r=async o=>{let c=Te(Ee(s),"history");await xd(c,{recursive:!0,mode:448}),await j(Te(c,`${o.id}.json`),o)},n=async(o,c,a)=>{let l=await Qe(o,c),p=te(await t()),u=await e(o,a);if(a?.throwIfAborted(),te(await t())!==p)throw new h("host_pair_changed","Plugin policy/activation changed during preflight; recheck update");return await i(o,u),{schema:1,id:Ed(),phase:"prepared",version:o,packageRoot:c,hostDigest:l,fingerprint:p,selections:u}};return{status:()=>He(s),stage:(o,c,a)=>W(Ee(s),async()=>{await jt(s);let l=await He(s);l&&await r(l.phase==="prepared"?{...l,phase:"cancelled",message:"Superseded before version selection; no code or data changed"}:l),await Ae(s,await n(o,c,a))}),cancel:(o,c,a)=>W(Ee(s),async()=>{let l=await He(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(gt(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 Ae(s,p),await r(p)}),select:(o,c,a)=>W(Ee(s),async()=>{await jt(s);let l=await He(s),p=l?.phase==="prepared"&&l.version===o&&l.packageRoot===c&&l.fingerprint===te(await t())?l:await n(o,c),{hostDigest:u,selections:w}=p,m=p.fingerprint;if(await Ae(s,p),await i(o,w),await Qe(o,c)!==u||te(await t())!==m)throw await Ae(s,{...p,phase:"required-action",message:"Preflight changed; host pointer not written"}),new h("host_pair_changed","Preflight changed; host pointer not written");await Ae(s,{...p,phase:"selecting"});let f=await a();await Ae(s,{...p,phase:"selected",...f?{selection:f}:{}})}),restart:(o,c,a)=>W(Ee(s),async()=>{let l=await He(s);if(!l||l.phase!=="selected"||l.version!==o||l.packageRoot!==c||l.hostDigest!==await Qe(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed; restart refused, inspect pair journal");if(l.selection&&te((await _d(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 Qe(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed during restart validation");await Ae(s,{...l,phase:"restart-requested",message:"Restart authorized; awaiting launcher receipt and selected host health admission"}),await a()})}}import{promisify as Yd}from"node:util";import{realpathSync as so,statSync as Rd}from"node:fs";import{basename as Cd,delimiter as Dd,dirname as io,join as br,resolve as Nd}from"node:path";function ro(s){if(!s)return null;try{let e=so(s);return Cd(e)==="npm-cli.js"&&Rd(e).isFile()?e:null}catch{return null}}function Hd({execPath:s=process.execPath,env:e=process.env}={}){let t=ro(e.npm_execpath);if(t)return t;let i=new Set([io(s)]);try{i.add(io(so(s)))}catch{}let r=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of r.split(Dd).filter(Boolean))i.add(Nd(n));for(let n of i)for(let o of[br(n,"node_modules","npm","bin","npm-cli.js"),br(n,"..","lib","node_modules","npm","bin","npm-cli.js"),br(n,"npm")]){let c=ro(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 no(s){return{file:process.execPath,args:[Hd(),...s]}}import{readFile as Od,rename as Md,writeFile as jd,unlink as Wd}from"node:fs/promises";import{join as $d}from"node:path";import{randomUUID as Vd}from"node:crypto";var kr=1,oo=s=>$d(s,"pi-web","launcher-handoff.json");function ao(s){return s?.protocol===kr&&typeof s.nonce=="string"&&s.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(s.requestId)&&Number.isSafeInteger(s.pid)&&s.pid>0&&["requested","draining","stopped","refused","failed"].includes(s.phase)}async function Pr(s){try{let e=JSON.parse(await Od(oo(s),"utf8"));if(!ao(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 Fd(s,e){let t=`${s}.${Vd()}.tmp`;try{await jd(t,JSON.stringify(e),{mode:384}),await Md(t,s)}finally{await Wd(t).catch(()=>{})}}async function co(s,e){if(!ao(e))throw new Error("Invalid launcher handoff receipt");await Fd(oo(s),e)}import{execFile as Ud}from"node:child_process";import{cp as Bd,readFile as Ir,realpath as Ld,rm as zd}from"node:fs/promises";import{join as mt,sep as qd}from"node:path";import{promisify as Gd}from"node:util";var lo=Gd(Ud),Sr=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Er(s){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=s;return Sr.map(t=>{let i=e[t];if(typeof i!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(i))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${i}`})}async function vi(s){return Promise.all(Sr.map(async e=>{let t=await lt(s,e),i=JSON.parse(await Ir(mt(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 po(s,e){let t=JSON.parse(await Ir(mt(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let i=t.peerDependencies===void 0?await vi(s):Er(t.peerDependencies);if(JSON.stringify(await vi(e))!==JSON.stringify(i))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let r=await lt(s,"node-pty"),n=await lt(e,"node-pty"),o=await Ld(mt(e,"../.."));if(r===n||!n.startsWith(o+qd))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let c=async u=>JSON.parse(await Ir(mt(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 zd(n,{recursive:!0,force:!0}),await Bd(r,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await lo(process.execPath,[mt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await lt(e,Sr[0]),{stdout:p}=await lo(process.execPath,[mt(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 Qd=Yd(Jd);function fo(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 Zd(s,e){try{let t=no(s),{stdout:i}=await Qd(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return i}catch(t){let i=t;throw new Error(i.stderr?.trim()||i.message)}}var Ii=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;validateHostedPair;hostedPair;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??Zd,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let i=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!i)return vi(this.packageRoot);let r=JSON.parse(i),n=Array.isArray(r)&&r.length===1?r[0]:r;return Er(n)},this.verifyPackage=e.verifyPackage??po,this.validateHostedPair=e.validateHostedPair,this.hostedPair=e.hostedPair,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?kr:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let i=await this.transaction();if(i&&!["committed","cancelled","failed"].includes(i.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let r=M(this.agentDir,"pi-web","launcher.json"),n=JSON.parse(await ge(r,"utf8")),o=p=>p.nonce===e&&p.pid===n.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(n))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let c=await Pr(this.agentDir);if(c?.nonce===e&&["requested","draining"].includes(c.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let a,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(a=await this.beforeRestart(),!o(JSON.parse(await ge(r,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:n.pid,phase:"requested"};try{await co(this.agentDir,p),l=!0}catch(u){let w=await Pr(this.agentDir).catch(()=>null);if(l=w?.nonce===e&&w?.requestId===t&&["requested","draining","stopped"].includes(w.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 Ve(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();return t?.phase==="restart-requested"&&t.version===e&&(!this.hostedPair||(await this.hostedPair.status?.())?.phase==="reconciled")&&await this.record({...t,phase:"committed",message:"Selected host is running and hosted protocol health admission completed"}),e}get transactionPath(){return M(this.agentDir,"pi-web","update-transaction.json")}async transaction(){try{let e=await oe(this.transactionPath);if(!e)return null;if(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||e.selectionPath!==M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json")||e.selectedDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.selectedDigest)||e.before!==void 0&&e.before!==null&&(typeof e.before!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.before)))throw new Error("\u66F4\u65B0\u4E8B\u52A1\u8BB0\u5F55\u65E0\u6548\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u8BCA\u65AD");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async record(e){if(await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await j(this.transactionPath,e),["failed","cancelled","committed"].includes(e.phase)){let t=M(this.agentDir,"pi-web","update-history");await ki(t,{recursive:!0}),await j(M(t,`${e.id}-${e.phase}.json`),e)}}async admittedFallback(e,t){if(!e.ownerNonce||!this.launcherNonce||e.ownerNonce===this.launcherNonce||e.before===void 0)return!1;let i=t??await this.current();if(e.version===i)return!1;try{let r=await oe(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 oe(M(this.agentDir,"pi-web","launcher.json"));if(t?.nonce!==this.launcherNonce||t.piPid!==process.pid||t.version!==(e??await this.current()))return!1;try{return await xr(M(this.agentDir,"pi-web","launcher.restart")),!1}catch(i){return i.code==="ENOENT"}}catch{return!1}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction();if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();if(r&&!["cancelled","reconciled","prepared"].includes(r.phase)){if(!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u9700\u8981\u5F53\u524D\u540E\u53F0\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E14\u4E0D\u80FD\u4E2D\u65AD\u542F\u52A8\u5668\u5DF2\u63A5\u53D7\u7684\u4EA4\u63A5");let n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");if(!r.selection||r.selection.path!==n)throw new Error("\u65E7\u5347\u7EA7\u4E8B\u52A1\u7F3A\u5C11\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u6062\u590D\u8BCA\u65AD");let o=await ge(n);if(te(o.toString("base64"))!==r.selection.digest)throw new Error("\u65E7\u5347\u7EA7\u9009\u62E9\u5DF2\u53D8\u5316\uFF0C\u6062\u590D\u672A\u8986\u76D6\u5176\u4ED6\u64CD\u4F5C");let c=JSON.parse(o.toString("utf8")),a=await this.current(),l=M(this.packageRoot,"bin","pi-webapp.mjs");await xr(l);let p=c.previous?.version===a&&c.previous.launcher===l?c.previous:this.desktopManaged?await li(this.agentDir,{version:a,launcher:l,desktopProtocolVersion:Fe}):{version:a,launcher:l,baseVersion:c.baseVersion??a};e={schema:1,id:r.id,phase:"selected",version:r.version,channel:await this.channel(),packageRoot:r.packageRoot,selectionPath:n,before:Buffer.from(JSON.stringify(p)).toString("base64"),selectedDigest:r.selection.digest,ownerNonce:this.launcherNonce,legacyRecovery:!0},await this.record(e)}else r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot)}if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot),this.preparedUpdate=void 0,this.restartPending=!1;return}if(e.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u540E\u53F0\u5F52\u5C5E\u6216\u4EA4\u63A5\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u8BF7\u4ECE\u5F53\u524D\u8FD0\u884C\u5B9E\u4F8B\u6062\u590D");if(e.phase==="restart-requested"&&!await this.admittedFallback(e))throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u5F53\u524D\u5165\u53E3\u6CA1\u6709\u5DF2\u786E\u8BA4\u56DE\u9000\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E0D\u80FD\u53D6\u6D88\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B\u7684\u4EA4\u63A5");let t=e,i=async()=>{if(t.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u5F52\u5C5E\u6216\u4EA4\u63A5\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(t.phase==="restart-requested"&&!await this.admittedFallback(t))throw new Error("\u91CD\u542F\u4EA4\u63A5\u7684\u5F52\u5C5E\u6216\u56DE\u9000\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(!t.selectedDigest)return;let r;try{r=await ge(t.selectionPath)}catch(n){if(n.code!=="ENOENT")throw n;r=null}if((r?.toString("base64")??null)!==t.before){if(!r||te(r.toString("base64"))!==t.selectedDigest)throw new Error("\u7248\u672C\u9009\u62E9\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u66F4\u6539\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u8BE5\u9009\u62E9\uFF1B\u5F53\u524D\u6570\u636E\u5DF2\u4FDD\u7559");if(t.before===null)await Wt(t.selectionPath);else if(typeof t.before=="string"){let n=`${t.selectionPath}.${bi()}.tmp`;try{await Pi(n,Buffer.from(t.before,"base64"),{mode:384}),await _r(n,t.selectionPath)}finally{await Wt(n,{force:!0})}}else throw new Error("\u7F3A\u5C11\u65E7\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u4E0D\u80FD\u81EA\u52A8\u6062\u590D\uFF1B\u8BF7\u4FDD\u7559\u4E8B\u52A1\u8BB0\u5F55")}};this.hostedPair?.cancel?await this.hostedPair.cancel(e.version,e.packageRoot,i):await W(M(this.agentDir,"pi-web","update-control"),i),await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0,this.restartPending=!1}get preferencePath(){return M(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ge(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${bi()}.tmp`;try{await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await Pi(t,JSON.stringify({channel:e}),{mode:384}),await _r(t,this.preferencePath)}finally{this.savingPreference=!1,await Wt(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),i=uo(M(this.packageRoot,".git")),r={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!i};this.desktopManaged&&(r.launcher=this.launcherIdentity(),r.launcherHandoff={supported:r.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(r.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let n=await this.transaction(),o=await this.hostedPair?.status?.();if(n&&!["failed","cancelled","committed"].includes(n.phase)?r.recovery={version:n.version,phase:n.phase,canCancel:n.legacyRecovery?await this.admittedLegacyRecovery(e):n.phase!=="restart-requested"||await this.admittedFallback(n,e)}:o&&!["cancelled","reconciled"].includes(o.phase)&&(r.recovery={version:o.version,phase:o.phase,canCancel:o.phase==="prepared"||await this.admittedLegacyRecovery(e)}),this.desktopManaged&&!this.desktopPackageUpdates)return{...r,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...r,canRestart:!1,reason:r.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};i?r.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":r.canRestart||(r.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&r.canRestart&&(r.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let c=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),a=Array.isArray(c)&&c.length===1?c[0]:c,l=t==="alpha"?a:{latest:a};if(!l||!mn(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(!oi(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ue(l.alpha,p)>0&&(p=l.alpha)}r.latest=p,r.downgrade=ue(p,e)<0,r.available=t==="stable"?ue(p,e)!==0:ue(p,e)>0,this.desktopManaged&&r.downgrade&&!this.desktopReleaseChannels&&ue(p,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(r.canRestart=!1,r.requiresDesktopUpgrade=!0,r.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(c){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${c instanceof Error?c.message:String(c)}`)}return r}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(uo(M(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let i=M(this.agentDir,"pi-web","releases");await ki(i,{recursive:!0});let r=await Kd(M(await Xd(i),`${t.latest}-`)),n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:bi(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:n,ownerNonce:this.launcherNonce};await this.record(o);let c=!1;try{let a=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...a,"--prefix",r,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=M(r,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:l},await this.record(o);let p=JSON.parse(await ge(M(l,"package.json"),"utf8"));if(p.name!=="pi-webapp"||p.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let u=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&fo(p)!==fo(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 w=M(l,"bin","pi-webapp.mjs");await Promise.all([w,M(l,"dist","extension.js"),M(l,"web","dist","index.html")].map(y=>xr(y))),await this.validateHostedPair?.(t.latest,l);let m=this.desktopManaged?await li(this.agentDir,{version:t.latest,launcher:w,desktopProtocolVersion:Fe}):null;this.desktopManaged&&await this.verifyPackage(this.packageRoot,l);let f=async()=>{let y;try{y=await ge(n)}catch(k){if(k.code!=="ENOENT")throw k;y=null}if(o={...o,phase:"selecting",before:y?.toString("base64")??null},await this.record(o),c=!0,this.desktopManaged){let k=m,E=await vn(this.agentDir,t.current),_=E?.version===t.current?E:null,H=process.env.PI_WEBAPP_DESKTOP_VERSION??E?.fallbackVersion??t.current,N={...k,...t.downgrade||E?.fallbackVersion?{fallbackVersion:H}:{},..._?{previous:_}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(N)).toString("base64"))},await this.record(o),await bn(this.agentDir,N)}else{let k=M(this.agentDir,"pi-web"),E=M(k,`update.${bi()}.tmp`);try{let _;try{_=JSON.parse(await ge(M(k,"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:w,baseVersion:H,...t.downgrade||_?.allowDowngrade===!0?{allowDowngrade:!0}:{},...N?{previous:N}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(T)).toString("base64"))},await this.record(o),await Pi(E,JSON.stringify(T),{mode:384}),await _r(E,M(k,"update.json"))}finally{await Wt(E,{force:!0})}}let P=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");return{path:P,digest:te((await ge(P)).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:w},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:w}}catch(a){throw c||await Wt(r,{recursive:!0,force:!0}),await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":"\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),a}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let t,i=!1;try{t=await this.beforeRestart?.(),await this.preparedUpdate?.select();let r=async()=>{let n=M(this.agentDir,"pi-web","launcher.restart"),o=await this.transaction();o&&await this.record({...o,phase:"restart-requested"});try{await Pi(n,JSON.stringify({nonce:this.launcherNonce,launcher:e.launcher}),{mode:384,flag:"wx"}),i=!0}catch(c){try{let a=JSON.parse(await ge(n,"utf8"));i=a.nonce===this.launcherNonce&&a.launcher===e.launcher}catch{}if(!i)throw c}};this.hostedPair?await this.hostedPair.restart(e.version,ho(ho(e.launcher)),r):await r(),this.restartPending=!0}catch(r){if(i){this.restartPending=!0;return}this.restartPending=!1;let n=await this.transaction();n?.phase==="restart-requested"&&await this.record({...n,phase:"selected",message:"Restart marker was not accepted; reverting owned selection"});let o=this.preparedUpdate;try{await this.cancel(),this.preparedUpdate=o}finally{t&&await t()}throw r}}};import{createHash as Qo,randomUUID as ih}from"node:crypto";import{randomUUID as Ru}from"node:crypto";import{access as Cu}from"node:fs/promises";import{join as ji}from"node:path";import{randomUUID as wo}from"node:crypto";import{randomUUID as ep}from"node:crypto";function go(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_${ep().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 tp;function mo(){return tp??=ip().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function ip(){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,w=0,m=!1,f=!1;try{let y=(N,T,Y)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:T,parameters:{type:"object",properties:{}},execute:Y}),P=()=>({content:[],details:void 0}),k=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(y(`__contract_${T.replace("-","_")}`,T,async()=>(w++,P())));N.registerTool(y("__contract_protected","direct",async()=>(w++,P()))),N.registerTool(y("__contract_direct","direct",async()=>(u++,P()))),N.registerTool(y("__contract_driver","direct",async(T,Y,b,v,$)=>{let we=await $.executeTool("__contract_hidden",{}),ye=await $.executeTool("__contract_model_only",{}),ie=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!we.isError||!ye.isError)&&p.push("nested-tool-exposure"),(ie.isError||u!==1)&&p.push("nested-tool-execution"),(!x.isError||w!==0)&&p.push("nested-tool-permission-guard"),m||p.push("nested-parent-identity"),f=!0,P()}))}]});await k.reload(),{session:l}=await s({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:k}),await l.bindExtensions({mode:"print"});let E=l.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(E);let _=0;l.agent.streamFunction=async N=>{let T=_++===0,Y={role:"assistant",api:N.api,provider:N.provider,model:N.id,timestamp:Date.now(),content:T?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:T?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},b=i();return b.push({type:"start",partial:Y}),b.push({type:"done",reason:T?"toolUse":"stop",message:Y}),b.end(Y),b};let H;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((N,T)=>{H=setTimeout(()=>T(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(H)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await n(a,{recursive:!0,force:!0})}}var Si=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=mo().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=go(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,w)=>{if(!this.allowed(e,i,n))throw new Error("Hosted tool denied by host policy");return this.service.invoke(i,{requestId:wo(),scope:{...e.scope},kind:"tool",action:n.action,input:u},w)}};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:rp};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:wo(),scope:t,kind:"action",action:i,input:r},n)}};async function rp(){throw new Error("Hosted tool unavailable")}import{randomBytes as ru,randomUUID as su,timingSafeEqual as nu}from"node:crypto";import{join as ke}from"node:path";var sp=30,yo=/^[a-z][a-z0-9-]{0,63}$/,np=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,$t=s=>{throw new h("invalid_package",s)},Ar=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?$t(`Invalid ${e} declaration`):s;function wt(s){let e=s&&typeof s=="object"?s:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),i=t.has("secrets")?Ar(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&yo.test(a)?a:$t("Invalid secret name")}):[],r=e.network,n=t.has("network")?Ar(r?.hosts,"network").map(c=>typeof c=="string"&&np.test(c)?c:$t("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Ar(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!yo.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<sp||a.intervalSec>86400?$t("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&$t("Duplicate schedule id"),{secrets:i,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as op}from"node:dns/promises";import{isIP as ap}from"node:net";var cp=new Set(["GET","POST","PATCH","PUT","DELETE"]),lp=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),dp=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Ei=(s,e)=>{throw new h("network_denied",s,{status:403,reason:e})};function pp(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if(ap(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 vo(s,e,t,i,r){let n=i;if(!n||typeof n!="object"||typeof n.url!="string")throw new h("invalid_input","Invalid network request");let o;try{o=new URL(n.url)}catch{throw new h("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Ei("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Ei("Host is not declared by the plugin","host");let c=(n.method??"GET").toUpperCase();if(!cp.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"||lp.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(_))throw new h("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=_}let l=null;if(n.secret!==void 0){if(t.includes(n.secret)||Ei("Secret is not declared by the plugin","secret"),l=await r.secrets.get(s,n.secret),!l)throw new h("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(r.resolve??(async E=>(await op(E,{all:!0})).map(_=>_.address)))(o.hostname);(!p.length||p.some(pp))&&Ei("Host resolves to a non-public address","address");let u=r.timeoutMs??2e4,w=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=[],y=0;if(m.body)for await(let E of m.body){if(y+=E.byteLength,y>w)throw new h("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let P=Buffer.concat(f).toString("utf8"),k={};return m.headers.forEach((E,_)=>{dp.has(_.toLowerCase())&&(k[_.toLowerCase()]=E)}),l&&(P=P.split(l).join("[redacted]")),{status:m.status,headers:k,body:P}}var xi=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new h("invalid_input",`Invalid ${t}`);return s};async function bo(s,e,t,i,r,n){let o=r&&typeof r=="object"&&!Array.isArray(r)?r:{};if(i==="sessions.create"){if(o.mode!=="plan")throw new h("invalid_input","Plugin sessions must start in plan mode");if(s.activeCount(e)>=n)throw new h("quota_exceeded","Too many active plugin sessions",{status:429});return s.create({pluginId:e,cwd:t,title:xi(o.title,200,"title"),prompt:xi(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=xi(o.sessionId,200,"sessionId");if(s.ownerOf(c)!==e)throw new h("session_denied","Session was not created by this plugin",{status:403});switch(i){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new h("invalid_input","Invalid mode");return await s.send(c,xi(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await s.release(c),{ok:!0};case"sessions.abort":return await s.abort(c),{ok:!0};case"sessions.events":return s.events(c,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new h("method_denied","Unknown sessions method")}}var up=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),_i=class{options;constructor(e){this.options=e}handles(e){return up.has(e)}async call(e,t,i,r,n){let o=wt(t);if(r==="network.fetch"){if(!o.networkHosts.length)throw new h("capability_denied","Plugin did not declare network access",{status:403});return vo(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 bo(this.options.sessions,e,i.scope.cwd,r,n,this.options.maxActiveSessions??3)}};var Ai=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let i=this.deps.setInterval??((r,n)=>{let o=setInterval(r,n);return o.unref(),o});this.timers.set(e,t.map(r=>i(()=>{this.tick(e,r)},r.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(i=>clearInterval(i));for(let i of this.timers.get(e)??[])t(i);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let i=`${e}\0${t.id}`;if(this.running.has(i))return!1;this.running.add(i);try{return await this.deps.invoke(e,t),!0}catch(r){return this.deps.onError?.(e,t,r),!1}finally{this.running.delete(i)}}};import{createHash as Or,timingSafeEqual as Hp}from"node:crypto";import{lstat as Co,mkdtemp as Hr,readdir as Op,readFile as Mp,realpath as jp,rename as Wp,rm as ze,writeFile as $p}from"node:fs/promises";import{tmpdir as Vp}from"node:os";import{join as B}from"node:path";import{gunzipSync as vp}from"node:zlib";import{mkdir as bp,writeFile as kp}from"node:fs/promises";import{dirname as Pp,join as Ip}from"node:path";import{constants as Tr}from"node:fs";import{lstat as Io,open as hp,readdir as ko,realpath as So}from"node:fs/promises";import{createHash as fp}from"node:crypto";import{join as Eo,relative as gp,resolve as mp,sep as wp}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},yp={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=>fp("sha256").update(s).digest("hex");function F(s){throw new h("invalid_package",s)}async function Ze(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=Eo(r,i[c]);let a=await Io(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 So(r);(n!==mp(s,e)||gp(s,n).startsWith(`..${wp}`))&&F("Resource escapes package root");let o=await hp(r,Tr.O_RDONLY|Tr.O_NONBLOCK|(Tr.O_NOFOLLOW??0));try{let c=await o.stat();(!c.isFile()||c.nlink!==1||c.size>t)&&F("Oversized or non-regular package file");let a=Buffer.alloc(Math.min(c.size+1,t+1)),l=0;for(;l<a.length;){let p=await o.read(a,l,a.length-l,l);if(!p.bytesRead)break;l+=p.bytesRead}return(l>t||l!==c.size)&&F("Package resource changed during read"),a.subarray(0,l)}finally{await o.close()}}function Po(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return F("Invalid package JSON")}}async function et(s,e){let t=await So(s);(await Io(s)).isSymbolicLink()&&F("Package root cannot be a symlink");let i=Po(await Ze(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"),Be(i.piWebapp)||F("Unsupported hosted manifest"),i.type!=="module"&&F("Hosted package must declare ESM module type");for(let u of await ko(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 w=i[u];w&&(typeof w!="object"||Object.keys(w).length>0)&&F("Hosted packages must contain all runtime dependencies")}let r=i.piWebapp,n=Po(await Ze(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 w=u,m={...w,path:typeof w.path=="string"&&w.path.startsWith("./")?w.path.slice(2):w.path};(!Ke(`./${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);yp[f]?.includes(m.mime)||F("Unsupported resource MIME");let y=f==="js"||f==="mjs"?K.js:f==="css"?K.css:f==="woff"||f==="woff2"?K.font:K.other;(m.bytes>y||(c+=m.bytes)>K.total)&&F("Resource budget exceeded");let P=await Ze(t,m.path,y);(P.length!==m.bytes||U(P)!==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,w=0){w>16&&F("Package directory nesting limit exceeded");for(let m of await ko(Eo(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,w+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,w)=>u.path.localeCompare(w.path))}));return{id:i.name,version:i.version,root:t,manifest:r,resources:o,digest:p}}async function xo(s,e,t){if(t!==s.digest||e.length>1536)return null;let i;try{i=decodeURIComponent(e)}catch{return null}if(!Ke(`./${i}`))return null;let r=s.resources.get(i);if(!r||i===s.manifest.backend.entry.slice(2))return null;let n=await Ze(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 Ti=64*1024*1024,Sp=K.total+K.files*2048,V=s=>{throw new h("invalid_archive",s)};function yt(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 _o(s){let e=yt(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 Ep(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 xp(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=yt(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 _p(s){if(!s.length||s.length>Ti)return V("Compressed archive exceeds budget");let e;try{e=vp(s,{maxOutputLength:Sp})}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 w=0;for(let H=0;H<512;H++)w+=H>=148&&H<156?32:u[H];if(_o(u.subarray(148,156))!==w)return V("Invalid tar header checksum");let m=yt(u.subarray(257,263));if(m&&m!=="ustar"&&m!=="ustar ")return V("Unsupported tar format");let f=u[156],y=yt(u.subarray(345,500)),P=(y?y+"/":"")+yt(u.subarray(0,100)),k=_o(u.subarray(124,136));if(a&&(a.path!==void 0&&(P=a.path),a.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(a.size))return V("Invalid PAX size");k=Number(a.size)}if(!Number.isSafeInteger(k)||k<0||k>K.total||r+k>e.length)return V("Truncated or oversized tar member");let E=e.subarray(r,r+k);if(r+=Math.ceil(k/512)*512,f===120){if(a||k>8192)return V("Oversized or chained PAX header");a=xp(E);continue}if(a=null,f!==0&&f!==48&&f!==53)return V("Links and special archive members are forbidden");let _=f===53;if(_&&k!==0||yt(u.subarray(157,257)))return V("Invalid archive link or directory");if(P=Ep(P),!P&&!_)return V("Invalid package root member");if(i.has(P))return V("Duplicate archive member");if(i.add(P),++n>K.files||(o+=k)>K.total)return V("Unpacked archive exceeds budget");t.push({path:P,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 w=u.path.split("/");for(let m=1;m<w.length;m++)if(p.has(w.slice(0,m).join("/")))return V("Archive file/directory collision")}return t}async function Rr(s,e){let t=_p(s);for(let i of t){if(!i.path)continue;let r=Ip(e,i.path);await bp(i.directory?r:Pp(r),{recursive:!0,mode:448}),i.directory||await kp(r,i.data,{flag:"wx",mode:384})}}import{lstat as Ap,mkdir as Tp,readdir as Rp,realpath as Cp,writeFile as Dp}from"node:fs/promises";import{dirname as Np,join as Cr}from"node:path";async function Ao(s,e){let t=await Cp(s),i=await Ze(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(w,m){if(m>16)throw new h("invalid_package","Package directory nesting limit exceeded");for(let f of await Rp(Cr(t,w),{withFileTypes:!0})){let y=`${w}/${f.name}`;if(++o>K.files)throw new h("invalid_package","Too many package entries");if(f.isDirectory()){await a(y,m+1);continue}if(!f.isFile())throw new h("invalid_package",`Links and non-regular files are forbidden: ${y}`);let P=await Ze(t,y,K.js);if((c+=P.length)>K.total)throw new h("invalid_package","Resource budget exceeded");let k=Cr(e,y);await Tp(Np(k),{recursive:!0,mode:448}),await Dp(k,P,{flag:"wx",mode:384}),n.push([y,U(P)])}}let l;try{l=await Ap(Cr(t,"dist"))}catch(w){throw w.code==="ENOENT"?new h("dist_missing","dist/ does not exist yet; build the plugin first"):w}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((w,m)=>w[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 Re(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 To(s){let e=be(s);if(e)return e;if(!oi(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 Dr(s){return!!To(s)}function vt(s,e){if(!Dr(s)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(r=>!r.trim()))return!1;let i=[];for(let r of t){let n=r.trim().split(/\s+/),o=!0;for(let c of n){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&To(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 w=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&ue(s,`${w}-0`)<0;break}}}i.push(o)}return i.some(Boolean)}var Oe=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=Oe){let t=e.find(i=>i.id===s);if(!t)throw new h("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Nr(s,e,t){let i=s.piWebapp;return s.name===e.id&&!!be(s.version)&&!s.deprecated&&Be(i)&&vt(t,i.hostRange)&&e.requiredCapabilities.every(r=>i.capabilities.includes(r))}function Ro(s,e,t,i,r){if(!s||typeof s!="object"||!("versions"in s)||!s.versions||typeof s.versions!="object"||Array.isArray(s.versions))throw new h("registry_invalid","Invalid registry version catalog");let n=Object.entries(s.versions);if(n.length>1e4)throw new h("registry_invalid","Registry version catalog exceeds budget");let c=n.flatMap(([a,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===a&&Nr(p,e,t)&&(!r||a===r)&&(!i||Re(a,i)>=0)?[p]:[]}).sort((a,l)=>Re(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 Fp(s,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new h("invalid_integrity","A single SHA-512 tarball integrity is required");let i=Buffer.from(t[1],"base64"),r=Or("sha512").update(s).digest();if(i.length!==r.length||!Hp(i,r))throw new h("integrity_mismatch","Downloaded package failed integrity verification")}var tt=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Dr(e.hostVersion))throw new h("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Oe,this.fetcher=e.fetch??Bn}async index(){let e=await ee(B(this.root,"installed.json"));if(!e){if(await X(B(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 B(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await oe(B(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(B(this.root,"install-journal.json"))}await this.recoverCollection(e);let i=B(this.root,"staging");await Z(i);for(let r of await Op(i)){if(!/^stage-[A-Za-z0-9]+$/.test(r)||(await Co(B(i,r))).isSymbolicLink())throw new h("invalid_storage","Invalid abandoned staging directory");await ze(B(i,r),{recursive:!0})}return e}async recoverCollection(e){let t=B(this.root,"gc-journal.json"),i=await oe(t);if(!i)return;if(i.schema!==1||Object.keys(i).some(n=>!["schema","pluginId","records"].includes(n))||!Array.isArray(i.records)||!i.records.length)throw new h("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");me(i.pluginId,this.catalog);for(let n of i.records)this.validateRecord(i.pluginId,n);let r=i.records.filter(n=>e.versions[i.pluginId]?.some(o=>o.directory===n.directory));if(r.length&&r.length!==i.records.length)throw new h("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!r.length){await Z(B(this.root,"versions")),await Z(B(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 Z(B(this.root,"versions")),await Z(B(this.root,"versions",U(e))),await j(B(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(B(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 Ro(c,n,this.hostVersion,t,i)}async install(e,t,i){let r=me(e,this.catalog);if(!Nr(t,r,this.hostVersion))throw new h("incompatible_plugin","Plugin release is incompatible with this host");let n=await this.download(this.trustedUrl(t.dist.tarball,r),Ti,i);return this.installArchive(e,n,t.dist.integrity,t.version,i)}async installArchive(e,t,i,r,n){let o=me(e,this.catalog);if(!be(r))throw new h("invalid_version","Choose an exact stable version");if(t.length>Ti)throw new h("download_too_large","Package archive exceeds budget");return Fp(t,i),W(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await Hr(B(this.root,"staging","stage-"));try{await Rr(t,a),n?.throwIfAborted();let l=await et(a,e);if(l.version!==r||!Be(l.manifest)||!vt(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 Z(B(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(B(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await Co(l),p=!0}catch(u){if(!$e(u))throw u}if(p){if((await et(l,e)).digest!==r.digest)throw new h("resource_changed","Installed package content was modified")}else await Wp(i,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await j(B(this.root,"installed.json"),t)),await ze(B(this.root,"install-journal.json")),{...r,root:await jp(l)}}async installDevArchive(e,t,i){me(e,this.catalog);let r=await Mp(t),n="sha512-"+Or("sha512").update(r).digest("base64"),o=await Hr(B(Vp(),"pi-dev-archive-"));try{await Rr(r,o);let c=(await et(o,e)).version;return await this.installArchive(e,r,n,c,i)}finally{await ze(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,i){let r=me(e,this.catalog);return W(this.root,async()=>{let n=await this.recoverLocked();i?.throwIfAborted();let o=await Hr(B(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await Ao(t,o);i?.throwIfAborted();let l=B(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],w=n.versions[e]??[],m=u?.contentHash===c?w.find(T=>T.version===u.version):void 0;if(m){let T=await et(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 y=Math.max(-1,...w.map(T=>be(T.version)).filter(T=>T&&T.major===f.major&&T.minor===f.minor).map(T=>T.patch)),P=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),y+1),k=`${f.major}.${f.minor}.${P}`;await $p(B(o,"package.json"),JSON.stringify({...a,version:k},null,2),{flag:"wx",mode:384});let E=await et(o,e);if(!vt(this.hostVersion,E.manifest.hostRange))throw new h("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let _=r.requiredCapabilities.filter(T=>!E.manifest.capabilities.includes(T));if(_.length)throw new h("incompatible_plugin",`Package lacks required capabilities: ${_.join(", ")}`);let H="sha512-"+Or("sha512").update(c).digest("base64"),N=await this.commitStaged(e,n,o,E,H,i);return p[e]={contentHash:c,version:k},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 et(this.path(n),e);if(o.digest!==n.digest)throw new h("resource_changed","Installed package integrity changed");if(!vt(this.hostVersion,o.manifest.hostRange)||!i.requiredCapabilities.every(c=>o.manifest.capabilities.includes(c)))throw new h("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){me(e,this.catalog),await W(this.root,async()=>{let i=await this.recoverLocked(),n=(i.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,i,n)})}};import{lstat as Ri,mkdir as Up,open as Do,realpath as No,readdir as Mr,link as Bp,rename as Lp,unlink as it,copyFile as zp,rm as qp}from"node:fs/promises";import{dirname as Gp,isAbsolute as Ho,join as O,relative as Oo,resolve as Jp,sep as jr,win32 as Kp}from"node:path";import{randomUUID as Wr}from"node:crypto";var Vt=192*1024*1024,Ft=512*1024,jo=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function Xp(s){if(!s||typeof s!="object"||Array.isArray(s))throw new h("invalid_input","Expected object input");return s}function Mo(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new h("invalid_input","Invalid state key");return s}function Ut(s){if(s&&(!jo(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 rt=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 ee(O(this.root,"active.json")).then(Ut)}async recover(){return W(this.root,async()=>{let e=await this.active(),t=await oe(O(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(o=>!["version","before","next"].includes(o))||Object.hasOwn(t,"version")&&t.version!==1)throw new h("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ut(t.next),Ut(t.before);let i=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,c)=>o===null||c===null?o===c:["version","generation","stateRef","schema","enabled","operationId"].every(a=>o[a]===c[a]))(e,i==="committed"?t.next:t.before))throw new h("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let n=t.before;if(i==="committed"&&n&&n.stateRef!==e.stateRef&&await j(O(this.root,"previous.json"),n),i==="committed"){let o=await oe(O(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(c=>["version","stateRef"].includes(c))&&await it(O(this.root,"fork.json"))}return await it(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 oe(O(this.root,"fork.json"));if(r&&(r.version!==1||r.stateRef!==t.stateRef||Object.keys(r).some(o=>!["version","stateRef"].includes(o))))throw new h("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let n=Ut({...t,generation:e+1,operationId:Wr()});await Z(O(this.root,"states")),await Z(O(this.root,"states",n.stateRef)),await j(O(this.root,"transition.json"),{version:1,before:i,next:n}),await this.checkpoint?.("prepared");try{await j(O(this.root,"active.json"),n)}catch(o){if((await this.active())?.operationId!==n.operationId)throw o}await this.checkpoint?.("committed");try{i&&i.stateRef!==n.stateRef&&await j(O(this.root,"previous.json"),i),await it(O(this.root,"transition.json")),await it(O(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),n})}async forkState(e){return W(this.root,async()=>{let t=await this.assertGeneration(e,!1),i=Wr(),r=O(this.root,"states",i);if(await oe(O(this.root,"fork.json")))throw new h("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await j(O(this.root,"fork.json"),{version:1,stateRef:i}),await Z(r);let n=O(this.root,"states",t.stateRef);for(let o of await Mr(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await X(O(n,o),Vt))throw new h("invalid_storage","Missing state file");await zp(O(n,o),O(r,o))}return await this.checkpoint?.("forked"),i})}async collect(e){return W(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await X(O(this.root,l),2*1024*1024))throw new h("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),i=Ut(await oe(O(this.root,"previous.json")));if(!t&&await X(O(this.root,"active.json"),2*1024*1024))throw new h("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let r=[t,i].filter(l=>!!l),n=O(this.root,"states");await Z(n);let o=await Mr(n),c=new Set(r.map(l=>l.stateRef));for(let l of o){if(!jo(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(n,l),u=await Ri(p);if(!u.isDirectory()||u.isSymbolicLink())throw new h("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let w of await Mr(p)){let m=await Ri(O(p,w));if(!/^[a-f0-9]{64}\.json$/.test(w)||!m.isFile()||m.isSymbolicLink()||m.nlink!==1)throw new h("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let f=await ee(O(p,w),Vt);if(!f)throw new h("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(f,"committed")){let y=f;if(Object.keys(y).some(P=>!["requestId","inputHash","nextHash","committed"].includes(P))||y.committed!==!0||!/^[a-f0-9]{64}$/.test(y.inputHash)||!/^[a-f0-9]{64}$/.test(y.nextHash)||typeof y.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(y=>!["revision","schema","value","requestId","inputHash"].includes(y)))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 qp(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=Xp(i);return W(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(n,e,Mo(r.key),r.scope),Vt);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(n,e,Mo(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)>Vt)throw new h("state_too_large","Plugin state exceeds limit");let a=await ee(o,Vt);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?Ft:r.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>Ft)throw new h("invalid_input","Invalid workspace read limit");let a=await X(o,c);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash: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")||Ho(t)||Kp.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let r=await No(e),n=Jp(r,t),o=Oo(r,n);if(!o||o===".."||o.startsWith(`..${jr}`)||Ho(o))throw new h("invalid_path","Workspace path escapes root");let c=r,a=o.split(jr);for(let p=0;p<a.length;p++){c=O(c,a[p]);let u;try{u=await Ri(c)}catch(w){if(!$e(w))throw w;if(p<a.length-1){if(!i||Oo(r,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await Up(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Ri(c)}}if(u&&(u.isSymbolicLink()||(p<a.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new h("invalid_path","Workspace path contains a link or non-regular file")}let l=await No(Gp(n));if(l!==r&&!l.startsWith(r+jr))throw new h("invalid_path","Workspace directory changed");return{target:n,parent:l}}async commitFile(e,t,i){if(typeof i.text!="string"||Buffer.byteLength(i.text)>Ft||!(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 ee(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==a))throw new h("duplicate_request","Request ID was reused with different content");let p;try{p=await Do(`${r}.lock`,"wx",384)}catch(w){throw w.code==="EEXIST"?new h("file_busy","Workspace file is locked; original file preserved"):w}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let w=await X(r,Ft),m=w?U(w):null;if(l&&m===a)return{hash:a};if(l?.committed||m!==i.expectedHash)throw new h("file_conflict","Workspace file already exists or changed externally");await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=O(n,`.plugin-${Wr()}.tmp`);let f=await Do(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 P=await X(r,Ft);if((P?U(P):null)!==i.expectedHash)throw new h("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),i.expectedHash===null){try{await Bp(u,r)}catch(k){throw k.code==="EEXIST"?new h("file_conflict","Workspace file was created concurrently"):k}await it(u),u=void 0}else await Lp(u,r),u=void 0;return await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await it(u).catch(()=>{}),await p.close(),await it(`${r}.lock`)}}};import{randomUUID as tu}from"node:crypto";import{fork as Yp}from"node:child_process";import{randomUUID as Qp}from"node:crypto";import{join as Zp}from"node:path";import{EventEmitter as eu}from"node:events";var Wo=192*1024*1024,Bt=class s{child;pending=new Map;events=new eu;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=Yp(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:Zp(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>Wo){this.unhealthy=!0;return}let i=e;if(i.type==="response"&&typeof i.id=="string"){let r=this.pending.get(i.id);if(!r)return;if(clearTimeout(r.timer),this.pending.delete(i.id),!r.expired){let n=i.error;i.ok===!0?r.resolve(i.value):r.reject(new h(n?.code??"plugin_failed",n?.message??"Plugin request failed",n))}this.inFlight||this.events.emit("idle")}else if(i.type==="broker-request"&&typeof i.id=="string"&&typeof i.invocationId=="string"&&typeof i.method=="string"){let r=this.pending.get(i.invocationId);try{if(!r?.invocation||r.expired)throw new h("invalid_lease","Plugin invocation lease is no longer writable");let n=await this.broker(r.invocation,i.method,i.input);this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!0,value:n})}catch(n){this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!1,error:G(n)})}}}request(e,t,i=3e4,r){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new h("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new h("worker_busy","Too many plugin requests"));let n=r?.requestId??Qp();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))>Wo?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 iu={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ci=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,i=iu,r){this.broker=e,this.workerEntry=t,this.hooks=i,this.capabilities=r}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await yr(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,i)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,i):this.broker.call(e,t,i);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new h("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new h("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new h("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let i;try{if(i=(await this.broker.recover()).active,i&&i.schema!==e.manifest.dataSchemaVersion)throw new h("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(l){throw this.worker||await this.releaseOwnership?.(),l}let r=i?.generation??0,n=this.worker;n||(this.phaseValue="starting");let o=null,c=!1,a=!1;try{if(o=await Bt.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):tu(),p=await this.broker.activate(r,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});c=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await n?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw c||(this.phaseValue=n?.healthy?"active":n?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue,r=await this.broker.active(),n=async()=>{if(!(!t||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(r))throw await this.releaseOwnership?.(),this.phaseValue="failed",new h("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Bt.start(t.package,t.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(c){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),c}}};this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin work is still draining; current host retained");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint work is still draining; current host retained");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(c){try{await n(),this.phaseValue=i,await this.hooks.resume()}catch(a){throw this.phaseValue="failed",a}throw c}let o=!1;return()=>this.serialize(async()=>{o||(await n(),this.phaseValue=i,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,i;try{i=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!i){if(t)throw this.phaseValue="failed",new h("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!i.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let r=this.phaseValue;this.phaseValue="draining";let n=!1;try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin still has in-flight work; not killed");if(n=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(i.generation,{version:i.version,stateRef:i.stateRef,schema:i.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=r,n&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(r){throw this.phaseValue=i,await this.hooks.resume().catch(()=>{}),r}})}};import{readFile as $o}from"node:fs/promises";var Di=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;pairAdmittedValue=!1;get pairAdmitted(){return this.pairAdmittedValue}constructor(e){this.options=e,this.installer=new tt({root:ke(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new _i(e.capabilities):void 0;this.scheduler=new Ai({invoke:async(i,r)=>{let n=this.closing?null:e.scheduledScope?.(i)??null;n&&await this.supervisor(i).invoke({requestId:su(),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 rt(ke(e.root,"data"),i.id,e.legacy?.(i.id)),n=e.hooks(i.id);this.supervisors.set(i.id,new Ci(r,e.workerEntry,{validateCandidate:o=>n.validateCandidate?.(o),canSwitch:()=>n.canSwitch(),freeze:()=>n.freeze(),resume:()=>n.resume(),committed:async o=>{if(o.enabled){let c=await this.installer.load(i.id,o.version);this.packages.set(i.id,c),this.assetTokens.set(i.id,ru(24).toString("base64url"));try{this.scheduler.start(i.id,wt(c.manifest).schedules)}catch(a){this.scheduler.stop(i.id),this.errors.set(i.id,G(a))}}else this.scheduler.stop(i.id),this.packages.delete(i.id),this.assetTokens.delete(i.id);await n.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),i=this.options.devArchives?.get(e);return t?r=>this.installer.installDevDirectory(e,t,r):i?r=>this.installer.installDevArchive(e,i,r):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){me(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new h("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new h("manager_closed","Plugin manager is shutting down"));let i=()=>W(Ee(this.options.root),async()=>(await jt(this.options.root),t())),r=(this.operations.get(e)??Promise.resolve()).then(i,i);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,G(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,i=!1){return this.options.lifecycle?this.options.lifecycle(e,t,i):t()}async policies(){let e=await ee(ke(this.options.root,"policies","policies.json"));if(!e){if(await X(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 ee(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||Re(n.version,t)>0;return o?this.available.set(e,n):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:n.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),n}catch(n){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:G(n).code,message:G(n).message}),n}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new h("invalid_input","Invalid plugin update policy");await W(Ee(this.options.root),async()=>{await jt(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 r=await this.policies();await j(ke(this.options.root,"policies","policies.json"),r)});let e=await He(this.options.root),t=gt(e);if(t&&e)try{if(await this.validatePairPackages(e.version,e.selections),e.version!==this.options.hostVersion||e.hostDigest!==await Qe(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Qe(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await $o(this.options.workerEntry)).equals(await $o(ke(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(r){let n=`Required action: restart the selected compatible host or inspect host-pair/intent.json with all owners stopped. ${G(r).message}; data retained`;for(let o of this.installer.catalog)this.errors.set(o.id,G(new h("host_pair_required",n)));await Ae(this.options.root,{...e,phase:"required-action",message:n}),t=!1}await this.installer.inventory();let i=te(await this.pairSnapshot());for(let r of this.installer.catalog){let n=this.supervisor(r.id),o=await n.broker.active();if(o?.enabled)try{let c=t?e?.selections.find(p=>p.id===r.id):void 0,a=c&&te(o)===te(c.before)&&e?.fingerprint===i,l=await this.installer.load(r.id,a?c.version:o.version);if(a&&l.digest!==c.digest)throw new Error("Staged plugin digest changed");await this.lifecycle(r.id,()=>n.replace(l)),this.packages.set(r.id,l),gt(e)||await this.collectSettled(r.id)}catch(c){let a=G(c),l=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool; do not delete the pair journal.":"Choose a compatible host/plugin and inspect plugin diagnostics; do not delete the pair journal.";this.errors.set(r.id,{...a,message:`Required action: plugin startup failed (${a.code}): ${a.message}; data retained. ${l}`})}}t&&e&&(await Ae(this.options.root,{...e,phase:this.errors.size?"required-action":"reconciled",message:this.errors.size?[...this.errors].map(([r,n])=>`${r}: ${n.message}`).join("; "):"Current compatible state admitted; no previous state restored"}),this.pairAdmittedValue=!this.errors.size)}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),i=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async n=>{let o=this.supervisor(n.id),c=await o.broker.active(),a=this.packages.get(n.id),l=(e.versions[n.id]??[]).map(p=>p.version).sort((p,u)=>Re(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)=>Re(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 w=await l(r);return await this.recordDevSync(e,w.version),{installed:!0,version:w.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),y=await n.broker.active();if(await this.recordDevSync(e,f.version),!y?.enabled)return{installed:!0,enabled:!1,version:f.version};if(y.version===f.version&&!n.pendingVersion)return{unchanged:!0,version:f.version};let P=await this.lifecycle(e,()=>n.replace(f));return P.pending||this.packages.set(e,f),P}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 w=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:w.version,message:"Selected compatible release installed; activation may wait for editors"}),!u?.enabled)return{installed:!0,enabled:!1,version:w.version};let m=await this.lifecycle(e,()=>n.replace(w));return m.pending||this.packages.set(e,w),m}case"uninstall":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new h("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=G(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async i=>this.installer.collect(e,async()=>{let r=(await this.policies())[e];return[...i.map(n=>n.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...r?.pinnedVersion?[r.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Reconnect the plugin view before editing",{status:409})):r.invoke(i)}flush(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Flush generation changed",{status:409})):r.flushAction(i)}async asset(e,t,i){let r=this.packages.get(e);if(!r)return null;let n=this.assetLeases.get(e);n||(n=new Map,this.assetLeases.set(e,n)),n.set(r.version,(n.get(r.version)??0)+1);try{return await xo(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)||!nu(n,Buffer.from(r))?null:this.asset(i,t[3],t[4])}async reconcileHostUpgrade(){if(gt(await He(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)=>Re(p,l))[0];try{await this.installer.load(r.id,c);continue}catch(l){if(G(l).code!=="incompatible_plugin")throw l}let a=await this.manage(r.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(i=!1)}catch(o){i=!1;let c=G(o);this.errors.set(r.id,c),await this.recordCheck(r.id,{status:"failed",code:c.code,message:c.message})}}return i}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}get hostPair(){return to(this.options.root,(e,t)=>this.prepareHostPair(e,t),()=>this.pairSnapshot(),(e,t)=>this.validatePairPackages(e,t))}async validatePairPackages(e,t){let i=new tt({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 tt({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(w=>w.version).sort((w,m)=>Re(m,w))[0],u;try{u=await i.load(c.id,l?.enabled?l.version:p),o.push({id:c.id,version:u.version,digest:u.digest,before:l});continue}catch(w){if(G(w).code!=="incompatible_plugin")throw w}try{let w=await i.check(c.id,p,void 0,t);u=w.version===p?await i.load(c.id,p):await i.install(c.id,w,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(w){let m=G(w);await this.recordCheck(c.id,{status:"failed",code:m.code,message:m.message}),this.errors.set(c.id,m);try{u=await i.load(c.id,p)}catch(f){throw new h("host_pair_required",`${m.message}; ${G(f).message}; current host/plugin and data retained`)}}o.push({id:c.id,version:u.version,digest:u.digest,before:l})}return o}async validateHostUpdate(e){let t=new tt({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,w)=>Re(w,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(w){throw new h("host_pair_required",`Host update blocked for ${o.id}@${u}: ${G(w).message}. Prepare a compatible pair; installed code/data retained`)}}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[],t=async()=>{let i=await Promise.allSettled(e.map(n=>n()));this.closing=!1;let r=i.find(n=>n.status==="rejected");if(r?.status==="rejected")throw r.reason};try{for(let i of this.supervisors.values())e.push(await i.suspendForRestart());return t}catch(i){throw await t(),i}}};import{randomUUID as ou}from"node:crypto";var D=s=>Object.assign(new Error(s),{status:409,code:"view_barrier"}),Lt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;constructor(e,t,i=2e4,r=15e3){this.pluginId=e,this.generation=t,this.pollMs=i,this.freezeMs=r}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,i){return e.scope.ownerId===i.ownerId&&e.scope.workspaceId===i.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let i=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&i&&this.barrier.pending.has(i.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&i.identity.generation===e.generation&&i.identity.mountId===e.mountId&&i.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&i.scope.ownerId===t.ownerId&&i.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let i=e.viewToken?this.views.get(e.viewToken):void 0;if(!i||i.identity.generation!==this.generation||e.generation!==i.identity.generation||e.mountId!==i.identity.mountId||e.sessionId!==i.identity.sessionId||t.ownerId!==i.scope.ownerId||t.workspaceId!==i.scope.workspaceId||t.sessionId!==i.identity.sessionId)throw D("Unknown or stale view action capability");if(this.switching&&i.kind==="controller")throw D("Controller admission paused during plugin switching");return i.initialized=!0,i.activeActions=(i.activeActions??0)+1,()=>{i.activeActions--}}enqueue(e,t,i=++this.sequence){return e.commands.push({id:i,type:t,generation:this.generation}),e.waiter?.(),i}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw D("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw D("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw D("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw D("Invalid registration capability");let o=e.viewToken??ou();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw D("View initialization was cancelled; register a new document identity");let c=this.views.get(o);if(c){if(!this.sameScope(c,e,t)||c.kind!==e.kind)throw D("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw D("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[]}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw D("Invalid view capability");let i=this.views.get(e.viewToken),r=this.recoveries.get(e.viewToken),n=this.retired.get(e.viewToken);if(n&&!this.sameScope(n,e,t))throw D("Unknown or stale view capability");if(e.operation==="reconcile"||e.operation==="recover"){if(i&&!this.sameScope(i,e,t)||r&&!this.sameScope(r,e,t))throw D("Unknown or stale view capability");if(r)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(r,"retained")};if(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!i)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||i.activeActions)return{viewToken:i.token,commands:[],recovery:this.recovery(i,"active")};if(i.kind==="controller")return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw D("Explicit recovery confirmation required");return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),this.recoveries.set(i.token,i),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retained")}}return{viewToken:i.token,commands:[],recovery:this.recovery(i,"unconfirmed")}}if(e.operation==="discard"&&r&&this.sameScope(r,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!i&&!r){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching)throw D("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!i||!this.sameScope(i,e,t))throw D("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(i.initialized||i.activeActions||this.switching)throw D("View already initialized; preserve its recovery record");this.retire(i);break;case"change":if(e.generation!==this.generation)throw D("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw D("Invalid view status");i.initialized=!0,i.dirty=e.dirty,i.busy=e.busy,(i.dirty||i.busy)&&i.frozen&&(i.frozen=!1,this.barrier?.reject(D("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw D("Invalid acknowledgement");let o=i.commands.find(c=>c.id===e.commandId);if(!o)throw D("Unknown command acknowledgement");i.commands=i.commands.filter(c=>c.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(i.frozen=!0,i.dirty=!1,i.busy=!1,this.barrier.pending.delete(i.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(D(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching||i.activeActions)throw D("View has an active barrier or action; discard refused");this.retire(i);break;case"close":if(i.activeActions)throw D("View action still in flight");if(i.kind!=="controller"&&(i.dirty||i.busy)&&!i.frozen)throw D("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(i.token))throw D("View must acknowledge freeze before closing");this.retire(i);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw D("Invalid poll cursor");if(i.waiter)throw D("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw D("Invalid poll mode");return!e.immediate&&!i.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),i.waiter=void 0,o()}i.waiter=a}),{viewToken:i.token,commands:i.commands.filter(o=>o.id>e.after)}}default:throw D("Unknown view operation")}return{viewToken:i.token,commands:[]}}freeze=async()=>{if(this.switching)throw D("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(i=>i.activeActions||i.kind!=="controller"&&!i.frozen&&(i.busy||!this.immediate&&["editor","workspace"].includes(i.kind)));throw D(`Close editors before updating; old version retained. Pending views: ${t.map(i=>`${i.kind}:${i.identity.mountId}${i.activeActions?` (action in flight x${i.activeActions})`:i.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,i)=>{let r=n=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,n?i(n):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(n=>n.token)),resolve:()=>r(),reject:n=>r(n),timer:setTimeout(()=>{let n=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));r(D(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${n.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let n of this.authoringViews())this.enqueue(n,"freeze",e);this.authoringViews().length||r()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw D("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(D("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(D("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var au="@chengzhiyi/pi-excalidraw",cu={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"}}},lu="@chengzhiyi/pi-github",du={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"}}},Vo=new Map([[au,cu],[lu,du]]);function $r(s,e){let t=s.get(e);if(!t)throw new h("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as pu}from"node:crypto";var uu="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"}),hu="Ov23limJmKiuu8cOP83E";function Vr(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||hu,scope:"repo",createUrl:uu}}var fu="https://github.com/login/device/code",gu="https://github.com/login/oauth/access_token",mu=8,Ni=class{flows=new Map;fetcher;now;constructor(e=(i,r)=>fetch(i,{...r,signal:r.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let i;try{i=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new h("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let r=await i.json().catch(()=>null);if(!r||typeof r!="object"||!i.ok&&!("error"in r))throw new h("oauth_failed",`GitHub sign-in failed (${i.status})`,{status:502});return r}async start(e,t,i){if(!i.clientId)throw new h("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[u,w]of this.flows)w.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=mu)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let r=await this.post(fu,{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=pu();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(gu,{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 Uo,readFileSync as Bo,statSync as wu}from"node:fs";import{lstat as yu,readdir as vu,writeFile as bu,mkdir as ku,rename as Pu}from"node:fs/promises";import{delimiter as Iu,dirname as Su,isAbsolute as Eu,join as st,resolve as zt}from"node:path";var Fo="@chengzhiyi/pi-github",Mi={[Fo]:{id:Fo,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"]}},Lo=()=>Object.keys(Mi).join(", ");function xu(s=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(s??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=n.lastIndexOf("="),c=n.slice(0,o),a=n.slice(o+1),l=Mi[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?Uo(zt(a))?null:`archive not found: ${zt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Lo()})`;if(p){i.push({level:"error",source:r,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,zt(a))}return{catalog:e,archives:t,notices:i}}var zo=s=>st(s,"pi-web","hosted-dev.json"),qo=s=>st(s,"pi-web","hosted-dev-status.json");function _u(s,e,t=process.cwd()){let i=[],r=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(Iu).map(c=>c.trim()).filter(Boolean);for(let c of n)i.push({path:zt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&Uo(e)){o=!0;try{let c=JSON.parse(Bo(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"||!Eu(l)?r.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):i.push({path:zt(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 Au(s){let e=(r,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${r}`}}),t;try{t=wu(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(Bo(st(s.path,"package.json"),"utf8"))}catch(r){return e(r.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof i.name!="string"?e("package.json has no name"):Mi[i.name]?Be(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: ${Lo()})`)}var Hi=class{catalog;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let t=xu(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=_u(this.env,this.configPath,this.cwd),i=[],r=new Map,n=new Map;for(let o of t.specs){let c=Au(o);if(c.notice){i.push(c.notice);continue}let a=c.pluginId;if(r.has(a)){i.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${r.get(a)}`});continue}if(this.archives.has(a)&&i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${a}; the dev directory wins`}),!this.catalog.some(l=>l.id===a)){if(!e){i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: ${a} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}this.catalog.push(Mi[a])}r.set(a,o.path),n.set(a,o.source)}for(let o of[...this.roots.keys()])r.has(o)||this.roots.delete(o);for(let[o,c]of r)this.roots.set(o,c);this.rootSource.clear();for(let[o,c]of n)this.rootSource.set(o,c);return this.fileNotices=t.notices,this.rootNotices=i,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Oi=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${G(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,i]of e){let r=this.roots.get(t);(!r||r.root!==i)&&(r={root:i,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,r));let n=await Tu(i);if(n===null){this.set(t,r,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),r.seen=void 0;continue}if(n!==r.seen){r.seen=n;continue}n===r.applied||this.stopped||await this.apply(t,r,n)}await this.publish()}set(e,t,i,r={}){let n=t.state!==i||t.message!==r.message||t.version!==r.version;t.state=i,t.message=r.message,t.code=r.code,t.version=r.version??t.version,n&&(t.at=new Date().toISOString(),this.log(`${e}: ${i}${r.version?` ${r.version}`:""}${r.message?` \u2014 ${r.message}`:""}`))}async apply(e,t,i){this.set(e,t,"switching");try{let n=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=i,n?.installed?n.pendingVersion?this.set(e,t,"pending",{version:n.version,message:`Waiting for editors to close before switching to ${n.pendingVersion}`}):this.set(e,t,"synced",{version:n.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(r){let n=G(r);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(n.code)||(t.applied=i),n.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:n.code,message:`${n.message} (${n.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let i=this.options.statusPath;if(!i)return;let r=Object.fromEntries([...this.roots].map(([c,a])=>[c,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),n=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(c=>c.id),plugins:r,notices:e.notices});if(n===this.lastStatus)return;this.lastStatus=n;let o=`${i}.${process.pid}.tmp`;try{await ku(Su(i),{recursive:!0}),await bu(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await Pu(o,i)}catch{}}};async function Tu(s){let e=[],t=async(i,r)=>{let n=await yu(i);e.push(`${r}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(st(s,"package.json"),"package.json");let i=async(r,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await vu(r,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await i(st(r,c.name),`${n}/${c.name}`,o+1):await t(st(r,c.name),`${n}/${c.name}`)};if(await i(st(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 Du(s){try{return[...wt(s).secrets]}catch{return[]}}var Wi=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ni;restartPreparation;restartResume;closing=!1;started=!1;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Vo,e.dev?.enabled&&(this.devWatcher=new Oi({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let i=await this.inventory();return i.plugins.find(r=>r.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):i}}})),this.adapter=new Si({policy:(t,i)=>{let r=e.policy?.(t,i);return{...r,enabled:!this.recovery.has(t)&&this.manager.tools.some(n=>n.pluginId===t)&&r?.enabled!==!1}},invoke:async(t,i,r)=>{r?.throwIfAborted(),this.scope(i.scope.sessionId,i.scope);let n=this.manager.tools.find(c=>c.pluginId===t);if(!n)throw new h("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,n.generation,i);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Di({...e,lifecycle:(t,i,r)=>this.lifecycle(t,i,r),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:i=>{if(i.length!==Object.keys($r(this.trusted,t).tools).length)throw new h("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,i),this.adapter.validateChange(t,i)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async i=>{try{let r=i.enabled?this.manager.tools.find(n=>n.pluginId===t)?.descriptors:[];if(!r)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,r),i.enabled){let n=await this.manager.installer.load(t,i.version);this.documents.set(t,{document:n.manifest.frontend.document.replace(/^\.\//,""),controller:n.manifest.frontend.controller.replace(/^\.\//,""),secrets:Du(n.manifest)})}else this.documents.delete(t);this.adapter.change(t,r),await this.coordinator(t).committed(i),e.changed?.(),this.recovery.delete(t)}catch(r){throw this.recovery.set(t,r),await this.coordinator(t).committed(i).catch(()=>{}),r}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,i,r)=>{let n=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!n)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(i))throw new h("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return r===null?await n.delete(t,i):await n.set(t,i,r),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let i=this.options.capabilities?.secrets;if(!i)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let n=this.documents.get(t.pluginId)?.secrets.includes(t.name)?Vr(t.pluginId,t.name):void 0;if(!n)throw new h("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,n)}let r=await this.deviceFlows.poll(t.deviceId);return r.status!=="granted"?{status:r.status}:(await i.set(r.pluginId,r.name,r.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,i)=>{if(!this.options.approvals)throw new h("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,i),this.inventory()},action:(t,i)=>this.action(t,i?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new h("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let i=t,r=this.scope(i.sessionId);return i.operation==="register"&&this.generation(i.pluginId,i.generation),this.coordinator(i.pluginId).handle(i,this.viewScope(r))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let i=$r(this.trusted,e);for(let r of t)if(!Object.hasOwn(i.tools,r.name)||i.tools[r.name]!==r.action||r.readonly!==i.readonlyActions.includes(r.action))throw new h("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new h("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let i=typeof e=="string"?this.options.resolveSession(e):null;if(!i||i.sessionId!==e||!i.cwd||!i.workspaceId||t&&(i.cwd!==t.cwd||i.workspaceId!==t.workspaceId))throw new h("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...i}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let i=this.manager.tools.find(r=>r.pluginId===e);if(!i||i.generation!==t)throw new h("stale_generation","Reconnect and re-handshake hosted views",{status:409});return i}enqueue(e,t=!1){let i=this.queue.then(async()=>{if(this.closing&&!t)throw new h("manager_closed","Host is shutting down");return e()});return this.queue=i.catch(()=>{}),i}lifecycle(e,t,i=!1){let r=this.switches.then(async()=>{if(this.closing&&!i)throw new h("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let n=await t();if(n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new rt(ji(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!i)throw new h("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return n}finally{if(!i)for(let n of this.views.values())n.allowImmediateReopen(!1);i||this.adapter.thaw()}});return this.switches=r.catch(()=>{}),r.catch(n=>{throw i&&this.adapter.thaw(),n})}async start(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Oe)try{let t=await new rt(ji(this.options.root,"data"),e.id).active();this.views.set(e.id,new Lt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new Lt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=ji(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&(this.manager.pairAdmitted?!(await this.manager.inventory()).plugins.some(i=>i.updateDiagnostic?.status==="failed"):await this.manager.reconcileHostUpgrade())&&(await Z(this.options.root),await j(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Oe)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 Cu(ji(t,"dist","hosted-worker.js"))}catch{throw new h("host_pair_required","Selected host has no hosted worker; keep current host/plugin pair")}})}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,i=new Map;for(let r of e.plugins){let n=r.enabled?this.documents.get(r.id)?.secrets??[]:[];t&&n.length&&i.set(r.id,await Promise.all(n.map(async o=>{let c=Vr(r.id,o);return{name:o,configured:await t.has(r.id,o),...c?{signIn:c.clientId?"browser":"token-page",...c.createUrl?{createUrl:c.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(r=>({pluginId:r.id,name:r.name,official:r.official,installed:r.installed,enabled:r.enabled,description:r.description,...i.has(r.id)?{secrets:i.get(r.id)}:{},icon:(this.options.catalog??Oe).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:Ru(),scope:i,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(i)))return await this.manager.flush(e.pluginId,e.generation,n);throw new h("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new h("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...n,kind:"action"})}finally{r()}}prepareRestart(){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let r of this.views.values())r.allowImmediateReopen(!0);let e=await this.manager.suspendForRestart(),t=!1,i=async()=>{if(!t)try{await e(),t=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(e){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}finally{for(let e of this.views.values())e.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as Nu,readdir as Hu,unlink as Ou}from"node:fs/promises";import{join as bt}from"node:path";import{randomUUID as Mu}from"node:crypto";var Fr="hosted-migration.json";function Go(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:i,sessionId:r}=t.scope,n=bt(s,U(JSON.stringify([i,r])));await Z(s),await Z(n);let o=bt(n,"scope.lock"),c;try{c=await Nu(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:Mu()}));let a=await ee(bt(n,Fr));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Hu(n),p=[];for(let w of l){if(w==="scope.lock"||w==="focus.json"||w===Fr||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(w))continue;if(!/^[\w-]{1,80}\.json$/.test(w))throw new h("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new h("invalid_storage","Too many legacy checkpoints");let m=await ee(bt(n,w),3*512*1024);if(!m||m.version!==1||m.cwd!==i||m.sessionId!==r||!m.draft||w!==`${m.draft.id}.json`)throw new h("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(m.draft)}let u=await ee(bt(n,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(w=>w.id===u)))throw new h("invalid_storage","Invalid legacy focused drawing");return a||await j(bt(n,Fr),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Ou(o)}}}import{join as zu}from"node:path";import{randomUUID as ju}from"node:crypto";var Wu=6e4,$i=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:i,title:r})=>({id:e,pluginId:t,sessionId:i,title:r}))}async authorize(e,t){let i=this.entries.get(t);if(i&&i.pluginId!==e)throw new h("execute_denied","Session belongs to another plugin",{status:403});if(i?.status==="allowed")return!0;throw i?.status==="pending"?new h("approval_required","Waiting for the user to approve execution",{status:409}):i?.status==="denied"&&this.now()-i.decidedAt<Wu?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:ju(),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 $u,readFile as Vu,rename as Fu,writeFile as Uu}from"node:fs/promises";import{randomUUID as Bu,createHash as Lu}from"node:crypto";import{join as Jo}from"node:path";var Vi=class{dir;queue=Promise.resolve();constructor(e){this.dir=Jo(e,"secrets")}file=e=>Jo(this.dir,`${Lu("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Vu(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!$e(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 $u(this.dir,{recursive:!0,mode:448});let r=`${this.file(e)}.${Bu()}.tmp`;await Uu(r,JSON.stringify(i),{mode:384}),await Fu(r,this.file(e))})}};function Ko(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 qu="scheduler";function Xo(s){let e=new $i({describe:s.sessionTitle,changed:s.changed}),t=()=>{let r=s.sessions();if(!r)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return r},i={createDetached:(...r)=>t().createDetached(...r),detachedOwner:r=>s.sessions()?.detachedOwner(r)??null,detachedCount:r=>s.sessions()?.detachedCount(r)??0,sendDetached:(...r)=>t().sendDetached(...r),abortDetached:r=>t().abortDetached(r),releaseDetached:async r=>{e.forget(r),await t().releaseDetached(r)},detachedEvents:(...r)=>t().detachedEvents(...r)};return{approvals:e,capabilities:{secrets:new Vi(zu(s.root,"capability-secrets")),sessions:Ko(i,(r,n)=>e.authorize(r,n))},scheduledScope:()=>{let r=s.activeWorkspace();if(!r)return null;try{return s.trustedScope(r,qu)}catch{return null}}}}async function Gu(){for(let s of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=si(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:At,buildId:Se,browser:si({}).browser}}async function Yo(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let 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:At,buildId:Se}}finally{await s.close()}}var qt=It(Ku(Qu(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),rh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[rh]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new We(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:Me()}),ce()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Ye,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Ye;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new We(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:Me()}),ce()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function Fi(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var sh=null;function nh(){return sh??=Zu.create({refreshOnCreate:!1})}var Ui=new Map;async function Pt(){let s=await nh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let i of Ui.keys())t.has(i)||(s.unregisterProvider(i),Ui.delete(i));for(let i of t){let r=e?.getRegisteredNativeProvider(i),n=e?.getRegisteredProviderConfig(i),o=r??n;!o||Ui.get(i)===o||(r?s.registerNativeProvider(r):n&&s.registerProvider(i,n),Ui.set(i,o))}return await s.refresh({allowNetwork:!1}),s}function le(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():Me()}function Me(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...Sn(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 qr(s,e,t,i,r){let n=he(s);je({...Me(),idle:n.isIdle()},e,r);let o=n.isIdle();o&&ft(()=>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:Me()})}catch(c){throw o&&(d.operation=void 0),c}}function Lr(){let s=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!s||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==s||d.tuiAgentError)return!1;let i=Me();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!i.paused&&!i.interactions.length};d.tuiPrompts.schedule(t,(i,r,n)=>qr(s,i,r,n))}function re(s){if(le().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function ia(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=le(),r=d.current?Me():null,n=await pt(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=r?await pt(r.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await ta.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});let l=(await Promise.all(s.map(async p=>{let w=(await Nt(p.path,c).catch(m=>(m instanceof Dt?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)||"\u5F53\u524D\u4F1A\u8BDD",modified:m.modified.toISOString(),idle:!0}));for(let m of a.filter(f=>f.cwd===p.path)){let f=w.findIndex(P=>P.id===m.sessionId),y={id:m.sessionId,workspaceId:p.id,path:m.path??w[f]?.path??null,name:m.name,modified:m.modified,idle:m.idle};f<0?w.unshift(y):w[f]=y}return p.path===n&&!w.some(m=>m.id===t.sessionId)&&w.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),w}))).flat();return{items:s,activeId:e,sessions:l}}var Zo=0;async function ce(){if(!d.bridge)return;let s=++Zo;try{let e=await ia();s===Zo&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function zr(s,e=!1){let t=d.workspaces?.get(s);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ue(t.path),!e&&d.current&&t.path===await pt(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:le()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=s,d.bridge?.publish({type:"snapshot",session:le()})}await ce()}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 ae(s){d.current=s,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:le()})}function ra(){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 eh.create(s,void 0,{projectTrusted:e})}async function sa(){let s=ra(),e=r=>({packages:(r.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:r.extensions??[],skills:r.skills??[]}),t=new ea({cwd:le().cwd,agentDir:Pe(),settingsManager:s}),i=Jn(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:i}}async function oh(s){re(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=ra();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 ea({cwd:le().cwd,agentDir:Pe(),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&&ae(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await sa()}function Bi(s,e=mr){if(d.hostedMode===!1||d.hostedMode===void 0&&d.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");d.hostedMode=!0;let t=(a,l)=>{let p=Ur(a);return{cwd:p,sessionId:l,workspaceId:Qo("sha256").update(p).digest("hex")}},i=kt(Pe(),"pi-web","hosted"),r=new Hi({configPath:zo(Pe())});d.hosted??=new Wi({root:i,...r.enabled?{dev:r,devStatusPath:qo(Pe())}:{},...r.catalog.length?{catalog:[...Oe,...r.catalog],devArchives:r.archives,devRoots:r.roots}:{},...Xo({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(Xu(It(qt,"../../package.json"),"utf8")).version,packageRoot:It(qt,"../.."),workerEntry:It(qt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${Qo("sha256").update(Pe()).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:()=>Go(kt(Pe(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Lr),d.pi=s,d.tools?.clear(),d.tools=new ht({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:Br,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new ut(s.events,a=>!!d.bridge&&a.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(a.pluginId),()=>{d.current&&d.selected==="tui"&&ae(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=s.events.on(hi,()=>{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())),await d.hosted?.start(),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new We(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:Me()}),ce()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Xe.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 ce())}).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),ce()}),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,Lr(),ae(l),ce()}),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:Br});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),ce()}),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:Je(a.message.content)},d.selected!=="tui"||d.bridge===null))return;let p=Date.now();p-d.lastStreamAt<60||(d.lastStreamAt=p,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),s.on("session_shutdown",async a=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,a.reason==="new"||a.reason==="resume"||a.reason==="fork"||a.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let l=d.bridge,p=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let u=d.workspaceSessions;d.workspaceSessions=null,await u?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,l?await l.close():await p?.close()});let c=async a=>{d.telemetry??=new xe;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=s,d.tuiCatalog=await Xe.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ui(An(Pe())),await d.workspaces.load());try{await d.workspaces.discover((await ta.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,w=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&&Ur(d.current.cwd)===f&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,y)=>d.bridge?.reportError?.(f,y),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(f,y)=>d.bridge?.breadcrumb?.(f,y),anonymize:f=>d.telemetry?.session(f)??"unavailable"},()=>{ce()},[],{adapter:d.hosted.adapter,scope:t}),w&&await d.workspaceSessions.open(w.path,{sessionManager:w.sessionManager});let m={hosted:d.hosted?.handlers,selfUpdate:new Ii({agentDir:Pe(),packageRoot:It(qt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,hostedPair:d.hosted.manager.hostPair,beforeRestart:()=>d.hosted.prepareRestart()}),snapshot:le,busyGitWorkspaces:()=>{let f=(d.workspaceSessions?.retainedSessions()??[]).filter(y=>!y.idle).map(y=>y.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{f.push(Ur(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=Fi();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Fi()?.asset(f)??null,async invokePluginAction(f,y,P,k){if(re(f),!Fi()?.has(y))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,_=d.tuiGeneration,H=d.workspaceSessions?.session,N={requestId:ih(),sessionId:f,pluginId:y,action:P,input:k},T=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(N):await fi(d.pi.events,N,15e3,d.tuiWaitController.signal);if(re(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&&ae(d.current),T},async resolvePluginInteraction(f,y,P,k){if(re(f),!Fi()?.has(y))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(f,y,P,k):d.interactions.resolve(f,y,P,k)},image(f,y,P){re(f);let E=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(H=>H.id===y);if(E?.type!=="message"||E.message.role!=="user"||!Array.isArray(E.message.content))return null;let _=E.message.content[P];return _?.type!=="image"?null:{data:Buffer.from(_.data,"base64"),mimeType:_.mimeType}},async workspaces(){return ia()},async addWorkspace(f,y){let P=await d.workspaces.add(f,y);try{await zr(P.id,!0)}catch(k){throw await ce(),k}},async selectWorkspace(f){await zr(f)},async newSessionInWorkspace(f){await zr(f,!0)},async removeWorkspace(f){if(f===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(f),await ce()},async selectSession(f,y,P){let k=d.workspaces?.get(f);if(!k)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ue(k.path),y===d.current?.sessionManager.getSessionId()&&k.path===await pt(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:le()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===y&&d.workspaceSessions.path===k.path)return;if(d.workspaceSessions?.hasSession(k.path,y))await d.workspaceSessions.open(k.path,{sessionId:y});else{if(!(await Nt(k.path)).some(_=>_.id===y&&_.path===P))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(k.path,{sessionFile:P})}d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:le()})}await ce()},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 y=f.scopedModels?.map(P=>`${P.model.provider}/${P.model.id}`)??[];return f.modelRegistry.getAvailable().filter(P=>y.length===0||y.includes(`${P.provider}/${P.id}`)).map(P=>({provider:P.provider,id:P.id,name:P.name}))},async providers(){let f=await Pt(),y=new Set((await f.listCredentials()).map(P=>P.providerId));return f.getProviders().map(P=>({id:P.id,name:P.name,configured:f.getProviderAuthStatus(P.id).configured,storedCredential:y.has(P.id),methods:[P.auth.apiKey?.login?"api_key":null,P.auth.oauth?"oauth":null].filter(k=>k!==null)}))},async providerModels(f){let y=await Pt();return cn(kt(Pe(),"models.json"),f,y)},async updateProviderModel(f,y,P){if(re(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=le().model;if(P.action==="remove"&&k===`${y}/${P.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(P.action==="save"&&P.originalId&&P.originalId!==P.model.id&&k===`${y}/${P.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let E=await Pt();await ln(kt(Pe(),"models.json"),y,P,E),await E.refresh({providers:[y],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[y],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[y],allowNetwork:!1});let _=P.action==="save"?P.model.id:P.action==="base_url"&&k?.startsWith(`${y}/`)?k.slice(y.length+1):null;if(_&&k===`${y}/${_}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(y,_)}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(y,_);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");ae(H)}},async logoutProvider(f,y){if(re(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=await Pt();if(!(await P.listCredentials()).some(k=>k.providerId===y))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await P.logout(y),await d.current?.modelRegistry.refresh({providers:[y],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[y],allowNetwork:!1})},async loginProvider(f,y,P){let k=await Pt();await k.login(f,y,tn(f,y,P)),await k.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,y){if(re(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=await Pt();if(P.getProvider(y.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await rn(kt(Pe(),"models.json"),y),await P.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(re(f),d.selected==="sdk"){let P=d.workspaceSessions?.session;if(!P||!P.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await P.compact(),d.bridge?.publish({type:"snapshot",session:le()});return}let y=he(f);if(!y.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");y.compact()},async setModel(f,y,P){if(re(f),d.selected==="sdk"){await d.workspaceSessions.setModel(y,P);return}let k=he(f);if(!k.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=k.modelRegistry.find(y,P);if(!E||!k.modelRegistry.getAvailable().some(_=>_.provider===y&&_.id===P))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(k)},async setThinkingLevel(f,y){if(re(f),!["off","minimal","low","medium","high","xhigh"].includes(y))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(y))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");E.setThinkingLevel(y),d.bridge?.publish({type:"snapshot",session:le()});return}let k=he(f);if(!k.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!k.model||!th(k.model).includes(y))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(y),ae(k)},config:sa,updateConfig:oh,async send(f,y,P=[],k,E){if(re(f),d.selected==="sdk"){await d.workspaceSessions.send(y,P,k,E);return}let _=he(f);if(je(Me(),y,E),E==="followUp"&&(!_.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(y,P,k),Lr();return}if(_.isIdle()&&d.tuiPrompts.sending)throw new ne("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await qr(f,y,P,k,E)},async updateQueuedPrompt(f,y,P,k){if(re(f),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(y,P,k);return}if(k.kind==="steer"&&he(f).isIdle())throw new ne("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(y,P,k,(E,_,H)=>qr(f,E,_,H,"steer"))},async abort(f){if(re(f),d.selected==="sdk")await d.workspaceSessions.stop();else{let y=he(f);if(y.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(Ct),y.abort()}},async resume(f,y){if(re(f),d.selected==="sdk"){await d.workspaceSessions.resume(y);return}let P=he(f);if(ft(()=>d.hosted?.adapter.assertAdmission(),y,(k,E)=>d.bridge?.reportError?.(k,E)),!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!P.model||!d.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!P.modelRegistry.hasConfiguredAuth(P.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");d.operation=y;try{d.pi.sendMessage(gi(le().messages),{triggerTurn:!0})}catch(k){throw d.operation=void 0,k}},async newSession(f){if(re(f),d.selected==="sdk"){let k=d.workspaces?.get(d.activeWorkspaceId??"");if(!k)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.open(k.path,"new"),await ce();return}let y=he(f);if(!y.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(y.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:le()}),await ce();return}if((await d.commandContext.newSession({withSession:async k=>{d.commandContext=k,d.replacementContext=k,d.replacementSessionId=k.sessionManager.getSessionId(),d.current=k}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await ce()}};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.newSession=d.lifecycle.wrap(m.newSession),m.updateConfig=d.lifecycle.wrap(m.updateConfig),d.bridge=await In(m,qt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let u=[],w=null;for(let m of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Ju).filter(Boolean))try{u.push(Yu(kt(It(m),"dist"),(f,y)=>{let P=String(y??"");["client.js","client.css"].includes(P)&&(w&&clearTimeout(w),w=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();w&&clearTimeout(w)}}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:Br}),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 yk=Bi;export{yk as default,Gu as verifySentryDisabledRelease,Yo as verifySentryNodeRelease};
46
+ `)}`:void 0,t<3&&s.cause instanceof Error&&(r.cause=Bn(s.cause,e,t+1)),lt(r)}import{randomUUID as zn}from"node:crypto";import{randomUUID as sd}from"node:crypto";import{EnvHttpProxyAgent as nd,getGlobalDispatcher as Um,setGlobalDispatcher as Lm}from"undici";var Un=s=>({httpProxy:s.http_proxy??s.HTTP_PROXY??s.all_proxy??s.ALL_PROXY??"",httpsProxy:s.https_proxy??s.HTTPS_PROXY??s.all_proxy??s.ALL_PROXY??"",noProxy:s.no_proxy??s.NO_PROXY??""});function od(s,e){let t=Un(s),i;try{i=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(i.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let r=t.noProxy.toLowerCase();if(r==="*")return!1;let n=Number(i.port)||(i.protocol==="https:"?443:80),o=i.hostname.toLowerCase();return!r.split(/[,\s]/).filter(Boolean).some(c=>{let a=c.match(/^(.+):(\d+)$/),l=(a?.[1]??c).replace(/^\*?\./,"");return(!a||Number(a[2])===n)&&(o===l||o.endsWith("."+l))})}function ad(s){let e=Un(s);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new nd(e)}function hr({env:s=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:i=!1}={}){let r,n=new Set,o=t===globalThis.fetch,c=(p,u)=>{try{e(p,u)}catch{}},a=p=>p?p.close().finally(()=>n.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let y={requestId:sd(),phase:"headers",proxied:o&&od(s,p)},m=i?void 0:r,f=!1,w=u?.signal??(p instanceof Request?p.signal:void 0),k=()=>P(),P=()=>{w?.removeEventListener("abort",k),!f&&i&&(f=!0,a(m).catch(()=>{}))},E;try{o?(m??=ad(s),n.add(m),i||(r=m),E=await t(p,{...u,dispatcher:m})):E=await t(p,u)}catch(T){throw c(T,y),P(),T}if(E.ok||c(void 0,{...y,status:E.status}),!E.body)return P(),E;let _=E.body.getReader();w?.addEventListener("abort",k,{once:!0}),w?.aborted&&P();let H=new ReadableStream({async pull(T){try{let Y=await _.read();Y.done?(T.close(),_.releaseLock(),P()):T.enqueue(Y.value)}catch(Y){c(Y,{...y,phase:"body"}),T.error(Y),_.releaseLock(),P()}},async cancel(T){try{await _.cancel(T)}finally{_.releaseLock(),P()}}}),N=new Response(H,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(N,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),N},close:async()=>{await Promise.all([...n].map(a))}}}var Ln=(s,e)=>hr({autoClose:!0}).fetch(s,e);var cd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),ld=s=>typeof s=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(s)?s:void 0;function fr(s,e={}){let t=[],i=new Set,r=(a,l=0)=>{if(!a||l>4||i.has(a)||t.length>=8)return;i.add(a);let p=ld(a.code);if(t.push({name:cd.has(a.name)?a.name:"Error",...p?{code:p}:{}}),r(a.cause,l+1),a instanceof AggregateError)for(let u of a.errors.slice(0,4))r(u,l+1)};r(s);let n=t.flatMap(a=>a.code?[a.code]:[]),o=e.stage==="model_admission"||n.some(a=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(a))?"lifecycle":n.some(a=>/CERT|TLS|SSL/.test(a))?"tls":n.some(a=>/^PROXY_/.test(a))||e.proxied&&n.some(a=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(a))?"proxy":n.some(a=>/TIMEOUT|ETIMEDOUT/.test(a))||t.some(a=>/TimeoutError$/.test(a.name))?"timeout":t.some(a=>a.name==="AbortError"||a.code==="ABORT_ERR"||a.code==="UND_ERR_ABORTED")?"cancelled":n.some(a=>/ENOTFOUND|EAI_AGAIN/.test(a))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",c=a=>typeof a=="string"&&/^[\w-]{1,80}$/.test(a)?a:void 0;return{errorId:zn(),requestId:c(e.requestId)??zn(),...c(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:o,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:t}}function qn({env:s=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return hr({env:s,fetchRequest:t,onFailure:(i,r)=>e(fr(i,{...r,stage:r.phase==="body"?"model_stream":"model_headers"}))})}function dd(s){let e={...process.env,...s};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])s&&t.toUpperCase()in s&&!(t in s)&&delete e[t];return e}var pd=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Gn(s,e,t=()=>{}){let i=s.agent.streamFunction;s.agent.streamFunction=async(r,n,o)=>{if(!pd.has(r.api))return i(r,n,o);let c=t(),a=qn({env:dd(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...c?{operationId:c}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await i(r,n,{...o,fetch:a.fetch});return l.result().finally(()=>a.close()).catch(()=>{}),l}catch(l){throw await a.close(),l}}}function gt(s,e,t){try{s()}catch(i){let r=fr(i,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...r})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:r.errorId,requestId:r.requestId,stage:r.stage,code:"hosted_admission_blocked",networkKind:r.kind,networkStage:r.stage,causeCodes:r.causes.flatMap(n=>n.code?[n.code]:[]).join(",")})}catch{}throw i}}var wd=["read","grep","find","ls"],Jn=200,wi=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Qe;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,i=()=>!1,r=()=>{},n={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},c=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=i,this.reportError=r,this.onSessionsChanged=o,this.customTools=c,this.offHosted=a?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return n.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{n.enabled()&&n.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return n.enabled()?n.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let i=await Ae(e),r=t==="continue"?this.selectedByWorkspace.get(i):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.sessionId):void 0;if(r){if(r.cwd!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(r);return}if(typeof t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let n;if(t==="new")n=Mt.create(i);else if(t==="continue"){let c=(await ht(i))[0];n=c?Mt.open(c.path):Mt.create(i)}else n="sessionManager"in t?t.sessionManager:Mt.open(t.sessionFile);if(await md(n.getCwd())!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(n.getSessionId());if(o){if(o.cwd!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(i,n,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await Ae(e));return!t||!this.blank(t)?!1:(this.activate(t),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:t,cwd:i,prompts:r}=e,n=t.sessionManager.getBranch(),o=n.flatMap(c=>{let a=Nt(c);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:i,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!r.sending,name:pi(t.sessionManager.getSessionName(),o),modified:n.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(t=>Nt(t)?.role==="user")}rename(e,t){let i=this.runtimes.get(e);if(!i||i.closing)return!1;if(i.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return i.session.setSessionName(t),!0}discard(e){return this.queue.run(async()=>{let t=this.runtimes.get(e);if(!t||t.closing)return null;if(t.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!t.session.isIdle||t.prompts.sending||t.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=this.active===t,r=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),i&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:r,cwd:t.cwd,wasActive:i}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,i,r){let n=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${i}: ${r}`;console.error(n),this.publishFor(e,{type:"error",message:n})}async replace(e,t,i,r){let n=this.runtimes.get(t.getSessionId()),o=await Ye.discover(e,this.isProjectTrusted(e)),c=hd(),a=await $n(e,o.extensionRoots),l=new fd({cwd:e,agentDir:gd(),noExtensions:!0,additionalExtensionPaths:a.paths,eventBus:c,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,t.getSessionId()))]:[]}),p=null;try{await l.reload();let u=l.getExtensions().errors;if(u.length)throw new Error(u.map(b=>`${b.path}: ${b.error}`).join("; "));let y=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:m}=await ud({cwd:e,sessionManager:t,model:y,resourceLoader:l,customTools:this.customTools}),f=new ft({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(b,v)=>this.telemetry.breadcrumb(b,v),anonymize:b=>this.telemetry.anonymize(b)}),w={session:m,cwd:e,catalog:o,bus:c,generation:++this.generation,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:f,streaming:null,prompts:null,detached:r?{owner:r,events:[],seq:0,lastText:"",restoreTools:null}:void 0};w.prompts=n?.prompts??new $e(()=>{let b=this.runtimes.get(t.getSessionId())??w;this.publishFor(b,{type:"snapshot",session:this.snapshotOf(b)}),!this.disposed&&!b.closing&&this.onSessionsChanged()}),p=w,Gn(m,b=>{w.networkDiagnostic=b},()=>w.operation?.operationId);let k=b=>this.publishFor(w,b),P=w.detached,E=(b,v)=>{P&&(P.events.push({seq:++P.seq,type:b,...v===void 0?{}:{text:v}}),P.events.length>Jn&&P.events.splice(0,P.events.length-Jn))};w.interactions=new ut(c,b=>!w.closing&&b.sessionId===m.sessionManager.getSessionId()&&o.has(b.pluginId),()=>k({type:"snapshot",session:this.snapshotOf(w)}));let _=0,H=c.on(hi,()=>k({type:"snapshot",session:this.snapshotOf(w)})),N=m.subscribe(b=>{if(P&&!w.closing&&(b.type==="message_end"&&b.message.role==="assistant"&&(b.message.stopReason==="error"?E("error",b.message.errorMessage??"Agent response failed"):P.lastText=b.message.content.flatMap(v=>v.type==="text"?[v.text]:[]).join(`
47
+ `)),b.type==="agent_settled"&&E("turn_end",P.lastText)),!this.disposed&&!w.closing){let v={...w.operation,session:this.telemetry.anonymize(m.sessionManager.getSessionId()),piVersion:mi,model:m.model?`${m.model.provider}/${m.model.id}`:null,thinkingLevel:m.thinkingLevel};if(b.type==="agent_start"&&this.telemetry.breadcrumb("agent_start",v),b.type==="tool_execution_start"&&f.start(b,v),b.type==="tool_execution_end"&&f.end(b,v),b.type==="message_end"&&b.message.role==="assistant"&&b.message.stopReason==="error"){w.agentErrorReported=!0;let $=w.networkDiagnostic,ye=this.reportError(new Error("Agent response failed"),{...w.operation,stage:"agent",code:"agent_failed",piVersion:mi,...$?{networkKind:$.kind,networkStage:$.stage,causeCodes:$.causes.flatMap(ve=>ve.code?[ve.code]:[]).join(","),requestId:$.requestId}:{}})??$?.errorId;k({type:"error",message:b.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:ye,...w.operation})}b.type==="message_end"&&b.message.role==="toolResult"&&f.message(b.message,v),b.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",v),f.clear(),w.operation=void 0)}b.type==="message_update"&&b.message.role==="assistant"&&(w.streaming={id:"stream",role:"assistant",timestamp:new Date(b.message.timestamp).toISOString(),blocks:Je(b.message.content)},Date.now()-_>=60&&(_=Date.now(),k({type:"stream",message:w.streaming}))),b.type==="agent_settled"&&this.scheduleQueued(w),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(b.type)&&((b.type==="message_end"&&b.message.role==="assistant"||b.type==="agent_settled")&&(w.streaming=null,k({type:"stream",message:null})),k({type:"snapshot",session:this.snapshotOf(w)}),!this.disposed&&!w.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(b.type)&&this.onSessionsChanged())});w.detach=()=>{H(),N()},w.releaseHosted=this.hosted?.adapter.attach(m);let T=[],Y=!0;if(await m.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Y&&T.push(b.error),this.diagnostic(w,o.plugins.find(v=>b.extensionPath.startsWith(v.root+"/"))?.id??b.extensionPath,b.event??"runtime",b.error)}}),Y=!1,T.length)throw new Error(T.join("; "));if(this.ensureAvailable(),n&&(!n.session.isIdle||n.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(n&&await this.close(n,i),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");w.detached&&(w.detached.restoreTools=m.getActiveToolNames(),m.setActiveToolsByName(wd)),this.runtimes.set(m.sessionManager.getSessionId(),w),p=null,w.detached?this.onSessionsChanged():this.activate(w)}catch(u){throw this.hosted?.adapter.releasePending(t.getSessionId()),p?await this.close(p,"quit"):(c.clear(),await a.release()),u}}async close(e,t){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await Wn(e.session,t,i=>this.diagnostic(e,"host","shutdown",i),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:i,catalog:r}=e,n=t.sessionManager.getBranch().flatMap(o=>{let c=Nt(o);return c?[c]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:i,name:pi(t.sessionManager.getSessionName(),n),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,paused:pt(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:n,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:or(t.sessionManager.getBranch(),r.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let i=t.session.extensionRunner,r=await fi(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||i!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),r}resolveInteraction(e,t,i,r){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,i,r)}async send(e,t=[],i,r){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let n=this.active;if(We(this.snapshot(),e,r),r==="followUp"&&(!n.session.isIdle||n.prompts.length>0)){n.prompts.enqueue(e,t,i),this.scheduleQueued(n);return}if(n.session.isIdle&&n.prompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(n,e,t,i,r)}async prompt(e,t,i,r,n){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");gt(()=>this.hosted?.adapter.assertAdmission(),r,this.reportError),We({...this.snapshotOf(e),idle:e.session.isIdle},t,n);let o=e.session,c=o.isIdle;c&&(e.operation=r,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...r,piVersion:mi});let a=!1,l,p,u=new Promise((y,m)=>{l=y,p=m});o.prompt(t,{images:i,streamingBehavior:n,preflightResult:y=>{y&&(a=!0,l())}}).then(()=>{a||l()}).catch(y=>{if(!a)p(y);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let m=this.reportError(Ne(y,"Agent response failed"),{...r,stage:"agent",code:"agent_failed",piVersion:mi});this.publishFor(e,{type:"error",message:y instanceof Error?y.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:m,...r})}});try{await u}catch(y){throw c&&(e.operation=void 0),y}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!pt(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,i,r)=>this.prompt(e,t,i,r))}async updateQueuedPrompt(e,t,i){let r=this.active;if(this.disposed||!r||r.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(i.kind==="steer"&&r.session.isIdle)throw new ae("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await r.prompts.update(e,t,i,(n,o,c)=>this.prompt(r,n,o,c,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Dt),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");gt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let i=t.session;if(!i.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!pt(i.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!i.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(i.modelRuntime.hasConfiguredAuth(i.model.provider)||await i.modelRuntime.checkAuth(i.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!pt(i.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let n=gi(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),i.sendCustomMessage(n,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let c=this.reportError(Ne(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:c,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let i=this.active;if(this.disposed||!i||i.closing||!i.session.isIdle||i.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=i.session.modelRuntime.getModel(e,t);if(!r)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await i.session.setModel(r),this.publishFor(i,{type:"snapshot",session:this.snapshotOf(i)})}createDetached(e,t,i){return this.queue.run(async()=>{this.ensureAvailable();let r=await Ae(e),n=Mt.create(r);return await this.replace(r,n,"new",t),this.runtimes.get(n.getSessionId()).session.setSessionName(i),n.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,i){let r=this.detachedRuntime(e);if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(i&&r.detached.restoreTools&&(r.session.setActiveToolsByName(r.detached.restoreTools),r.detached.restoreTools=null),!r.session.isIdle||r.prompts.length>0){r.prompts.enqueue(t,[],void 0),this.scheduleQueued(r);return}await this.prompt(r,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let i=this.detachedRuntime(e)?.detached;if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:i.events.filter(r=>r.seq>t),next:i.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as yd,mkdir as vd,rename as bd,unlink as kd}from"node:fs/promises";import{basename as Pd,join as Kn}from"node:path";var Id=s=>Kn(s,"pi-web","trash");async function Xn(s,e){let t=Id(e);await vd(t,{recursive:!0});let i=Kn(t,`${Date.now()}_${Pd(s)}`);try{await bd(s,i)}catch(r){let n=r.code;if(n==="ENOENT")return null;if(n!=="EXDEV")throw r;await yd(s,i),await kd(s)}return i}import{basename as gr,dirname as Sd}from"node:path";function Yn(s,e){let t=i=>e[i].map(r=>({name:i==="skills"&&gr(r.path).toLowerCase()==="skill.md"?gr(Sd(r.path)):gr(r.path),path:r.path,source:r.metadata.source,scope:r.metadata.scope,enabled:r.enabled}));return{packages:s.map(i=>({name:i.source,path:i.installedPath??"",source:i.source,scope:i.scope,enabled:!!i.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as Ed}from"node:child_process";var xd=(s,e)=>new Promise((t,i)=>{Ed(s,[...e],{windowsHide:!0},r=>{r?i(r):t()})});async function mr(s,e=process.platform,t=process.env,i=xd){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let r=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return r===null?!1:(await i(r,[s]),!0)}import{execFile as rp}from"node:child_process";import{randomUUID as bi}from"node:crypto";import{existsSync as go}from"node:fs";import{access as xr,mkdir as ki,mkdtemp as sp,readFile as ge,realpath as np,rename as _r,rm as $t,writeFile as Pi}from"node:fs/promises";import{dirname as mo,join as M}from"node:path";import{createHash as vr,randomUUID as Hd}from"node:crypto";import{mkdir as Od,readFile as Md,readdir as jd,realpath as ro}from"node:fs/promises";import{join as Re}from"node:path";import{constants as wr}from"node:fs";import{DatabaseSync as _d}from"node:sqlite";import{lstat as eo,mkdir as Ad,open as jt,rename as Td,unlink as to}from"node:fs/promises";import{dirname as Rd,join as Qn,resolve as Cd}from"node:path";import{randomUUID as Dd}from"node:crypto";import{setTimeout as Nd}from"node:timers/promises";async function Z(s){await Ad(s,{recursive:!0,mode:448});let e=await eo(s);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function X(s,e){let t;try{t=await jt(s,wr.O_RDONLY|wr.O_NONBLOCK|(wr.O_NOFOLLOW??0))}catch(i){if(Ve(i))return null;throw i}try{let i=await t.stat();if(!i.isFile()||i.nlink>1||i.size>e)throw new h("invalid_storage","Invalid storage record size or type");let r=Buffer.alloc(Math.min(i.size+1,e+1)),n=0;for(;n<r.length;){let o=await t.read(r,n,r.length-n,n);if(!o.bytesRead)break;n+=o.bytesRead}if(n>e||n!==i.size)throw new h("invalid_storage","Storage record changed during read");return r.subarray(0,n)}finally{await t.close()}}async function ee(s,e=2*1024*1024){let t=await X(s,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new h("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function ce(s){let e=await X(s,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new h("gc_recovery_required",`Invalid journal ${s}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new h("gc_recovery_required",`Invalid journal ${s}; original bytes preserved`);return t}async function j(s,e){let t=`${s}.${Dd()}.tmp`,i=await jt(t,"wx",384);try{try{await i.writeFile(JSON.stringify(e)),await i.sync()}finally{await i.close()}await Td(t,s);let r;try{r=await jt(Rd(s),"r"),await r.sync()}catch(n){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(n.code??""))throw n}finally{await r?.close()}}finally{await to(t).catch(()=>{})}}var io='{"version":2,"mechanism":"sqlite-exclusive"}',Zn=s=>s.toString("utf8")===io,yi=new Set;async function yr(s,e,t=0){await Z(s);let i=Qn(s,`${e}.lock`),r=Qn(s,`${e}.ownership.sqlite`),n=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new h(n,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await jt(r,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await eo(r);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new h("invalid_storage","Ownership database must be a small, single-link regular file");let l=new _d(r,{allowExtension:!1}),p=Cd(r),u=Date.now()+t,y=!1;try{for(;;){if(!yi.has(p))try{l.exec("BEGIN EXCLUSIVE"),yi.add(p),y=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=u)throw new h(n,"Another host owns this plugin storage; wait for it to stop before retrying");await Nd(10)}let f=await X(i,4096);if(f===null){let w;try{w=await jt(i,"wx",384),await w.writeFile(io),await w.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await w?.close()}f=await X(i,4096)}if(f===null||!Zn(f))throw o()}catch(f){throw l.close(),y&&yi.delete(p),f}let m=!1;return async()=>{if(m)return;let f=await X(i,4096);if(f===null||!Zn(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await to(i),l.close(),yi.delete(p),m=!0}}async function W(s,e,t=2e3){let i=await yr(s,"transaction",t);try{return await e()}finally{await i()}}var Ee=s=>Re(s,"host-pair"),te=s=>vr("sha256").update(JSON.stringify(s)).digest("hex");async function Wd(s){let e=vr("sha256"),t=0,i=0;async function r(n){let o=(await jd(Re(s,n),{withFileTypes:!0})).sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(let c of o){if(!n&&c.name==="node_modules")continue;let a=n?`${n}/${c.name}`:c.name;if(c.isSymbolicLink()||!c.isFile()&&!c.isDirectory())throw new h("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new h("host_pair_required","Candidate package resource budget exceeded");if(c.isDirectory()){await r(a);continue}let l=await X(Re(s,a),64*1024*1024);if(!l||(i+=l.length)>256*1024*1024)throw new h("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,vr("sha256").update(l).digest("hex")]))}}return await r(""),e.digest("hex")}async function Ze(s,e){let t=await ro(e),i=Re(e,"dist","hosted-worker.js");if(await ro(i)!==Re(t,"dist","hosted-worker.js"))throw new h("host_pair_required","Candidate worker must remain inside the staged host");let r=await X(Re(e,"package.json"),512*1024);if(!r)throw new h("host_pair_required","Candidate package metadata missing");let n=JSON.parse(r.toString("utf8")),o=n.piWebappHostedRuntime;if(n.name!=="pi-webapp"||n.version!==s||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(a=>o.capabilities.includes(a)))throw new h("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let c=await X(i,32*1024*1024);if(!c)throw new h("host_pair_required","Candidate worker missing");return te([r.toString("base64"),c.toString("base64"),await Wd(e)])}async function Oe(s){let e=await ce(Re(Ee(s),"intent.json"));if(e&&(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||typeof e.packageRoot!="string"||!/^[a-f0-9]{64}$/.test(e.hostDigest)||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!Array.isArray(e.selections)||e.selections.some(t=>!t||typeof t.id!="string"||typeof t.version!="string"||!/^[a-f0-9]{64}$/.test(t.digest)||!Object.hasOwn(t,"before"))||e.selection&&(typeof e.selection.path!="string"||!/^[a-f0-9]{64}$/.test(e.selection.digest))||!["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(e.phase)))throw new h("host_pair_required","Invalid host pair journal; preserve data and inspect intent.json with all owners stopped");if(e){let{lifecyclePhase:t,...i}=e;e={...i,phase:i.phase==="selected"&&t==="restart-requested"?"restart-requested":i.phase==="reconciled"&&t==="cancelled"?"cancelled":i.phase}}return e}async function Te(s,e){let{lifecyclePhase:t,...i}=e,r=i.phase==="cancelled"?{...i,phase:"reconciled",lifecyclePhase:"cancelled"}:i.phase==="restart-requested"?{...i,phase:"selected",lifecyclePhase:"restart-requested"}:i;await j(Re(Ee(s),"intent.json"),r)}var mt=s=>s&&!["prepared","reconciled","cancelled"].includes(s.phase);async function Wt(s){let e=await Oe(s);if(e&&mt(e))throw new h("host_pair_required",`Host pair selection pending (${e.version}, ${e.phase}): ${e.message??"restart selected host, or stop all owners and inspect host-pair/intent.json"}; data retained`)}function so(s,e,t,i=async()=>{}){let r=async o=>{let c=Re(Ee(s),"history");await Od(c,{recursive:!0,mode:448}),await j(Re(c,`${o.id}.json`),o)},n=async(o,c,a)=>{let l=await Ze(o,c),p=te(await t()),u=await e(o,a);if(a?.throwIfAborted(),te(await t())!==p)throw new h("host_pair_changed","Plugin policy/activation changed during preflight; recheck update");return await i(o,u),{schema:1,id:Hd(),phase:"prepared",version:o,packageRoot:c,hostDigest:l,fingerprint:p,selections:u}};return{status:()=>Oe(s),stage:(o,c,a)=>W(Ee(s),async()=>{await Wt(s);let l=await Oe(s);l&&await r(l.phase==="prepared"?{...l,phase:"cancelled",message:"Superseded before version selection; no code or data changed"}:l),await Te(s,await n(o,c,a))}),cancel:(o,c,a)=>W(Ee(s),async()=>{let l=await Oe(s);if(!l||l.phase==="cancelled"||l.phase==="reconciled")return;if(o&&l.version!==o||c&&l.packageRoot!==c)throw new h("host_pair_changed","Another update owns this transaction");if(mt(l)&&!a)throw new h("host_pair_required","Selected update requires its owned pointer recovery receipt before cancellation");await a?.();let p={...l,phase:"cancelled",message:"Update cancelled; current runtime and plugin data retained"};await Te(s,p),await r(p)}),select:(o,c,a)=>W(Ee(s),async()=>{await Wt(s);let l=await Oe(s),p=l?.phase==="prepared"&&l.version===o&&l.packageRoot===c&&l.fingerprint===te(await t())?l:await n(o,c),{hostDigest:u,selections:y}=p,m=p.fingerprint;if(await Te(s,p),await i(o,y),await Ze(o,c)!==u||te(await t())!==m)throw await Te(s,{...p,phase:"required-action",message:"Preflight changed; host pointer not written"}),new h("host_pair_changed","Preflight changed; host pointer not written");await Te(s,{...p,phase:"selecting"});let f=await a();await Te(s,{...p,phase:"selected",...f?{selection:f}:{}})}),restart:(o,c,a)=>W(Ee(s),async()=>{let l=await Oe(s);if(!l||l.phase!=="selected"||l.version!==o||l.packageRoot!==c||l.hostDigest!==await Ze(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed; restart refused, inspect pair journal");if(l.selection&&te((await Md(l.selection.path)).toString("base64"))!==l.selection.digest)throw new h("host_pair_changed","Host selection pointer changed; restart refused");if(await i(o,l.selections),l.hostDigest!==await Ze(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed during restart validation");await Te(s,{...l,phase:"restart-requested",message:"Restart authorized; awaiting launcher receipt and selected host health admission"}),await a()})}}import{promisify as op}from"node:util";import{realpathSync as ao,statSync as $d}from"node:fs";import{basename as Vd,delimiter as Fd,dirname as no,join as br,resolve as Bd}from"node:path";function oo(s){if(!s)return null;try{let e=ao(s);return Vd(e)==="npm-cli.js"&&$d(e).isFile()?e:null}catch{return null}}function Ud({execPath:s=process.execPath,env:e=process.env}={}){let t=oo(e.npm_execpath);if(t)return t;let i=new Set([no(s)]);try{i.add(no(ao(s)))}catch{}let r=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of r.split(Fd).filter(Boolean))i.add(Bd(n));for(let n of i)for(let o of[br(n,"node_modules","npm","bin","npm-cli.js"),br(n,"..","lib","node_modules","npm","bin","npm-cli.js"),br(n,"npm")]){let c=oo(o);if(c)return c}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function co(s){return{file:process.execPath,args:[Ud(),...s]}}import{readFile as Ld,rename as zd,writeFile as qd,unlink as Gd}from"node:fs/promises";import{join as Jd}from"node:path";import{randomUUID as Kd}from"node:crypto";var kr=1,lo=s=>Jd(s,"pi-web","launcher-handoff.json");function po(s){return s?.protocol===kr&&typeof s.nonce=="string"&&s.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(s.requestId)&&Number.isSafeInteger(s.pid)&&s.pid>0&&["requested","draining","stopped","refused","failed"].includes(s.phase)}async function Pr(s){try{let e=JSON.parse(await Ld(lo(s),"utf8"));if(!po(e))throw new Error("Invalid launcher handoff journal; original data retained");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Xd(s,e){let t=`${s}.${Kd()}.tmp`;try{await qd(t,JSON.stringify(e),{mode:384}),await zd(t,s)}finally{await Gd(t).catch(()=>{})}}async function uo(s,e){if(!po(e))throw new Error("Invalid launcher handoff receipt");await Xd(lo(s),e)}import{execFile as Yd}from"node:child_process";import{cp as Qd,readFile as Ir,realpath as Zd,rm as ep}from"node:fs/promises";import{join as wt,sep as tp}from"node:path";import{promisify as ip}from"node:util";var ho=ip(Yd),Sr=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Er(s){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=s;return Sr.map(t=>{let i=e[t];if(typeof i!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(i))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${i}`})}async function vi(s){return Promise.all(Sr.map(async e=>{let t=await dt(s,e),i=JSON.parse(await Ir(wt(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(i.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${i.version}`}))}async function fo(s,e){let t=JSON.parse(await Ir(wt(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let i=t.peerDependencies===void 0?await vi(s):Er(t.peerDependencies);if(JSON.stringify(await vi(e))!==JSON.stringify(i))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let r=await dt(s,"node-pty"),n=await dt(e,"node-pty"),o=await Zd(wt(e,"../.."));if(r===n||!n.startsWith(o+tp))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let c=async u=>JSON.parse(await Ir(wt(u,"package.json"),"utf8")).version;if(await c(r)!==await c(n))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await ep(n,{recursive:!0,force:!0}),await Qd(r,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await ho(process.execPath,[wt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await dt(e,Sr[0]),{stdout:p}=await ho(process.execPath,[wt(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:a,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==i[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}var ap=op(rp);function wo(s){let e=s.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function cp(s,e){try{let t=co(s),{stdout:i}=await ap(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return i}catch(t){let i=t;throw new Error(i.stderr?.trim()||i.message)}}var Ii=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;validateHostedPair;hostedPair;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??cp,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let i=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!i)return vi(this.packageRoot);let r=JSON.parse(i),n=Array.isArray(r)&&r.length===1?r[0]:r;return Er(n)},this.verifyPackage=e.verifyPackage??fo,this.validateHostedPair=e.validateHostedPair,this.hostedPair=e.hostedPair,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?kr:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let i=await this.transaction();if(i&&!["committed","cancelled","failed"].includes(i.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let r=M(this.agentDir,"pi-web","launcher.json"),n=JSON.parse(await ge(r,"utf8")),o=p=>p.nonce===e&&p.pid===n.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(n))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let c=await Pr(this.agentDir);if(c?.nonce===e&&["requested","draining"].includes(c.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let a,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(a=await this.beforeRestart(),!o(JSON.parse(await ge(r,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:n.pid,phase:"requested"};try{await uo(this.agentDir,p),l=!0}catch(u){let y=await Pr(this.agentDir).catch(()=>null);if(l=y?.nonce===e&&y?.requestId===t&&["requested","draining","stopped"].includes(y.phase),!l)throw u}this.restartPending=!0}finally{!l&&a&&await a()}}async current(){let e=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Fe(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();return t?.phase==="restart-requested"&&t.version===e&&(!this.hostedPair||(await this.hostedPair.status?.())?.phase==="reconciled")&&await this.record({...t,phase:"committed",message:"Selected host is running and hosted protocol health admission completed"}),e}get transactionPath(){return M(this.agentDir,"pi-web","update-transaction.json")}async transaction(){try{let e=await ce(this.transactionPath);if(!e)return null;if(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||e.selectionPath!==M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json")||e.selectedDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.selectedDigest)||e.before!==void 0&&e.before!==null&&(typeof e.before!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.before)))throw new Error("\u66F4\u65B0\u4E8B\u52A1\u8BB0\u5F55\u65E0\u6548\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u8BCA\u65AD");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async record(e){if(await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await j(this.transactionPath,e),["failed","cancelled","committed"].includes(e.phase)){let t=M(this.agentDir,"pi-web","update-history");await ki(t,{recursive:!0}),await j(M(t,`${e.id}-${e.phase}.json`),e)}}async admittedFallback(e,t){if(!e.ownerNonce||!this.launcherNonce||e.ownerNonce===this.launcherNonce||e.before===void 0)return!1;let i=t??await this.current();if(e.version===i)return!1;try{let r=await ce(M(this.agentDir,"pi-web","launcher.json"));if(r?.nonce!==this.launcherNonce||r.version!==i||r.piPid!==process.pid)return!1;let n;try{n=(await ge(e.selectionPath)).toString("base64")}catch(o){if(o.code!=="ENOENT")return!1;n=null}return n===e.before}catch{return!1}}async admittedLegacyRecovery(e){if(!this.launcherNonce)return!1;try{let t=await ce(M(this.agentDir,"pi-web","launcher.json"));if(t?.nonce!==this.launcherNonce||t.piPid!==process.pid||t.version!==(e??await this.current()))return!1;try{return await xr(M(this.agentDir,"pi-web","launcher.restart")),!1}catch(i){return i.code==="ENOENT"}}catch{return!1}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction();if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();if(r&&!["cancelled","reconciled","prepared"].includes(r.phase)){if(!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u9700\u8981\u5F53\u524D\u540E\u53F0\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E14\u4E0D\u80FD\u4E2D\u65AD\u542F\u52A8\u5668\u5DF2\u63A5\u53D7\u7684\u4EA4\u63A5");let n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");if(!r.selection||r.selection.path!==n)throw new Error("\u65E7\u5347\u7EA7\u4E8B\u52A1\u7F3A\u5C11\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u6062\u590D\u8BCA\u65AD");let o=await ge(n);if(te(o.toString("base64"))!==r.selection.digest)throw new Error("\u65E7\u5347\u7EA7\u9009\u62E9\u5DF2\u53D8\u5316\uFF0C\u6062\u590D\u672A\u8986\u76D6\u5176\u4ED6\u64CD\u4F5C");let c=JSON.parse(o.toString("utf8")),a=await this.current(),l=M(this.packageRoot,"bin","pi-webapp.mjs");await xr(l);let p=c.previous?.version===a&&c.previous.launcher===l?c.previous:this.desktopManaged?await di(this.agentDir,{version:a,launcher:l,desktopProtocolVersion:Be}):{version:a,launcher:l,baseVersion:c.baseVersion??a};e={schema:1,id:r.id,phase:"selected",version:r.version,channel:await this.channel(),packageRoot:r.packageRoot,selectionPath:n,before:Buffer.from(JSON.stringify(p)).toString("base64"),selectedDigest:r.selection.digest,ownerNonce:this.launcherNonce,legacyRecovery:!0},await this.record(e)}else r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot)}if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot),this.preparedUpdate=void 0,this.restartPending=!1;return}if(e.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u540E\u53F0\u5F52\u5C5E\u6216\u4EA4\u63A5\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u8BF7\u4ECE\u5F53\u524D\u8FD0\u884C\u5B9E\u4F8B\u6062\u590D");if(e.phase==="restart-requested"&&!await this.admittedFallback(e))throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u5F53\u524D\u5165\u53E3\u6CA1\u6709\u5DF2\u786E\u8BA4\u56DE\u9000\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E0D\u80FD\u53D6\u6D88\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B\u7684\u4EA4\u63A5");let t=e,i=async()=>{if(t.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u5F52\u5C5E\u6216\u4EA4\u63A5\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(t.phase==="restart-requested"&&!await this.admittedFallback(t))throw new Error("\u91CD\u542F\u4EA4\u63A5\u7684\u5F52\u5C5E\u6216\u56DE\u9000\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(!t.selectedDigest)return;let r;try{r=await ge(t.selectionPath)}catch(n){if(n.code!=="ENOENT")throw n;r=null}if((r?.toString("base64")??null)!==t.before){if(!r||te(r.toString("base64"))!==t.selectedDigest)throw new Error("\u7248\u672C\u9009\u62E9\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u66F4\u6539\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u8BE5\u9009\u62E9\uFF1B\u5F53\u524D\u6570\u636E\u5DF2\u4FDD\u7559");if(t.before===null)await $t(t.selectionPath);else if(typeof t.before=="string"){let n=`${t.selectionPath}.${bi()}.tmp`;try{await Pi(n,Buffer.from(t.before,"base64"),{mode:384}),await _r(n,t.selectionPath)}finally{await $t(n,{force:!0})}}else throw new Error("\u7F3A\u5C11\u65E7\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u4E0D\u80FD\u81EA\u52A8\u6062\u590D\uFF1B\u8BF7\u4FDD\u7559\u4E8B\u52A1\u8BB0\u5F55")}};this.hostedPair?.cancel?await this.hostedPair.cancel(e.version,e.packageRoot,i):await W(M(this.agentDir,"pi-web","update-control"),i),await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0,this.restartPending=!1}get preferencePath(){return M(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ge(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${bi()}.tmp`;try{await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await Pi(t,JSON.stringify({channel:e}),{mode:384}),await _r(t,this.preferencePath)}finally{this.savingPreference=!1,await $t(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),i=go(M(this.packageRoot,".git")),r={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!i};this.desktopManaged&&(r.launcher=this.launcherIdentity(),r.launcherHandoff={supported:r.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(r.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let n=await this.transaction(),o=await this.hostedPair?.status?.();if(n&&!["failed","cancelled","committed"].includes(n.phase)?r.recovery={version:n.version,phase:n.phase,canCancel:n.legacyRecovery?await this.admittedLegacyRecovery(e):n.phase!=="restart-requested"||await this.admittedFallback(n,e)}:o&&!["cancelled","reconciled"].includes(o.phase)&&(r.recovery={version:o.version,phase:o.phase,canCancel:o.phase==="prepared"||await this.admittedLegacyRecovery(e)}),this.desktopManaged&&!this.desktopPackageUpdates)return{...r,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...r,canRestart:!1,reason:r.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};i?r.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":r.canRestart||(r.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&r.canRestart&&(r.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let c=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),a=Array.isArray(c)&&c.length===1?c[0]:c,l=t==="alpha"?a:{latest:a};if(!l||!wn(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let p=l.latest;if(t==="alpha"&&l.alpha!==void 0){if(!ai(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ue(l.alpha,p)>0&&(p=l.alpha)}r.latest=p,r.downgrade=ue(p,e)<0,r.available=t==="stable"?ue(p,e)!==0:ue(p,e)>0,this.desktopManaged&&r.downgrade&&!this.desktopReleaseChannels&&ue(p,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(r.canRestart=!1,r.requiresDesktopUpgrade=!0,r.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(c){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${c instanceof Error?c.message:String(c)}`)}return r}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(go(M(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let i=M(this.agentDir,"pi-web","releases");await ki(i,{recursive:!0});let r=await sp(M(await np(i),`${t.latest}-`)),n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:bi(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:n,ownerNonce:this.launcherNonce};await this.record(o);let c=!1;try{let a=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...a,"--prefix",r,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=M(r,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:l},await this.record(o);let p=JSON.parse(await ge(M(l,"package.json"),"utf8"));if(p.name!=="pi-webapp"||p.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let u=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&wo(p)!==wo(u))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let y=M(l,"bin","pi-webapp.mjs");await Promise.all([y,M(l,"dist","extension.js"),M(l,"web","dist","index.html")].map(w=>xr(w))),await this.validateHostedPair?.(t.latest,l);let m=this.desktopManaged?await di(this.agentDir,{version:t.latest,launcher:y,desktopProtocolVersion:Be}):null;this.desktopManaged&&await this.verifyPackage(this.packageRoot,l);let f=async()=>{let w;try{w=await ge(n)}catch(P){if(P.code!=="ENOENT")throw P;w=null}if(o={...o,phase:"selecting",before:w?.toString("base64")??null},await this.record(o),c=!0,this.desktopManaged){let P=m,E=await bn(this.agentDir,t.current),_=E?.version===t.current?E:null,H=process.env.PI_WEBAPP_DESKTOP_VERSION??E?.fallbackVersion??t.current,N={...P,...t.downgrade||E?.fallbackVersion?{fallbackVersion:H}:{},..._?{previous:_}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(N)).toString("base64"))},await this.record(o),await kn(this.agentDir,N)}else{let P=M(this.agentDir,"pi-web"),E=M(P,`update.${bi()}.tmp`);try{let _;try{_=JSON.parse(await ge(M(P,"update.json"),"utf8"))}catch{}let H=_?.baseVersion??t.current,N=_?.version===t.current?_:void 0;N&&delete N.previous;let T={version:t.latest,launcher:y,baseVersion:H,...t.downgrade||_?.allowDowngrade===!0?{allowDowngrade:!0}:{},...N?{previous:N}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(T)).toString("base64"))},await this.record(o),await Pi(E,JSON.stringify(T),{mode:384}),await _r(E,M(P,"update.json"))}finally{await $t(E,{force:!0})}}let k=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");return{path:k,digest:te((await ge(k)).toString("base64"))}};return this.hostedPair?.stage&&await this.hostedPair.stage(t.latest,l,this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted(),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={update:{version:t.latest,launcher:y},channel:t.channel??"stable",select:async()=>{this.hostedPair?await this.hostedPair.select(t.latest,l,f):await W(M(this.agentDir,"pi-web","update-control"),f),o={...o,phase:"selected"},await this.record(o)}},{version:t.latest,launcher:y}}catch(a){throw c||await $t(r,{recursive:!0,force:!0}),await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":"\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),a}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let t,i=!1;try{t=await this.beforeRestart?.(),await this.preparedUpdate?.select();let r=async()=>{let n=M(this.agentDir,"pi-web","launcher.restart"),o=await this.transaction();o&&await this.record({...o,phase:"restart-requested"});try{await Pi(n,JSON.stringify({nonce:this.launcherNonce,launcher:e.launcher}),{mode:384,flag:"wx"}),i=!0}catch(c){try{let a=JSON.parse(await ge(n,"utf8"));i=a.nonce===this.launcherNonce&&a.launcher===e.launcher}catch{}if(!i)throw c}};this.hostedPair?await this.hostedPair.restart(e.version,mo(mo(e.launcher)),r):await r(),this.restartPending=!0}catch(r){if(i){this.restartPending=!0;return}this.restartPending=!1;let n=await this.transaction();n?.phase==="restart-requested"&&await this.record({...n,phase:"selected",message:"Restart marker was not accepted; reverting owned selection"});let o=this.preparedUpdate;try{await this.cancel(),this.preparedUpdate=o}finally{t&&await t()}throw r}}};import{createHash as ta,randomUUID as ph}from"node:crypto";import{randomUUID as $u}from"node:crypto";import{access as Vu}from"node:fs/promises";import{join as ji}from"node:path";import{randomUUID as bo}from"node:crypto";import{randomUUID as lp}from"node:crypto";function yo(s){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof s[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let i=`__pi_web_contract_${lp().replaceAll("-","")}`,r;try{if(r=s.getActiveTools(),!Array.isArray(r))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let n={name:i,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{s.registerTool(n),s.setActiveTools([...r,i]),(s.getAllTools().find(c=>c.name===i)?.exposure!=="hidden"||s.getActiveTools().includes(i))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};s.registerTool({...n,parameters:o}),s.getAllTools().find(c=>c.name===i)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{s.setActiveTools(r)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var dp;function vo(){return dp??=pp().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function pp(){let{createAgentSession:s,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:i}=await import("@earendil-works/pi-ai"),{mkdtemp:r,rm:n}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:c}=await import("node:path"),a=await r(c(o(),"pi-sdk-contract-")),l,p=[],u=0,y=0,m=!1,f=!1;try{let w=(N,T,Y)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:T,parameters:{type:"object",properties:{}},execute:Y}),k=()=>({content:[],details:void 0}),P=new e({cwd:a,agentDir:a,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[N=>{N.on("tool_call",T=>{if(T.toolName==="__contract_direct"&&(m=!!T.parentToolCallId),T.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let T of["hidden","model-only"])N.registerTool(w(`__contract_${T.replace("-","_")}`,T,async()=>(y++,k())));N.registerTool(w("__contract_protected","direct",async()=>(y++,k()))),N.registerTool(w("__contract_direct","direct",async()=>(u++,k()))),N.registerTool(w("__contract_driver","direct",async(T,Y,b,v,$)=>{let ye=await $.executeTool("__contract_hidden",{}),ve=await $.executeTool("__contract_model_only",{}),se=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!ye.isError||!ve.isError)&&p.push("nested-tool-exposure"),(se.isError||u!==1)&&p.push("nested-tool-execution"),(!x.isError||y!==0)&&p.push("nested-tool-permission-guard"),m||p.push("nested-parent-identity"),f=!0,k()}))}]});await P.reload(),{session:l}=await s({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:P}),await l.bindExtensions({mode:"print"});let E=l.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(E);let _=0;l.agent.streamFunction=async N=>{let T=_++===0,Y={role:"assistant",api:N.api,provider:N.provider,model:N.id,timestamp:Date.now(),content:T?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:T?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},b=i();return b.push({type:"start",partial:Y}),b.push({type:"done",reason:T?"toolUse":"stop",message:Y}),b.end(Y),b};let H;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((N,T)=>{H=setTimeout(()=>T(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(H)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await n(a,{recursive:!0,force:!0})}}var Si=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=vo().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(i=>i.compatible===!1||!i.busy)),new Promise((i,r)=>{t=setTimeout(()=>r(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(i){throw this.thaw(),i}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let i=this.install(e,t);i.ready=!0;try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}install(e,t){let i={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(i),typeof e.on!="function")return i.compatible=!1,i.missing=["on"],i;let r=n=>{if(typeof n!="function")throw new Error("SDK event subscription cannot be released");i.handlers.push(n)};try{r(e.on("before_agent_start",async()=>{for(;this.frozen&&i.compatible!==!1&&!i.busy&&!i.disposed;)await new Promise(n=>this.waiters.add(n));if(i.disposed)throw new Error("Hosted session disposed");i.busy=i.compatible!==!1})),r(e.on("agent_settled",()=>{i.busy=!1,this.notify()})),r(e.on("tool_call",n=>{let o=i.owned.get(n.toolName);if(!o)return;let c=this.descriptors.get(o)?.find(a=>a.name===n.toolName);if(!c||!this.allowed(i,o,c,!!n.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),r(e.on("session_start",()=>{i.ready=!0,this.publish(i)})),r(e.on("session_shutdown",()=>this.release(i)))}catch{for(let n of i.handlers)try{n()}catch{}i.handlers=[],i.compatible=!1,i.missing=["hosted-lifecycle-events"]}return i}attach(e){let t=[...this.bindings].find(i=>i.scope.sessionId===e.sessionManager.getSessionId()&&!i.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(i=>{i.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(i){throw this.release(t),i}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,i,r=!1){let n=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&n.enabled&&(!n.allowlist||n.allowlist.includes(i.name))&&(!n.planMode||i.readonly===!0)&&(!r||n.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(r=>r.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let i=structuredClone(t);this.validateChange(e,i),this.descriptors.set(e,i);for(let r of this.bindings)r.ready&&this.publish(r)}validateChange(e,t){for(let r of this.bindings)if(r.compatible!==!1)for(let[n,o]of r.owned)this.assertOwner(r,o,n);let i=new Set;for(let r of t){if(!r.name||!r.action||!r.parameters||r.parameters.type!=="object"||i.has(r.name))throw new Error("Invalid hosted tool descriptor");i.add(r.name);for(let[n,o]of this.descriptors)if(n!==e&&o.some(c=>c.name===r.name))throw new Error(`Hosted tool ownership conflict: ${r.name}`);for(let n of this.bindings)n.compatible!==!1&&this.assertOwner(n,e,r.name)}}assertOwner(e,t,i){let r=e.owned.get(i);if(r&&r!==t)throw new Error(`Hosted tool ownership conflict: ${i}`);let n=e.pi.getAllTools().find(o=>o.name===i);if(n&&(!r||n.parameters!==e.definitions.get(i)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${i}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let i=yo(e.pi);e.compatible=i.supported,e.missing=i.missing}if(!e.compatible)return;for(let[i,r]of e.owned)this.assertOwner(e,r,i);for(let[i,r]of this.descriptors)for(let n of r)this.assertOwner(e,i,n.name);let t=new Set;for(let[i,r]of this.descriptors)for(let n of r){if(e.owned.set(n.name,i),!this.allowed(e,i,n))continue;t.add(n.name);let o=this.service.policy(i,e.scope),c=o.exposure??"direct",a=!o.allowNested&&c==="direct"?"model-only":c,l={name:n.name,label:n.label,description:n.description,parameters:structuredClone(n.parameters),exposure:a,execute:async(p,u,y)=>{if(!this.allowed(e,i,n))throw new Error("Hosted tool denied by host policy");return this.service.invoke(i,{requestId:bo(),scope:{...e.scope},kind:"tool",action:n.action,input:u},y)}};e.pi.registerTool(l),e.definitions.set(n.name,l)}for(let i of e.owned.keys())if(!t.has(i)){let r={name:i,label:i,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:up};e.pi.registerTool(r),e.definitions.set(i,r)}e.pi.setActiveTools(e.pi.getActiveTools().filter(i=>{let r=e.definitions.get(i);return!r||r.exposure==="direct"||r.exposure==="model-only"}))}async invokeAction(e,t,i,r,n){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(c=>c.scope.sessionId===t.sessionId&&c.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:bo(),scope:t,kind:"action",action:i,input:r},n)}};async function up(){throw new Error("Hosted tool unavailable")}import{randomBytes as uu,randomUUID as hu,timingSafeEqual as fu}from"node:crypto";import{join as Pe}from"node:path";var hp=30,ko=/^[a-z][a-z0-9-]{0,63}$/,fp=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Vt=s=>{throw new h("invalid_package",s)},Ar=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?Vt(`Invalid ${e} declaration`):s;function yt(s){let e=s&&typeof s=="object"?s:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),i=t.has("secrets")?Ar(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&ko.test(a)?a:Vt("Invalid secret name")}):[],r=e.network,n=t.has("network")?Ar(r?.hosts,"network").map(c=>typeof c=="string"&&fp.test(c)?c:Vt("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Ar(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!ko.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<hp||a.intervalSec>86400?Vt("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&Vt("Duplicate schedule id"),{secrets:i,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as gp}from"node:dns/promises";import{isIP as mp}from"node:net";var wp=new Set(["GET","POST","PATCH","PUT","DELETE"]),yp=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),vp=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Ei=(s,e)=>{throw new h("network_denied",s,{status:403,reason:e})};function bp(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if(mp(e)===4){let[t,i]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&i===254||t===172&&i>=16&&i<=31||t===192&&i===168||t===100&&i>=64&&i<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function Po(s,e,t,i,r){let n=i;if(!n||typeof n!="object"||typeof n.url!="string")throw new h("invalid_input","Invalid network request");let o;try{o=new URL(n.url)}catch{throw new h("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Ei("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Ei("Host is not declared by the plugin","host");let c=(n.method??"GET").toUpperCase();if(!wp.has(c))throw new h("invalid_input","Unsupported method");if(n.body!==void 0&&(typeof n.body!="string"||n.body.length>1024*1024))throw new h("invalid_input","Invalid body");let a={};for(let[E,_]of Object.entries(n.headers??{})){if(typeof _!="string"||yp.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(_))throw new h("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=_}let l=null;if(n.secret!==void 0){if(t.includes(n.secret)||Ei("Secret is not declared by the plugin","secret"),l=await r.secrets.get(s,n.secret),!l)throw new h("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(r.resolve??(async E=>(await gp(E,{all:!0})).map(_=>_.address)))(o.hostname);(!p.length||p.some(bp))&&Ei("Host resolves to a non-public address","address");let u=r.timeoutMs??2e4,y=r.maxResponseBytes??2*1024*1024,m=await(r.fetch??fetch)(o,{method:c,headers:a,body:n.body,redirect:"manual",signal:AbortSignal.timeout(u)}),f=[],w=0;if(m.body)for await(let E of m.body){if(w+=E.byteLength,w>y)throw new h("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let k=Buffer.concat(f).toString("utf8"),P={};return m.headers.forEach((E,_)=>{vp.has(_.toLowerCase())&&(P[_.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:m.status,headers:P,body:k}}var xi=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new h("invalid_input",`Invalid ${t}`);return s};async function Io(s,e,t,i,r,n){let o=r&&typeof r=="object"&&!Array.isArray(r)?r:{};if(i==="sessions.create"){if(o.mode!=="plan")throw new h("invalid_input","Plugin sessions must start in plan mode");if(s.activeCount(e)>=n)throw new h("quota_exceeded","Too many active plugin sessions",{status:429});return s.create({pluginId:e,cwd:t,title:xi(o.title,200,"title"),prompt:xi(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=xi(o.sessionId,200,"sessionId");if(s.ownerOf(c)!==e)throw new h("session_denied","Session was not created by this plugin",{status:403});switch(i){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new h("invalid_input","Invalid mode");return await s.send(c,xi(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await s.release(c),{ok:!0};case"sessions.abort":return await s.abort(c),{ok:!0};case"sessions.events":return s.events(c,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new h("method_denied","Unknown sessions method")}}var kp=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),_i=class{options;constructor(e){this.options=e}handles(e){return kp.has(e)}async call(e,t,i,r,n){let o=yt(t);if(r==="network.fetch"){if(!o.networkHosts.length)throw new h("capability_denied","Plugin did not declare network access",{status:403});return Po(e,o.networkHosts,o.secrets,n,this.options)}if(!o.sessions||!this.options.sessions)throw new h("capability_denied","Sessions capability is unavailable",{status:403});return Io(this.options.sessions,e,i.scope.cwd,r,n,this.options.maxActiveSessions??3)}};var Ai=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let i=this.deps.setInterval??((r,n)=>{let o=setInterval(r,n);return o.unref(),o});this.timers.set(e,t.map(r=>i(()=>{this.tick(e,r)},r.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(i=>clearInterval(i));for(let i of this.timers.get(e)??[])t(i);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let i=`${e}\0${t.id}`;if(this.running.has(i))return!1;this.running.add(i);try{return await this.deps.invoke(e,t),!0}catch(r){return this.deps.onError?.(e,t,r),!1}finally{this.running.delete(i)}}};import{createHash as Or,timingSafeEqual as Up}from"node:crypto";import{lstat as Ho,mkdtemp as Hr,readdir as Lp,readFile as zp,realpath as qp,rename as Gp,rm as ze,writeFile as Jp}from"node:fs/promises";import{tmpdir as Kp}from"node:os";import{join as U}from"node:path";import{gunzipSync as Ap}from"node:zlib";import{mkdir as Tp,writeFile as Rp}from"node:fs/promises";import{dirname as Cp,join as Dp}from"node:path";import{constants as Tr}from"node:fs";import{lstat as xo,open as Pp,readdir as So,realpath as _o}from"node:fs/promises";import{createHash as Ip}from"node:crypto";import{join as Ao,relative as Sp,resolve as Ep,sep as xp}from"node:path";var K={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},_p={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"]},B=s=>Ip("sha256").update(s).digest("hex");function F(s){throw new h("invalid_package",s)}async function et(s,e,t){let i=e.split("/");(!i.length||i.some(c=>!c||c==="."||c===".."||!/^[\w.-]+$/.test(c)))&&F("Invalid resource path");let r=s;for(let c=0;c<i.length;c++){r=Ao(r,i[c]);let a=await xo(r);(a.isSymbolicLink()||(c<i.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&F("Links and non-regular package files are forbidden")}let n=await _o(r);(n!==Ep(s,e)||Sp(s,n).startsWith(`..${xp}`))&&F("Resource escapes package root");let o=await Pp(r,Tr.O_RDONLY|Tr.O_NONBLOCK|(Tr.O_NOFOLLOW??0));try{let c=await o.stat();(!c.isFile()||c.nlink!==1||c.size>t)&&F("Oversized or non-regular package file");let a=Buffer.alloc(Math.min(c.size+1,t+1)),l=0;for(;l<a.length;){let p=await o.read(a,l,a.length-l,l);if(!p.bytesRead)break;l+=p.bytesRead}return(l>t||l!==c.size)&&F("Package resource changed during read"),a.subarray(0,l)}finally{await o.close()}}function Eo(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return F("Invalid package JSON")}}async function tt(s,e){let t=await _o(s);(await xo(s)).isSymbolicLink()&&F("Package root cannot be a symlink");let i=Eo(await et(t,"package.json",K.other));(!i||typeof i.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(i.name)||i.name.length>214||e&&i.name!==e)&&F("Package identity mismatch"),(typeof i.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(i.version))&&F("Invalid package version"),Ue(i.piWebapp)||F("Unsupported hosted manifest"),i.type!=="module"&&F("Hosted package must declare ESM module type");for(let u of await So(t,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&F("Undeclared package-root asset or code");i.scripts&&Object.keys(i.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&F("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let y=i[u];y&&(typeof y!="object"||Object.keys(y).length>0)&&F("Hosted packages must contain all runtime dependencies")}let r=i.piWebapp,n=Eo(await et(t,r.resourcesManifest.slice(2),K.other));(!n||n.version!==1||!Array.isArray(n.files)||!n.files.length||n.files.length>K.files)&&F("Invalid resource manifest");let o=new Map,c=0;for(let u of n.files){(!u||typeof u!="object")&&F("Invalid resource entry");let y=u,m={...y,path:typeof y.path=="string"&&y.path.startsWith("./")?y.path.slice(2):y.path};(!Xe(`./${m.path}`)||typeof m.sha256!="string"||!/^[a-f0-9]{64}$/.test(m.sha256)||!Number.isSafeInteger(m.bytes)||m.bytes<0||o.has(m.path))&&F("Invalid or duplicate resource");let f=m.path.split(".").at(-1);_p[f]?.includes(m.mime)||F("Unsupported resource MIME");let w=f==="js"||f==="mjs"?K.js:f==="css"?K.css:f==="woff"||f==="woff2"?K.font:K.other;(m.bytes>w||(c+=m.bytes)>K.total)&&F("Resource budget exceeded");let k=await et(t,m.path,w);(k.length!==m.bytes||B(k)!==m.sha256)&&F("Resource integrity mismatch"),o.set(m.path,Object.freeze({...m}))}for(let u of[r.backend.entry,r.frontend.document,r.frontend.controller])o.has(u.slice(2))||F("Entrypoint is absent from resource manifest");let a=0;async function l(u,y=0){y>16&&F("Package directory nesting limit exceeded");for(let m of await So(Ao(t,u),{withFileTypes:!0})){++a>K.files*2&&F("Too many package entries");let f=`${u}/${m.name}`;(m.isSymbolicLink()||!m.isDirectory()&&!m.isFile())&&F("Invalid archive member"),m.isDirectory()?await l(f,y+1):f!==r.resourcesManifest.slice(2)&&!o.has(f)&&F("Undeclared distribution asset")}}await l("dist");let p=B(JSON.stringify({id:i.name,version:i.version,manifest:r,resources:[...o.values()].sort((u,y)=>u.path.localeCompare(y.path))}));return{id:i.name,version:i.version,root:t,manifest:r,resources:o,digest:p}}async function To(s,e,t){if(t!==s.digest||e.length>1536)return null;let i;try{i=decodeURIComponent(e)}catch{return null}if(!Xe(`./${i}`))return null;let r=s.resources.get(i);if(!r||i===s.manifest.backend.entry.slice(2))return null;let n=await et(s.root,i,r.bytes);if(n.length!==r.bytes||B(n)!==r.sha256)throw new h("resource_changed","Installed resource integrity mismatch");return{bytes:n,mime:r.mime}}var Ti=64*1024*1024,Np=K.total+K.files*2048,V=s=>{throw new h("invalid_archive",s)};function vt(s){let e=s.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?s:s.subarray(0,e))}catch{return V("Archive has invalid UTF-8 paths")}}function Ro(s){let e=vt(s).trim();if(!/^[0-7]+$/.test(e))return V("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:V("Archive number exceeds limits")}function Hp(s){let e=s.endsWith("/")?s.slice(0,-1):s;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return V("Archive must have one package root");let t=e.slice(8);return t.split("/").some(i=>!i||i==="."||i===".."||!/^[A-Za-z0-9_@.-]+$/.test(i))?V("Archive path is not a safe relative package path"):t}function Op(s){let e={},t=0;for(;t<s.length;){let i=s.indexOf(32,t);if(i<0)return V("Invalid PAX header");let r=s.subarray(t,i).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(r))return V("Invalid PAX record length");let n=Number(r),o=t+n;if(o>s.length||o<=i+2||s[o-1]!==10)return V("Truncated PAX record");let c=vt(s.subarray(i+1,o-1)),a=c.indexOf("=");if(a<1)return V("Invalid PAX record");let l=c.slice(0,a),p=c.slice(a+1);if(Object.hasOwn(e,l)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(l))return V("Unsupported PAX feature");e[l]=p,t=o}return e}function Mp(s){if(!s.length||s.length>Ti)return V("Compressed archive exceeds budget");let e;try{e=Ap(s,{maxOutputLength:Np})}catch{return V("Invalid or oversized gzip archive")}let t=[],i=new Set,r=0,n=0,o=0,c=0,a=null,l=!1;for(;r+512<=e.length;){let u=e.subarray(r,r+512);if(r+=512,u.every(H=>H===0)){if(a||e.subarray(r).some(H=>H!==0))return V("Unexpected archive data after end marker");l=!0;break}if(++c>K.files*2)return V("Too many archive headers");let y=0;for(let H=0;H<512;H++)y+=H>=148&&H<156?32:u[H];if(Ro(u.subarray(148,156))!==y)return V("Invalid tar header checksum");let m=vt(u.subarray(257,263));if(m&&m!=="ustar"&&m!=="ustar ")return V("Unsupported tar format");let f=u[156],w=vt(u.subarray(345,500)),k=(w?w+"/":"")+vt(u.subarray(0,100)),P=Ro(u.subarray(124,136));if(a&&(a.path!==void 0&&(k=a.path),a.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(a.size))return V("Invalid PAX size");P=Number(a.size)}if(!Number.isSafeInteger(P)||P<0||P>K.total||r+P>e.length)return V("Truncated or oversized tar member");let E=e.subarray(r,r+P);if(r+=Math.ceil(P/512)*512,f===120){if(a||P>8192)return V("Oversized or chained PAX header");a=Op(E);continue}if(a=null,f!==0&&f!==48&&f!==53)return V("Links and special archive members are forbidden");let _=f===53;if(_&&P!==0||vt(u.subarray(157,257)))return V("Invalid archive link or directory");if(k=Hp(k),!k&&!_)return V("Invalid package root member");if(i.has(k))return V("Duplicate archive member");if(i.add(k),++n>K.files||(o+=P)>K.total)return V("Unpacked archive exceeds budget");t.push({path:k,data:E,directory:_})}if(!l||!i.has("package.json"))return V("Archive is incomplete or has no package.json");let p=new Set(t.filter(u=>!u.directory).map(u=>u.path));for(let u of t){let y=u.path.split("/");for(let m=1;m<y.length;m++)if(p.has(y.slice(0,m).join("/")))return V("Archive file/directory collision")}return t}async function Rr(s,e){let t=Mp(s);for(let i of t){if(!i.path)continue;let r=Dp(e,i.path);await Tp(i.directory?r:Cp(r),{recursive:!0,mode:448}),i.directory||await Rp(r,i.data,{flag:"wx",mode:384})}}import{lstat as jp,mkdir as Wp,readdir as $p,realpath as Vp,writeFile as Fp}from"node:fs/promises";import{dirname as Bp,join as Cr}from"node:path";async function Co(s,e){let t=await Vp(s),i=await et(t,"package.json",K.other),r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new h("invalid_package","package.json is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new h("invalid_package","package.json must be an object");let n=[],o=0,c=0;async function a(y,m){if(m>16)throw new h("invalid_package","Package directory nesting limit exceeded");for(let f of await $p(Cr(t,y),{withFileTypes:!0})){let w=`${y}/${f.name}`;if(++o>K.files)throw new h("invalid_package","Too many package entries");if(f.isDirectory()){await a(w,m+1);continue}if(!f.isFile())throw new h("invalid_package",`Links and non-regular files are forbidden: ${w}`);let k=await et(t,w,K.js);if((c+=k.length)>K.total)throw new h("invalid_package","Resource budget exceeded");let P=Cr(e,w);await Wp(Bp(P),{recursive:!0,mode:448}),await Fp(P,k,{flag:"wx",mode:384}),n.push([w,B(k)])}}let l;try{l=await jp(Cr(t,"dist"))}catch(y){throw y.code==="ENOENT"?new h("dist_missing","dist/ does not exist yet; build the plugin first"):y}if(!l.isDirectory())throw new h("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...u}=r;return n.sort((y,m)=>y[0].localeCompare(m[0])),{contentHash:B(JSON.stringify({package:u,files:n})),packageJson:r}}function ke(s){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(s);return!e||e[0]!==s||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Ce(s,e){let t=ke(s),i=ke(e);if(!t||!i)throw new h("invalid_version","Only exact stable semantic versions are supported");return t.major-i.major||t.minor-i.minor||t.patch-i.patch}function Do(s){let e=ke(s);if(e)return e;if(!ai(s))return null;let[t,i]=s.split("-alpha."),r=ke(t),n=Number(i);return r&&Number.isSafeInteger(n)?{...r,alpha:n}:null}function Dr(s){return!!Do(s)}function bt(s,e){if(!Dr(s)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(r=>!r.trim()))return!1;let i=[];for(let r of t){let n=r.trim().split(/\s+/),o=!0;for(let c of n){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&Do(a[2]);if(!a||!l)return!1;let p=a[2],u=ue(s,p);switch(a[1]??"="){case"=":o&&=u===0;break;case">=":o&&=u>=0;break;case"<=":o&&=u<=0;break;case">":o&&=u>0;break;case"<":o&&=u<0;break;case"~":o&&=u>=0&&ue(s,`${l.major}.${l.minor+1}.0-0`)<0;break;case"^":{let y=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&ue(s,`${y}-0`)<0;break}}}i.push(o)}return i.some(Boolean)}var Me=Object.freeze([Object.freeze({id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"]})]);function me(s,e=Me){let t=e.find(i=>i.id===s);if(!t)throw new h("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Nr(s,e,t){let i=s.piWebapp;return s.name===e.id&&!!ke(s.version)&&!s.deprecated&&Ue(i)&&bt(t,i.hostRange)&&e.requiredCapabilities.every(r=>i.capabilities.includes(r))}function No(s,e,t,i,r){if(!s||typeof s!="object"||!("versions"in s)||!s.versions||typeof s.versions!="object"||Array.isArray(s.versions))throw new h("registry_invalid","Invalid registry version catalog");let n=Object.entries(s.versions);if(n.length>1e4)throw new h("registry_invalid","Registry version catalog exceeds budget");let c=n.flatMap(([a,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===a&&Nr(p,e,t)&&(!r||a===r)&&(!i||Ce(a,i)>=0)?[p]:[]}).sort((a,l)=>Ce(l.version,a.version))[0];if(!c)throw new h("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!c.dist||typeof c.dist.tarball!="string"||typeof c.dist.integrity!="string")throw new h("registry_invalid","Release is missing its immutable tarball integrity");return c}function Xp(s,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new h("invalid_integrity","A single SHA-512 tarball integrity is required");let i=Buffer.from(t[1],"base64"),r=Or("sha512").update(s).digest();if(i.length!==r.length||!Up(i,r))throw new h("integrity_mismatch","Downloaded package failed integrity verification")}var it=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Dr(e.hostVersion))throw new h("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Me,this.fetcher=e.fetch??Ln}async index(){let e=await ee(U(this.root,"installed.json"));if(!e){if(await X(U(this.root,"installed.json"),2*1024*1024))throw new h("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new h("invalid_storage","Invalid plugin installation index");for(let[t,i]of Object.entries(e.versions))if(this.catalog.some(r=>r.id===t)){if(!Array.isArray(i)||i.length>16||new Set(i.map(r=>r.version)).size!==i.length)throw new h("invalid_storage","Invalid installed version list");for(let r of i)this.validateRecord(t,r)}return e}validateRecord(e,t){if(!t||!ke(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${B(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new h("invalid_storage","Invalid installed plugin record")}path(e){return U(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await ce(U(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(n=>!["schema","pluginId","next"].includes(n)))throw new h("invalid_storage","Invalid install journal");me(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let r=e.versions[t.pluginId]?.find(n=>n.version===t.next.version);if(r&&r.digest!==t.next.digest)throw new h("invalid_storage","Conflicting installation journal");await ze(U(this.root,"install-journal.json"))}await this.recoverCollection(e);let i=U(this.root,"staging");await Z(i);for(let r of await Lp(i)){if(!/^stage-[A-Za-z0-9]+$/.test(r)||(await Ho(U(i,r))).isSymbolicLink())throw new h("invalid_storage","Invalid abandoned staging directory");await ze(U(i,r),{recursive:!0})}return e}async recoverCollection(e){let t=U(this.root,"gc-journal.json"),i=await ce(t);if(!i)return;if(i.schema!==1||Object.keys(i).some(n=>!["schema","pluginId","records"].includes(n))||!Array.isArray(i.records)||!i.records.length)throw new h("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");me(i.pluginId,this.catalog);for(let n of i.records)this.validateRecord(i.pluginId,n);let r=i.records.filter(n=>e.versions[i.pluginId]?.some(o=>o.directory===n.directory));if(r.length&&r.length!==i.records.length)throw new h("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!r.length){await Z(U(this.root,"versions")),await Z(U(this.root,"versions",B(i.pluginId)));for(let n of i.records)await ze(this.path(n),{recursive:!0,force:!0})}await ze(t)}async collect(e,t){return me(e,this.catalog),W(this.root,async()=>{let i=await this.recoverLocked(),r=i.versions[e]??[],n=new Set(await t()),o=r.at(-1);o&&n.add(o.version);let c=r.filter(a=>!n.has(a.version));return await this.removeLocked(e,i,c),c.map(a=>a.version)})}async removeLocked(e,t,i){i.length&&(await Z(U(this.root,"versions")),await Z(U(this.root,"versions",B(e))),await j(U(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:i}),t.versions[e]=(t.versions[e]??[]).filter(r=>!i.some(n=>n.directory===r.directory)),t.revision++,await j(U(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return W(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let i;try{i=new URL(e)}catch{throw new h("registry_denied","Invalid registry URL")}let r=new URL(t.registry);if(i.protocol!=="https:"||i.origin!==r.origin||i.username||i.password||i.hash||i.search)throw new h("registry_denied","Only the official registry origin is permitted");return i}async download(e,t,i,r="tarball"){let n=AbortSignal.any([AbortSignal.timeout(6e4),...i?[i]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:n,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw i?.aborted?i.reason:new h("registry_unreachable",u instanceof Error?u.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new h(o.status===404?`${r}_not_found`:"download_failed",`Registry ${r} request failed (${o.status})`);if(o.url&&new URL(o.url).origin!==e.origin)throw new h("registry_denied","Registry redirect is forbidden");let c=o.body.getReader(),a=[],l=0,p=()=>{c.cancel(n.reason).catch(()=>{})};n.addEventListener("abort",p,{once:!0});try{if(n.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new h("download_too_large","Registry response exceeds budget");for(;;){let u=await c.read();if(u.done)break;if(l+=u.value.length,l>t)throw new h("download_too_large","Registry response exceeds budget");a.push(Buffer.from(u.value))}return n.throwIfAborted(),Buffer.concat(a)}catch(u){throw i?.aborted?i.reason:u instanceof h?u:new h("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{n.removeEventListener("abort",p),await c.cancel().catch(()=>{}),c.releaseLock()}}async check(e,t,i,r){let n=me(e,this.catalog);if(i&&!ke(i))throw new h("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${n.registry}/${encodeURIComponent(e)}`,n),c,a=await this.download(o,8*1024*1024,r,"metadata");try{c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{throw new h("registry_invalid","Invalid registry metadata JSON")}return No(c,n,this.hostVersion,t,i)}async install(e,t,i){let r=me(e,this.catalog);if(!Nr(t,r,this.hostVersion))throw new h("incompatible_plugin","Plugin release is incompatible with this host");let n=await this.download(this.trustedUrl(t.dist.tarball,r),Ti,i);return this.installArchive(e,n,t.dist.integrity,t.version,i)}async installArchive(e,t,i,r,n){let o=me(e,this.catalog);if(!ke(r))throw new h("invalid_version","Choose an exact stable version");if(t.length>Ti)throw new h("download_too_large","Package archive exceeds budget");return Xp(t,i),W(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await Hr(U(this.root,"staging","stage-"));try{await Rr(t,a),n?.throwIfAborted();let l=await tt(a,e);if(l.version!==r||!Ue(l.manifest)||!bt(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(p=>l.manifest.capabilities.includes(p)))throw new h("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,c,a,l,i,n)}finally{await ze(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,i,r,n,o){let c=t.versions[e]?.find(u=>u.version===r.version);if(c&&c.digest!==r.digest)throw new h("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:r.version,digest:r.digest,integrity:n,directory:`${B(e)}/${r.version}-${r.digest}`,installedAt:new Date().toISOString()};if(await Z(U(this.root,"versions",B(e))),!c&&(t.versions[e]?.length??0)>=16)throw new h("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await j(U(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await Ho(l),p=!0}catch(u){if(!Ve(u))throw u}if(p){if((await tt(l,e)).digest!==r.digest)throw new h("resource_changed","Installed package content was modified")}else await Gp(i,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await j(U(this.root,"installed.json"),t)),await ze(U(this.root,"install-journal.json")),{...r,root:await qp(l)}}async installDevArchive(e,t,i){me(e,this.catalog);let r=await zp(t),n="sha512-"+Or("sha512").update(r).digest("base64"),o=await Hr(U(Kp(),"pi-dev-archive-"));try{await Rr(r,o);let c=(await tt(o,e)).version;return await this.installArchive(e,r,n,c,i)}finally{await ze(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,i){let r=me(e,this.catalog);return W(this.root,async()=>{let n=await this.recoverLocked();i?.throwIfAborted();let o=await Hr(U(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await Co(t,o);i?.throwIfAborted();let l=U(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],y=n.versions[e]??[],m=u?.contentHash===c?y.find(T=>T.version===u.version):void 0;if(m){let T=await tt(this.path(m),e);if(T.digest!==m.digest)throw new h("resource_changed","Installed package integrity changed");return T}let f=typeof a.version=="string"?ke(a.version):null;if(!f)throw new h("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let w=Math.max(-1,...y.map(T=>ke(T.version)).filter(T=>T&&T.major===f.major&&T.minor===f.minor).map(T=>T.patch)),k=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),w+1),P=`${f.major}.${f.minor}.${k}`;await Jp(U(o,"package.json"),JSON.stringify({...a,version:P},null,2),{flag:"wx",mode:384});let E=await tt(o,e);if(!bt(this.hostVersion,E.manifest.hostRange))throw new h("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let _=r.requiredCapabilities.filter(T=>!E.manifest.capabilities.includes(T));if(_.length)throw new h("incompatible_plugin",`Package lacks required capabilities: ${_.join(", ")}`);let H="sha512-"+Or("sha512").update(c).digest("base64"),N=await this.commitStaged(e,n,o,E,H,i);return p[e]={contentHash:c,version:P},await j(l,p),N}finally{await ze(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let i=me(e,this.catalog);return W(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]?.find(c=>c.version===t);if(!n)throw new h("not_installed","Plugin version is not installed");let o=await tt(this.path(n),e);if(o.digest!==n.digest)throw new h("resource_changed","Installed package integrity changed");if(!bt(this.hostVersion,o.manifest.hostRange)||!i.requiredCapabilities.every(c=>o.manifest.capabilities.includes(c)))throw new h("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){me(e,this.catalog),await W(this.root,async()=>{let i=await this.recoverLocked(),n=(i.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,i,n)})}};import{lstat as Ri,mkdir as Yp,open as Oo,realpath as Mo,readdir as Mr,link as Qp,rename as Zp,unlink as rt,copyFile as eu,rm as tu}from"node:fs/promises";import{dirname as iu,isAbsolute as jo,join as O,relative as Wo,resolve as ru,sep as jr,win32 as su}from"node:path";import{randomUUID as Wr}from"node:crypto";var Ft=192*1024*1024,Bt=512*1024,Vo=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function nu(s){if(!s||typeof s!="object"||Array.isArray(s))throw new h("invalid_input","Expected object input");return s}function $o(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new h("invalid_input","Invalid state key");return s}function Ut(s){if(s&&(!Vo(s.stateRef)||typeof s.version!="string"||!Number.isSafeInteger(s.generation)||s.generation<1||!Number.isSafeInteger(s.schema)||s.schema<1||typeof s.enabled!="boolean"||typeof s.operationId!="string"))throw new h("invalid_storage","Invalid active plugin record");return s}var st=class{root;pluginId;legacy;checkpoint;constructor(e,t,i,r){this.root=O(e,B(t)),this.pluginId=t,this.legacy=i,this.checkpoint=r}active(){return ee(O(this.root,"active.json")).then(Ut)}async recover(){return W(this.root,async()=>{let e=await this.active(),t=await ce(O(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(o=>!["version","before","next"].includes(o))||Object.hasOwn(t,"version")&&t.version!==1)throw new h("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ut(t.next),Ut(t.before);let i=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,c)=>o===null||c===null?o===c:["version","generation","stateRef","schema","enabled","operationId"].every(a=>o[a]===c[a]))(e,i==="committed"?t.next:t.before))throw new h("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let n=t.before;if(i==="committed"&&n&&n.stateRef!==e.stateRef&&await j(O(this.root,"previous.json"),n),i==="committed"){let o=await ce(O(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(c=>["version","stateRef"].includes(c))&&await rt(O(this.root,"fork.json"))}return await rt(O(this.root,"transition.json")),{active:e,recovered:i}})}async activate(e,t){return W(this.root,async()=>{let i=await this.active();if((i?.generation??0)!==e)throw new h("stale_generation","Plugin activation changed concurrently");let r=await ce(O(this.root,"fork.json"));if(r&&(r.version!==1||r.stateRef!==t.stateRef||Object.keys(r).some(o=>!["version","stateRef"].includes(o))))throw new h("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let n=Ut({...t,generation:e+1,operationId:Wr()});await Z(O(this.root,"states")),await Z(O(this.root,"states",n.stateRef)),await j(O(this.root,"transition.json"),{version:1,before:i,next:n}),await this.checkpoint?.("prepared");try{await j(O(this.root,"active.json"),n)}catch(o){if((await this.active())?.operationId!==n.operationId)throw o}await this.checkpoint?.("committed");try{i&&i.stateRef!==n.stateRef&&await j(O(this.root,"previous.json"),i),await rt(O(this.root,"transition.json")),await rt(O(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),n})}async forkState(e){return W(this.root,async()=>{let t=await this.assertGeneration(e,!1),i=Wr(),r=O(this.root,"states",i);if(await ce(O(this.root,"fork.json")))throw new h("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await j(O(this.root,"fork.json"),{version:1,stateRef:i}),await Z(r);let n=O(this.root,"states",t.stateRef);for(let o of await Mr(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await X(O(n,o),Ft))throw new h("invalid_storage","Missing state file");await eu(O(n,o),O(r,o))}return await this.checkpoint?.("forked"),i})}async collect(e){return W(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await X(O(this.root,l),2*1024*1024))throw new h("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),i=Ut(await ce(O(this.root,"previous.json")));if(!t&&await X(O(this.root,"active.json"),2*1024*1024))throw new h("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let r=[t,i].filter(l=>!!l),n=O(this.root,"states");await Z(n);let o=await Mr(n),c=new Set(r.map(l=>l.stateRef));for(let l of o){if(!Vo(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(n,l),u=await Ri(p);if(!u.isDirectory()||u.isSymbolicLink())throw new h("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let y of await Mr(p)){let m=await Ri(O(p,y));if(!/^[a-f0-9]{64}\.json$/.test(y)||!m.isFile()||m.isSymbolicLink()||m.nlink!==1)throw new h("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let f=await ee(O(p,y),Ft);if(!f)throw new h("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(f,"committed")){let w=f;if(Object.keys(w).some(k=>!["requestId","inputHash","nextHash","committed"].includes(k))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new h("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(f).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new h("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(f)}}}}for(let l of c)if(!o.includes(l))throw new h("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let a=await e(r);for(let l of o)c.has(l)||await tu(O(n,l),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let i=await this.active();if(!i||i.generation!==e||t&&!i.enabled)throw new h("stale_generation","Plugin generation is no longer active");return i}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new h("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,i,r="session"){if(r!=="session"&&r!=="workspace")throw new h("invalid_input","Invalid state scope");let n=r==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return O(this.root,"states",e.stateRef,`${B(n+":state:"+i)}.json`)}async call(e,t,i){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new h("invalid_lease","Invalid invocation lease");this.scopeKey(e);let r=nu(i);return W(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(n,e,$o(r.key),r.scope),Ft);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(n,e,$o(r.key),r.scope);if(!Number.isSafeInteger(r.expectedRevision)||r.expectedRevision<0||r.schema!==n.schema||!Object.hasOwn(r,"value"))throw new h("invalid_input","Invalid state revision or schema");if(JSON.stringify(r.value)===void 0)throw new h("invalid_input","State value must be JSON serializable");let c=JSON.stringify(r);if(Buffer.byteLength(c)>Ft)throw new h("state_too_large","Plugin state exceeds limit");let a=await ee(o,Ft);a&&this.validateState(a);let l=B(c);if(a?.requestId===e.requestId&&a.inputHash===l)return{revision:a.revision,schema:a.schema,value:a.value};if((a?.revision??0)!==r.expectedRevision)throw new h("revision_conflict","Plugin state changed concurrently");let p={revision:r.expectedRevision+1,schema:n.schema,value:r.value,requestId:e.requestId,inputHash:l};return await j(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,r.path),c=r.maxBytes===void 0?Bt:r.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>Bt)throw new h("invalid_input","Invalid workspace read limit");let a=await X(o,c);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash:B(a)}:null}case"workspace.commit":return this.commitFile(n,e,r);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new h("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new h("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,i=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||jo(t)||su.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let r=await Mo(e),n=ru(r,t),o=Wo(r,n);if(!o||o===".."||o.startsWith(`..${jr}`)||jo(o))throw new h("invalid_path","Workspace path escapes root");let c=r,a=o.split(jr);for(let p=0;p<a.length;p++){c=O(c,a[p]);let u;try{u=await Ri(c)}catch(y){if(!Ve(y))throw y;if(p<a.length-1){if(!i||Wo(r,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await Yp(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Ri(c)}}if(u&&(u.isSymbolicLink()||(p<a.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new h("invalid_path","Workspace path contains a link or non-regular file")}let l=await Mo(iu(n));if(l!==r&&!l.startsWith(r+jr))throw new h("invalid_path","Workspace directory changed");return{target:n,parent:l}}async commitFile(e,t,i){if(typeof i.text!="string"||Buffer.byteLength(i.text)>Bt||!(i.expectedHash===null||typeof i.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(i.expectedHash)))throw new h("invalid_input","Invalid file content or expected hash");let{target:r,parent:n}=await this.fileTarget(t.scope.cwd,i.path,!0),o=O(this.root,"states",e.stateRef,`${B(this.scopeKey(t)+":file:"+t.requestId+":"+String(i.path))}.json`),c=B(JSON.stringify(i)),a=B(i.text),l=await ee(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==a))throw new h("duplicate_request","Request ID was reused with different content");let p;try{p=await Oo(`${r}.lock`,"wx",384)}catch(y){throw y.code==="EEXIST"?new h("file_busy","Workspace file is locked; original file preserved"):y}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let y=await X(r,Bt),m=y?B(y):null;if(l&&m===a)return{hash:a};if(l?.committed||m!==i.expectedHash)throw new h("file_conflict","Workspace file already exists or changed externally");await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=O(n,`.plugin-${Wr()}.tmp`);let f=await Oo(u,"wx",384);try{await f.writeFile(i.text),await f.sync()}finally{await f.close()}if((await this.fileTarget(t.scope.cwd,i.path)).parent!==n)throw new h("file_conflict","Workspace directory changed during save");let k=await X(r,Bt);if((k?B(k):null)!==i.expectedHash)throw new h("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),i.expectedHash===null){try{await Qp(u,r)}catch(P){throw P.code==="EEXIST"?new h("file_conflict","Workspace file was created concurrently"):P}await rt(u),u=void 0}else await Zp(u,r),u=void 0;return await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await rt(u).catch(()=>{}),await p.close(),await rt(`${r}.lock`)}}};import{randomUUID as du}from"node:crypto";import{fork as ou}from"node:child_process";import{randomUUID as au}from"node:crypto";import{join as cu}from"node:path";import{EventEmitter as lu}from"node:events";var Fo=192*1024*1024,Lt=class s{child;pending=new Map;events=new lu;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,i,r){this.package=e,this.generation=t,this.broker=r;let n={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(n[o]=process.env[o]);this.child=ou(i,[],{env:n,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new h("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,t,i,r,n=1e4){let o=new s(e,t,i,r);try{await o.request("initialize",{entry:cu(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},n);let c=await o.request("describe",void 0,n);if(!c||!Array.isArray(c.tools)||c.tools.length>128)throw new h("invalid_tools","Invalid hosted tool catalog");let a=new Set;for(let l of c.tools){if(!l||typeof l.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(l.name)||a.has(l.name)||typeof l.label!="string"||typeof l.description!="string"||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!l.parameters||typeof l.parameters!="object"||Array.isArray(l.parameters)||l.parameters.type!=="object")throw new h("invalid_tools","Invalid or duplicate tool descriptor");a.add(l.name)}return o.tools=structuredClone(c.tools),await o.request("health",void 0,n),o}catch(c){throw await o.dispose(),c}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>Fo){this.unhealthy=!0;return}let i=e;if(i.type==="response"&&typeof i.id=="string"){let r=this.pending.get(i.id);if(!r)return;if(clearTimeout(r.timer),this.pending.delete(i.id),!r.expired){let n=i.error;i.ok===!0?r.resolve(i.value):r.reject(new h(n?.code??"plugin_failed",n?.message??"Plugin request failed",n))}this.inFlight||this.events.emit("idle")}else if(i.type==="broker-request"&&typeof i.id=="string"&&typeof i.invocationId=="string"&&typeof i.method=="string"){let r=this.pending.get(i.invocationId);try{if(!r?.invocation||r.expired)throw new h("invalid_lease","Plugin invocation lease is no longer writable");let n=await this.broker(r.invocation,i.method,i.input);this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!0,value:n})}catch(n){this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!1,error:G(n)})}}}request(e,t,i=3e4,r){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new h("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new h("worker_busy","Too many plugin requests"));let n=r?.requestId??au();if(this.pending.has(n))return Promise.reject(new h("duplicate_request","An identical request is still running"));let o={type:"request",id:n,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>Fo?Promise.reject(new h("message_too_large","Plugin request exceeds limit")):new Promise((c,a)=>{let l=setTimeout(()=>{let p=this.pending.get(n);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(n),a(new h("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},i);this.pending.set(n,{resolve:c,reject:a,timer:l,invocation:r,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(n),a(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,t,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(t=>{let i=()=>{clearTimeout(r),this.events.off("idle",i),t(!0)},r=setTimeout(()=>{this.events.off("idle",i),t(!1)},e);this.events.once("idle",i)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new h("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let t=()=>{clearTimeout(i),e()},i=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var pu={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ci=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,i=pu,r){this.broker=e,this.workerEntry=t,this.hooks=i,this.capabilities=r}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await yr(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,i)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,i):this.broker.call(e,t,i);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new h("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new h("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new h("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let i;try{if(i=(await this.broker.recover()).active,i&&i.schema!==e.manifest.dataSchemaVersion)throw new h("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(l){throw this.worker||await this.releaseOwnership?.(),l}let r=i?.generation??0,n=this.worker;n||(this.phaseValue="starting");let o=null,c=!1,a=!1;try{if(o=await Lt.start(e,r+1,this.workerEntry,this.callBroker),this.phaseValue="draining",n&&!await n.waitForIdle(t))throw new h("drain_pending","Plugin calls are still running; switch deferred without killing them");if(a=!0,await this.hooks.freeze(),n&&!await n.waitForIdle(t))throw new h("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new h("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let l=i?await this.broker.forkState(r):du(),p=await this.broker.activate(r,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});c=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await n?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw c||(this.phaseValue=n?.healthy?"active":n?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue,r=await this.broker.active(),n=async()=>{if(!(!t||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(r))throw await this.releaseOwnership?.(),this.phaseValue="failed",new h("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Lt.start(t.package,t.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(c){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),c}}};this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin work is still draining; current host retained");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint work is still draining; current host retained");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(c){try{await n(),this.phaseValue=i,await this.hooks.resume()}catch(a){throw this.phaseValue="failed",a}throw c}let o=!1;return()=>this.serialize(async()=>{o||(await n(),this.phaseValue=i,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,i;try{i=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!i){if(t)throw this.phaseValue="failed",new h("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!i.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let r=this.phaseValue;this.phaseValue="draining";let n=!1;try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin still has in-flight work; not killed");if(n=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(i.generation,{version:i.version,stateRef:i.stateRef,schema:i.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=r,n&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(r){throw this.phaseValue=i,await this.hooks.resume().catch(()=>{}),r}})}};import{readFile as Bo}from"node:fs/promises";var Di=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;pairAdmittedValue=!1;get pairAdmitted(){return this.pairAdmittedValue}constructor(e){this.options=e,this.installer=new it({root:Pe(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new _i(e.capabilities):void 0;this.scheduler=new Ai({invoke:async(i,r)=>{let n=this.closing?null:e.scheduledScope?.(i)??null;n&&await this.supervisor(i).invoke({requestId:hu(),scope:n,kind:"action",action:r.action,input:{schedule:r.id}})},onError:(i,r,n)=>e.onScheduleError?.(i,r.id,n),...e.scheduleTimers});for(let i of this.installer.catalog){let r=new st(Pe(e.root,"data"),i.id,e.legacy?.(i.id)),n=e.hooks(i.id);this.supervisors.set(i.id,new Ci(r,e.workerEntry,{validateCandidate:o=>n.validateCandidate?.(o),canSwitch:()=>n.canSwitch(),freeze:()=>n.freeze(),resume:()=>n.resume(),committed:async o=>{if(o.enabled){let c=await this.installer.load(i.id,o.version);this.packages.set(i.id,c),this.assetTokens.set(i.id,uu(24).toString("base64url"));try{this.scheduler.start(i.id,yt(c.manifest).schedules)}catch(a){this.scheduler.stop(i.id),this.errors.set(i.id,G(a))}}else this.scheduler.stop(i.id),this.packages.delete(i.id),this.assetTokens.delete(i.id);await n.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),i=this.options.devArchives?.get(e);return t?r=>this.installer.installDevDirectory(e,t,r):i?r=>this.installer.installDevArchive(e,i,r):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){me(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new h("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new h("manager_closed","Plugin manager is shutting down"));let i=()=>W(Ee(this.options.root),async()=>(await Wt(this.options.root),t())),r=(this.operations.get(e)??Promise.resolve()).then(i,i);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,G(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,i=!1){return this.options.lifecycle?this.options.lifecycle(e,t,i):t()}async policies(){let e=await ee(Pe(this.options.root,"policies","policies.json"));if(!e){if(await X(Pe(this.options.root,"policies","policies.json"),2*1024*1024))throw new h("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,i]of Object.entries(e))if(this.installer.catalog.some(r=>r.id===t)&&(!i||!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion)))throw new h("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await ee(Pe(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await W(Pe(this.options.root,"policies"),async()=>{let i=await this.diagnostics();i[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await j(Pe(this.options.root,"policies","update-checks.json"),i)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,i,r){try{let n=await this.installer.check(e,t,i,r),o=!t||Ce(n.version,t)>0;return o?this.available.set(e,n):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:n.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),n}catch(n){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:G(n).code,message:G(n).message}),n}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new h("invalid_input","Invalid plugin update policy");await W(Ee(this.options.root),async()=>{await Wt(this.options.root),await W(Pe(this.options.root,"policies"),async()=>{let i=await this.policies();i[e]={updatePolicy:"notify"},await j(Pe(this.options.root,"policies","policies.json"),i)})})}async start(){await W(Ee(this.options.root),()=>this.startLocked())}async startLocked(){await W(Pe(this.options.root,"policies"),async()=>{let r=await this.policies();await j(Pe(this.options.root,"policies","policies.json"),r)});let e=await Oe(this.options.root),t=mt(e);if(t&&e)try{if(await this.validatePairPackages(e.version,e.selections),e.version!==this.options.hostVersion||e.hostDigest!==await Ze(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Ze(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Bo(this.options.workerEntry)).equals(await Bo(Pe(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(r){let n=`Required action: restart the selected compatible host or inspect host-pair/intent.json with all owners stopped. ${G(r).message}; data retained`;for(let o of this.installer.catalog)this.errors.set(o.id,G(new h("host_pair_required",n)));await Te(this.options.root,{...e,phase:"required-action",message:n}),t=!1}await this.installer.inventory();let i=te(await this.pairSnapshot());for(let r of this.installer.catalog){let n=this.supervisor(r.id),o=await n.broker.active();if(o?.enabled)try{let c=t?e?.selections.find(p=>p.id===r.id):void 0,a=c&&te(o)===te(c.before)&&e?.fingerprint===i,l=await this.installer.load(r.id,a?c.version:o.version);if(a&&l.digest!==c.digest)throw new Error("Staged plugin digest changed");await this.lifecycle(r.id,()=>n.replace(l)),this.packages.set(r.id,l),mt(e)||await this.collectSettled(r.id)}catch(c){let a=G(c),l=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool; do not delete the pair journal.":"Choose a compatible host/plugin and inspect plugin diagnostics; do not delete the pair journal.";this.errors.set(r.id,{...a,message:`Required action: plugin startup failed (${a.code}): ${a.message}; data retained. ${l}`})}}t&&e&&(await Te(this.options.root,{...e,phase:this.errors.size?"required-action":"reconciled",message:this.errors.size?[...this.errors].map(([r,n])=>`${r}: ${n.message}`).join("; "):"Current compatible state admitted; no previous state restored"}),this.pairAdmittedValue=!this.errors.size)}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),i=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async n=>{let o=this.supervisor(n.id),c=await o.broker.active(),a=this.packages.get(n.id),l=(e.versions[n.id]??[]).map(p=>p.version).sort((p,u)=>Ce(u,p));return{id:n.id,name:n.name,description:n.description,official:!0,installed:!!l.length,installedVersions:l,version:l[0]??null,activeVersion:c?.version??null,enabled:c?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[n.id]?.updatePolicy??"notify",pinnedVersion:t[n.id]?.pinnedVersion,updateDiagnostic:i[n.id],availableVersion:this.available.get(n.id)?.version??(i[n.id]?.status==="available"?i[n.id].version??null:null),...this.errors.has(n.id)?{error:this.errors.get(n.id)}:{},...a&&o.phase==="active"?{digest:a.digest,document:a.manifest.frontend.document.slice(2),controller:a.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(n.id)}/${this.assetTokens.get(n.id)}/${a.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,i,r){return this.serialize(e,async()=>{let n=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],c=o.map(l=>l.version).sort((l,p)=>Ce(p,l))[0],a=await(async()=>{switch(t){case"check":return this.isDevPlugin(e)?{version:c??null,dev:!0}:{version:(await this.check(e,c,void 0,r)).version};case"install":{let l=this.devSource(e);if(l){let y=await l(r);return await this.recordDevSync(e,y.version),{installed:!0,version:y.version}}let p=await this.check(e,c,i,r),u=await this.installer.install(e,p,r);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:u.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:u.version}}case"enable":{let l=i??c;if(!l)throw new h("not_installed","Install the plugin first");let p=await this.installer.load(e,l),u=await this.lifecycle(e,()=>n.replace(p));return u.pending||this.packages.set(e,p),u}case"retry":{let l=n.pendingVersion,p=await this.lifecycle(e,()=>n.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!c)throw new h("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let f=await l(r),w=await n.broker.active();if(await this.recordDevSync(e,f.version),!w?.enabled)return{installed:!0,enabled:!1,version:f.version};if(w.version===f.version&&!n.pendingVersion)return{unchanged:!0,version:f.version};let k=await this.lifecycle(e,()=>n.replace(f));return k.pending||this.packages.set(e,f),k}let p=await this.check(e,c,i,r),u=await n.broker.active();if(p.version===c&&(!u?.enabled||u.version===c)&&!n.pendingVersion)return{unchanged:!0,version:c};let y=p.version===c?await this.installer.load(e,c):await this.installer.install(e,p,r);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:y.version,message:"Selected compatible release installed; activation may wait for editors"}),!u?.enabled)return{installed:!0,enabled:!1,version:y.version};let m=await this.lifecycle(e,()=>n.replace(y));return m.pending||this.packages.set(e,y),m}case"uninstall":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new h("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=G(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async i=>this.installer.collect(e,async()=>{let r=(await this.policies())[e];return[...i.map(n=>n.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...r?.pinnedVersion?[r.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Reconnect the plugin view before editing",{status:409})):r.invoke(i)}flush(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Flush generation changed",{status:409})):r.flushAction(i)}async asset(e,t,i){let r=this.packages.get(e);if(!r)return null;let n=this.assetLeases.get(e);n||(n=new Map,this.assetLeases.set(e,n)),n.set(r.version,(n.get(r.version)??0)+1);try{return await To(r,i,t)}finally{let o=n.get(r.version)-1;o?n.set(r.version,o):n.delete(r.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let i;try{i=decodeURIComponent(t[1])}catch{return null}let r=this.assetTokens.get(i),n=Buffer.from(t[2]);return!r||n.length!==Buffer.byteLength(r)||!fu(n,Buffer.from(r))?null:this.asset(i,t[3],t[4])}async reconcileHostUpgrade(){if(mt(await Oe(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),i=!0;for(let r of this.installer.catalog){let n=e.versions[r.id];if(n?.length)try{let o=await this.supervisor(r.id).broker.active(),c=o?.enabled?o.version:n.map(l=>l.version).sort((l,p)=>Ce(p,l))[0];try{await this.installer.load(r.id,c);continue}catch(l){if(G(l).code!=="incompatible_plugin")throw l}let a=await this.manage(r.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(i=!1)}catch(o){i=!1;let c=G(o);this.errors.set(r.id,c),await this.recordCheck(r.id,{status:"failed",code:c.code,message:c.message})}}return i}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}get hostPair(){return so(this.options.root,(e,t)=>this.prepareHostPair(e,t),()=>this.pairSnapshot(),(e,t)=>this.validatePairPackages(e,t))}async validatePairPackages(e,t){let i=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog});for(let r of t)if((await i.load(r.id,r.version)).digest!==r.digest)throw new h("host_pair_changed","Staged plugin digest changed; selection refused")}async prepareHostPair(e,t){let i=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),r=await this.installer.inventory(),n=await this.policies(),o=[];for(let c of this.installer.catalog){let a=r.versions[c.id];if(!a?.length)continue;let l=await this.supervisor(c.id).broker.active(),p=a.map(y=>y.version).sort((y,m)=>Ce(m,y))[0],u;try{u=await i.load(c.id,l?.enabled?l.version:p),o.push({id:c.id,version:u.version,digest:u.digest,before:l});continue}catch(y){if(G(y).code!=="incompatible_plugin")throw y}try{let y=await i.check(c.id,p,void 0,t);u=y.version===p?await i.load(c.id,p):await i.install(c.id,y,t),await this.recordCheck(c.id,{status:"up-to-date",version:u.version,message:"Compatible combination prepared for software update"}),this.errors.delete(c.id)}catch(y){let m=G(y);await this.recordCheck(c.id,{status:"failed",code:m.code,message:m.message}),this.errors.set(c.id,m);try{u=await i.load(c.id,p)}catch(f){throw new h("host_pair_required",`${m.message}; ${G(f).message}; current host/plugin and data retained`)}}o.push({id:c.id,version:u.version,digest:u.digest,before:l})}return o}async validateHostUpdate(e){let t=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),i=await this.installer.inventory(),r=await this.policies(),n=!1;for(let o of this.installer.catalog){let c=i.versions[o.id];if(!c?.length)continue;n=!0;let a=await this.supervisor(o.id).broker.active(),l=c.map(u=>u.version).sort((u,y)=>Ce(y,u))[0],p=new Set([l,...a?[a.version]:[],...r[o.id]?.pinnedVersion?[r[o.id].pinnedVersion]:[],...this.supervisor(o.id).pendingVersion?[this.supervisor(o.id).pendingVersion]:[]]);for(let u of p)try{await t.load(o.id,u)}catch(y){throw new h("host_pair_required",`Host update blocked for ${o.id}@${u}: ${G(y).message}. Prepare a compatible pair; installed code/data retained`)}}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[],t=async()=>{let i=await Promise.allSettled(e.map(n=>n()));this.closing=!1;let r=i.find(n=>n.status==="rejected");if(r?.status==="rejected")throw r.reason};try{for(let i of this.supervisors.values())e.push(await i.suspendForRestart());return t}catch(i){throw await t(),i}}};import{randomUUID as gu}from"node:crypto";var D=s=>Object.assign(new Error(s),{status:409,code:"view_barrier"}),zt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;constructor(e,t,i=2e4,r=15e3){this.pluginId=e,this.generation=t,this.pollMs=i,this.freezeMs=r}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,i){return e.scope.ownerId===i.ownerId&&e.scope.workspaceId===i.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let i=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&i&&this.barrier.pending.has(i.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&i.identity.generation===e.generation&&i.identity.mountId===e.mountId&&i.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&i.scope.ownerId===t.ownerId&&i.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let i=e.viewToken?this.views.get(e.viewToken):void 0;if(!i||i.identity.generation!==this.generation||e.generation!==i.identity.generation||e.mountId!==i.identity.mountId||e.sessionId!==i.identity.sessionId||t.ownerId!==i.scope.ownerId||t.workspaceId!==i.scope.workspaceId||t.sessionId!==i.identity.sessionId)throw D("Unknown or stale view action capability");if(this.switching&&i.kind==="controller")throw D("Controller admission paused during plugin switching");return i.initialized=!0,i.activeActions=(i.activeActions??0)+1,()=>{i.activeActions--}}enqueue(e,t,i=++this.sequence){return e.commands.push({id:i,type:t,generation:this.generation}),e.waiter?.(),i}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw D("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw D("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw D("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw D("Invalid registration capability");let o=e.viewToken??gu();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw D("View initialization was cancelled; register a new document identity");let c=this.views.get(o);if(c){if(!this.sameScope(c,e,t)||c.kind!==e.kind)throw D("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw D("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[]}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw D("Invalid view capability");let i=this.views.get(e.viewToken),r=this.recoveries.get(e.viewToken),n=this.retired.get(e.viewToken);if(n&&!this.sameScope(n,e,t))throw D("Unknown or stale view capability");if(e.operation==="reconcile"||e.operation==="recover"){if(i&&!this.sameScope(i,e,t)||r&&!this.sameScope(r,e,t))throw D("Unknown or stale view capability");if(r)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(r,"retained")};if(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!i)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||i.activeActions)return{viewToken:i.token,commands:[],recovery:this.recovery(i,"active")};if(i.kind==="controller")return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw D("Explicit recovery confirmation required");return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),this.recoveries.set(i.token,i),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retained")}}return{viewToken:i.token,commands:[],recovery:this.recovery(i,"unconfirmed")}}if(e.operation==="discard"&&r&&this.sameScope(r,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!i&&!r){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching)throw D("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!i||!this.sameScope(i,e,t))throw D("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(i.initialized||i.activeActions||this.switching)throw D("View already initialized; preserve its recovery record");this.retire(i);break;case"change":if(e.generation!==this.generation)throw D("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw D("Invalid view status");i.initialized=!0,i.dirty=e.dirty,i.busy=e.busy,(i.dirty||i.busy)&&i.frozen&&(i.frozen=!1,this.barrier?.reject(D("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw D("Invalid acknowledgement");let o=i.commands.find(c=>c.id===e.commandId);if(!o)throw D("Unknown command acknowledgement");i.commands=i.commands.filter(c=>c.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(i.frozen=!0,i.dirty=!1,i.busy=!1,this.barrier.pending.delete(i.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(D(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching||i.activeActions)throw D("View has an active barrier or action; discard refused");this.retire(i);break;case"close":if(i.activeActions)throw D("View action still in flight");if(i.kind!=="controller"&&(i.dirty||i.busy)&&!i.frozen)throw D("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(i.token))throw D("View must acknowledge freeze before closing");this.retire(i);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw D("Invalid poll cursor");if(i.waiter)throw D("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw D("Invalid poll mode");return!e.immediate&&!i.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),i.waiter=void 0,o()}i.waiter=a}),{viewToken:i.token,commands:i.commands.filter(o=>o.id>e.after)}}default:throw D("Unknown view operation")}return{viewToken:i.token,commands:[]}}freeze=async()=>{if(this.switching)throw D("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(i=>i.activeActions||i.kind!=="controller"&&!i.frozen&&(i.busy||!this.immediate&&["editor","workspace"].includes(i.kind)));throw D(`Close editors before updating; old version retained. Pending views: ${t.map(i=>`${i.kind}:${i.identity.mountId}${i.activeActions?` (action in flight x${i.activeActions})`:i.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,i)=>{let r=n=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,n?i(n):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(n=>n.token)),resolve:()=>r(),reject:n=>r(n),timer:setTimeout(()=>{let n=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));r(D(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${n.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let n of this.authoringViews())this.enqueue(n,"freeze",e);this.authoringViews().length||r()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw D("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(D("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(D("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var mu="@chengzhiyi/pi-excalidraw",wu={tools:{excalidraw_read_me:"reference",excalidraw_create_view:"view",diagram_reference:"reference",diagram_create:"create",diagram_read:"read",diagram_patch:"patch"},readonlyActions:["read","reference"],actions:["list","new","open","import","get","focus","sync","initialize","accept","reject","save"],checkpointActions:["sync","get","list"],contribution:{entry:{label:"Excalidraw",description:{zh:"\u624B\u7ED8\u56FE\u7A3F",en:"Editable drawings"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["excalidraw_create_view","diagram_create","diagram_patch"],toolViews:["excalidraw_create_view","diagram_create","diagram_patch"],panelAlias:{prefix:"diagram:",kind:"editor",title:"Excalidraw"}}},yu="@chengzhiyi/pi-github",vu={tools:{},readonlyActions:[],actions:["get","configure","pickup","sync","cancel","approve","reject","answer","remove"],checkpointActions:["get"],contribution:{entry:{label:"GitHub",description:{zh:"GitHub \u4EFB\u52A1",en:"GitHub tasks"},kind:"workspace"},panels:["workspace"],artifactTools:[],toolViews:[],panelAlias:{prefix:"github:",kind:"workspace",title:"GitHub"}}},Uo=new Map([[mu,wu],[yu,vu]]);function $r(s,e){let t=s.get(e);if(!t)throw new h("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as bu}from"node:crypto";var ku="https://github.com/settings/personal-access-tokens/new?"+new URLSearchParams({name:"pi-webapp",description:"pi-webapp GitHub plugin",issues:"write",pull_requests:"write",contents:"write"}),Pu="Ov23limJmKiuu8cOP83E";function Vr(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||Pu,scope:"repo",createUrl:ku}}var Iu="https://github.com/login/device/code",Su="https://github.com/login/oauth/access_token",Eu=8,Ni=class{flows=new Map;fetcher;now;constructor(e=(i,r)=>fetch(i,{...r,signal:r.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let i;try{i=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new h("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let r=await i.json().catch(()=>null);if(!r||typeof r!="object"||!i.ok&&!("error"in r))throw new h("oauth_failed",`GitHub sign-in failed (${i.status})`,{status:502});return r}async start(e,t,i){if(!i.clientId)throw new h("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[u,y]of this.flows)y.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=Eu)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let r=await this.post(Iu,{client_id:i.clientId,scope:i.scope}),{device_code:n,user_code:o,verification_uri:c}=r,a=Number(r.expires_in),l=Math.max(Number(r.interval)||5,1);if(typeof n!="string"||typeof o!="string"||typeof c!="string"||!c.startsWith("https://github.com/")||!Number.isFinite(a))throw new h("oauth_failed",typeof r.error_description=="string"?r.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=bu();return this.flows.set(p,{pluginId:e,name:t,clientId:i.clientId,deviceCode:n,expiresAt:this.now()+a*1e3,interval:l,nextPoll:this.now()+l*1e3}),{deviceId:p,userCode:o,verificationUri:c,interval:l,expiresIn:a}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let i=await this.post(Su,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof i.access_token=="string"&&i.access_token)return this.flows.delete(e),{status:"granted",token:i.access_token,pluginId:t.pluginId,name:t.name};switch(i.error){case"authorization_pending":return{status:"pending"};case"slow_down":return t.interval+=5,t.nextPoll=this.now()+t.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as zo,readFileSync as qo,statSync as xu}from"node:fs";import{lstat as _u,readdir as Au,writeFile as Tu,mkdir as Ru,rename as Cu}from"node:fs/promises";import{delimiter as Du,dirname as Nu,isAbsolute as Hu,join as nt,resolve as qt}from"node:path";var Lo="@chengzhiyi/pi-github",Mi={[Lo]:{id:Lo,name:"GitHub",icon:"github",description:{zh:"\u628A GitHub issue \u4EA4\u7ED9 agent\uFF1A\u5148\u51FA\u65B9\u6848\uFF0C\u7ECF\u4F60\u6279\u51C6\u540E\u5B9E\u73B0\u5E76\u63D0\u4EA4\u8349\u7A3F PR\u3002",en:"Hand GitHub issues to an agent: it plans, you approve, then it implements and opens a draft PR."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","panels","scheduler","network","secrets","sessions"]}},Go=()=>Object.keys(Mi).join(", ");function Ou(s=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(s??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=n.lastIndexOf("="),c=n.slice(0,o),a=n.slice(o+1),l=Mi[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?zo(qt(a))?null:`archive not found: ${qt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Go()})`;if(p){i.push({level:"error",source:r,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,qt(a))}return{catalog:e,archives:t,notices:i}}var Jo=s=>nt(s,"pi-web","hosted-dev.json"),Ko=s=>nt(s,"pi-web","hosted-dev-status.json");function Mu(s,e,t=process.cwd()){let i=[],r=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(Du).map(c=>c.trim()).filter(Boolean);for(let c of n)i.push({path:qt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&zo(e)){o=!0;try{let c=JSON.parse(qo(e,"utf8")),a=c&&typeof c=="object"?c.roots:void 0;if(!Array.isArray(a))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let l of a)typeof l!="string"||!Hu(l)?r.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):i.push({path:qt(l),source:e})}catch(c){r.push({level:"error",source:e,message:`cannot read dev configuration: ${c instanceof Error?c.message:String(c)}`})}}return{specs:i,notices:r,configured:o}}function ju(s){let e=(r,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${r}`}}),t;try{t=xu(s.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let i;try{i=JSON.parse(qo(nt(s.path,"package.json"),"utf8"))}catch(r){return e(r.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof i.name!="string"?e("package.json has no name"):Mi[i.name]?Ue(i.piWebapp)?{pluginId:i.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',i.name):e(`unknown plugin id "${i.name}" (known: ${Go()})`)}var Hi=class{catalog;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let t=Ou(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let i=this.refresh(!0);this.enabled||=i.configured}refresh(e=!1){let t=Mu(this.env,this.configPath,this.cwd),i=[],r=new Map,n=new Map;for(let o of t.specs){let c=ju(o);if(c.notice){i.push(c.notice);continue}let a=c.pluginId;if(r.has(a)){i.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${r.get(a)}`});continue}if(this.archives.has(a)&&i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${a}; the dev directory wins`}),!this.catalog.some(l=>l.id===a)){if(!e){i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: ${a} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}this.catalog.push(Mi[a])}r.set(a,o.path),n.set(a,o.source)}for(let o of[...this.roots.keys()])r.has(o)||this.roots.delete(o);for(let[o,c]of r)this.roots.set(o,c);this.rootSource.clear();for(let[o,c]of n)this.rootSource.set(o,c);return this.fileNotices=t.notices,this.rootNotices=i,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Oi=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${G(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,i]of e){let r=this.roots.get(t);(!r||r.root!==i)&&(r={root:i,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,r));let n=await Wu(i);if(n===null){this.set(t,r,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),r.seen=void 0;continue}if(n!==r.seen){r.seen=n;continue}n===r.applied||this.stopped||await this.apply(t,r,n)}await this.publish()}set(e,t,i,r={}){let n=t.state!==i||t.message!==r.message||t.version!==r.version;t.state=i,t.message=r.message,t.code=r.code,t.version=r.version??t.version,n&&(t.at=new Date().toISOString(),this.log(`${e}: ${i}${r.version?` ${r.version}`:""}${r.message?` \u2014 ${r.message}`:""}`))}async apply(e,t,i){this.set(e,t,"switching");try{let n=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=i,n?.installed?n.pendingVersion?this.set(e,t,"pending",{version:n.version,message:`Waiting for editors to close before switching to ${n.pendingVersion}`}):this.set(e,t,"synced",{version:n.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(r){let n=G(r);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(n.code)||(t.applied=i),n.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:n.code,message:`${n.message} (${n.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let i=this.options.statusPath;if(!i)return;let r=Object.fromEntries([...this.roots].map(([c,a])=>[c,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),n=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(c=>c.id),plugins:r,notices:e.notices});if(n===this.lastStatus)return;this.lastStatus=n;let o=`${i}.${process.pid}.tmp`;try{await Ru(Nu(i),{recursive:!0}),await Tu(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await Cu(o,i)}catch{}}};async function Wu(s){let e=[],t=async(i,r)=>{let n=await _u(i);e.push(`${r}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(nt(s,"package.json"),"package.json");let i=async(r,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await Au(r,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await i(nt(r,c.name),`${n}/${c.name}`,o+1):await t(nt(r,c.name),`${n}/${c.name}`)};if(await i(nt(s,"dist"),"dist",0),!e.some(r=>r.startsWith("dist/resources.json:")))return null}catch(i){if(i.code==="ENOENT")return null;throw i}return e.join("|")}function Fu(s){try{return[...yt(s).secrets]}catch{return[]}}var Wi=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ni;restartPreparation;restartResume;closing=!1;started=!1;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Uo,e.dev?.enabled&&(this.devWatcher=new Oi({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let i=await this.inventory();return i.plugins.find(r=>r.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):i}}})),this.adapter=new Si({policy:(t,i)=>{let r=e.policy?.(t,i);return{...r,enabled:!this.recovery.has(t)&&this.manager.tools.some(n=>n.pluginId===t)&&r?.enabled!==!1}},invoke:async(t,i,r)=>{r?.throwIfAborted(),this.scope(i.scope.sessionId,i.scope);let n=this.manager.tools.find(c=>c.pluginId===t);if(!n)throw new h("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,n.generation,i);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Di({...e,lifecycle:(t,i,r)=>this.lifecycle(t,i,r),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:i=>{if(i.length!==Object.keys($r(this.trusted,t).tools).length)throw new h("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,i),this.adapter.validateChange(t,i)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async i=>{try{let r=i.enabled?this.manager.tools.find(n=>n.pluginId===t)?.descriptors:[];if(!r)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,r),i.enabled){let n=await this.manager.installer.load(t,i.version);this.documents.set(t,{document:n.manifest.frontend.document.replace(/^\.\//,""),controller:n.manifest.frontend.controller.replace(/^\.\//,""),secrets:Fu(n.manifest)})}else this.documents.delete(t);this.adapter.change(t,r),await this.coordinator(t).committed(i),e.changed?.(),this.recovery.delete(t)}catch(r){throw this.recovery.set(t,r),await this.coordinator(t).committed(i).catch(()=>{}),r}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,i,r)=>{let n=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!n)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(i))throw new h("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return r===null?await n.delete(t,i):await n.set(t,i,r),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let i=this.options.capabilities?.secrets;if(!i)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let n=this.documents.get(t.pluginId)?.secrets.includes(t.name)?Vr(t.pluginId,t.name):void 0;if(!n)throw new h("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,n)}let r=await this.deviceFlows.poll(t.deviceId);return r.status!=="granted"?{status:r.status}:(await i.set(r.pluginId,r.name,r.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,i)=>{if(!this.options.approvals)throw new h("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,i),this.inventory()},action:(t,i)=>this.action(t,i?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new h("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let i=t,r=this.scope(i.sessionId);return i.operation==="register"&&this.generation(i.pluginId,i.generation),this.coordinator(i.pluginId).handle(i,this.viewScope(r))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let i=$r(this.trusted,e);for(let r of t)if(!Object.hasOwn(i.tools,r.name)||i.tools[r.name]!==r.action||r.readonly!==i.readonlyActions.includes(r.action))throw new h("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new h("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let i=typeof e=="string"?this.options.resolveSession(e):null;if(!i||i.sessionId!==e||!i.cwd||!i.workspaceId||t&&(i.cwd!==t.cwd||i.workspaceId!==t.workspaceId))throw new h("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...i}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let i=this.manager.tools.find(r=>r.pluginId===e);if(!i||i.generation!==t)throw new h("stale_generation","Reconnect and re-handshake hosted views",{status:409});return i}enqueue(e,t=!1){let i=this.queue.then(async()=>{if(this.closing&&!t)throw new h("manager_closed","Host is shutting down");return e()});return this.queue=i.catch(()=>{}),i}lifecycle(e,t,i=!1){let r=this.switches.then(async()=>{if(this.closing&&!i)throw new h("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let n=await t();if(n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new st(ji(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!i)throw new h("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return n}finally{if(!i)for(let n of this.views.values())n.allowImmediateReopen(!1);i||this.adapter.thaw()}});return this.switches=r.catch(()=>{}),r.catch(n=>{throw i&&this.adapter.thaw(),n})}async start(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Me)try{let t=await new st(ji(this.options.root,"data"),e.id).active();this.views.set(e.id,new zt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new zt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=ji(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&(this.manager.pairAdmitted?!(await this.manager.inventory()).plugins.some(i=>i.updateDiagnostic?.status==="failed"):await this.manager.reconcileHostUpgrade())&&(await Z(this.options.root),await j(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Me)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}async validateHostUpdate(e,t){await this.enqueue(async()=>{if(await this.manager.validateHostUpdate(e))try{await Vu(ji(t,"dist","hosted-worker.js"))}catch{throw new h("host_pair_required","Selected host has no hosted worker; keep current host/plugin pair")}})}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,i=new Map;for(let r of e.plugins){let n=r.enabled?this.documents.get(r.id)?.secrets??[]:[];t&&n.length&&i.set(r.id,await Promise.all(n.map(async o=>{let c=Vr(r.id,o);return{name:o,configured:await t.has(r.id,o),...c?{signIn:c.clientId?"browser":"token-page",...c.createUrl?{createUrl:c.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(r=>({pluginId:r.id,name:r.name,official:r.official,installed:r.installed,enabled:r.enabled,description:r.description,...i.has(r.id)?{secrets:i.get(r.id)}:{},icon:(this.options.catalog??Me).find(n=>n.id===r.id)?.icon,hasRetainedData:r.activeVersion!==null,phase:this.recovery.has(r.id)?"reconnect-required":r.phase,updatePolicy:r.updatePolicy,pinnedVersion:r.pinnedVersion,updateDiagnostic:r.updateDiagnostic,...r.enabled&&r.activeVersion?{version:r.activeVersion}:r.version?{version:r.version}:{},...r.availableVersion?{availableVersion:r.availableVersion}:{},...r.pendingVersion?{pendingVersion:r.pendingVersion}:{},...r.generation!==null?{generation:r.generation}:{},...this.recovery.has(r.id)||r.error?{error:this.recovery.get(r.id)instanceof Error?this.recovery.get(r.id).message:r.error?.message??"Recovery required",errorCode:this.recovery.has(r.id)?"reconnect_required":r.error?.code}:{},...r.enabled&&r.assetBase&&this.documents.has(r.id)&&this.trusted.has(r.id)?{documentUrl:r.assetBase+this.documents.get(r.id).document,controllerUrl:r.assetBase+this.documents.get(r.id).controller,contribution:structuredClone(this.trusted.get(r.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let i=this.downloads.get(e.pluginId);if(!i||i.id!==e.downloadId)throw new h("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return i.abort.abort(new h("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let t=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(t){if(this.downloads.has(e.pluginId))throw new h("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,t)}try{return await this.enqueue(async()=>{let i=this.coordinator(e.pluginId);i.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new h("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let r=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||r&&typeof r=="object"&&"reconnectRequired"in r&&r.reconnectRequired)throw new h("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{i.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let i=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new h("action_denied","Action is not reviewed by this host",{status:403});let r=this.coordinator(e.pluginId).admitAction(e,this.viewScope(i));try{let n={requestId:$u(),scope:i,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(i)))return await this.manager.flush(e.pluginId,e.generation,n);throw new h("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new h("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...n,kind:"action"})}finally{r()}}prepareRestart(){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let r of this.views.values())r.allowImmediateReopen(!0);let e=await this.manager.suspendForRestart(),t=!1,i=async()=>{if(!t)try{await e(),t=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(e){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}finally{for(let e of this.views.values())e.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as Bu,readdir as Uu,unlink as Lu}from"node:fs/promises";import{join as kt}from"node:path";import{randomUUID as zu}from"node:crypto";var Fr="hosted-migration.json";function Xo(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:i,sessionId:r}=t.scope,n=kt(s,B(JSON.stringify([i,r])));await Z(s),await Z(n);let o=kt(n,"scope.lock"),c;try{c=await Bu(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new h("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):a}try{await c.writeFile(JSON.stringify({pid:process.pid,operationId:zu()}));let a=await ee(kt(n,Fr));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Uu(n),p=[];for(let y of l){if(y==="scope.lock"||y==="focus.json"||y===Fr||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(y))continue;if(!/^[\w-]{1,80}\.json$/.test(y))throw new h("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new h("invalid_storage","Too many legacy checkpoints");let m=await ee(kt(n,y),3*512*1024);if(!m||m.version!==1||m.cwd!==i||m.sessionId!==r||!m.draft||y!==`${m.draft.id}.json`)throw new h("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(m.draft)}let u=await ee(kt(n,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(y=>y.id===u)))throw new h("invalid_storage","Invalid legacy focused drawing");return a||await j(kt(n,Fr),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Lu(o)}}}import{join as eh}from"node:path";import{randomUUID as qu}from"node:crypto";var Gu=6e4,$i=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:i,title:r})=>({id:e,pluginId:t,sessionId:i,title:r}))}async authorize(e,t){let i=this.entries.get(t);if(i&&i.pluginId!==e)throw new h("execute_denied","Session belongs to another plugin",{status:403});if(i?.status==="allowed")return!0;throw i?.status==="pending"?new h("approval_required","Waiting for the user to approve execution",{status:409}):i?.status==="denied"&&this.now()-i.decidedAt<Gu?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:qu(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new h("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,t){let i=[...this.entries.values()].find(r=>r.id===e&&r.status==="pending");if(!i)throw new h("unknown_approval","No such pending approval",{status:404});i.status=t?"allowed":"denied",i.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as Ju,readFile as Ku,rename as Xu,writeFile as Yu}from"node:fs/promises";import{randomUUID as Qu,createHash as Zu}from"node:crypto";import{join as Yo}from"node:path";var Vi=class{dir;queue=Promise.resolve();constructor(e){this.dir=Yo(e,"secrets")}file=e=>Yo(this.dir,`${Zu("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Ku(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Ve(t))throw new h("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let t=this.queue.then(e,e);return this.queue=t.catch(()=>{}),t}async get(e,t){return(await this.read(e))[t]??null}has(e,t){return this.get(e,t).then(i=>i!==null)}set(e,t,i){return this.mutate(e,r=>{r[t]=i})}delete(e,t){return this.mutate(e,i=>{delete i[t]})}mutate(e,t){return this.serialize(async()=>{let i=await this.read(e);t(i),await Ju(this.dir,{recursive:!0,mode:448});let r=`${this.file(e)}.${Qu()}.tmp`;await Yu(r,JSON.stringify(i),{mode:384}),await Xu(r,this.file(e))})}};function Qo(s,e){let t=i=>({seq:i.seq,type:i.type,...i.text===void 0?{}:{text:i.text}});return{async create({pluginId:i,cwd:r,title:n,prompt:o}){let c=await s.createDetached(r,i,n);try{await s.sendDetached(c,o,!1)}catch(a){throw await s.releaseDetached(c),a}return{sessionId:c}},ownerOf:i=>s.detachedOwner(i),activeCount:i=>s.detachedCount(i),async send(i,r,n){let o=s.detachedOwner(i);if(n==="execute"&&(!o||!await e(o,i)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await s.sendDetached(i,r,n==="execute")},abort:i=>s.abortDetached(i),release:i=>s.releaseDetached(i),async events(i,r){let n=s.detachedEvents(i,r);return{events:n.events.map(t),next:n.next}}}}var th="scheduler";function Zo(s){let e=new $i({describe:s.sessionTitle,changed:s.changed}),t=()=>{let r=s.sessions();if(!r)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return r},i={createDetached:(...r)=>t().createDetached(...r),detachedOwner:r=>s.sessions()?.detachedOwner(r)??null,detachedCount:r=>s.sessions()?.detachedCount(r)??0,sendDetached:(...r)=>t().sendDetached(...r),abortDetached:r=>t().abortDetached(r),releaseDetached:async r=>{e.forget(r),await t().releaseDetached(r)},detachedEvents:(...r)=>t().detachedEvents(...r)};return{approvals:e,capabilities:{secrets:new Vi(eh(s.root,"capability-secrets")),sessions:Qo(i,(r,n)=>e.authorize(r,n))},scheduledScope:()=>{let r=s.activeWorkspace();if(!r)return null;try{return s.trustedScope(r,th)}catch{return null}}}}async function ih(){for(let s of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=ni(s),t=new xe({env:s,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:Tt,buildId:Se,browser:ni({}).browser}}async function ea(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let s=new xe({monitor:!1});try{if(await s.ready,!s.enabled)throw new Error("Sentry verification transport is disabled");let e=s.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await s.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Tt,buildId:Se}}finally{await s.close()}}var Gt=St(sh(ah(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),uh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[uh]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Qe,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Qe;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function Fi(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var hh=null;function fh(){return hh??=ch.create({refreshOnCreate:!1})}var Bi=new Map;async function It(){let s=await fh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let i of Bi.keys())t.has(i)||(s.unregisterProvider(i),Bi.delete(i));for(let i of t){let r=e?.getRegisteredNativeProvider(i),n=e?.getRegisteredProviderConfig(i),o=r??n;!o||Bi.get(i)===o||(r?s.registerNativeProvider(r):n&&s.registerProvider(i,n),Bi.set(i,o))}return await s.refresh({allowNetwork:!1}),s}function re(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():je()}function je(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...En(d.current,d.current.sessionManager.getSessionName(),d.tuiCatalog?.ids()??[]),idle:d.current.isIdle()&&!d.tuiPrompts.sending,streaming:d.tuiStreaming,queuedPrompts:d.tuiPrompts.view(),hasPendingPrompts:d.current.hasPendingMessages?.()??!1,interactions:d.interactions?.pending(d.current.sessionManager.getSessionId())??[]}}async function Gr(s,e,t,i,r){let n=he(s);We({...je(),idle:n.isIdle()},e,r);let o=n.isIdle();o&&gt(()=>d.hosted?.adapter.assertAdmission(),i,(c,a)=>d.bridge?.reportError?.(c,a)),o&&(d.operation=i);try{let c=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===s)await d.replacementContext.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:r});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:r})}d.current?.sessionManager.getSessionId()===s&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:je()})}catch(c){throw o&&(d.operation=void 0),c}}function Lr(){let s=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!s||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==s||d.tuiAgentError)return!1;let i=je();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!i.paused&&!i.interactions.length};d.tuiPrompts.schedule(t,(i,r,n)=>Gr(s,i,r,n))}function ne(s){if(re().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function na(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=re(),r=d.current?je():null,n=await Ke(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=r?await Ke(r.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await qr.listAll(),a=d.workspaceSessions?.retainedSessions()??[];r&&o&&a.push({sessionId:r.sessionId,cwd:o,path:null,name:r.name,modified:r.messages.at(-1)?.timestamp??new Date().toISOString(),idle:r.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&r.idle&&d.tuiPrompts.length===0&&!r.messages.some(p=>p.role==="user")});let l=(await Promise.all(s.map(async p=>{let y=(await ht(p.path,c).catch(m=>(m instanceof Ht?p.available=!1:d.bridge?.reportError?.(m,{stage:"workspace_sessions"}),[]))).map(m=>({id:m.id,workspaceId:p.id,path:m.path,name:m.name||m.firstMessage?.slice(0,50)||"",modified:m.modified.toISOString(),idle:!0}));for(let m of a.filter(f=>f.cwd===p.path)){if(m.blank&&m.sessionId!==t.sessionId)continue;let f=y.findIndex(k=>k.id===m.sessionId),w={id:m.sessionId,workspaceId:p.id,path:m.path??y[f]?.path??null,name:m.name,modified:m.modified,idle:m.idle};f<0?y.unshift(w):y[f]=w}return p.path===n&&!y.some(m=>m.id===t.sessionId)&&y.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),y}))).flat();return{items:s,activeId:e,sessions:l}}var ia=0;async function ie(){if(!d.bridge)return;let s=++ia;try{let e=await na();s===ia&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function zr(s,e=!1){let t=d.workspaces?.get(s);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(t.path),!e&&d.current&&t.path===await Ke(d.current.cwd)&&!d.workspaceSessions?.hasWorkspace(t.path))d.selected="tui",d.activeWorkspaceId=s,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:re()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await d.workspaceSessions.reuseBlank(t.path))&&await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=s,d.bridge?.publish({type:"snapshot",session:re()})}await ie()}async function ra(s,e,t){let i=d.workspaces?.get(s);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=await Ae(i.path);if(d.workspaceSessions?.hasSession(r,e)||d.current?.sessionManager.getSessionId()===e&&await Ke(d.current.cwd)===r)return i;if(!(await ht(r)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return i}function he(s){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function le(s){d.current=s,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:re()})}function oa(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let s=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!s)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return lh.create(s,void 0,{projectTrusted:e})}async function aa(){let s=oa(),e=r=>({packages:(r.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:r.extensions??[],skills:r.skills??[]}),t=new sa({cwd:re().cwd,agentDir:we(),settingsManager:s}),i=Yn(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:i}}async function gh(s){ne(s.sessionId);let e=d.selected==="tui"?he(s.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=oa();if(s.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let i=s.value.trim(),r=s.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(s.kind==="packages"){let n=new sa({cwd:re().cwd,agentDir:we(),settingsManager:t});s.action==="add"?await n.installAndPersist(i,{local:s.scope==="project"}):await n.removeAndPersist(i,{local:s.scope==="project"})}else if(s.kind==="extensions"){let n=r.extensions??[],o=s.action==="add"?[...new Set([...n,i])]:n.filter(c=>c!==i);s.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let n=r.skills??[],o=s.action==="add"?[...new Set([...n,i])]:n.filter(c=>c!==i);s.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&le(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await aa()}function Ui(s,e=mr){if(d.hostedMode===!1||d.hostedMode===void 0&&d.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");d.hostedMode=!0;let t=(a,l)=>{let p=Br(a);return{cwd:p,sessionId:l,workspaceId:ta("sha256").update(p).digest("hex")}},i=Pt(we(),"pi-web","hosted"),r=new Hi({configPath:Jo(we())});d.hosted??=new Wi({root:i,...r.enabled?{dev:r,devStatusPath:Ko(we())}:{},...r.catalog.length?{catalog:[...Me,...r.catalog],devArchives:r.archives,devRoots:r.roots}:{},...Zo({root:i,sessions:()=>d.workspaceSessions,activeWorkspace:()=>d.workspaceSessions?.path??null,trustedScope:t,sessionTitle:a=>d.workspaceSessions?.retainedSessions().find(l=>l.sessionId===a)?.name,changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(nh(St(Gt,"../../package.json"),"utf8")).version,packageRoot:St(Gt,"../.."),workerEntry:St(Gt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${ta("sha256").update(we()).digest("hex")}`,resolveSession:a=>{let l=d.current;if(l?.sessionManager.getSessionId()===a)return t(l.cwd,a);let p=d.workspaceSessions?.hostedScope(a);return p?t(p.cwd,a):null},legacy:()=>Xo(Pt(we(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Lr),d.pi=s,d.tools?.clear(),d.tools=new ft({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(a,l)=>d.bridge?.reportError?.(a,l),breadcrumb:(a,l)=>d.bridge?.breadcrumb?.(a,l),anonymize:a=>d.telemetry?.session(a)??"unavailable"});let n=a=>({...d.operation,session:d.telemetry?.session(a.sessionManager.getSessionId()),piVersion:Ur,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new ut(s.events,a=>!!d.bridge&&a.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(a.pluginId),()=>{d.current&&d.selected==="tui"&&le(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=s.events.on(hi,()=>{d.selected==="tui"&&d.current&&le(d.current)})};o(),s.on("session_start",async(a,l)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,o(),d.current=l,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(s,t(l.cwd,l.sessionManager.getSessionId())),await d.hosted?.start(),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Ye.discover(l.cwd,l.isProjectTrusted?.()??!1);if(d.current!==l)return;d.tuiCatalog=p}d.replacementSessionId!==l.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),le(l),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(l.cwd).then(async p=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==l.sessionManager.getSessionId()||(d.activeWorkspaceId=p.id,await ie())}).catch(p=>{d.bridge?.publish({type:"error",message:p instanceof Error?p.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(p,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&l.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,c(l).catch(p=>{l.ui.notify(p instanceof Error?p.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),s.on("agent_start",(a,l)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",n(l)),le(l),ie()}),s.on("agent_end",(a,l)=>le(l)),s.on("agent_settled",(a,l)=>{d.bridge?.breadcrumb?.("agent_end",n(l)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Lr(),le(l),ie()}),s.on("tool_execution_start",(a,l)=>{d.tools?.start(a,n(l))}),s.on("tool_execution_end",(a,l)=>{d.tools?.end(a,n(l))}),s.on("model_select",(a,l)=>le(l)),s.on("thinking_level_select",(a,l)=>le(l)),s.on("message_end",(a,l)=>{if(a.message.role==="assistant"&&a.message.stopReason==="error"){d.tuiAgentError=!0;let p=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion:Ur});d.selected==="tui"&&d.bridge?.publish({type:"error",message:a.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:p,...d.operation})}a.message.role==="toolResult"&&d.tools?.message(a.message,n(l)),a.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&a.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),le(l),ie()}),s.on("session_info_changed",(a,l)=>le(l)),s.on("message_update",(a,l)=>{if(d.current=l,a.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(a.message.timestamp).toISOString(),blocks:Je(a.message.content)},d.selected!=="tui"||d.bridge===null))return;let p=Date.now();p-d.lastStreamAt<60||(d.lastStreamAt=p,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),s.on("session_shutdown",async a=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,a.reason==="new"||a.reason==="resume"||a.reason==="fork"||a.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let l=d.bridge,p=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let u=d.workspaceSessions;d.workspaceSessions=null,await u?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,l?await l.close():await p?.close()});let c=async a=>{d.telemetry??=new xe;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=s,d.tuiCatalog=await Ye.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ui(Tn(we())),await d.workspaces.load());try{await d.workspaces.discover((await qr.listAll()).map(u=>u.cwd))}catch(u){a.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${u instanceof Error?u.message:String(u)}`,"warning")}let l=await d.workspaces.add(a.cwd);if(d.selected==="tui"&&(d.activeWorkspaceId=l.id),d.bridge&&(d.bridge.protocolVersion!==7||d.bridge.buildId!==Se||typeof d.bridge.reportError!="function"||typeof d.bridge.runPluginTool!="function")){let u=d.bridge;if(d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)&&d.workspaceSessions.session&&!d.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");d.bridge=null,await u.close(),await d.telemetry.close(),d.telemetry=new xe}if(d.bridge===null){let u=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,y=u?.session&&u.path?{path:u.path,sessionManager:u.session.sessionManager}:null;u&&(await u.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new wi(f=>{d.selected==="sdk"&&d.bridge?.publish(f)},()=>d.current?.model,f=>{try{return!!d.current&&Br(d.current.cwd)===f&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,w)=>d.bridge?.reportError?.(f,w),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(f,w)=>d.bridge?.breadcrumb?.(f,w),anonymize:f=>d.telemetry?.session(f)??"unavailable"},()=>{ie()},[],{adapter:d.hosted.adapter,scope:t}),y&&await d.workspaceSessions.open(y.path,{sessionManager:y.sessionManager});let m={hosted:d.hosted?.handlers,selfUpdate:new Ii({agentDir:we(),packageRoot:St(Gt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,hostedPair:d.hosted.manager.hostPair,beforeRestart:()=>d.hosted.prepareRestart()}),snapshot:re,busyGitWorkspaces:()=>{let f=(d.workspaceSessions?.retainedSessions()??[]).filter(w=>!w.idle).map(w=>w.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{f.push(Br(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=Fi();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Fi()?.asset(f)??null,async invokePluginAction(f,w,k,P){if(ne(f),!Fi()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,_=d.tuiGeneration,H=d.workspaceSessions?.session,N={requestId:ph(),sessionId:f,pluginId:w,action:k,input:P},T=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(N):await fi(d.pi.events,N,15e3,d.tuiWaitController.signal);if(ne(f),E!==d.selected||(E==="tui"?_!==d.tuiGeneration:H!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&le(d.current),T},async resolvePluginInteraction(f,w,k,P){if(ne(f),!Fi()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(f,w,k,P):d.interactions.resolve(f,w,k,P)},image(f,w,k){ne(f);let E=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(H=>H.id===w);if(E?.type!=="message"||E.message.role!=="user"||!Array.isArray(E.message.content))return null;let _=E.message.content[k];return _?.type!=="image"?null:{data:Buffer.from(_.data,"base64"),mimeType:_.mimeType}},async workspaces(){return na()},async addWorkspace(f,w){let k=await d.workspaces.add(f,w);try{await zr(k.id,!0)}catch(P){throw await ie(),P}},async selectWorkspace(f){await zr(f)},async newSessionInWorkspace(f){await zr(f,!0)},async removeWorkspace(f){if(f===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(f),await ie()},async selectSession(f,w,k){let P=d.workspaces?.get(f);if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(P.path),w===d.current?.sessionManager.getSessionId()&&P.path===await Ke(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:re()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===w&&d.workspaceSessions.path===P.path)return;if(d.workspaceSessions?.hasSession(P.path,w))await d.workspaceSessions.open(P.path,{sessionId:w});else{if(!(await ht(P.path)).some(_=>_.id===w&&_.path===k))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(P.path,{sessionFile:k})}d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:re()})}await ie()},async renameSession(f,w,k,P){let E=P.replace(/\s+/g," ").trim();if(E.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await ra(f,w,k),d.current?.sessionManager.getSessionId()===w&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(w,E)||qr.open(k).appendSessionInfo(E),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===w&&d.bridge?.publish({type:"snapshot",session:re()}),await ie()},async deleteSession(f,w,k){let P=await ra(f,w,k);if(d.current?.sessionManager.getSessionId()===w)throw new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664");let E=await d.workspaceSessions?.discard(w)??null,_=E?.path??(k||null);_&&await Xn(_,we()),E?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(P.path,"new"),d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:re()})),await ie()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let f=d.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let w=f.scopedModels?.map(k=>`${k.model.provider}/${k.model.id}`)??[];return f.modelRegistry.getAvailable().filter(k=>w.length===0||w.includes(`${k.provider}/${k.id}`)).map(k=>({provider:k.provider,id:k.id,name:k.name}))},async providers(){let f=await It(),w=new Set((await f.listCredentials()).map(k=>k.providerId));return f.getProviders().map(k=>({id:k.id,name:k.name,configured:f.getProviderAuthStatus(k.id).configured,storedCredential:w.has(k.id),methods:[k.auth.apiKey?.login?"api_key":null,k.auth.oauth?"oauth":null].filter(P=>P!==null)}))},async providerModels(f){let w=await It();return ln(Pt(we(),"models.json"),f,w)},async updateProviderModel(f,w,k){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let P=re().model;if(k.action==="remove"&&P===`${w}/${k.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(k.action==="save"&&k.originalId&&k.originalId!==k.model.id&&P===`${w}/${k.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let E=await It();await dn(Pt(we(),"models.json"),w,k,E),await E.refresh({providers:[w],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[w],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[w],allowNetwork:!1});let _=k.action==="save"?k.model.id:k.action==="base_url"&&P?.startsWith(`${w}/`)?P.slice(w.length+1):null;if(_&&P===`${w}/${_}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(w,_)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let H=he(f),N=H.modelRegistry.find(w,_);if(!N||!d.pi||!await d.pi.setModel(N))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");le(H)}},async logoutProvider(f,w){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let k=await It();if(!(await k.listCredentials()).some(P=>P.providerId===w))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await k.logout(w),await d.current?.modelRegistry.refresh({providers:[w],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[w],allowNetwork:!1})},async loginProvider(f,w,k){let P=await It();await P.login(f,w,rn(f,w,k)),await P.refresh({providers:[f],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[f],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[f],allowNetwork:!1})},async addCustomProvider(f,w){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let k=await It();if(k.getProvider(w.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await sn(Pt(we(),"models.json"),w),await k.refresh({allowNetwork:!1}),await d.current?.modelRegistry.refresh({allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return d.selected==="tui"?(d.pi?.getCommands()??[]).filter(f=>f.name!=="web"&&f.name!=="web-dev-reload").map(f=>({name:f.name,description:f.description})):[]},async compact(f){if(ne(f),d.selected==="sdk"){let k=d.workspaceSessions?.session;if(!k||!k.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await k.compact(),d.bridge?.publish({type:"snapshot",session:re()});return}let w=he(f);if(!w.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");w.compact()},async setModel(f,w,k){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.setModel(w,k);return}let P=he(f);if(!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=P.modelRegistry.find(w,k);if(!E||!P.modelRegistry.getAvailable().some(_=>_.provider===w&&_.id===k))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(E))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");le(P)},async setThinkingLevel(f,w){if(ne(f),!["off","minimal","low","medium","high","xhigh"].includes(w))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(d.selected==="sdk"){let E=d.workspaceSessions?.session;if(!E||!E.isIdle||!E.getAvailableThinkingLevels().includes(w))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");E.setThinkingLevel(w),d.bridge?.publish({type:"snapshot",session:re()});return}let P=he(f);if(!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!P.model||!dh(P.model).includes(w))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.setThinkingLevel(w),le(P)},config:aa,updateConfig:gh,async send(f,w,k=[],P,E){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.send(w,k,P,E);return}let _=he(f);if(We(je(),w,E),E==="followUp"&&(!_.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(w,k,P),Lr();return}if(_.isIdle()&&d.tuiPrompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Gr(f,w,k,P,E)},async updateQueuedPrompt(f,w,k,P){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(w,k,P);return}if(P.kind==="steer"&&he(f).isIdle())throw new ae("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(w,k,P,(E,_,H)=>Gr(f,E,_,H,"steer"))},async abort(f){if(ne(f),d.selected==="sdk")await d.workspaceSessions.stop();else{let w=he(f);if(w.isIdle()&&!d.tuiPrompts.sending)return;if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.tools?.cancel(),d.bridge?.breadcrumb?.("cancel",{...d.operation}),d.pi.appendEntry(Dt),w.abort()}},async resume(f,w){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.resume(w);return}let k=he(f);if(gt(()=>d.hosted?.adapter.assertAdmission(),w,(P,E)=>d.bridge?.reportError?.(P,E)),!k.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!k.model||!d.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!k.modelRegistry.hasConfiguredAuth(k.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");d.operation=w;try{d.pi.sendMessage(gi(re().messages),{triggerTurn:!0})}catch(P){throw d.operation=void 0,P}},async newSession(f){if(ne(f),d.selected==="sdk"){let P=d.workspaces?.get(d.activeWorkspaceId??"");if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(P.path)||await d.workspaceSessions.open(P.path,"new"),await ie();return}let w=he(f);if(!w.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(w.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:re()}),await ie();return}if((await d.commandContext.newSession({withSession:async P=>{d.commandContext=P,d.replacementContext=P,d.replacementSessionId=P.sessionManager.getSessionId(),d.current=P}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await ie()}};m.addWorkspace=d.lifecycle.wrap(m.addWorkspace),m.selectWorkspace=d.lifecycle.wrap(m.selectWorkspace),m.newSessionInWorkspace=d.lifecycle.wrap(m.newSessionInWorkspace),m.removeWorkspace=d.lifecycle.wrap(m.removeWorkspace),m.selectSession=d.lifecycle.wrap(m.selectSession),m.renameSession=d.lifecycle.wrap(m.renameSession),m.deleteSession=d.lifecycle.wrap(m.deleteSession),m.newSession=d.lifecycle.wrap(m.newSession),m.updateConfig=d.lifecycle.wrap(m.updateConfig),d.bridge=await Sn(m,Gt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let u=[],y=null;for(let m of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(rh).filter(Boolean))try{u.push(oh(Pt(St(m),"dist"),(f,w)=>{let k=String(w??"");["client.js","client.css"].includes(k)&&(y&&clearTimeout(y),y=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(f){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${m}: ${String(f)}`})}d.stopPluginWatch=()=>{for(let m of u)m.close();y&&clearTimeout(y)}}let p=await e(d.bridge.url).catch(()=>!1);a.ui.notify(`pi-webapp: ${d.bridge.url}`,p?"info":"warning"),a.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(l){throw d.telemetry?.capture(l,{stage:"open_web",piVersion:Ur}),d.bridge||(await d.telemetry?.close(),d.telemetry=null),l}};s.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(a,l)=>c(l)}),s.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(a,l)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(a))throw new Error("Launcher stop receipt ID required");try{await d.hosted?.shutdown(),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!0})}`,"info")}catch(p){console.error("pi-webapp: plugin shutdown refused the stop request:",p),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!1})}`,"warning")}}}),s.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(a,l)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await l.waitForIdle(),await d.lifecycle.run(async()=>{let p=d.workspaceSessions?.session;p&&(await p.waitForIdle(),await d.workspaceSessions.reload()),await l.reload()}))}})}var Ck=Ui;export{Ck as default,ih as verifySentryDisabledRelease,ea as verifySentryNodeRelease};
48
48
 
49
- //# debugId=fbbcbd4a-0bea-4e92-adf3-88783db8ace0
49
+ //# debugId=21797faa-38d4-4a0e-a037-226896d3ebe4