pi-webapp 0.1.54-alpha.2 → 0.1.54-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/extension.js +40 -36
  2. package/dist/hosted-recovery.js +2 -2
  3. package/dist/hosted-worker.js +2 -2
  4. package/package.json +2 -2
  5. package/web/dist/.vite/manifest.json +40 -40
  6. package/web/dist/assets/{MarkdownText-ozc5ubjI.js → MarkdownText-Dek0vMEt.js} +4 -4
  7. package/web/dist/assets/{app-zBuL5kvH.js → app-CPp0_pSX.js} +5 -5
  8. package/web/dist/assets/app.js +4 -4
  9. package/web/dist/assets/{code-editor-Bqv_YjkY.js → code-editor-0exAlmp9.js} +4 -4
  10. package/web/dist/assets/{dist-DxkYOh1x.js → dist-BARanDSI.js} +2 -2
  11. package/web/dist/assets/{dist-DcCXZ8Rj.js → dist-BDGl5CoK.js} +2 -2
  12. package/web/dist/assets/{dist-Dofxo368.js → dist-BKDAtAc4.js} +2 -2
  13. package/web/dist/assets/{dist-CEWKL9kJ.js → dist-BRWi0191.js} +2 -2
  14. package/web/dist/assets/{dist-BR6sl7cV.js → dist-BqbkTGkq.js} +2 -2
  15. package/web/dist/assets/{dist-DSv6YTbw.js → dist-BsLAIspO.js} +2 -2
  16. package/web/dist/assets/{dist-D8zBFk2N.js → dist-D-xrsUdb.js} +2 -2
  17. package/web/dist/assets/{dist-D94MLsYm.js → dist-D8Xrr9TB.js} +2 -2
  18. package/web/dist/assets/{dist-CR7xsvSD.js → dist-IvCUEFtm.js} +2 -2
  19. package/web/dist/assets/{dist-DtgEbjMA.js → dist-JswL9B9u.js} +2 -2
  20. package/web/dist/assets/{dist-DPMSomV_.js → dist-NLiHH-dW.js} +2 -2
  21. package/web/dist/assets/{graphql-t5l6XeUa.js → graphql-CS7RiINc.js} +2 -2
  22. package/web/dist/assets/{http-CA54Nmhu.js → http-BbJ-0d2B.js} +2 -2
  23. package/web/dist/assets/{php-DjAwqY1k.js → php-DGzbCYMe.js} +2 -2
  24. package/web/dist/assets/{plugin-muXBtnku.js → plugin-D3ViiAZ1.js} +2 -2
  25. package/web/dist/assets/{plugin-DgvXwDBK.js → plugin-DIqp6uGq.js} +3 -3
  26. package/web/dist/assets/plugin-Yj1w71cu.js +18 -0
  27. package/web/dist/assets/plugin2.css +1 -1
  28. package/web/dist/assets/{rst-6Nsa0tEe.js → rst-BEZOkmPp.js} +2 -2
  29. package/web/dist/assets/{ruby-BIfqPC89.js → ruby-By9RhgN3.js} +2 -2
  30. package/web/dist/assets/{svelte-DXhPh5aW.js → svelte-Ca0V3N3j.js} +2 -2
  31. package/web/dist/assets/{vue-DpKsjiHm.js → vue-C8usJwj9.js} +2 -2
  32. package/web/dist/assets/plugin-CmmnhL_a.js +0 -18
package/dist/extension.js CHANGED
@@ -1,53 +1,57 @@
1
- (function(){try{var n=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="493c6a42-4fe5-4290-8ae9-a8d404360b8a",n._sentryDebugIdIdentifier="sentry-dbid-493c6a42-4fe5-4290-8ae9-a8d404360b8a")}catch{}})();import{delimiter as ah,dirname as ch,join as wt,resolve as vt}from"node:path";import{readFileSync as lh,realpathSync as Yi,watch as dh}from"node:fs";import{fileURLToPath as ph}from"node:url";import{DefaultPackageManager as Ma,getAgentDir as me,ModelRuntime as uh,SessionManager as tn,SettingsManager as fh,VERSION as Qi}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as hh}from"@earendil-works/pi-ai";import{randomBytes as js,randomUUID as ii,timingSafeEqual as Yl}from"node:crypto";import{readFile as Ql,readdir as Zl}from"node:fs/promises";import{createServer as ed}from"node:http";import{join as ni}from"node:path";import{getAgentDir as td}from"@earendil-works/pi-coding-agent";import{isAbsolute as mc,relative as wc}from"node:path";var rt={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var an={id:rt.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 Va}from"node:child_process";import{realpath as Ua}from"node:fs/promises";import{isAbsolute as cn,relative as Ba,sep as La,win32 as za}from"node:path";var A=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function j(n,e,t=2*1024*1024,r={}){let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,o)=>{let c,a=Va("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:n,env:{...i,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new A("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let 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 A("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 A("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):w==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new A("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new A("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new A(l.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});a.stdin?.on("error",l=>{c=l}),r.input!==void 0&&a.stdin?.end(r.input)})}async function pe(n){let e=await Ua(n),t;try{t=(await j(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(i){if(i instanceof A&&i.status===404)return{kind:"not-repository"};if(i instanceof A&&i.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw i}let r=Ba(t,e).split(La).join("/");if(r===".."||r.startsWith("../")||cn(r))throw new A("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function Le(n){if(typeof n!="string"||!n||n.length>4096||n.includes("\0")||n.includes("\\")||cn(n)||za.isAbsolute(n)||n.split("/").some(e=>!e||e==="."||e===".."))throw new A("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as nc}from"node:crypto";import{lstat as qr,realpath as Pn}from"node:fs/promises";import{dirname as kn,isAbsolute as sc,relative as oc,resolve as It}from"node:path";import{lstat as tc}from"node:fs/promises";import{resolve as rc}from"node:path";import{createHash as qa}from"node:crypto";import{constants as Te}from"node:fs";import{open as Br,opendir as Ga,realpath as ln,stat as qt}from"node:fs/promises";import{isAbsolute as pn,relative as Ja,resolve as Ka,sep as Xa,win32 as Ya}from"node:path";var Qa=1e3,Za={bytes:512*1024,lines:1e4},Lr={bytes:5*1024*1024,lines:2e5},un=8*1024*1024,ec=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Ur=n=>qa("sha256").update(n).digest("hex"),H=class extends Error{status;reason;constructor(e,t=400,r){super(e),this.name="WorkspaceFileError",this.status=t,this.reason=r}};function dn(n,e){let t=Ja(n,e);return t!==".."&&!t.startsWith(`..${Xa}`)&&!pn(t)}async function kt(n,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||pn(e)||Ya.isAbsolute(e))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await ln(n),r=Ka(t,e);if(!dn(t,r))throw new H("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let i=await ln(r);if(!dn(t,i))throw new H("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return i}async function Gt(n){try{return await n()}catch(e){if(e instanceof H)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new H("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new H("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function fn(n,e){return Gt(async()=>{let t=await kt(n,e),r=[],i=!1;for await(let s of await Ga(t)){if(s.name===".git")continue;if(r.length===Qa){i=!0;break}let o=e?`${e}/${s.name}`:s.name,c=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let a=await qt(await kt(n,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}r.push({name:s.name,path:o,kind:c})}return r.sort((s,o)=>+(o.kind==="directory")-+(s.kind==="directory")||ec.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:r,truncated:i}})}function hn(n){if(n.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(n[0]===255&&n[1]===216&&n[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(n.subarray(0,6).toString("ascii")))return"image/gif";if(n.subarray(0,4).toString("ascii")==="RIFF"&&n.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Pt(n,e,t=Za){return Gt(async()=>{let r=await kt(n,e);if(!(await qt(r)).isFile())throw new H("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Br(r,Te.O_RDONLY|Te.O_NONBLOCK|(Te.O_NOFOLLOW??0));try{let s=await i.stat();if(!s.isFile())throw new H("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let o={path:e,size:s.size},c=Buffer.alloc(16);await i.read(c,0,c.length,0);let a=hn(c),l=a?un:t.bytes;if(s.size>l)return{...o,kind:"too-large",limit:l,unit:"bytes"};let p=Buffer.alloc(Math.min(s.size+1,l+1)),u=0;for(;u<p.length;){let{bytesRead:f}=await i.read(p,u,p.length-u,u);if(!f)break;u+=f}if(u>s.size)throw new H("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let w=p.subarray(0,u);if(a)return{...o,kind:"image",mimeType:a,data:w.toString("base64")};if(w.some(f=>f===0||f<32&&![9,10,12,13,27].includes(f)))return{...o,kind:"unsupported"};let m=1;for(let f=0;f<w.length-1;f++)if(w[f]===10&&++m>t.lines)return{...o,kind:"too-large",limit:t.lines,unit:"lines"};try{return{...o,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(w),version:Ur(w)}}catch{return{...o,kind:"unsupported"}}}finally{await i.close()}})}async function gn(n,e){return Gt(async()=>{let t=await kt(n,e);if(!(await qt(t)).isFile())throw new H("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Br(t,Te.O_RDONLY|Te.O_NONBLOCK|(Te.O_NOFOLLOW??0));try{let i=await r.stat();if(!i.isFile())throw new H("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(i.size>un)throw new H("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(i.size+1),o=0;for(;o<s.length;){let{bytesRead:l}=await r.read(s,o,s.length-o,o);if(!l)break;o+=l}if(o>i.size)throw new H("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=s.subarray(0,o),a=hn(c);if(!a)throw new H("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:c}}finally{await r.close()}})}async function mn(n,e,t,r){if(typeof t!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new H("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let i=Buffer.from(t,"utf8"),{bytes:s,lines:o}=Lr;if(i.length>s)throw new H(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let c=1;for(let a of i)if(a===10&&++c>o+1)throw new H(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${o} \u884C`,413);return Gt(async()=>{let a=await kt(n,e);if(!(await qt(a)).isFile())throw new H("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let l=await Br(a,Te.O_RDWR|Te.O_NONBLOCK|(Te.O_NOFOLLOW??0));try{let p=await l.stat();if(!p.isFile())throw new H("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new H("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");let u=Buffer.alloc(p.size+1),w=0;for(;w<u.length;){let{bytesRead:f}=await l.read(u,w,u.length-w,w);if(!f)break;w+=f}if(w>p.size||Ur(u.subarray(0,w))!==r)throw new H("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");await l.truncate(0);let m=0;for(;m<i.length;)m+=(await l.write(i,m,i.length-m,m)).bytesWritten;return await l.sync(),{path:e,size:i.length,version:Ur(i)}}finally{await l.close()}})}var ic=1e3,wn=512*1024,yn=1e4;function vn(n,e){return e.startsWith(n)&&e.slice(n.length)||void 0}async function it(n){let e=await pe(n);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,i=await j(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:t,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=i.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);s.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);s.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){s.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(s.ahead=Number(P[1]),s.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 w=vn(r,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!w)continue;if(s.entries.length===ic){s.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..."},k=m===void 0?void 0:vn(r,m);k&&(y.originalPath=k),s.entries.push(y)}return s}async function bn(n,e,t){if(Le(e),!["staged","unstaged","untracked"].includes(t))throw new A("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await it(n);if(r.kind!=="repository")throw new A("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i={path:e,area:t},s=r.entries.find(c=>c.path===e);if(!s)return{...i,kind:"empty"};if(s.conflict)return{...i,kind:"conflict"};if(s.submodule)return{...i,kind:"submodule"};if(t==="untracked"){if(!s.untracked)return{...i,kind:"empty"};if(!(await tc(rc(n,e))).isFile())return{...i,kind:"unsupported"};let c=await Pt(n,e);if(c.kind==="too-large")return{...i,kind:"too-large"};if(c.kind!=="text")return{...i,kind:"binary"};if(!c.text)return{...i,kind:"empty"};let a=c.text.split(`
2
- `),l=a.at(-1)==="";l&&a.pop();let p=`--- /dev/null
1
+ (function(){try{var n=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new n.Error().stack;e&&(n._sentryDebugIds=n._sentryDebugIds||{},n._sentryDebugIds[e]="4bfba74a-9d1c-4bfc-bdd9-a7aeb8a78cad",n._sentryDebugIdIdentifier="sentry-dbid-4bfba74a-9d1c-4bfc-bdd9-a7aeb8a78cad")}catch{}})();import{delimiter as Dh,dirname as Oh,join as yt,resolve as bt}from"node:path";import{readFileSync as Hh,realpathSync as on,watch as Mh}from"node:fs";import{fileURLToPath as Wh}from"node:url";import{DefaultPackageManager as sc,getAgentDir as we,ModelRuntime as jh,SessionManager as dn,SettingsManager as $h,VERSION as an}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as Fh}from"@earendil-works/pi-ai";import{randomBytes as so,randomUUID as li,timingSafeEqual as Ed}from"node:crypto";import{readFile as xd,readdir as _d}from"node:fs/promises";import{createServer as Td}from"node:http";import{join as di}from"node:path";import{getAgentDir as Ad}from"@earendil-works/pi-coding-agent";import{isAbsolute as $c,relative as Fc}from"node:path";var de={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var gn={id:de.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 dc}from"node:child_process";import{realpath as pc}from"node:fs/promises";import{isAbsolute as mn,relative as uc,sep as fc,win32 as hc}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function j(n,e,t=2*1024*1024,r={}){let i=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,o)=>{let a,c=dc("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:n,env:{...i,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(a){o(new R("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let w=l.killed||l.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(u)?"index_locked":/already exists/i.test(u)?"branch_exists":/already checked out|used by worktree/i.test(u)?"branch_in_use":/would be overwritten|local changes/i.test(u)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(u)?"identity_missing":"git_failed";o(new R("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",w==="outcome_unknown"?503:409,w));return}let h=l.code;h==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):h==="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))});c.stdin?.on("error",l=>{a=l}),r.input!==void 0&&c.stdin?.end(r.input)})}async function ue(n){let e=await pc(n),t;try{t=(await j(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(i){if(i instanceof R&&i.status===404)return{kind:"not-repository"};if(i instanceof R&&i.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw i}let r=uc(t,e).split(fc).join("/");if(r===".."||r.startsWith("../")||mn(r))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function qe(n){if(typeof n!="string"||!n||n.length>4096||n.includes("\0")||n.includes("\\")||mn(n)||hc.isAbsolute(n)||n.split("/").some(e=>!e||e==="."||e===".."))throw new R("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as _c}from"node:crypto";import{lstat as Yr,realpath as Rn}from"node:fs/promises";import{dirname as An,isAbsolute as Tc,relative as Ac,resolve as St}from"node:path";import{lstat as Sc}from"node:fs/promises";import{resolve as Ec}from"node:path";import{createHash as gc}from"node:crypto";import{constants as Re}from"node:fs";import{open as Jr,opendir as mc,realpath as wn,stat as Gt}from"node:fs/promises";import{isAbsolute as vn,relative as wc,resolve as yc,sep as vc,win32 as bc}from"node:path";var kc=1e3,Pc={bytes:512*1024,lines:1e4},Kr={bytes:5*1024*1024,lines:2e5},bn=8*1024*1024,Ic=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Gr=n=>gc("sha256").update(n).digest("hex"),M=class extends Error{status;reason;constructor(e,t=400,r){super(e),this.name="WorkspaceFileError",this.status=t,this.reason=r}};function yn(n,e){let t=wc(n,e);return t!==".."&&!t.startsWith(`..${vc}`)&&!vn(t)}async function Pt(n,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||vn(e)||bc.isAbsolute(e))throw new M("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await wn(n),r=yc(t,e);if(!yn(t,r))throw new M("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let i=await wn(r);if(!yn(t,i))throw new M("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return i}async function Jt(n){try{return await n()}catch(e){if(e instanceof M)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new M("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new M("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function kn(n,e){return Jt(async()=>{let t=await Pt(n,e),r=[],i=!1;for await(let s of await mc(t)){if(s.name===".git")continue;if(r.length===kc){i=!0;break}let o=e?`${e}/${s.name}`:s.name,a=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let c=await Gt(await Pt(n,o));a=c.isDirectory()?"directory":c.isFile()?"file":"other"}catch{}r.push({name:s.name,path:o,kind:a})}return r.sort((s,o)=>+(o.kind==="directory")-+(s.kind==="directory")||Ic.compare(s.name,o.name)||s.name.localeCompare(o.name)),{path:e,entries:r,truncated:i}})}function Pn(n){if(n.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(n[0]===255&&n[1]===216&&n[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(n.subarray(0,6).toString("ascii")))return"image/gif";if(n.subarray(0,4).toString("ascii")==="RIFF"&&n.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function It(n,e,t=Pc){return Jt(async()=>{let r=await Pt(n,e);if(!(await Gt(r)).isFile())throw new M("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Jr(r,Re.O_RDONLY|Re.O_NONBLOCK|(Re.O_NOFOLLOW??0));try{let s=await i.stat();if(!s.isFile())throw new M("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let o={path:e,size:s.size},a=Buffer.alloc(16);await i.read(a,0,a.length,0);let c=Pn(a),l=c?bn:t.bytes;if(s.size>l)return{...o,kind:"too-large",limit:l,unit:"bytes"};let p=Buffer.alloc(Math.min(s.size+1,l+1)),u=0;for(;u<p.length;){let{bytesRead:v}=await i.read(p,u,p.length-u,u);if(!v)break;u+=v}if(u>s.size)throw new M("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let h=p.subarray(0,u);if(c)return{...o,kind:"image",mimeType:c,data:h.toString("base64")};if(h.some(v=>v===0||v<32&&![9,10,12,13,27].includes(v)))return{...o,kind:"unsupported"};let w=1;for(let v=0;v<h.length-1;v++)if(h[v]===10&&++w>t.lines)return{...o,kind:"too-large",limit:t.lines,unit:"lines"};try{return{...o,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(h),version:Gr(h)}}catch{return{...o,kind:"unsupported"}}}finally{await i.close()}})}async function In(n,e){return Jt(async()=>{let t=await Pt(n,e);if(!(await Gt(t)).isFile())throw new M("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Jr(t,Re.O_RDONLY|Re.O_NONBLOCK|(Re.O_NOFOLLOW??0));try{let i=await r.stat();if(!i.isFile())throw new M("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(i.size>bn)throw new M("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(i.size+1),o=0;for(;o<s.length;){let{bytesRead:l}=await r.read(s,o,s.length-o,o);if(!l)break;o+=l}if(o>i.size)throw new M("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let a=s.subarray(0,o),c=Pn(a);if(!c)throw new M("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:c,bytes:a}}finally{await r.close()}})}async function Sn(n,e,t,r){if(typeof t!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new M("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let i=Buffer.from(t,"utf8"),{bytes:s,lines:o}=Kr;if(i.length>s)throw new M(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let a=1;for(let c of i)if(c===10&&++a>o+1)throw new M(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${o} \u884C`,413);return Jt(async()=>{let c=await Pt(n,e);if(!(await Gt(c)).isFile())throw new M("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let l=await Jr(c,Re.O_RDWR|Re.O_NONBLOCK|(Re.O_NOFOLLOW??0));try{let p=await l.stat();if(!p.isFile())throw new M("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new M("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");let u=Buffer.alloc(p.size+1),h=0;for(;h<u.length;){let{bytesRead:v}=await l.read(u,h,u.length-h,h);if(!v)break;h+=v}if(h>p.size||Gr(u.subarray(0,h))!==r)throw new M("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");await l.truncate(0);let w=0;for(;w<i.length;)w+=(await l.write(i,w,i.length-w,w)).bytesWritten;return await l.sync(),{path:e,size:i.length,version:Gr(i)}}finally{await l.close()}})}var xc=1e3,En=512*1024,xn=1e4;function _n(n,e){return e.startsWith(n)&&e.slice(n.length)||void 0}async function nt(n){let e=await ue(n);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,i=await j(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:t,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=i.split("\0");for(let a=0;a<o.length;a++){let c=o[a];if(c.startsWith("# branch.oid ")){let P=c.slice(13);s.head=P==="(initial)"?null:P;continue}if(c.startsWith("# branch.head ")){let P=c.slice(14);s.branch=P==="(detached)"?null:P;continue}if(c.startsWith("# branch.upstream ")){s.upstream=c.slice(18);continue}if(c.startsWith("# branch.ab ")){let P=c.match(/\+(\d+) -(\d+)/);P&&(s.ahead=Number(P[1]),s.behind=Number(P[2]));continue}let l=c[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=c.indexOf(" ",u)+1;let h=_n(r,c.slice(u)),w=l==="2"?o[++a]:void 0;if(!h)continue;if(s.entries.length===xc){s.truncated=!0;continue}let v=c.slice(0,u).split(" "),m={path:h,index:l==="?"?"?":v[1][0],worktree:l==="?"?"?":v[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&v[2]!=="N..."},b=w===void 0?void 0:_n(r,w);b&&(m.originalPath=b),s.entries.push(m)}return s}async function Tn(n,e,t){if(qe(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await nt(n);if(r.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i={path:e,area:t},s=r.entries.find(a=>a.path===e);if(!s)return{...i,kind:"empty"};if(s.conflict)return{...i,kind:"conflict"};if(s.submodule)return{...i,kind:"submodule"};if(t==="untracked"){if(!s.untracked)return{...i,kind:"empty"};if(!(await Sc(Ec(n,e))).isFile())return{...i,kind:"unsupported"};let a=await It(n,e);if(a.kind==="too-large")return{...i,kind:"too-large"};if(a.kind!=="text")return{...i,kind:"binary"};if(!a.text)return{...i,kind:"empty"};let c=a.text.split(`
2
+ `),l=c.at(-1)==="";l&&c.pop();let p=`--- /dev/null
3
3
  +++ b/${e.replace(/[\r\n]/g," ")}
4
- @@ -0,0 +1,${a.length} @@
5
- ${a.map(u=>`+${u}`).join(`
4
+ @@ -0,0 +1,${c.length} @@
5
+ ${c.map(u=>`+${u}`).join(`
6
6
  `)}
7
7
  ${l?"":`\
8
- `}`;return Buffer.byteLength(p)>wn||a.length>yn?{...i,kind:"too-large"}:{...i,kind:"text",patch:p}}if(s.untracked||(t==="staged"?s.index:s.worktree)===".")return{...i,kind:"empty"};let o=t==="staged"&&s.originalPath?[e,s.originalPath]:[e];try{let c=await j(n,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],wn);return c?c.split(`
9
- `).length>yn?{...i,kind:"too-large"}:/^Binary files /m.test(c)?{...i,kind:"binary"}:{...i,kind:"text",patch:c}:{...i,kind:"empty"}}catch(c){if(c instanceof A&&c.status===413)return{...i,kind:"too-large"};throw c}}var zr=new Set,z=(n,e=409)=>{throw new A("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,n)};async function ac(n){return Pn(It(n,(await j(n,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Gr(n,e,t=!1){let r=null;try{let i=await pe(n);i.kind==="repository"&&(r=await ac(i.cwd))}catch(i){if(!t)throw i}if(!r)return e();if(zr.has(r))return z("busy");zr.add(r);try{return await e()}finally{zr.delete(r)}}async function Jt(n){let e=await pe(n),t={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return t;let r=await it(e.root);if(r.kind!=="repository")return t;let[i,s,o]=await Promise.all([j(e.cwd,["ls-files","--stage","-z"]),j(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),j(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 qr(It(o.replace(/\n$/,""),m)),m}catch(f){if(f.code==="ENOENT")return null;throw f}}))).filter(Boolean),l=await Promise.all(r.entries.map(async m=>{try{let f=await qr(It(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=s.split(`
10
- `).filter(Boolean).map(m=>{let[f,,y]=m.split("\0");return{name:f,current:f===r.branch,occupied:!!y&&f!==r.branch}}),u=r.truncated||p.length>512?"too_many_changes":a.includes("index.lock")?"index_locked":a.length||r.entries.some(m=>m.conflict)?"operation_in_progress":null,w=nc("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:i,refs:s,entries:r.entries,files:l,present:a})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:w,staged:r.entries.filter(m=>!m.untracked&&m.index!==".").length,dirty:r.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function cc(n,e){Le(e);let t=kn(It(n.cwd,e));for(;;)try{let s=await Pn(t),o=oc(n.cwd,s);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||sc(o))return z("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;t=kn(t)}let r=await it(n.cwd),i=r.kind==="repository"?r.entries.find(s=>s.path===e):void 0;if(!i||i.submodule||i.conflict)return z("invalid_path",400);try{let s=await qr(It(n.cwd,e));if(!s.isFile()&&!s.isSymbolicLink())return z("invalid_path",400)}catch(s){if(s.code!=="ENOENT")throw s}return i}async function In(n,e,t){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new A("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Gr(n,async()=>{let i=await pe(n);if(i.kind!=="repository")return z("invalid_path",404);t(i.root);let s=await Jt(i.cwd);if(s.version!==e.expected)return z("state_changed");if(s.blocked)return z(s.blocked);let o,c;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return z("invalid_path",400);let p=await cc(i,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return z("state_changed");let u=[e.path];r==="unstage"&&p.originalPath&&(Le(p.originalPath),u.push(p.originalPath)),o=r==="stage"?["add","--",...u]:s.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(r==="commit"){if(i.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(!s.staged)return z("nothing_staged",400);c=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!s.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 j(i.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=s.branches.find(w=>w.name===e.branch),u=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return z("branch_exists");if(r==="switch-branch"&&(!p||p.current))return z("invalid_branch",400);if(u&&i.scope)return z("root_required",400);if(u&&s.dirty)return z("dirty_worktree");if(p?.occupied)return z("branch_in_use");o=r==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:u?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let a=await Jt(i.cwd);if(a.version!==e.expected||a.blocked)return z(a.blocked??"state_changed");t(i.root),await j(i.cwd,o,2*1024*1024,{write:!0,input:c});let l=(await j(i.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:l}})}import{createHash as lc}from"node:crypto";var St=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Sn="%H%x00%P%x00%an%x00%aI%x00%s",En=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function xn(n){let[e,t,r]=await Promise.all([j(n,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),j(n,["rev-parse","--verify","--quiet","HEAD"]).then(c=>c.trim(),()=>null),j(n,["symbolic-ref","-q","HEAD"]).then(c=>c.trim(),()=>null)]),i=[];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||!St.test(m))continue;let f=a.startsWith("refs/heads/")?"branch":a.startsWith("refs/remotes/")?"remote":"tag";i.push({name:a.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:m,kind:f})}if(i.length>512)throw new A("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let s=[...new Set([...i.map(c=>c.hash),...t&&St.test(t)?[t]:[]])].sort(),o=lc("sha256").update(JSON.stringify({refs:i,head:t,symbolic:r})).digest("hex");return{refs:i,tips:s,head:t,snapshot:o}}function _n(n){let[e,t,r,i,s]=n;if(!e||!St.test(e)||!t?.split(" ").filter(Boolean).every(o=>St.test(o)))throw new A("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:r,authoredAt:i,subject:s}}async function Tn(n,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 A("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let r=await pe(n),i={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return i;let s=await xn(r.cwd),o=0;if(e.cursor!==void 0){let u;try{u=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new A("\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 A("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(u.snapshot!==s.snapshot)throw new A("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);o=u.offset}let c={...i,root:r.root,scope:r.scope,head:s.head,snapshot:s.snapshot,refs:s.refs};if(!s.tips.length)return c;let l=(await j(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${Sn}`,`--max-count=${t+1}`,`--skip=${o}`,...s.tips,"--"])).split("\0");if(l.at(-1)===""&&l.pop(),l.length%5)throw new A("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let p=[];for(let u=0;u<l.length;u+=5)p.push(_n(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:s.snapshot,offset:o+t})).toString("base64url")),c}async function An(n,e){if(typeof e!="string"||!St.test(e))throw new A("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await pe(n);if(t.kind!=="repository")throw new A("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await xn(t.cwd);if(!r.tips.length)throw new A("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await j(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await j(t.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new A("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function Rn(n,e,t){if(!Number.isInteger(t)||t<0||t>=Math.max(1,e.length))throw new A("\u7236\u63D0\u4EA4\u9009\u62E9\u65E0\u6548");return e.length?[e[t],n]:[n]}async function Cn(n,e,t){let i=(await j(n.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${Sn}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(i.at(-1)===""&&i.pop(),i.length!==10)throw new A("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let s=_n(i.slice(0,5)),o=Rn(e,s.parents,t),c=["diff-tree","--root","-r","--no-commit-id",...En],[a,l]=await Promise.all([j(n.cwd,[...c,"--name-status","-z",...o,"--","."]),j(n.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 A("\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,k]=p.get(f)??[null,null];w.push({path:f,status:u[m],additions:y,deletions:k})}return{...s,email:i[5],committer:i[6],committerEmail:i[7],committedAt:i[8],message:i[9],root:n.root,scope:n.scope,parentIndex:t,files:w,truncated:u.length>2e3}}async function Nn(n,e,t=0){return Cn(await An(n,e),e,t)}async function Dn(n,e,t,r=0){Le(t);let i=await An(n,e),s=await Cn(i,e,r),o=s.files.find(a=>a.path===t);if(!o)throw new A("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let c={hash:e,path:t,parentIndex:r,parentHash:s.parents[r]??null};if(o.additions===null)return{...c,kind:"binary"};try{let a=await j(i.cwd,["diff-tree","--root","-r","--no-commit-id",...En,"--src-prefix=a/","--dst-prefix=b/","-p",...Rn(e,s.parents,r),"--",t],524288);return a.split(`
12
- `).length>1e4?{...c,kind:"too-large"}:a?{...c,kind:"text",patch:a}:{...c,kind:"empty"}}catch(a){if(a instanceof A&&a.status===413)return{...c,kind:"too-large"};throw a}}var On=["/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 Hn(n,e,t){if(n.endsWith("/control"))return Jt(e);if(n.endsWith("/status"))return it(e);if(n.endsWith("/history")){if(t.limit!==void 0&&typeof t.limit!="number"||t.cursor!==void 0&&typeof t.cursor!="string")throw new A("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");return Tn(e,{limit:t.limit,cursor:t.cursor})}if(n.endsWith("/diff")){if(typeof t.path!="string"||!["staged","unstaged","untracked"].includes(t.area))throw new A("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return bn(e,t.path,t.area)}if(typeof t.hash!="string"||t.parentIndex!==void 0&&(!Number.isInteger(t.parentIndex)||t.parentIndex<0))throw new A("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let r=t.parentIndex;if(n.endsWith("/commit-detail"))return Nn(e,t.hash,r);if(n.endsWith("/commit-diff")&&typeof t.path=="string")return Dn(e,t.hash,t.path,r);throw new A("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Xt=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),dc=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Mn={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},pc=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"]),uc=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/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search","/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 Wn(n){return n==="/api/message"||n==="/api/prompt-queue"||n.startsWith("/api/provider/")||n.startsWith("/api/workspace/files/")||n.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(n)}function ue(n){return n.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 Pe(n){let e={};for(let t of pc){let r=n[t];t==="toolName"?typeof r=="string"&&(Xt.has(r)||r==="custom")&&(e[t]=r):t==="failureKind"?dc.has(r)&&(e[t]=r):t==="level"?(r==="warning"||r==="error")&&(e[t]=r):t==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[t]=r):t==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[t]=r):t==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[t]=r):t==="route"&&typeof r=="string"?e[t]=uc.has(r.split("?")[0])?r.split("?")[0]:"[route]":t==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[t]=r.split("/").map(ue).join("/"):typeof r=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(r)?r:ue(r).slice(0,t==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[t]=r)}return e}function Jr(n){let e=n.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 nt(n,e=0){let t=n instanceof Error?n:new Error(typeof n=="string"?n:"Non-Error rejection"),r=new Error(ue(t.message));if(r.name=ue(t.name).slice(0,100),t.stack){let i=t.stack.split(`
13
- `).slice(1,31).map(s=>{let o=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${ue(s.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:ue(s)});r.stack=`${r.name}: ${r.message}
8
+ `}`;return Buffer.byteLength(p)>En||c.length>xn?{...i,kind:"too-large"}:{...i,kind:"text",patch:p}}if(s.untracked||(t==="staged"?s.index:s.worktree)===".")return{...i,kind:"empty"};let o=t==="staged"&&s.originalPath?[e,s.originalPath]:[e];try{let a=await j(n,["diff","--no-ext-diff","--no-textconv","--no-color","--no-renames","--relative","--src-prefix=a/","--dst-prefix=b/",...t==="staged"?["--cached"]:[],"--",...o],En);return a?a.split(`
9
+ `).length>xn?{...i,kind:"too-large"}:/^Binary files /m.test(a)?{...i,kind:"binary"}:{...i,kind:"text",patch:a}:{...i,kind:"empty"}}catch(a){if(a instanceof R&&a.status===413)return{...i,kind:"too-large"};throw a}}var Xr=new Set,z=(n,e=409)=>{throw new R("Git \u72B6\u6001\u4E0D\u5141\u8BB8\u6B64\u64CD\u4F5C\uFF0C\u8BF7\u5237\u65B0\u540E\u68C0\u67E5",e,n)};async function Rc(n){return Rn(St(n,(await j(n,["rev-parse","--git-common-dir"])).replace(/\n$/,"")))}async function Qr(n,e,t=!1){let r=null;try{let i=await ue(n);i.kind==="repository"&&(r=await Rc(i.cwd))}catch(i){if(!t)throw i}if(!r)return e();if(Xr.has(r))return z("busy");Xr.add(r);try{return await e()}finally{Xr.delete(r)}}async function Kt(n){let e=await ue(n),t={kind:e.kind,root:null,scope:"",head:null,branch:null,version:"",staged:0,dirty:!1,blocked:null,branches:[]};if(e.kind!=="repository")return t;let r=await nt(e.root);if(r.kind!=="repository")return t;let[i,s,o]=await Promise.all([j(e.cwd,["ls-files","--stage","-z"]),j(e.cwd,["for-each-ref","--format=%(refname:short)%00%(objectname)%00%(worktreepath)","refs/heads"]),j(e.cwd,["rev-parse","--absolute-git-dir"])]),a=["MERGE_HEAD","CHERRY_PICK_HEAD","REVERT_HEAD","rebase-merge","rebase-apply","sequencer","BISECT_LOG","index.lock"],c=(await Promise.all(a.map(async w=>{try{return await Yr(St(o.replace(/\n$/,""),w)),w}catch(v){if(v.code==="ENOENT")return null;throw v}}))).filter(Boolean),l=await Promise.all(r.entries.map(async w=>{try{let v=await Yr(St(e.root,w.path));return[w.path,v.size,v.mtimeMs,v.ctimeMs,v.ino,v.mode]}catch(v){if(["ENOENT","ENOTDIR"].includes(v.code??""))return[w.path,"missing"];throw v}})),p=s.split(`
10
+ `).filter(Boolean).map(w=>{let[v,,m]=w.split("\0");return{name:v,current:v===r.branch,occupied:!!m&&v!==r.branch}}),u=r.truncated||p.length>512?"too_many_changes":c.includes("index.lock")?"index_locked":c.length||r.entries.some(w=>w.conflict)?"operation_in_progress":null,h=_c("sha256").update(JSON.stringify({head:r.head,branch:r.branch,index:i,refs:s,entries:r.entries,files:l,present:c})).digest("hex");return{kind:"repository",root:e.root,scope:e.scope,head:r.head,branch:r.branch,version:h,staged:r.entries.filter(w=>!w.untracked&&w.index!==".").length,dirty:r.entries.length>0,blocked:u,branches:p.slice(0,512)}}async function Cc(n,e){qe(e);let t=An(St(n.cwd,e));for(;;)try{let s=await Rn(t),o=Ac(n.cwd,s);if(o===".."||o.startsWith(`..${process.platform==="win32"?"\\":"/"}`)||Tc(o))return z("invalid_path",403);break}catch(s){if(s.code!=="ENOENT")throw s;t=An(t)}let r=await nt(n.cwd),i=r.kind==="repository"?r.entries.find(s=>s.path===e):void 0;if(!i||i.submodule||i.conflict)return z("invalid_path",400);try{let s=await Yr(St(n.cwd,e));if(!s.isFile()&&!s.isSymbolicLink())return z("invalid_path",400)}catch(s){if(s.code!=="ENOENT")throw s}return i}async function Cn(n,e,t){let r=e.action;if(!["stage","unstage","commit","create-branch","switch-branch"].includes(r)||typeof e.expected!="string"||!/^[a-f0-9]{64}$/.test(e.expected))throw new R("Git \u64CD\u4F5C\u53C2\u6570\u65E0\u6548");return Qr(n,async()=>{let i=await ue(n);if(i.kind!=="repository")return z("invalid_path",404);t(i.root);let s=await Kt(i.cwd);if(s.version!==e.expected)return z("state_changed");if(s.blocked)return z(s.blocked);let o,a;if(r==="stage"||r==="unstage"){if(typeof e.path!="string")return z("invalid_path",400);let p=await Cc(i,e.path);if(r==="stage"&&!p.untracked&&p.worktree==="."||r==="unstage"&&(p.untracked||p.index==="."))return z("state_changed");let u=[e.path];r==="unstage"&&p.originalPath&&(qe(p.originalPath),u.push(p.originalPath)),o=r==="stage"?["add","--",...u]:s.head?["restore","--staged","--",...u]:["rm","--cached","-f","--ignore-unmatch","--",...u]}else if(r==="commit"){if(i.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(!s.staged)return z("nothing_staged",400);a=e.message,o=["commit","--file=-","--cleanup=verbatim"]}else{if(!s.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 j(i.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=s.branches.find(h=>h.name===e.branch),u=r==="switch-branch"||e.checkout===!0;if(r==="create-branch"&&p)return z("branch_exists");if(r==="switch-branch"&&(!p||p.current))return z("invalid_branch",400);if(u&&i.scope)return z("root_required",400);if(u&&s.dirty)return z("dirty_worktree");if(p?.occupied)return z("branch_in_use");o=r==="switch-branch"?["switch","--no-guess","--no-overwrite-ignore","--",e.branch]:u?["switch","--no-guess","--no-overwrite-ignore","-c",e.branch,"--","HEAD"]:["branch","--",e.branch,"HEAD"]}let c=await Kt(i.cwd);if(c.version!==e.expected||c.blocked)return z(c.blocked??"state_changed");t(i.root),await j(i.cwd,o,2*1024*1024,{write:!0,input:a});let l=(await j(i.cwd,["rev-parse","--verify","--quiet","HEAD"]).catch(()=>"")).trim()||null;return{action:r,head:l}})}import{createHash as Nc}from"node:crypto";var Et=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Nn="%H%x00%P%x00%an%x00%aI%x00%s",Dn=["--no-ext-diff","--no-textconv","--no-renames","--no-color","--relative"];async function On(n){let[e,t,r]=await Promise.all([j(n,["for-each-ref","--format=%(refname)%00%(objecttype)%00%(objectname)%00%(*objecttype)%00%(*objectname)","refs/heads","refs/remotes","refs/tags"]),j(n,["rev-parse","--verify","--quiet","HEAD"]).then(a=>a.trim(),()=>null),j(n,["symbolic-ref","-q","HEAD"]).then(a=>a.trim(),()=>null)]),i=[];for(let a of e.split(`
11
+ `).filter(Boolean)){let[c,l,p,u,h]=a.split("\0"),w=l==="commit"?p:u==="commit"?h:void 0;if(!w||!Et.test(w))continue;let v=c.startsWith("refs/heads/")?"branch":c.startsWith("refs/remotes/")?"remote":"tag";i.push({name:c.replace(/^refs\/(?:heads|remotes|tags)\//,""),hash:w,kind:v})}if(i.length>512)throw new R("\u4ED3\u5E93\u5F15\u7528\u8FC7\u591A\uFF0C\u6682\u4E0D\u652F\u6301\u8BFB\u53D6\u5386\u53F2",413);let s=[...new Set([...i.map(a=>a.hash),...t&&Et.test(t)?[t]:[]])].sort(),o=Nc("sha256").update(JSON.stringify({refs:i,head:t,symbolic:r})).digest("hex");return{refs:i,tips:s,head:t,snapshot:o}}function Hn(n){let[e,t,r,i,s]=n;if(!e||!Et.test(e)||!t?.split(" ").filter(Boolean).every(o=>Et.test(o)))throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);return{hash:e,parents:t.split(" ").filter(Boolean),author:r,authoredAt:i,subject:s}}async function Mn(n,e={}){let t=e.limit??50;if(!Number.isInteger(t)||t<1||t>100||e.cursor!==void 0&&(typeof e.cursor!="string"||e.cursor.length>256))throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");let r=await ue(n),i={kind:r.kind,root:null,scope:"",head:null,snapshot:"",refs:[],commits:[],nextCursor:null};if(r.kind!=="repository")return i;let s=await On(r.cwd),o=0;if(e.cursor!==void 0){let u;try{u=JSON.parse(Buffer.from(e.cursor,"base64url").toString("utf8"))}catch{throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548")}if(!u||typeof u.snapshot!="string"||!/^[a-f0-9]{64}$/.test(u.snapshot)||!Number.isInteger(u.offset)||u.offset<1||u.offset>1e4)throw new R("\u5386\u53F2\u5206\u9875\u53C2\u6570\u65E0\u6548");if(u.snapshot!==s.snapshot)throw new R("\u4ED3\u5E93\u5F15\u7528\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u5386\u53F2",409);o=u.offset}let a={...i,root:r.root,scope:r.scope,head:s.head,snapshot:s.snapshot,refs:s.refs};if(!s.tips.length)return a;let l=(await j(r.cwd,["log","--no-notes","--no-show-signature","--encoding=UTF-8","--topo-order","-z",`--format=${Nn}`,`--max-count=${t+1}`,`--skip=${o}`,...s.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(Hn(l.slice(u,u+5)));return a.commits=p.slice(0,t),p.length>t&&o+t<=1e4&&(a.nextCursor=Buffer.from(JSON.stringify({snapshot:s.snapshot,offset:o+t})).toString("base64url")),a}async function Wn(n,e){if(typeof e!="string"||!Et.test(e))throw new R("\u63D0\u4EA4\u6807\u8BC6\u65E0\u6548");let t=await ue(n);if(t.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r=await On(t.cwd);if(!r.tips.length)throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);if((await j(t.cwd,["cat-file","-t",e]).catch(()=>"")).trim()!=="commit"||(await j(t.cwd,["rev-list","--max-count=1",e,"--not",...r.tips,"--"])).trim())throw new R("\u63D0\u4EA4\u4E0D\u5B58\u5728\u6216\u5DF2\u4E0D\u53EF\u8FBE",404);return t}function jn(n,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],n]:[n]}async function $n(n,e,t){let i=(await j(n.cwd,["show","-s","--no-notes","--no-show-signature","--encoding=UTF-8","-z",`--format=${Nn}%x00%ae%x00%cn%x00%ce%x00%cI%x00%B`,e,"--"],262144)).split("\0");if(i.at(-1)===""&&i.pop(),i.length!==10)throw new R("\u63D0\u4EA4\u683C\u5F0F\u65E0\u6548",422);let s=Hn(i.slice(0,5)),o=jn(e,s.parents,t),a=["diff-tree","--root","-r","--no-commit-id",...Dn],[c,l]=await Promise.all([j(n.cwd,[...a,"--name-status","-z",...o,"--","."]),j(n.cwd,[...a,"--numstat","-z",...o,"--","."])]),p=new Map;for(let w of l.split("\0").filter(Boolean)){let v=w.match(/^(\d+|-)\t(\d+|-)\t([\s\S]+)$/);v&&p.set(v[3],[v[1]==="-"?null:Number(v[1]),v[2]==="-"?null:Number(v[2])])}let u=c.split("\0");if(u.at(-1)===""&&u.pop(),u.length%2)throw new R("\u63D0\u4EA4\u6587\u4EF6\u683C\u5F0F\u65E0\u6548",422);let h=[];for(let w=0;w<u.length&&h.length<1e3;w+=2){let v=u[w+1],[m,b]=p.get(v)??[null,null];h.push({path:v,status:u[w],additions:m,deletions:b})}return{...s,email:i[5],committer:i[6],committerEmail:i[7],committedAt:i[8],message:i[9],root:n.root,scope:n.scope,parentIndex:t,files:h,truncated:u.length>2e3}}async function Fn(n,e,t=0){return $n(await Wn(n,e),e,t)}async function Ln(n,e,t,r=0){qe(t);let i=await Wn(n,e),s=await $n(i,e,r),o=s.files.find(c=>c.path===t);if(!o)throw new R("\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u76EE\u5F55\u7684\u63D0\u4EA4\u6539\u52A8\u4E2D",404);let a={hash:e,path:t,parentIndex:r,parentHash:s.parents[r]??null};if(o.additions===null)return{...a,kind:"binary"};try{let c=await j(i.cwd,["diff-tree","--root","-r","--no-commit-id",...Dn,"--src-prefix=a/","--dst-prefix=b/","-p",...jn(e,s.parents,r),"--",t],524288);return c.split(`
12
+ `).length>1e4?{...a,kind:"too-large"}:c?{...a,kind:"text",patch:c}:{...a,kind:"empty"}}catch(c){if(c instanceof R&&c.status===413)return{...a,kind:"too-large"};throw c}}var Un=["/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 Vn(n,e,t){if(n.endsWith("/control"))return Kt(e);if(n.endsWith("/status"))return nt(e);if(n.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 Mn(e,{limit:t.limit,cursor:t.cursor})}if(n.endsWith("/diff")){if(typeof t.path!="string"||!["staged","unstaged","untracked"].includes(t.area))throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548");return Tn(e,t.path,t.area)}if(typeof t.hash!="string"||t.parentIndex!==void 0&&(!Number.isInteger(t.parentIndex)||t.parentIndex<0))throw new R("\u63D0\u4EA4\u53C2\u6570\u65E0\u6548");let r=t.parentIndex;if(n.endsWith("/commit-detail"))return Fn(e,t.hash,r);if(n.endsWith("/commit-diff")&&typeof t.path=="string")return Ln(e,t.hash,t.path,r);throw new R("Git \u5DEE\u5F02\u53C2\u6570\u65E0\u6548")}var Yt=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),Dc=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),Bn={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},Oc=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"]),Hc=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/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search","/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 zn(n){return n==="/api/message"||n==="/api/prompt-queue"||n.startsWith("/api/provider/")||n.startsWith("/api/workspace/files/")||n.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(n)}function fe(n){return n.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 Se(n){let e={};for(let t of Oc){let r=n[t];t==="toolName"?typeof r=="string"&&(Yt.has(r)||r==="custom")&&(e[t]=r):t==="failureKind"?Dc.has(r)&&(e[t]=r):t==="level"?(r==="warning"||r==="error")&&(e[t]=r):t==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(e[t]=r):t==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(e[t]=r):t==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(e[t]=r):t==="route"&&typeof r=="string"?e[t]=Hc.has(r.split("?")[0])?r.split("?")[0]:"[route]":t==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?e[t]=r.split("/").map(fe).join("/"):typeof r=="string"?e[t]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(t)&&/^[\w-]{1,80}$/.test(r)?r:fe(r).slice(0,t==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(e[t]=r)}return e}function Zr(n){let e=n.replace(/\\/g,"/").split(/[?#]/)[0];return e.startsWith("node:")?e.slice(0,150):`app:///${(e.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/)?.[1]??e.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function st(n,e=0){let t=n instanceof Error?n:new Error(typeof n=="string"?n:"Non-Error rejection"),r=new Error(fe(t.message));if(r.name=fe(t.name).slice(0,100),t.stack){let i=t.stack.split(`
13
+ `).slice(1,31).map(s=>{let o=s.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return o?`${fe(s.slice(0,o.index))}${o[1]}:${o[2]}:${o[3]}${o[4]}`:fe(s)});r.stack=`${r.name}: ${r.message}
14
14
  ${i.join(`
15
- `)}`}else r.stack=void 0;return e<3&&t.cause!==void 0&&(r.cause=nt(t.cause,e+1)),r}function Ae(n,e){let t=new Error(e);return n instanceof Error&&(t.name=n.name,n.stack&&(t.stack=`${t.name}: ${e}
15
+ `)}`}else r.stack=void 0;return e<3&&t.cause!==void 0&&(r.cause=st(t.cause,e+1)),r}function Ce(n,e){let t=new Error(e);return n instanceof Error&&(t.name=n.name,n.stack&&(t.stack=`${t.name}: ${e}
16
16
  ${n.stack.split(`
17
17
  `).slice(1).join(`
18
- `)}`)),t}function fc(n){return{...n.filename?{filename:Jr(n.filename)}:{},...n.abs_path?{abs_path:Jr(n.abs_path)}:{},...n.function?{function:ue(n.function)}:{},lineno:n.lineno,colno:n.colno,in_app:n.in_app}}function hc(n){let e=Pe(n.contexts?.diagnostic??{}),t=jn(e);return{event_id:n.event_id,timestamp:n.timestamp,platform:n.platform,level:n.level,release:n.release,dist:n.dist,environment:ue(n.environment??"production"),...n.message?{message:ue(n.message)}:{},exception:n.exception?{values:n.exception.values?.slice(0,4).map(r=>({type:ue(r.type??"Error"),value:ue(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(fc)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.mechanism.handled}}:{}}))}:void 0,tags:{side:n.tags?.side,buildId:n.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...t?{fingerprint:t}:{},contexts:{diagnostic:e},breadcrumbs:n.breadcrumbs?.slice(-100).map(r=>({timestamp:r.timestamp,category:ue(r.category??"app"),data:Pe(r.data??{})})),debug_meta:n.debug_meta?{images:n.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:Jr(r.code_file)}:{}}))}:void 0}}function jn(n){if(!(n.stage!=="tool"||n.originalStackAvailable!==!1||!n.toolName||!n.failureKind))return["pi-webapp-tool-result",String(n.toolName),String(n.toolId??"builtin"),String(n.failureKind),String(n.errorCode??"unknown")]}function $n(n,e){return e.attachments=[],hc(n)}var Et=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let r={timestamp:Date.now()/1e3,category:ue(e),data:Pe(t)},i=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:i}),this.bytes+=i;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},Kr=class{windowAt=-1;total=0;seen=new Map;take(e,t=Date.now()){(this.windowAt<0||t-this.windowAt>=6e4)&&(this.windowAt=t,this.total=0);let r=this.seen.get(e);if(r&&t-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:r?.repeats??0}}},gc=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 ze(n){return n instanceof Error&&(n.name==="AbortError"||gc.has(n.message))}var Kt=class{budget=new Kr;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,r,i,s=new Et){this.client=e,this.side=t,this.buildId=r,this.scopeClass=i.Scope,this.breadcrumbs=s,e.addIntegration(i.linkedErrorsIntegration({limit:4}))}setState(e){this.state=Pe(e)}capture(e,t={},r){try{if(ze(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let i=nt(e),s=Pe({...this.state,...t}),o=jn(s),c=o?JSON.stringify(o):`${i.name}:${i.message}:${i.stack?.split(`
19
- `)[1]??""}:${t.stage??""}`,a=this.budget.take(c);if(!a)return;let l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),s.level==="warning"&&l.setLevel("warning"),o&&l.setFingerprint(o),l.setContext("diagnostic",{...s,repeats:a.repeats});for(let p of this.breadcrumbs.snapshot())l.addBreadcrumb(p,100);return l.captureException(i,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function Fn(n,e){return n({...e,bufferSize:20},async({body:t})=>{let r=await fetch(e.url,{method:"POST",body:t,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var Vn={metadata:an,routes:On,coordinateStart:(n,e)=>Gr(n,e,!0),requestFailure:n=>n instanceof A?{status:n.status,body:{error:n.message,errorCode:"validation_error",reason:n.reason}}:null,async handle({path:n,body:e,snapshot:t,busyWorkspaces:r,json:i}){let s=t();if(e.sessionId!==s.sessionId){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||r().some(u=>{let w=(m,f)=>{let y=wc(m,f);return y!==".."&&!y.startsWith("../")&&!y.startsWith("..\\")&&!mc(y)};return w(p,u)||w(u,p)}),c=p=>{let u=t();if(u.sessionId!==s.sessionId||u.cwd!==s.cwd)throw new A("\u4F1A\u8BDD\u5DF2\u5207\u6362",409,"session_changed");if(o(p))throw new A("\u5171\u7528\u6B64\u5DE5\u4F5C\u6811\u7684\u804A\u5929\u6B63\u5728\u8FD0\u884C",409,"agent_busy")},a=n.endsWith("/write"),l=a?await In(s.cwd,e,c):await Hn(n,s.cwd,e);if(!a){let p=t();if(p.sessionId!==s.sessionId||p.cwd!==s.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(n.endsWith("/control")){let u=l;u.root&&o(u.root)&&(u.blocked??="agent_busy")}}i(200,l)}catch(o){if(o instanceof A||o instanceof H)i(o.status,{error:o.message,errorCode:"validation_error",...o instanceof A?{reason:o.reason}:{}});else throw Ae(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var Un={id:rt.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u3001\u641C\u7D22\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF0C\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\uFF0C\u5E76\u7F16\u8F91\u6587\u672C\u6587\u4EF6\u3002",en:"Browse and search workspace files, preview code, Markdown and images, and edit text files."}};import{lstat as yc,open as vc,opendir as bc,realpath as kc}from"node:fs/promises";import{join as zn}from"node:path";var Pc=5e3,Xr=2e4,Bn=100,Ln=200,Ic=5e3,Sc=512*1024,Ec=4e3,xc=240,_c=new Set([".git","node_modules",".hg",".svn"]);function Tc(n,e){return e.startsWith(n)&&e.slice(n.length)||void 0}function Ac(n,e){return n==="D"||e==="D"?n==="A"?"added":"deleted":n==="A"&&(e==="."||e==="M")?"added":"modified"}async function qn(n){let e;try{e=await pe(n)}catch(s){if(s instanceof A)return{kind:"unavailable",entries:[],truncated:!1};throw s}if(e.kind!=="repository")return{kind:e.kind,entries:[],truncated:!1};let t;try{t=await j(e.cwd,["status","--porcelain=v2","-z","--untracked-files=normal","--ignored=matching","--","."],8*1024*1024)}catch(s){if(s instanceof A)return{kind:"unavailable",entries:[],truncated:!1};throw s}let r={kind:"repository",entries:[],truncated:!1},i=t.split("\0");for(let s=0;s<i.length;s++){let o=i[s],c=o[0];if(!["1","2","u","?","!"].includes(c??""))continue;let a=c==="?"||c==="!"?1:c==="1"?8:c==="2"?9:10,l=0;for(let m=0;m<a;m++)l=o.indexOf(" ",l)+1;c==="2"&&s++;let p=Tc(e.scope,o.slice(l));if(!p)continue;if(r.entries.length===Pc){r.truncated=!0;break}let u=o.slice(2,4),w=c==="?"?"untracked":c==="!"?"ignored":c==="u"?"conflict":Ac(u[0],u[1]);r.entries.push({path:p,state:w})}return r}async function Rc(n){let e=await kc(n),t;try{t=await pe(e)}catch{t=void 0}if(t?.kind==="repository")try{let o=(await j(e,["ls-files","-z","--cached","--others","--exclude-standard","--deduplicate","--","."],33554432)).split("\0").filter(Boolean);return{root:e,paths:o.slice(0,Xr),truncated:o.length>Xr}}catch(s){if(!(s instanceof A))throw s}let r=[],i=[""];for(;i.length;){let s=i.shift(),o;try{o=await bc(zn(e,s))}catch{continue}for await(let c of o){let a=s?`${s}/${c.name}`:c.name;if(c.isDirectory())_c.has(c.name)||i.push(a);else if(c.isFile()){if(r.length===Xr)return{root:e,paths:r,truncated:!0};r.push(a)}}}return{root:e,paths:r,truncated:!1}}function Cc(n,e){let t=n.toLowerCase(),r=t.slice(t.lastIndexOf("/")+1);if(r===e)return 0;if(r.startsWith(e))return 1;if(r.includes(e))return 2;if(t.includes(e))return 3;let i=0;for(let s of e)if(i=t.indexOf(s,i)+1,!i)return;return 4}async function Gn(n,e,t){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new H("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(t!=="name"&&t!=="content")throw new H("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:i,paths:s,truncated:o}=await Rc(n);if(t==="name"){let u=s.flatMap(w=>{let m=Cc(w,r);return m===void 0?[]:[{path:w,score:m}]}).sort((w,m)=>w.score-m.score||w.path.length-m.path.length||w.path.localeCompare(m.path));return{kind:"name",results:u.slice(0,Bn).map(({path:w})=>({path:w})),truncated:o||u.length>Bn}}let c=[],a=Date.now()+Ec,l=0,p=o;for(let u of s){if(c.length>=Ln||l>=Ic||Date.now()>a){p=!0;break}let w=zn(i,u);try{let m=await yc(w);if(!m.isFile()||m.size===0||m.size>Sc)continue;l++;let f=await vc(w,"r"),y;try{y=await f.readFile()}finally{await f.close()}if(y.includes(0))continue;let k=y.toString("utf8").split(`
20
- `);for(let P=0;P<k.length;P++){let E=k[P],T=E.toLowerCase().indexOf(r);if(T<0)continue;let D=Math.max(0,T-60);if(c.push({path:u,line:P+1,text:(D?"\u2026":"")+E.slice(D,D+xc).replace(/\r$/u,"")}),c.length>=Ln)break}}catch{}}return{kind:"content",results:c,truncated:p}}var Jn={metadata:Un,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search"],async handle({path:n,body:e,snapshot:t,json:r,res:i}){let s=t();if(e.sessionId!==s.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let o=n.slice(n.lastIndexOf("/")+1);if(!(o==="status"||o==="search")&&(typeof e.path!="string"||e.path.length>4096)){r(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}let a=e.path,l=()=>{let p=t();return p.sessionId!==s.sessionId||p.cwd!==s.cwd};try{if(o==="raw"){let u=await gn(s.cwd,a);if(l()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}i.writeHead(200,{"Content-Type":u.mimeType,"Content-Length":u.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),i.end(u.bytes);return}if(o==="write"&&l()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let p=o==="list"?await fn(s.cwd,a):o==="write"?await mn(s.cwd,a,e.text,e.version):o==="status"?await qn(s.cwd):o==="search"?await Gn(s.cwd,e.query,e.mode):await Pt(s.cwd,a,Lr);if(o!=="write"&&l()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,p)}catch(p){if(p instanceof H)r(p.status,{error:p.message,errorCode:"validation_error",...p.reason?{reason:p.reason}:{}});else throw Ae(p,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var Kn={id:rt.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 Qn,constants as Yr,statSync as Zn}from"node:fs";import{createRequire as Fc}from"node:module";import{execFile as es}from"node:child_process";import{accessSync as Nc,chmodSync as Dc,constants as Oc,statSync as Hc}from"node:fs";import{createRequire as Mc}from"node:module";import{dirname as Wc,join as jc}from"node:path";var Xn=Mc(import.meta.url);function $c(n){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=jc(n,e,"spawn-helper"),r;try{r=Hc(t).mode}catch(i){if(i.code==="ENOENT")continue;throw i}try{Nc(t,Oc.X_OK)}catch{Dc(t,r|73)}}}function Yn(...n){return $c(Wc(Xn.resolve("node-pty/package.json"))),Xn("node-pty").spawn(...n)}var Re=class extends Error{reason;constructor(e,t,r){super(t,{cause:r}),this.reason=e}},ts=Fc(import.meta.url),Qr=class{pid;pty;screen;serializer;followers=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,r,i,s,o,c,a){this.sessionId=e,this.abandoned=c,this.graceMs=a;let{Terminal:l}=ts("@xterm/headless"),{SerializeAddon:p}=ts("@xterm/addon-serialize");this.screen=new l({cols:r,rows:i,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([w,m])=>m!==void 0&&!/^PI_WEBAPP_RESTART_/.test(w)));try{this.pty=Yn(s,o,{name:"xterm-256color",cwd:t,cols:r,rows:i,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(w){throw this.screen.dispose(),new Re("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=>es("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(i=>es("ps",["-axo","pid=,ppid="],(s,o)=>i(s?"":o)))).trim().split(`
21
- `).map(i=>i.trim().split(/\s+/).map(Number)),r=i=>t.filter(([,s])=>s===i).flatMap(([s])=>[...r(s),s]);for(let i of[...r(this.pid),this.pid])try{process.kill(i,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending,this.followers.clear(),this.screen.dispose()}},Yt=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,r,i,s){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 Re("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(Qn(o,Yr.X_OK),!Zn(o).isFile())throw new Error("Not a shell file")}catch(l){throw new Re("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(!Zn(r).isDirectory())throw new Error("Not a directory");Qn(r,Yr.R_OK|Yr.X_OK)}catch(l){throw new Re("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 Qr(t,r,i,s,o,c,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,a),a}get(e,t){let r=this.terminals.get(e);if(!r||r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}async remove(e,t){let r=this.terminals.get(e);if(r){if(r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var rs=(n,e)=>Number.isInteger(n)&&Number.isInteger(e)&&Number(n)>=2&&Number(n)<=500&&Number(e)>=1&&Number(e)<=300;async function is(n,e,t,r,i,s){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=n.slice(14),a=r();if(c!=="close"&&e.sessionId!==a.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((c==="create"||c==="resize")&&!rs(e.cols,e.rows)){o(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(c==="input"&&(typeof e.data!="string"||Buffer.byteLength(e.data)>16384)){o(400,{error:"\u7EC8\u7AEF\u8F93\u5165\u65E0\u6548\u6216\u8FC7\u5927"});return}try{if(c==="create"){i.create(e.id,e.sessionId,a.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(c==="close"){await i.remove(e.id,e.sessionId),o(200,{closed:!0});return}let l=i.get(e.id,e.sessionId);if(c==="attach"){let p=!1,u;t.once("close",()=>{p=!0,u?.(),s.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)}
22
- `),!0))),p?u():s.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 Re?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 Re?l.reason:c==="create"?"terminal_runtime_unavailable":void 0})}}function ns(){let n=new Yt,e=new Set,t=async()=>{for(let r of e)r.end();e.clear(),await n.clear()};return{metadata:Kn,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),handle:r=>is(r.path,r.body,r.res,r.snapshot,n,e),restartBlocker:()=>n.size?`\u6709 ${n.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:t,disable:t,async close(){await t(),await n.close()}}}function ss(){return[Jn,ns(),Vn]}import{createHash as Vc,randomUUID as Uc}from"node:crypto";import{mkdir as Bc,open as Lc,readFile as zc,rename as qc,rm as os,writeFile as Gc}from"node:fs/promises";import{dirname as Jc}from"node:path";var Q=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},Qt=class n{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await zc(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 Vc("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,r,i){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let s=`${this.file}.${Uc()}.tmp`,o=`${this.file}.lock`,c;try{if(r!==this.revision())throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");i();let a=new Set(this.disabled);t?a.delete(e):a.add(e),await Bc(Jc(this.file),{recursive:!0});try{c=await Lc(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()})+`
23
- `);let l=new n(this.file);if(await l.load(),l.revision()!==r)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await Gc(s,JSON.stringify({version:1,disabled:[...a].sort()},null,2)+`
24
- `,{mode:384}),i(),await qc(s,this.file),this.disabled=a}finally{this.changing=!1;try{await os(s,{force:!0})}finally{c&&(await c.close(),await os(o,{force:!0}))}}}};var Zt=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===t&&!r.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!t.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>t.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,r,i){if(!this.plugins.some(s=>s.metadata.id===e))throw new Q("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new Q("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,r,i),t||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(i=>i.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=t.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await t.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,t,r,i,s){let o=this.plugins.find(c=>c.metadata.id===e);if(!o?.agentAction||!this.preferences.enabled(e))throw new Q("\u7ED8\u56FE\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await o.agentAction(t,r,i,s)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new Q("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let i=t;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let o=i;i=()=>s.coordinateStart(e,o)}try{return await i()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof Q)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let r=t.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as Kc,opendir as Xc,stat as Yc}from"node:fs/promises";import{homedir as Qc}from"node:os";import{basename as Zc,dirname as as,join as cs,posix as el,resolve as ls,win32 as tl}from"node:path";function ds(n){return process.platform==="win32"?tl.isAbsolute(n)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(n):el.isAbsolute(n)}function rl(n,e,t){if(n.length===t&&e.name.localeCompare(n[n.length-1].name)>=0)return!0;let r=0,i=n.length;for(;r<i;){let s=r+i>>>1;e.name.localeCompare(n[s].name)<0?i=s:r=s+1}return n.splice(r,0,e),n.length<=t?!1:(n.pop(),!0)}async function ps(n){if(n!==void 0&&!ds(n))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=Qc(),t=ls(n??e),r=[];for(let a=t;;a=as(a)){let l=as(a);if(r.unshift({name:l===a?a:Zc(a),path:a,hidden:!1}),l===a)break}let i=[],s=!1,o=await Xc(t);for await(let a of o)!a.isDirectory()&&!a.isSymbolicLink()||rl(i,{name:a.name,isDirectory:a.isDirectory(),isSymbolicLink:a.isSymbolicLink()},1001)&&(s=!0);let c=[];for(let a of i){let l=cs(t,a.name);if(!a.isDirectory&&a.isSymbolicLink)try{if(!(await Yc(l)).isDirectory())continue}catch{continue}if(c.length===1e3){s=!0;break}c.push({name:a.name,path:l,hidden:a.name.startsWith(".")})}return{path:t,home:e,crumbs:r,entries:c,truncated:s}}async function us(n,e){if(!ds(n))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let t=cs(ls(n),e);return await Kc(t),t}import{execFile as il}from"node:child_process";import{accessSync as nl,constants as sl}from"node:fs";import{delimiter as ol,join as al}from"node:path";var cl=(n,e,t)=>new Promise((r,i)=>{il(n,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(s,o,c)=>{s?i(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:o,stderr:c})):r({stdout:o,stderr:c})})});function ll(n){for(let e of(n??"").split(ol))if(e)for(let t of["zenity","kdialog"])try{return nl(al(e,t),sl.X_OK),!0}catch{}return!1}function fs(n=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":n==="darwin"||n==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&ll(e.PATH)?"native":"browse"}function er(n){if(!(typeof n!="object"||n===null||!("code"in n)))return typeof n.code=="string"||typeof n.code=="number"?n.code:void 0}function dl(n){return typeof n=="object"&&n!==null&&"stderr"in n&&typeof n.stderr=="string"?n.stderr:""}function Zr(n){return n.replace(/[\r\n]+$/,"")||null}async function hs(n,e=process.platform,t=cl){if(e==="darwin")try{let r=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],n);return Zr(r.stdout)}catch(r){if(!n.aborted&&er(r)===1&&/(?:User canceled|-128)/i.test(dl(r)))return null;throw r}if(e==="linux"){try{return Zr((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],n)).stdout)}catch(r){if(n.aborted)throw r;if(er(r)===1)return null;if(er(r)!=="ENOENT")throw r}try{return Zr((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],n)).stdout)}catch(r){if(n.aborted)throw r;if(er(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as pl,randomUUID as ul}from"node:crypto";import{mkdir as fl,readFile as hl,writeFile as gl}from"node:fs/promises";import{join as gs}from"node:path";import{getAgentDir as ml}from"@earendil-works/pi-coding-agent";var tr=20*1024*1024,ms=20,wl=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function yl(n){let e=n.indexOf("."),t=(e<0?n:n.slice(0,e)).replace(/[. ]+$/u,"");return wl.test(t)}function vl(n,e){let t=0,r="";for(let i of Buffer.from(n).toString("utf8")){let s=Buffer.byteLength(i);if(t+s>e)break;r+=i,t+=s}return r}function bl(n){if(n===void 0)return"file";let t=n.slice(Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return yl(t)&&(t=`_${t}`),t=vl(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function kl(n){return n.length>=8&&n.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":n.length>=3&&n.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":n.length>=6&&["GIF87a","GIF89a"].includes(n.toString("ascii",0,6))?"image/gif":n.length>=12&&n.toString("ascii",0,4)==="RIFF"&&n.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function ws(n,e,t,r){if(r.byteLength===0||r.byteLength>tr)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let i=bl(e),s=pl("sha256").update(r).digest("hex"),o=gs(ml(),"pi-web","attachments",s);await fl(o,{recursive:!0});let c=gs(o,i);try{await gl(c,r,{flag:"wx",mode:384})}catch(a){if(!(a instanceof Error&&"code"in a&&a.code==="EEXIST"))throw a}return{id:ul(),name:i,bytes:r.byteLength,path:c,mediaType:kl(r)??t.replace(/^image\//,"application/"),sessionId:n}}async function ys(n){return{type:"image",data:(await hl(n.path)).toString("base64"),mimeType:n.mediaType}}import{randomBytes as Pl}from"node:crypto";function vs(n,e,t){return n!=="openai-codex"||e!=="oauth"?t:{...t,prompt:r=>r.type==="select"&&r.options.some(i=>i.id==="browser")&&r.options.some(i=>i.id==="device_code")?Promise.resolve("browser"):t.prompt(r)}}var rr=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,r,i,s){let o=this.getActive();if(o){if(o.providerId===e&&o.method===t&&i===void 0)return o;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let c=Pl(18).toString("base64url"),a={view:{id:c,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(c,a),r(e,t,{signal:a.controller.signal,notify:l=>{a.view={...a.view,event:l,...l.type==="auth_url"||l.type==="device_code"?{authorization:l}:{}}},prompt:l=>{if(l.type==="secret"&&i!==void 0){let p=i;return i=void 0,Promise.resolve(p)}return new Promise((p,u)=>{let{signal: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 Mc(n){return{...n.filename?{filename:Zr(n.filename)}:{},...n.abs_path?{abs_path:Zr(n.abs_path)}:{},...n.function?{function:fe(n.function)}:{},lineno:n.lineno,colno:n.colno,in_app:n.in_app}}function Wc(n){let e=Se(n.contexts?.diagnostic??{}),t=qn(e);return{event_id:n.event_id,timestamp:n.timestamp,platform:n.platform,level:n.level,release:n.release,dist:n.dist,environment:fe(n.environment??"production"),...n.message?{message:fe(n.message)}:{},exception:n.exception?{values:n.exception.values?.slice(0,4).map(r=>({type:fe(r.type??"Error"),value:fe(r.value??""),...r.stacktrace?{stacktrace:{frames:r.stacktrace.frames?.slice(-30).map(Mc)}}:{},...r.mechanism?{mechanism:{type:r.mechanism.type,handled:r.mechanism.handled}}:{}}))}:void 0,tags:{side:n.tags?.side,buildId:n.tags?.buildId,...e.toolName?{toolName:e.toolName}:{},...e.failureKind?{failureKind:e.failureKind}:{},...e.errorCode?{errorCode:e.errorCode}:{}},...t?{fingerprint:t}:{},contexts:{diagnostic:e},breadcrumbs:n.breadcrumbs?.slice(-100).map(r=>({timestamp:r.timestamp,category:fe(r.category??"app"),data:Se(r.data??{})})),debug_meta:n.debug_meta?{images:n.debug_meta.images?.slice(0,10).map(r=>({type:r.type,debug_id:r.debug_id,...r.code_file?{code_file:Zr(r.code_file)}:{}}))}:void 0}}function qn(n){if(!(n.stage!=="tool"||n.originalStackAvailable!==!1||!n.toolName||!n.failureKind))return["pi-webapp-tool-result",String(n.toolName),String(n.toolId??"builtin"),String(n.failureKind),String(n.errorCode??"unknown")]}function Gn(n,e){return e.attachments=[],Wc(n)}var xt=class{items=[];bytes=0;encoder=new TextEncoder;add(e,t={}){let r={timestamp:Date.now()/1e3,category:fe(e),data:Se(t)},i=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:i}),this.bytes+=i;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:e})=>e)}},ei=class{windowAt=-1;total=0;seen=new Map;take(e,t=Date.now()){(this.windowAt<0||t-this.windowAt>=6e4)&&(this.windowAt=t,this.total=0);let r=this.seen.get(e);if(r&&t-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(e,{at:t,repeats:0}),{repeats:r?.repeats??0}}},jc=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(n){return n instanceof Error&&(n.name==="AbortError"||jc.has(n.message))}var Xt=class{budget=new ei;breadcrumbs;scopeClass;seen=new WeakSet;state={};client;side;buildId;constructor(e,t,r,i,s=new xt){this.client=e,this.side=t,this.buildId=r,this.scopeClass=i.Scope,this.breadcrumbs=s,e.addIntegration(i.linkedErrorsIntegration({limit:4}))}setState(e){this.state=Se(e)}capture(e,t={},r){try{if(Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}let i=st(e),s=Se({...this.state,...t}),o=qn(s),a=o?JSON.stringify(o):`${i.name}:${i.message}:${i.stack?.split(`
19
+ `)[1]??""}:${t.stage??""}`,c=this.budget.take(a);if(!c)return;let l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),s.level==="warning"&&l.setLevel("warning"),o&&l.setFingerprint(o),l.setContext("diagnostic",{...s,repeats:c.repeats});for(let p of this.breadcrumbs.snapshot())l.addBreadcrumb(p,100);return l.captureException(i,r?{event_id:r}:void 0)}catch{return}}ignore(e){this.seen.add(e)}};function Jn(n,e){return n({...e,bufferSize:20},async({body:t})=>{let r=await fetch(e.url,{method:"POST",body:t,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}var Kn={metadata:gn,routes:Un,coordinateStart:(n,e)=>Qr(n,e,!0),requestFailure:n=>n instanceof R?{status:n.status,body:{error:n.message,errorCode:"validation_error",reason:n.reason}}:null,async handle({path:n,body:e,snapshot:t,busyWorkspaces:r,json:i}){let s=t();if(e.sessionId!==s.sessionId){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{let o=p=>!t().idle||r().some(u=>{let h=(w,v)=>{let m=Fc(w,v);return m!==".."&&!m.startsWith("../")&&!m.startsWith("..\\")&&!$c(m)};return h(p,u)||h(u,p)}),a=p=>{let u=t();if(u.sessionId!==s.sessionId||u.cwd!==s.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")},c=n.endsWith("/write"),l=c?await Cn(s.cwd,e,a):await Vn(n,s.cwd,e);if(!c){let p=t();if(p.sessionId!==s.sessionId||p.cwd!==s.cwd){i(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(n.endsWith("/control")){let u=l;u.root&&o(u.root)&&(u.blocked??="agent_busy")}}i(200,l)}catch(o){if(o instanceof R||o instanceof M)i(o.status,{error:o.message,errorCode:"validation_error",...o instanceof R?{reason:o.reason}:{}});else throw Ce(o,"Git \u64CD\u4F5C\u5931\u8D25")}}};var Xn={id:de.files,kind:"builtin",version:"1.0.0",name:{zh:"\u5DE5\u4F5C\u533A\u6587\u4EF6",en:"Workspace files"},description:{zh:"\u6D4F\u89C8\u3001\u641C\u7D22\u5DE5\u4F5C\u533A\u6587\u4EF6\uFF0C\u9884\u89C8\u4EE3\u7801\u3001Markdown \u4E0E\u56FE\u7247\uFF0C\u5E76\u7F16\u8F91\u6587\u672C\u6587\u4EF6\u3002",en:"Browse and search workspace files, preview code, Markdown and images, and edit text files."}};import{lstat as Lc,open as Uc,opendir as Vc,realpath as Bc}from"node:fs/promises";import{join as Zn}from"node:path";var zc=5e3,ti=2e4,Yn=100,Qn=200,qc=5e3,Gc=512*1024,Jc=4e3,Kc=240,Xc=new Set([".git","node_modules",".hg",".svn"]);function Yc(n,e){return e.startsWith(n)&&e.slice(n.length)||void 0}function Qc(n,e){return n==="D"||e==="D"?n==="A"?"added":"deleted":n==="A"&&(e==="."||e==="M")?"added":"modified"}async function es(n){let e;try{e=await ue(n)}catch(s){if(s instanceof R)return{kind:"unavailable",entries:[],truncated:!1};throw s}if(e.kind!=="repository")return{kind:e.kind,entries:[],truncated:!1};let t;try{t=await j(e.cwd,["status","--porcelain=v2","-z","--untracked-files=normal","--ignored=matching","--","."],8*1024*1024)}catch(s){if(s instanceof R)return{kind:"unavailable",entries:[],truncated:!1};throw s}let r={kind:"repository",entries:[],truncated:!1},i=t.split("\0");for(let s=0;s<i.length;s++){let o=i[s],a=o[0];if(!["1","2","u","?","!"].includes(a??""))continue;let c=a==="?"||a==="!"?1:a==="1"?8:a==="2"?9:10,l=0;for(let w=0;w<c;w++)l=o.indexOf(" ",l)+1;a==="2"&&s++;let p=Yc(e.scope,o.slice(l));if(!p)continue;if(r.entries.length===zc){r.truncated=!0;break}let u=o.slice(2,4),h=a==="?"?"untracked":a==="!"?"ignored":a==="u"?"conflict":Qc(u[0],u[1]);r.entries.push({path:p,state:h})}return r}async function Zc(n){let e=await Bc(n),t;try{t=await ue(e)}catch{t=void 0}if(t?.kind==="repository")try{let o=(await j(e,["ls-files","-z","--cached","--others","--exclude-standard","--deduplicate","--","."],33554432)).split("\0").filter(Boolean);return{root:e,paths:o.slice(0,ti),truncated:o.length>ti}}catch(s){if(!(s instanceof R))throw s}let r=[],i=[""];for(;i.length;){let s=i.shift(),o;try{o=await Vc(Zn(e,s))}catch{continue}for await(let a of o){let c=s?`${s}/${a.name}`:a.name;if(a.isDirectory())Xc.has(a.name)||i.push(c);else if(a.isFile()){if(r.length===ti)return{root:e,paths:r,truncated:!0};r.push(c)}}}return{root:e,paths:r,truncated:!1}}function el(n,e){let t=n.toLowerCase(),r=t.slice(t.lastIndexOf("/")+1);if(r===e)return 0;if(r.startsWith(e))return 1;if(r.includes(e))return 2;if(t.includes(e))return 3;let i=0;for(let s of e)if(i=t.indexOf(s,i)+1,!i)return;return 4}async function ts(n,e,t){if(typeof e!="string"||!e.trim()||e.length>200||e.includes("\0"))throw new M("\u641C\u7D22\u5185\u5BB9\u65E0\u6548");if(t!=="name"&&t!=="content")throw new M("\u641C\u7D22\u65B9\u5F0F\u65E0\u6548");let r=e.trim().toLowerCase(),{root:i,paths:s,truncated:o}=await Zc(n);if(t==="name"){let u=s.flatMap(h=>{let w=el(h,r);return w===void 0?[]:[{path:h,score:w}]}).sort((h,w)=>h.score-w.score||h.path.length-w.path.length||h.path.localeCompare(w.path));return{kind:"name",results:u.slice(0,Yn).map(({path:h})=>({path:h})),truncated:o||u.length>Yn}}let a=[],c=Date.now()+Jc,l=0,p=o;for(let u of s){if(a.length>=Qn||l>=qc||Date.now()>c){p=!0;break}let h=Zn(i,u);try{let w=await Lc(h);if(!w.isFile()||w.size===0||w.size>Gc)continue;l++;let v=await Uc(h,"r"),m;try{m=await v.readFile()}finally{await v.close()}if(m.includes(0))continue;let b=m.toString("utf8").split(`
20
+ `);for(let P=0;P<b.length;P++){let S=b[P],_=S.toLowerCase().indexOf(r);if(_<0)continue;let C=Math.max(0,_-60);if(a.push({path:u,line:P+1,text:(C?"\u2026":"")+S.slice(C,C+Kc).replace(/\r$/u,"")}),a.length>=Qn)break}}catch{}}return{kind:"content",results:a,truncated:p}}var rs={metadata:Xn,routes:["/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/workspace/files/write","/api/workspace/files/status","/api/workspace/files/search"],async handle({path:n,body:e,snapshot:t,json:r,res:i}){let s=t();if(e.sessionId!==s.sessionId){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let o=n.slice(n.lastIndexOf("/")+1);if(!(o==="status"||o==="search")&&(typeof e.path!="string"||e.path.length>4096)){r(400,{error:"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548"});return}let c=e.path,l=()=>{let p=t();return p.sessionId!==s.sessionId||p.cwd!==s.cwd};try{if(o==="raw"){let u=await In(s.cwd,c);if(l()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}i.writeHead(200,{"Content-Type":u.mimeType,"Content-Length":u.bytes.length,"Cache-Control":"no-store","X-Content-Type-Options":"nosniff"}),i.end(u.bytes);return}if(o==="write"&&l()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}let p=o==="list"?await kn(s.cwd,c):o==="write"?await Sn(s.cwd,c,e.text,e.version):o==="status"?await es(s.cwd):o==="search"?await ts(s.cwd,e.query,e.mode):await It(s.cwd,c,Kr);if(o!=="write"&&l()){r(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}r(200,p)}catch(p){if(p instanceof M)r(p.status,{error:p.message,errorCode:"validation_error",...p.reason?{reason:p.reason}:{}});else throw Ce(p,o==="write"?"\u5DE5\u4F5C\u533A\u6587\u4EF6\u4FDD\u5B58\u5931\u8D25":"\u5DE5\u4F5C\u533A\u6587\u4EF6\u8BFB\u53D6\u5931\u8D25")}}};var is={id:de.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 ri,statSync as as}from"node:fs";import{createRequire as ll}from"node:module";import{execFile as cs}from"node:child_process";import{accessSync as tl,chmodSync as rl,constants as il,statSync as nl}from"node:fs";import{createRequire as sl}from"node:module";import{dirname as ol,join as al}from"node:path";var ns=sl(import.meta.url);function cl(n){if(process.platform==="darwin")for(let e of["build/Release","build/Debug",`prebuilds/darwin-${process.arch}`]){let t=al(n,e,"spawn-helper"),r;try{r=nl(t).mode}catch(i){if(i.code==="ENOENT")continue;throw i}try{tl(t,il.X_OK)}catch{rl(t,r|73)}}}function ss(...n){return cl(ol(ns.resolve("node-pty/package.json"))),ns("node-pty").spawn(...n)}var Ne=class extends Error{reason;constructor(e,t,r){super(t,{cause:r}),this.reason=e}},ls=ll(import.meta.url),ii=class{pid;pty;screen;serializer;followers=new Set;outputListeners=new Set;pending=Promise.resolve();exit;disposed=!1;done;expire;closing;sessionId;abandoned;graceMs;constructor(e,t,r,i,s,o,a,c){this.sessionId=e,this.abandoned=a,this.graceMs=c;let{Terminal:l}=ls("@xterm/headless"),{SerializeAddon:p}=ls("@xterm/addon-serialize");this.screen=new l({cols:r,rows:i,scrollback:2e3,allowProposedApi:!0}),this.serializer=new p,this.screen.loadAddon(this.serializer);let u=Object.fromEntries(Object.entries(process.env).filter(([h,w])=>w!==void 0&&!/^PI_WEBAPP_RESTART_/.test(h)));try{this.pty=ss(s,o,{name:"xterm-256color",cwd:t,cols:r,rows:i,env:{...u,TERM:"xterm-256color",COLORTERM:"truecolor"}})}catch(h){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",h)}this.pid=this.pty.pid,this.screen.onData(h=>{!this.followers.size&&!this.exit&&!this.disposed&&this.pty.write(h)}),this.pty.onData(h=>{this.disposed||(this.pty.pause(),this.pending=this.pending.then(()=>new Promise(w=>{if(this.disposed){w();return}this.screen.write(h,()=>{this.broadcast({type:"output",data:h});for(let v of this.outputListeners)v(h);w()})})).finally(()=>{!this.exit&&!this.disposed&&this.pty.resume()}))}),this.done=new Promise(h=>this.pty.onExit(({exitCode:w,signal:v})=>{this.exit={type:"exit",exitCode:w,signal:v},this.pending.then(()=>{this.broadcast(this.exit);for(let m of this.outputListeners)m("");h()})})),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)}get exitCode(){return this.exit?.exitCode}get running(){return!this.exit&&!this.disposed}settle(e,t,r,i){return new Promise(s=>{let o,a="",c=!i,l=()=>{clearTimeout(o),clearTimeout(u),this.outputListeners.delete(p),r?.removeEventListener("abort",l),s()},p=h=>{if(!this.running){l();return}!c&&a.length<64*1024&&(a+=h,c=i(a)),clearTimeout(o),c&&(o=setTimeout(l,e))},u=setTimeout(l,t);this.outputListeners.add(p),r?.addEventListener("abort",l,{once:!0}),r?.aborted?l():p("")})}async text(e){if(await this.pending,this.disposed)throw new Error("Terminal closed");let t=this.screen.buffer.active,r=t.length-1;for(;r>=0&&!t.getLine(r)?.translateToString(!0).trim();)r--;let i=[];for(let s=Math.max(0,r-e*4);s<=r;s++){let o=t.getLine(s);if(!o)continue;let a=o.translateToString(!0);o.isWrapped&&i.length?i[i.length-1]+=a:i.push(a)}return i.slice(-e).join(`
21
+ `)}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=>cs("taskkill",["/pid",String(this.pid),"/T","/F"],()=>e()));else{let t=(await new Promise(i=>cs("ps",["-axo","pid=,ppid="],(s,o)=>i(s?"":o)))).trim().split(`
22
+ `).map(i=>i.trim().split(/\s+/).map(Number)),r=i=>t.filter(([,s])=>s===i).flatMap(([s])=>[...r(s),s]);for(let i of[...r(this.pid),this.pid])try{process.kill(i,"SIGKILL")}catch{}}this.pty.kill(),this.pty.resume(),await this.done}await this.pending;for(let e of this.outputListeners)e("");this.followers.clear(),this.screen.dispose()}},Qt=class{terminals=new Map;stopped=!1;options;constructor(e={}){this.options=e}create(e,t,r,i,s){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(os(o,ri.X_OK),!as(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(!as(r).isDirectory())throw new Error("Not a directory");os(r,ri.R_OK|ri.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 a=this.options.shellArgs??(process.platform==="win32"?[]:["-i"]),c=new ii(t,r,i,s,o,a,()=>{this.remove(e,t)},this.options.graceMs??5*6e4);return this.terminals.set(e,c),c}get(e,t){let r=this.terminals.get(e);if(!r||r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5B58\u5728\u6216\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");return r}resolve(e,t){if(e!==void 0)return{id:e,terminal:this.get(e,t)};let r=[...this.terminals].filter(([,i])=>i.sessionId===t&&i.running);if(r.length===1)return{id:r[0][0],terminal:r[0][1]};throw new Error(r.length?`This session has ${r.length} open terminals (${r.map(([i])=>i).join(", ")}); pass terminalId.`:"This session has no open terminal. Ask the user to open one in the workspace panel.")}async remove(e,t){let r=this.terminals.get(e);if(r){if(r.sessionId!==t)throw new Error("\u7EC8\u7AEF\u4E0D\u5C5E\u4E8E\u6B64\u4F1A\u8BDD");await r.close(),this.terminals.get(e)===r&&this.terminals.delete(e)}}get size(){return this.terminals.size}async clear(){await Promise.all([...this.terminals.values()].map(e=>e.close())),this.terminals.clear()}async close(){this.stopped=!0,await this.clear()}};var ds=(n,e)=>Number.isInteger(n)&&Number.isInteger(e)&&Number(n)>=2&&Number(n)<=500&&Number(e)>=1&&Number(e)<=300,ps="terminal-input";async function us(n,e,t,r,i,s){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 a=n.slice(14),c=r();if(a!=="close"&&e.sessionId!==c.sessionId){o(409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if((a==="create"||a==="resize")&&!ds(e.cols,e.rows)){o(400,{error:"\u7EC8\u7AEF\u5C3A\u5BF8\u65E0\u6548"});return}if(a==="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(a==="create"){i.create(e.id,e.sessionId,c.cwd,e.cols,e.rows),o(201,{id:e.id});return}if(a==="close"){await i.remove(e.id,e.sessionId),o(200,{closed:!0});return}let l=i.get(e.id,e.sessionId);if(a==="attach"){let p=!1,u;t.once("close",()=>{p=!0,u?.(),s.delete(t)}),u=await l.attach(h=>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(h)}
23
+ `),!0))),p?u():s.add(t);return}if(a==="input")l.write(e.data);else if(a==="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:a==="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:a==="create"?"terminal_runtime_unavailable":void 0})}}var dl=/^[a-f0-9-]{36}$/i,fs=32*1024,pl=300,ul=3e4,ms=n=>n<32||n>=127&&n<=159,ws=n=>{if(!n||typeof n!="object"||Array.isArray(n))throw new Error("Invalid terminal tool input");return n};function ys(n){if(n!==void 0){if(typeof n!="string"||!dl.test(n))throw new Error("terminalId must be the terminal tab's contentId");return n}}function ni(n,e,t,r,i){if(n===void 0)return e;if(!Number.isInteger(n)||n<t||n>r)throw new Error(`${i} must be an integer from ${t} to ${r}`);return n}function er(n){let e=ws(n);if(typeof e.text!="string")throw new Error("text must be a string");let t=e.text.replace(/\r\n?/g,`
24
+ `);if(Buffer.byteLength(t)>4096)throw new Error(`text is longer than ${4096} bytes`);if([...t].some(i=>i!==" "&&i!==`
25
+ `&&ms(i.charCodeAt(0))))throw new Error("text may not contain control characters other than tab and newline");if(e.enter!==void 0&&typeof e.enter!="boolean")throw new Error("enter must be a boolean");let r=e.enter??!0;if(!t&&!r)throw new Error("Nothing to send");return{terminalId:ys(e.terminalId),text:t,enter:r,waitMs:ni(e.waitMs,3e3,0,ul,"waitMs"),lines:ni(e.lines,40,1,500,"lines")}}function hs(n){let e="";for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);if(r===27){let i=n[t+1];if(i==="]"){for(t+=2;t<n.length&&n.charCodeAt(t)!==7&&n.charCodeAt(t)!==27;)t++;n.charCodeAt(t)===27&&t++}else if(i==="[")for(t+=2;t<n.length&&(n.charCodeAt(t)<64||n.charCodeAt(t)>126);)t++;else t+=i==="("||i===")"?2:1;continue}r===8?e=e.slice(0,-1):!ms(r)&&!/\s/u.test(n[t])&&(e+=n[t])}return e}var fl=n=>{let e=hs(n);return t=>{let r=hs(t);return!!r&&!e.startsWith(r)}};async function gs(n,e,t){let r=await e.text(t),i=r.length>fs;return{terminalId:n,output:i?r.slice(-fs):r,truncated:i,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}}async function vs(n,e,t,r,i){if(t==="prepare"){let s=er(r),{id:o,terminal:a}=n.resolve(s.terminalId,e);if(!a.running)throw new Error("The terminal's shell has exited. Ask the user to open a new terminal.");return{terminalId:o}}if(t==="send"){let s=er(r);if(!s.terminalId)throw new Error("terminalId is required");let{id:o,terminal:a}=n.resolve(s.terminalId,e);return i?.throwIfAborted(),a.write(s.text.replace(/\n/g,"\r")+(s.enter?"\r":"")),s.waitMs&&await a.settle(pl,s.waitMs,i,fl(s.text)),gs(o,a,s.lines)}if(t==="read"){let s=ws(r),{id:o,terminal:a}=n.resolve(ys(s.terminalId),e);return gs(o,a,ni(s.lines,100,1,500,"lines"))}throw new Error(`Unknown terminal action: ${t}`)}function bs(){let n=new Qt,e=new Set,t=async()=>{for(let r of e)r.end();e.clear(),await n.clear()};return{metadata:is,routes:["create","attach","input","resize","close"].map(r=>`/api/terminal/${r}`),agentAction:(r,i,s,o,a)=>vs(n,i,s,o,a),handle:r=>us(r.path,r.body,r.res,r.snapshot,n,e),restartBlocker:()=>n.size?`\u6709 ${n.size} \u4E2A\u7EC8\u7AEF\u6B63\u5728\u8FD0\u884C\uFF0C\u5347\u7EA7\u4F1A\u5173\u95ED\u5B83\u4EEC`:null,releaseForRestart:t,disable:t,async close(){await t(),await n.close()}}}import{randomUUID as hl}from"node:crypto";import{Type as be}from"@earendil-works/pi-ai";var ks=be.String({pattern:"^[a-fA-F0-9-]{36}$",description:`The terminal tab's contentId, for example from the [pi-web workspace tab in view] line of kind "terminal". Optional when this session has exactly one open terminal.`}),Ps=n=>be.Optional(be.Integer({minimum:1,maximum:500,description:`How many trailing lines of the terminal to return (default ${n}).`}));function Is(n,e=""){let t=n.exitCode===void 0?"":` The shell has exited with code ${n.exitCode}.`;return{content:[{type:"text",text:`${e}Terminal ${n.terminalId}${n.truncated?" (output truncated to the most recent part)":""}:${t}
26
+ ${n.output}`}],details:n}}function Ss(n){return[{name:"terminal_send",label:"terminal_send",description:`Type a command into one of the user's open workspace terminal tabs (their live interactive shell) and return the terminal's recent output. Use this when the user asks you to run something in "this"/"the" terminal they are looking at; for your own work use bash instead. The user must approve each call in the Web UI before anything is typed, so send one complete command at a time and do not assume it ran if the call fails. Enter is pressed after the text unless enter is false. Output is read after the terminal is quiet for a moment or waitMs passes; for long-running commands call terminal_read later.`,parameters:be.Object({terminalId:be.Optional(ks),text:be.String({maxLength:4096,description:"Text to type. Newlines separate lines; no other control characters."}),enter:be.Optional(be.Boolean({description:"Press Enter after the text (default true)."})),waitMs:be.Optional(be.Integer({minimum:0,maximum:3e4,description:"Longest time to wait for output before returning (default 3000)."})),lines:Ps(40)}),async execute(e,t,r,i,s){r?.throwIfAborted();let o=s.sessionManager.getSessionId(),a=er(t),{terminalId:c}=await n.run(s.cwd,o,"prepare",t,r),l={terminalId:c,text:a.text,enter:a.enter},p=await n.ask({requestId:hl(),sessionId:o,pluginId:de.terminal,kind:ps,data:l},r);if(!p||typeof p!="object"||p.allow!==!0)throw new Error("The user declined; nothing was typed into the terminal.");return Is(await n.run(s.cwd,o,"send",{...a,terminalId:c},r),"Sent after the user approved. ")}},{name:"terminal_read",label:"terminal_read",description:"Read the recent text of one of the user's open workspace terminal tabs (scrollback included, plain text). Use it to see what the user is looking at in a terminal or to check on a command started with terminal_send. Does not type anything.",parameters:be.Object({terminalId:be.Optional(ks),lines:Ps(100)}),async execute(e,t,r,i,s){return r?.throwIfAborted(),Is(await n.run(s.cwd,s.sessionManager.getSessionId(),"read",t,r))}}]}function Es(n){let e={run:(...t)=>n.run(de.terminal,...t),ask:n.ask};return Ss(e)}function xs(){return[rs,bs(),Kn]}import{createHash as gl,randomUUID as ml}from"node:crypto";import{mkdir as wl,open as yl,readFile as vl,rename as bl,rm as _s,writeFile as kl}from"node:fs/promises";import{dirname as Pl}from"node:path";var Z=class extends Error{status;constructor(e,t=409){super(e),this.status=t}},rr=class n{disabled=new Set;changing=!1;file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await vl(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 Z("\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 gl("sha256").update(JSON.stringify([...this.disabled].sort())).digest("hex")}async set(e,t,r,i){if(this.changing)throw new Z("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.changing=!0;let s=`${this.file}.${ml()}.tmp`,o=`${this.file}.lock`,a;try{if(r!==this.revision())throw new Z("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u53D8\u5316\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5");i();let c=new Set(this.disabled);t?c.delete(e):c.add(e),await wl(Pl(this.file),{recursive:!0});try{a=await yl(o,"wx",384)}catch(p){throw p.code==="EEXIST"?new Z("\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 a.writeFile(JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()})+`
27
+ `);let l=new n(this.file);if(await l.load(),l.revision()!==r)throw new Z("\u63D2\u4EF6\u914D\u7F6E\u5DF2\u7531\u5176\u4ED6\u670D\u52A1\u4FEE\u6539\uFF0C\u8BF7\u91CD\u542F\u5F53\u524D\u670D\u52A1\u540E\u91CD\u8BD5");await kl(s,JSON.stringify({version:1,disabled:[...c].sort()},null,2)+`
28
+ `,{mode:384}),i(),await bl(s,this.file),this.disabled=c}finally{this.changing=!1;try{await _s(s,{force:!0})}finally{a&&(await a.close(),await _s(o,{force:!0}))}}}};var ir=class{routes;running=new Map;changing=!1;plugins;preferences;constructor(e,t){if(this.plugins=e,this.preferences=t,this.routes=e.flatMap(r=>[...r.routes]),new Set(e.map(r=>r.metadata.id)).size!==e.length||new Set(this.routes).size!==this.routes.length)throw new Error("Duplicate server plugin registration")}get mutating(){return this.changing}actionRoute(e,t){return this.plugins.find(r=>r.metadata.id===e)?.routes.find(r=>r.split("/").at(-1)===t&&!r.endsWith("/attach"))}external(e){let t=new Set(this.plugins.map(r=>r.metadata.id));return{plugins:e.plugins.filter(r=>!t.has(r.id)),errors:[...e.errors,...e.plugins.filter(r=>t.has(r.id)).map(r=>`Plugin ID reserved by host: ${r.id}`)]}}catalog(e){let t=this.external(e);return{...t,plugins:[...this.plugins.filter(r=>this.preferences.enabled(r.metadata.id)).map(r=>({id:r.metadata.id,client:`builtin:${r.metadata.id}`})),...t.plugins]}}inventory(e){return{revision:this.preferences.revision(),scope:"global",items:[...this.plugins.map(t=>({...t.metadata,enabled:this.preferences.enabled(t.metadata.id),managed:!0})),...this.external(e).plugins.map(t=>({id:t.id,name:t.id,description:{zh:"\u7531 Pi \u8F6F\u4EF6\u5305\u63D0\u4F9B\u7684 Web \u63D2\u4EF6\u3002\u8BF7\u5728\u5305\u4E0E\u6269\u5C55\u4E2D\u7BA1\u7406\u5176\u8FD0\u884C\u65F6\u3002",en:"Web plugin supplied by a Pi package. Manage its runtime under Packages & extensions."},version:"",kind:"external",enabled:!0,managed:!1,reason:"pi-runtime-owned"}))]}}async toggle(e,t,r,i){if(!this.plugins.some(s=>s.metadata.id===e))throw new Z("\u6B64\u63D2\u4EF6\u9700\u8981\u901A\u8FC7 Pi \u8F6F\u4EF6\u5305\u7BA1\u7406",400);if(this.changing||[...this.running.values()].some(s=>s>0))throw new Z("\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210");this.changing=!0;try{await this.preferences.set(e,t,r,i),t||await this.plugins.find(s=>s.metadata.id===e)?.disable?.()}finally{this.changing=!1}}async dispatch(e){let t=this.plugins.find(i=>i.routes.includes(e.path));if(!t)return!1;if(this.changing)return e.json(409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"}),!0;if(!this.preferences.enabled(t.metadata.id))return e.json(403,{error:"\u63D2\u4EF6\u5DF2\u505C\u7528",errorCode:"plugin_disabled"}),!0;let r=t.metadata.id;this.running.set(r,(this.running.get(r)??0)+1);try{await t.handle(e)}finally{this.running.set(r,this.running.get(r)-1)}return!0}async runAgentAction(e,t,r,i,s,o){let a=this.plugins.find(c=>c.metadata.id===e);if(!a?.agentAction||!this.preferences.enabled(e))throw new Z("\u63D2\u4EF6\u4E0D\u53EF\u7528\u6216\u5DF2\u505C\u7528",403);if(this.changing)throw new Z("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");this.running.set(e,(this.running.get(e)??0)+1);try{return await a.agentAction(t,r,i,s,o)}finally{this.running.set(e,this.running.get(e)-1)}}async coordinateStart(e,t){if(this.changing)throw new Z("\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");let r="@host/start";this.running.set(r,(this.running.get(r)??0)+1);let i=t;for(let s of this.plugins)if(s.coordinateStart&&this.preferences.enabled(s.metadata.id)){let o=i;i=()=>s.coordinateStart(e,o)}try{return await i()}finally{this.running.set(r,this.running.get(r)-1)}}requestFailure(e){if(e instanceof Z)return{status:e.status,body:{error:e.message,errorCode:"validation_error",reason:"plugin_busy"}};for(let t of this.plugins){let r=t.requestFailure?.(e);if(r)return r}return null}restartBlocker(){return this.changing||[...this.running.values()].some(e=>e>0)?"\u63D2\u4EF6\u64CD\u4F5C\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5B8C\u6210\u540E\u518D\u5347\u7EA7":null}restartConfirmations(){return this.plugins.flatMap(e=>e.restartBlocker?.()??[])}async releaseForRestart(){await Promise.all(this.plugins.filter(e=>e.restartBlocker?.()).map(e=>e.releaseForRestart?.()))}async close(){await Promise.all(this.plugins.map(e=>e.close?.()))}};import{mkdir as Il,opendir as Sl,stat as El}from"node:fs/promises";import{homedir as xl}from"node:os";import{basename as _l,dirname as Ts,join as As,posix as Tl,resolve as Rs,win32 as Al}from"node:path";function Cs(n){return process.platform==="win32"?Al.isAbsolute(n)&&/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(n):Tl.isAbsolute(n)}function Rl(n,e,t){if(n.length===t&&e.name.localeCompare(n[n.length-1].name)>=0)return!0;let r=0,i=n.length;for(;r<i;){let s=r+i>>>1;e.name.localeCompare(n[s].name)<0?i=s:r=s+1}return n.splice(r,0,e),n.length<=t?!1:(n.pop(),!0)}async function Ns(n){if(n!==void 0&&!Cs(n))throw new Error("\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");let e=xl(),t=Rs(n??e),r=[];for(let c=t;;c=Ts(c)){let l=Ts(c);if(r.unshift({name:l===c?c:_l(c),path:c,hidden:!1}),l===c)break}let i=[],s=!1,o=await Sl(t);for await(let c of o)!c.isDirectory()&&!c.isSymbolicLink()||Rl(i,{name:c.name,isDirectory:c.isDirectory(),isSymbolicLink:c.isSymbolicLink()},1001)&&(s=!0);let a=[];for(let c of i){let l=As(t,c.name);if(!c.isDirectory&&c.isSymbolicLink)try{if(!(await El(l)).isDirectory())continue}catch{continue}if(a.length===1e3){s=!0;break}a.push({name:c.name,path:l,hidden:c.name.startsWith(".")})}return{path:t,home:e,crumbs:r,entries:a,truncated:s}}async function Ds(n,e){if(!Cs(n))throw new Error("\u7236\u76EE\u5F55\u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");if(!e.trim()||e==="."||e===".."||/[/\\]/.test(e))throw new Error("\u6587\u4EF6\u5939\u540D\u79F0\u65E0\u6548");let t=As(Rs(n),e);return await Il(t),t}import{execFile as Cl}from"node:child_process";import{accessSync as Nl,constants as Dl}from"node:fs";import{delimiter as Ol,join as Hl}from"node:path";var Ml=(n,e,t)=>new Promise((r,i)=>{Cl(n,[...e],{encoding:"utf8",signal:t,windowsHide:!0},(s,o,a)=>{s?i(Object.assign(new Error(s.message,{cause:s}),{code:s.code,stdout:o,stderr:a})):r({stdout:o,stderr:a})})});function Wl(n){for(let e of(n??"").split(Ol))if(e)for(let t of["zenity","kdialog"])try{return Nl(Hl(e,t),Dl.X_OK),!0}catch{}return!1}function Os(n=process.platform,e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?"browse":n==="darwin"||n==="linux"&&(e.DISPLAY||e.WAYLAND_DISPLAY)&&Wl(e.PATH)?"native":"browse"}function nr(n){if(!(typeof n!="object"||n===null||!("code"in n)))return typeof n.code=="string"||typeof n.code=="number"?n.code:void 0}function jl(n){return typeof n=="object"&&n!==null&&"stderr"in n&&typeof n.stderr=="string"?n.stderr:""}function si(n){return n.replace(/[\r\n]+$/,"")||null}async function Hs(n,e=process.platform,t=Ml){if(e==="darwin")try{let r=await t("osascript",["-e",'set selectedFolder to choose folder with prompt "Select Workspace Directory"',"-e","POSIX path of selectedFolder"],n);return si(r.stdout)}catch(r){if(!n.aborted&&nr(r)===1&&/(?:User canceled|-128)/i.test(jl(r)))return null;throw r}if(e==="linux"){try{return si((await t("zenity",["--file-selection","--directory","--title=Select Workspace Directory"],n)).stdout)}catch(r){if(n.aborted)throw r;if(nr(r)===1)return null;if(nr(r)!=="ENOENT")throw r}try{return si((await t("kdialog",["--getexistingdirectory",".","--title","Select Workspace Directory"],n)).stdout)}catch(r){if(n.aborted)throw r;if(nr(r)===1)return null;throw r}}throw new Error(`\u5F53\u524D\u7CFB\u7EDF\u4E0D\u652F\u6301\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\uFF1A${e}`)}import{createHash as $l,randomUUID as Fl}from"node:crypto";import{mkdir as Ll,readFile as Ul,writeFile as Vl}from"node:fs/promises";import{join as Ms}from"node:path";import{getAgentDir as Bl}from"@earendil-works/pi-coding-agent";var sr=20*1024*1024,Ws=20,zl=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;function ql(n){let e=n.indexOf("."),t=(e<0?n:n.slice(0,e)).replace(/[. ]+$/u,"");return zl.test(t)}function Gl(n,e){let t=0,r="";for(let i of Buffer.from(n).toString("utf8")){let s=Buffer.byteLength(i);if(t+s>e)break;r+=i,t+=s}return r}function Jl(n){if(n===void 0)return"file";let t=n.slice(Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"))+1).replace(/[\u0000-\u001f\u007f]/g,"").replace(/[<>:"|?*]/g,"_").trim().replace(/[. ]+$/u,"");return ql(t)&&(t=`_${t}`),t=Gl(t,255).replace(/[. ]+$/u,""),t===""||t==="."||t===".."?"file":t}function Kl(n){return n.length>=8&&n.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?"image/png":n.length>=3&&n.subarray(0,3).equals(Buffer.from([255,216,255]))?"image/jpeg":n.length>=6&&["GIF87a","GIF89a"].includes(n.toString("ascii",0,6))?"image/gif":n.length>=12&&n.toString("ascii",0,4)==="RIFF"&&n.toString("ascii",8,12)==="WEBP"?"image/webp":null}async function js(n,e,t,r){if(r.byteLength===0||r.byteLength>sr)throw new Error("\u6587\u4EF6\u4E3A\u7A7A\u6216\u8D85\u8FC7 20 MB");let i=Jl(e),s=$l("sha256").update(r).digest("hex"),o=Ms(Bl(),"pi-web","attachments",s);await Ll(o,{recursive:!0});let a=Ms(o,i);try{await Vl(a,r,{flag:"wx",mode:384})}catch(c){if(!(c instanceof Error&&"code"in c&&c.code==="EEXIST"))throw c}return{id:Fl(),name:i,bytes:r.byteLength,path:a,mediaType:Kl(r)??t.replace(/^image\//,"application/"),sessionId:n}}async function $s(n){return{type:"image",data:(await Ul(n.path)).toString("base64"),mimeType:n.mediaType}}import{randomBytes as Xl}from"node:crypto";function Fs(n,e,t){return n!=="openai-codex"||e!=="oauth"?t:{...t,prompt:r=>r.type==="select"&&r.options.some(i=>i.id==="browser")&&r.options.some(i=>i.id==="device_code")?Promise.resolve("browser"):t.prompt(r)}}var or=class{flows=new Map;reportError;constructor(e=()=>{}){this.reportError=e}start(e,t,r,i,s){let o=this.getActive();if(o){if(o.providerId===e&&o.method===t&&i===void 0)return o;throw new Error("\u5176\u4ED6\u63D0\u4F9B\u65B9\u7684\u767B\u5F55\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u5F53\u524D\u767B\u5F55")}this.flows.clear();let a=Xl(18).toString("base64url"),c={view:{id:a,providerId:e,method:t,status:"running"},controller:new AbortController};return this.flows.set(a,c),r(e,t,{signal:c.controller.signal,notify:l=>{c.view={...c.view,event:l,...l.type==="auth_url"||l.type==="device_code"?{authorization:l}:{}}},prompt:l=>{if(l.type==="secret"&&i!==void 0){let p=i;return i=void 0,Promise.resolve(p)}return new Promise((p,u)=>{let{signal:h,...w}=l;c.answer=p,c.reject=u,c.view={...c.view,status:"waiting",prompt:w},h?.aborted?u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")):h?.addEventListener("abort",()=>u(new Error("\u767B\u5F55\u8F93\u5165\u5DF2\u53D6\u6D88")),{once:!0})})}}).then(()=>{c.view.status!=="cancelled"&&(c.view={id:a,providerId:e,method:t,status:"done"})}).catch(l=>{if(c.view.status!=="cancelled"){let p=new Error("Provider login failed");l instanceof Error&&l.stack&&(p.stack=`${p.message}
25
29
  ${l.stack.split(`
26
30
  `).slice(1).join(`
27
- `)}`);let u=this.reportError(p,{...s,stage:"provider_login"});a.view={id:c,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:u}}}),{...a.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(s=>s.id===t))return!1;let i=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},i(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as Il}from"node:crypto";import{readFile as Sl,rename as El,rm as xl,stat as _l,writeFile as Tl,mkdir as Al}from"node:fs/promises";import{dirname as Rl}from"node:path";var Cl=["openai-completions","openai-responses","anthropic-messages"];function ei(n){if(!n||typeof n!="object")return!1;let e=n;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||!Cl.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 bs(n,e){if(!ei(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 Sl(n,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let r;if(t===void 0)r={providers:{}};else{try{r=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let i={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await Al(Rl(n),{recursive:!0});let s=t===void 0?384:(await _l(n)).mode&511,o=`${n}.pi-web-${Il(6).toString("hex")}.tmp`;try{await Tl(o,`${JSON.stringify(i,null,2)}
28
- `,{mode:s,flag:"wx"}),await El(o,n)}finally{await xl(o,{force:!0})}}import{randomBytes as Nl}from"node:crypto";import{mkdir as Dl,readFile as Ol,rename as Hl,rm as Ml,stat as Wl,writeFile as jl}from"node:fs/promises";import{dirname as $l}from"node:path";function ks(n){if(!n||n.length>2048)return!1;try{let e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function Ps(n){if(!n||typeof n!="object")return!1;let e=n;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Is(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&ks(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Is(n){if(!n||typeof n!="object")return!1;let e=n;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 Ss(n){let e;try{e=await Ol(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function Fl(n,e,t){await Dl($l(n),{recursive:!0});let r=t===void 0?384:(await Wl(n)).mode&511,i=`${n}.pi-web-${Nl(6).toString("hex")}.tmp`;try{await jl(i,`${JSON.stringify(e,null,2)}
29
- `,{mode:r,flag:"wx"}),await Hl(i,n)}finally{await Ml(i,{force:!0})}}async function Es(n,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Ss(n),i=r.providers[e],s=new Set(i?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:i?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:s.has(o.id)?"custom":"builtin",overridden:!!i?.modelOverrides?.[o.id]}))}}async function xs(n,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i,existing:s}=await Ss(n),o={...i.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!ks(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(!Is(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)||r.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)||r.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&&r.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?i.providers[e]=o:delete i.providers[e],await Fl(n,i,s)}function _s(n){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(n.trim())}import{randomBytes as Ts,createHash as Vl}from"node:crypto";import{fileURLToPath as Ul}from"node:url";var xt="pi-webapp@0.1.54-alpha.2+e84106fa5a9d3059db5b",Ie="e84106fa5a9d3059db5b";var Bl="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ir(n=process.env,e=console.warn){let t=r=>{let i={enabled:!1,environment:n.PI_WEB_SENTRY_ENVIRONMENT||"production",release:xt,buildId:Ie},s=n[`PI_WEB_SENTRY_${r}_DSN`]??n.PI_WEB_SENTRY_DSN??Bl;if(n.PI_WEB_SENTRY_ENABLED!=="true"||!s)return i;try{let o=new URL(s);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...i,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),i}};return{browser:t("BROWSER"),node:t("NODE")}}var Ee=class{config;ready;reporter;client;salt=Ts(16);breadcrumbs=new Et;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=ir(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Ul(import.meta.url).replace(/\\/g,"/"),r=t.lastIndexOf("/src/"),i=r>=0?t.slice(0,r+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:i)&&this.capture(s,{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:Ie,integrations:[],transport:e.transport??(r=>Fn(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:$n,sendClientReports:!1,dataCollection:{...Mn,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Kt(this.client,"node",Ie,t,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||ze(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let r=Ts(16).toString("hex");return this.early.push({error:nt(e),context:Pe(t),eventId:r}),r}catch{return}}setState(e){this.state=Pe({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return Vl("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(r=>{t=setTimeout(r,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as rd}from"@earendil-works/pi-coding-agent";function Oe(n,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(n.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!n.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 ql}from"node:crypto";var As="[pi-web workspace tab in view] ",Rs=' \u2014 The user wrote this while looking at that workspace tab. Read "this", "here" or "current" as its content, and when a tool can act on that content (for example read and patch the open drawing or file), act on it in place instead of creating something new.';function Ll(n){return{title:n.title,kind:n.kind,contentId:n.contentId,...n.plugin?{plugin:n.plugin}:{},...n.detail?{detail:n.detail}:{},...n.reference?{reference:n.reference}:{}}}function zl(n){let e=n.endsWith(Rs)?n.slice(0,-Rs.length):n;try{let t=JSON.parse(e);if(typeof t.title!="string"||typeof t.kind!="string"||typeof t.contentId!="string")return null;for(let r of["plugin","detail","reference"])if(t[r]!==void 0&&typeof t[r]!="string")return null;return Ll(t)}catch{return null}}function _t(n){let e=[],t=n;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let s;try{s=JSON.parse(i[2])}catch{break}e.unshift({name:s,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(s)}),t=t.slice(0,i.index)}let r=t.lastIndexOf(As);if(r!==-1&&(r===0||t.slice(r-2,r)===`
31
+ `)}`);let u=this.reportError(p,{...s,stage:"provider_login"});c.view={id:a,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}}}),{...c.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(s=>s.id===t))return!1;let i=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},i(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as Yl}from"node:crypto";import{readFile as Ql,rename as Zl,rm as ed,stat as td,writeFile as rd,mkdir as id}from"node:fs/promises";import{dirname as nd}from"node:path";var sd=["openai-completions","openai-responses","anthropic-messages"];function oi(n){if(!n||typeof n!="object")return!1;let e=n;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||!sd.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 Ls(n,e){if(!oi(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 Ql(n,"utf8")}catch(a){if(a.code!=="ENOENT")throw a}let r;if(t===void 0)r={providers:{}};else{try{r=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let i={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await id(nd(n),{recursive:!0});let s=t===void 0?384:(await td(n)).mode&511,o=`${n}.pi-web-${Yl(6).toString("hex")}.tmp`;try{await rd(o,`${JSON.stringify(i,null,2)}
32
+ `,{mode:s,flag:"wx"}),await Zl(o,n)}finally{await ed(o,{force:!0})}}import{randomBytes as od}from"node:crypto";import{mkdir as ad,readFile as cd,rename as ld,rm as dd,stat as pd,writeFile as ud}from"node:fs/promises";import{dirname as fd}from"node:path";function Us(n){if(!n||n.length>2048)return!1;try{let e=new URL(n);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function Vs(n){if(!n||typeof n!="object")return!1;let e=n;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Bs(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&Us(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Bs(n){if(!n||typeof n!="object")return!1;let e=n;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 zs(n){let e;try{e=await cd(n,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function hd(n,e,t){await ad(fd(n),{recursive:!0});let r=t===void 0?384:(await pd(n)).mode&511,i=`${n}.pi-web-${od(6).toString("hex")}.tmp`;try{await ud(i,`${JSON.stringify(e,null,2)}
33
+ `,{mode:r,flag:"wx"}),await ld(i,n)}finally{await dd(i,{force:!0})}}async function qs(n,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await zs(n),i=r.providers[e],s=new Set(i?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:i?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:s.has(o.id)?"custom":"builtin",overridden:!!i?.modelOverrides?.[o.id]}))}}async function Gs(n,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i,existing:s}=await zs(n),o={...i.providers[e]??{}},a=[...o.models??[]],c={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!Us(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(!Bs(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:a.findIndex(h=>h.id===p);if(p===void 0&&(a.some(h=>h.id===l.id)||r.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(a.some(w=>w.id===l.id)||r.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let h={...a[u],...l};for(let w of["name","contextWindow","maxTokens","input"])l[w]===void 0&&delete h[w];a[u]=h}else if(p!==void 0&&r.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:h,...w}=l;c[p]={...c[p],...w};for(let v of["name","contextWindow","maxTokens","input"])l[v]===void 0&&delete c[p][v]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");a.push(l)}}else{let l=a.findIndex(p=>p.id===t.id);if(l>=0)a.splice(l,1);else if(Object.hasOwn(c,t.id))delete c[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")}a.length?o.models=a:delete o.models,Object.keys(c).length?o.modelOverrides=c:delete o.modelOverrides,Object.keys(o).length?i.providers[e]=o:delete i.providers[e],await hd(n,i,s)}function Js(n){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(n.trim())}import{randomBytes as Ks,createHash as gd}from"node:crypto";import{fileURLToPath as md}from"node:url";var _t="pi-webapp@0.1.54-alpha.3+9b481b9a718850f1d64d",Ee="9b481b9a718850f1d64d";var wd="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ar(n=process.env,e=console.warn){let t=r=>{let i={enabled:!1,environment:n.PI_WEB_SENTRY_ENVIRONMENT||"production",release:_t,buildId:Ee},s=n[`PI_WEB_SENTRY_${r}_DSN`]??n.PI_WEB_SENTRY_DSN??wd;if(n.PI_WEB_SENTRY_ENABLED!=="true"||!s)return i;try{let o=new URL(s);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...i,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),i}};return{browser:t("BROWSER"),node:t("NODE")}}var _e=class{config;ready;reporter;client;salt=Ks(16);breadcrumbs=new xt;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=ar(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=md(import.meta.url).replace(/\\/g,"/"),r=t.lastIndexOf("/src/"),i=r>=0?t.slice(0,r+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:i)&&this.capture(s,{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:Ee,integrations:[],transport:e.transport??(r=>Jn(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:Gn,sendClientReports:!1,dataCollection:{...Bn,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Xt(this.client,"node",Ee,t,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||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 r=Ks(16).toString("hex");return this.early.push({error:st(e),context:Se(t),eventId:r}),r}catch{return}}setState(e){this.state=Se({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return gd("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(r=>{t=setTimeout(r,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as Rd}from"@earendil-works/pi-coding-agent";function Me(n,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(n.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!n.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 bd}from"node:crypto";var Xs="[pi-web workspace tab in view] ",Ys=' \u2014 The user wrote this while looking at that workspace tab. Read "this", "here" or "current" as its content, and when a tool can act on that content (for example read and patch the open drawing or file), act on it in place instead of creating something new.';function yd(n){return{title:n.title,kind:n.kind,contentId:n.contentId,...n.plugin?{plugin:n.plugin}:{},...n.detail?{detail:n.detail}:{},...n.reference?{reference:n.reference}:{}}}function vd(n){let e=n.endsWith(Ys)?n.slice(0,-Ys.length):n;try{let t=JSON.parse(e);if(typeof t.title!="string"||typeof t.kind!="string"||typeof t.contentId!="string")return null;for(let r of["plugin","detail","reference"])if(t[r]!==void 0&&typeof t[r]!="string")return null;return yd(t)}catch{return null}}function Tt(n){let e=[],t=n;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let s;try{s=JSON.parse(i[2])}catch{break}e.unshift({name:s,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(s)}),t=t.slice(0,i.index)}let r=t.lastIndexOf(Xs);if(r!==-1&&(r===0||t.slice(r-2,r)===`
30
34
 
31
35
  `)&&!t.slice(r).includes(`
32
- `)){let i=zl(t.slice(r+As.length));if(i)return{text:t.slice(0,Math.max(0,r-2)),attachments:e,context:i}}return{text:t,attachments:e}}var Tt=n=>Buffer.byteLength(n.text)+n.images.reduce((e,t)=>e+t.data.length,0),oe=class extends Error{status=409},He=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,..._t(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((i,s)=>i+Tt(s),Tt({text:e,images:t}))>64*1024*1024)throw new oe("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:ql(),revision:1,text:e,images:t.map(i=>({...i})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new oe("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let r=this.entries.find(i=>i.id===e);if(!r||r.revision!==t)throw new oe("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new oe("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,t,r,i){let s=this.find(e,t);if(r.kind==="remove"){this.entries=this.entries.filter(o=>o!==s),this.changed();return}if(r.kind==="edit"){let o=_t(s.text),c=s.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),c].filter(Boolean).join(`
36
+ `)){let i=vd(t.slice(r+Xs.length));if(i)return{text:t.slice(0,Math.max(0,r-2)),attachments:e,context:i}}return{text:t,attachments:e}}var At=n=>Buffer.byteLength(n.text)+n.images.reduce((e,t)=>e+t.data.length,0),oe=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=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((i,s)=>i+At(s),At({text:e,images:t}))>64*1024*1024)throw new oe("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:bd(),revision:1,text:e,images:t.map(i=>({...i})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new oe("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let r=this.entries.find(i=>i.id===e);if(!r||r.revision!==t)throw new oe("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new oe("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,t,r,i){let s=this.find(e,t);if(r.kind==="remove"){this.entries=this.entries.filter(o=>o!==s),this.changed();return}if(r.kind==="edit"){let o=Tt(s.text),a=s.text.slice(o.text.length).replace(/^\n\n/u,""),c=[r.text.trim(),a].filter(Boolean).join(`
33
37
 
34
- `);if(this.validateText(a),this.entries.reduce((l,p)=>l+Tt(p),0)-Tt(s)+Tt({text:a,images:s.images})>64*1024*1024)throw new oe("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=a,s.revision++,delete s.error,this.changed();return}await this.deliver(s,i)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,t){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var h=class extends Error{code;status;reason;constructor(e,t,r={}){super(t),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function K(n){let e=n&&typeof n=="object"?n:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:n instanceof Error?n.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Me=n=>n.code==="ENOENT";var Cs=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function ti(n,e,t,r){if(!n)throw new h("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return n.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new h("invalid_input","Expected plugin request object",{status:400});let i=t;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","status","cancel-initialization"].includes(String(i.operation)))throw new h("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(i.operation!=="pollMany")return n.views(i);if(!Array.isArray(i.views)||!i.views.length||i.views.length>64||i.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new h("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(i.views.map(async s=>{try{return{reply:await n.views({...s,operation:"poll",immediate:!0})}}catch(o){return{failure:nr(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new h("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof i.id!="string"||!/^[a-f0-9-]{36}$/.test(i.id)||i.decision!=="allow"&&i.decision!=="deny")throw new h("invalid_input","Invalid approval decision",{status:400});if(!n.decide)throw new h("hosted_unavailable","Approvals are not available in this runtime",{status:503});return n.decide(i.id,i.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new h("host_restarting","Host is updating; secret changes are fenced",{status:409});if(i.auth!==void 0){if(!n.secretAuth)throw new h("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(i.auth==="start"&&typeof i.pluginId=="string"&&i.pluginId.length<=214&&typeof i.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(i.name))return n.secretAuth({phase:"start",pluginId:i.pluginId,name:i.name});if((i.auth==="poll"||i.auth==="cancel")&&typeof i.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(i.deviceId))return n.secretAuth({phase:i.auth,deviceId:i.deviceId});throw new h("invalid_input","Invalid sign-in request",{status:400})}if(typeof i.pluginId!="string"||i.pluginId.length>214||typeof i.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i.name)||!(i.value===null||typeof i.value=="string"&&i.value.length>=1&&i.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(i.value)))throw new h("invalid_input","Invalid secret request",{status:400});if(!n.secret)throw new h("hosted_unavailable","Secrets are not available in this runtime",{status:503});return n.secret(i.pluginId,i.name,i.value)}if(typeof i.pluginId!="string"||i.pluginId.length>214)throw new h("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new h("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof i.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(i.operation)||i.version!==void 0&&(typeof i.version!="string"||!/^\d+\.\d+\.\d+$/.test(i.version)))throw new h("invalid_input","Invalid plugin management request",{status:400});if(i.downloadId!==void 0&&(typeof i.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(i.downloadId))||i.operation==="cancel-download"&&!i.downloadId)throw new h("invalid_input","Exact download identity required",{status:400});if(i.reopenEditors!==void 0&&typeof i.reopenEditors!="boolean")throw new h("invalid_input","Invalid editor reopen consent",{status:400});if(i.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(i.updatePolicy)||i.operation==="policy"&&(typeof i.updatePolicy!="string"||i.updatePolicy==="pinned"&&!i.version))throw new h("invalid_input","Invalid update policy or missing exact pin",{status:400});return n.manage({pluginId:i.pluginId,operation:i.operation,...typeof i.downloadId=="string"?{downloadId:i.downloadId}:{},...typeof i.updatePolicy=="string"?{updatePolicy:i.updatePolicy}:{},...typeof i.version=="string"?{version:i.version}:{},...typeof i.reopenEditors=="boolean"?{reopenEditors:i.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof i.sessionId!="string"||!i.sessionId||i.sessionId.length>200||!Number.isSafeInteger(i.generation)||Number(i.generation)<1||typeof i.action!="string"||!/^[\w.-]{1,80}$/.test(i.action))throw new h("invalid_input","Invalid plugin action request",{status:400});if(i.viewToken!==void 0&&(typeof i.viewToken!="string"||i.viewToken.length>200)||i.mountId!==void 0&&(typeof i.mountId!="string"||i.mountId.length>200))throw new h("invalid_input","Invalid view flush capability",{status:400});return n.action({sessionId:i.sessionId,pluginId:i.pluginId,generation:Number(i.generation),action:i.action,input:i.input??{},...typeof i.viewToken=="string"?{viewToken:i.viewToken}:{},...typeof i.mountId=="string"?{mountId:i.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new h("invalid_route","Unknown hosted plugin route",{status:404})}function nr(n){let e=K(n);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","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 Ns}from"node:fs/promises";import{join as Ds}from"node:path";async function Os(n){try{let e=JSON.parse(await Ns(Ds(n,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await Ns(Ds(n,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let o of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let i={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(s=>[`/${s}`,{path:s,type:i[s.split(".").pop()]}]))}catch{return{}}}import{access as Jl,readFile as Ws,realpath as ar,rename as Lm,rm as zm,writeFile as qm}from"node:fs/promises";import{dirname as or,join as Ce,resolve as Kl,sep as Ms}from"node:path";import{createRequire as Xl}from"node:module";var Gl=/^(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 xe(n){let e=typeof n=="string"&&Gl.exec(n);if(!e||e[0]!==n)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||r.some(i=>/^\d+$/.test(i)&&i.length>1&&i[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:r}}function fe(n,e){let t=xe(n),r=xe(e);for(let i=0;i<3;i++)if(t.core[i]!==r.core[i])return t.core[i]>r.core[i]?1:-1;if(!t.prerelease.length||!r.prerelease.length)return+!t.prerelease.length-+!r.prerelease.length;for(let i=0;i<Math.max(t.prerelease.length,r.prerelease.length);i++){let s=t.prerelease[i],o=r.prerelease[i];if(s===void 0||o===void 0)return s===void 0?-1:1;if(s===o)continue;let c=/^\d+$/.test(s),a=/^\d+$/.test(o);return c!==a?c?-1:1:c&&s.length!==o.length?s.length>o.length?1:-1:s>o?1:-1}return 0}function Hs(n){try{return xe(n).prerelease.length===0}catch{return!1}}function sr(n){try{return xe(n),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(n)}catch{return!1}}var We=1;async function st(n,e){let t=Xl(Ce(n,"package.json"));for(let r of t.resolve.paths(e)??[]){let i=Ce(r,e);try{if(JSON.parse(await Ws(Ce(i,"package.json"),"utf8")).name===e)return await ar(i)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function ri(n,e){if(fe(e?.version,e?.version),e.desktopProtocolVersion!==We||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await ar(Kl(or(e.launcher),"..")),r=await ar(Ce(n,"pi-web","releases")),i=or(or(t));if(await ar(e.launcher)!==Ce(t,"bin","pi-webapp.mjs")||or(i)!==r||!i.startsWith(r+Ms)||!i.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(i.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await Ws(Ce(t,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==We)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 st(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(i+Ms))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let c=Ce(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,c,Ce(t,"dist","extension.js"),Ce(t,"web","dist","index.html")].map(a=>Jl(a))),e.fallbackVersion!==void 0&&xe(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:We,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var id={"/":{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(n,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:n.getHeader("X-Request-ID"),operationId:n.getHeader("X-Operation-ID")}),n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify(t))}function nd(n,e){let t=n.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let r=Buffer.from(t.slice(7),"utf8");return r.length===e.length&&Yl(r,e)}async function $s(n,e=64*1024){let t=0,r=[];for await(let i of n){let s=Buffer.isBuffer(i)?i:Buffer.from(i);if(t+=s.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function sd(n){let e=0,t=[];for await(let r of n){let i=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=i.length,e>tr)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(i)}return Buffer.concat(t)}async function od(n,e=0){await new Promise((r,i)=>{n.once("error",i),n.listen(e,"127.0.0.1",()=>{n.off("error",i),r()})});let t=n.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function Fs(n,e,t=new Ee,r={}){t.setState({piVersion:rd});let i=process.env.PI_WEBAPP_RESTART_TOKEN,s=i&&/^[A-Za-z0-9_-]{32}$/.test(i)?i:js(24).toString("base64url"),o=Buffer.from(s),c=fs(),a=new Set,l=new Qt(r.pluginSettingsFile??ni(td(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new Zt(ss(),l),u=async()=>await n.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())}
35
- `)},f=new Map,y=new rr((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,T=!1,D={...id,...await Os(e)};for(let b of await Zl(ni(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"};D[`/assets/${b}`]={path:`assets/${b}`,type:$[v[1]]}}let M=ed(async(b,v)=>{let $=js(18).toString("base64"),we=le=>typeof le=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(le),ye=we(b.headers["x-request-id"])?b.headers["x-request-id"]:ii(),ne={requestId:ye,operationId:we(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",ye),ne.operationId&&v.setHeader("X-Operation-ID",ne.operationId);let x="/",Fa=performance.now(),ce=(le,g,S)=>{let C=!ze(le)&&Wn(x)?Ae(le,"Agent or provider operation failed"):le,U=t.capture(C,{...ne,route:x,method:b.method,status:g,stage:"http"});I(v,g,{error:S,errorId:U,errorReported:t.enabled,errorCode:ze(le)?"validation_error":"unexpected_error"})};v.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...ne,route:x,method:b.method,status:v.statusCode,durationMs:Math.round(performance.now()-Fa)})});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 le=D[x];if(b.method==="GET"&&le){try{let g=await Ql(ni(e,le.path));v.writeHead(200,{"Content-Type":le.type,"Cache-Control":"no-store"}),v.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${$}">`):g)}catch(g){ce(g,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let g=await n.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 n.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){ce(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(v,404,{error:"\u672A\u627E\u5230"});return}if(!nd(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 ti(n.hosted,x,void 0))}catch(g){let S=nr(g);I(v,S.status,S.body)}return}if(b.method==="POST"&&Cs.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 $s(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 ti(n.hosted,x,g,{draining:E}))}catch(S){let _=nr(S);I(v,_.status,_.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 n.selfUpdate?.runningVersion()??null,desktopProtocolVersion:We,...n.selfUpdate?.launcherIdentity?{launcher:n.selfUpdate.launcherIdentity(),desktopHandoffProtocol:n.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){ce(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{I(v,200,await n.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){ce(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/image"){let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId")??"",_=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==n.snapshot().sessionId||!_||!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 U=n.image?.(S,_,C);if(!U||!["image/png","image/jpeg","image/webp","image/gif"].includes(U.mimeType)){I(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":U.mimeType,"Cache-Control":"private, no-store"}),v.end(U.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"),_=g.searchParams.get("name");try{if(!S||!_||_.length>1024||S!==n.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)>tr){I(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await ws(S,_,b.headers["content-type"]??"application/octet-stream",await sd(b));if(S!==n.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){ce(C,400,C instanceof Error?C.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/session"){try{let g=n.snapshot();k(g),I(v,200,g)}catch(g){ce(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){ce(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){ce(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/providers"){try{I(v,200,await n.providers?.()??[])}catch(g){ce(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/models"){let g=new URL(b.url??x,P).searchParams.get("providerId")??"";try{if(!g||!n.providerModels){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(v,200,await n.providerModels(g))}catch(S){ce(S,400,S instanceof Error?S.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/login/active"){I(v,200,{active:y.getActive()??null});return}if(b.method==="GET"&&x==="/api/provider/login"){let g=new URL(b.url??x,P).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 n.models():x==="/api/config"?await n.config():x==="/api/commands"?n.commands?.()??[]:await n.workspaces())}catch(g){ce(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=n.snapshot(),k(g)}catch(S){ce(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})}
36
- `),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 $s(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||ze(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(!n.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||T||y.getActive()){I(v,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let _=p.restartBlocker()??p.restartConfirmations()[0];if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length||_){I(v,409,{error:_??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7A7A\u95F2\u540E\u518D\u4EA4\u63A5\u542F\u52A8\u5668\uFF1B\u8FD0\u884C\u72B6\u6001\u5DF2\u4FDD\u7559"});return}E=!0;try{await n.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 _=()=>{if(n.snapshot().sessionId!==g.sessionId)throw new Q("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!n.snapshot().idle||(n.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,_),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:()=>n.snapshot(),busyWorkspaces:()=>n.busyGitWorkspaces?.()??[],json:(S,_)=>I(v,S,_)}))return;if(x==="/api/plugin-interaction"){if(g.sessionId!==n.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||!n.resolvePluginInteraction||!("value"in g)){I(v,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(n.snapshot().cwd,async()=>n.resolvePluginInteraction(g.sessionId,g.pluginId,g.requestId,g.value)),I(v,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(g.sessionId!==n.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 U="input"in g?g.input:{};if(!U||typeof U!="object"||Array.isArray(U)){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:C,body:{...U,sessionId:g.sessionId},res:v,snapshot:()=>n.snapshot(),busyWorkspaces:()=>n.busyGitWorkspaces?.()??[],json:(ke,Be)=>I(v,ke,ke>=200&&ke<300?{value:Be}:Be)});return}if(!n.invokePluginAction){I(v,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let _=await p.coordinateStart(n.snapshot().cwd,async()=>n.invokePluginAction(g.sessionId,g.pluginId,g.action,"input"in g?g.input:void 0));I(v,200,{value:_});return}if(x==="/api/update/channel"){if(g.sessionId!==n.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(!n.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 n.selfUpdate.setChannel(g.channel));return}if(x==="/api/update/cancel"){if(g.sessionId!==n.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!n.selfUpdate?.cancel){I(v,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await n.selfUpdate.cancel(),I(v,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(T){I(v,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(g.sessionId!==n.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!n.snapshot().idle){I(v,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!n.selfUpdate){I(v,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let S=p.restartBlocker();if((n.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 _=g,C="channel"in _||"version"in _||"allowDowngrade"in _;if(C&&(_.channel!=="stable"&&_.channel!=="alpha"||typeof _.version!="string"||_.allowDowngrade!==void 0&&typeof _.allowDowngrade!="boolean")){I(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(_.force!==void 0&&typeof _.force!="boolean"){I(v,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let U=_.force===!0,ke=q=>I(v,409,{error:q.join("\uFF1B"),reason:"update_confirm_required"}),Be=p.restartConfirmations();if(Be.length&&!U){ke(Be);return}T=!0;let bt;try{bt=await n.selfUpdate.prepare(C?{channel:_.channel,version:_.version,allowDowngrade:_.allowDowngrade}:void 0);let q=p.restartBlocker();if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length||q)throw new Error(q??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let nn=p.restartConfirmations();if(nn.length&&!U){ke(nn);return}U&&await p.releaseForRestart(),E=!0;try{await n.selfUpdate.requestRestart(bt,{force:U})}catch(sn){let on=sn?.code;if(!U&&(on==="view_barrier"||on==="drain_pending")){E=!1,ke(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw sn}}catch(q){throw E=!1,q}finally{T=!1}I(v,202,{accepted:!0,version:bt.version});return}if(x==="/api/provider/custom"){if(g.sessionId!==n.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in g)||!ei(g.provider)||!n.addCustomProvider){I(v,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await n.addCustomProvider(g.sessionId,g.provider),I(v,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(g.sessionId!==n.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)||!Ps(g.change)||!n.updateProviderModel){I(v,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await n.updateProviderModel(g.sessionId,g.providerId,g.change)}else{if(!n.logoutProvider){I(v,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await n.logoutProvider(g.sessionId,g.providerId)}I(v,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(g.sessionId!==n.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"||!n.loginProvider||!n.providers){I(v,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await n.providers()).some(U=>U.id===g.providerId&&U.methods.includes(g.method))){I(v,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let _="initialSecret"in g?g.initialSecret:void 0;if(_!==void 0&&(g.method!=="api_key"||typeof _!="string"||!_.trim()||_.length>16384)){I(v,400,{error:"API Key \u65E0\u6548"});return}let C=y.start(g.providerId,g.method,n.loginProvider,_,ne);I(v,202,{id:C.id});return}if(!("id"in g)||typeof g.id!="string"){I(v,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(x==="/api/provider/login/cancel"){I(v,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!==n.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 hs(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 ps("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 us(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 n.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 n.selectWorkspace(g.id):x==="/api/workspace/new-session"?await n.newSessionInWorkspace(g.id):await n.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 n.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(!n.renameSession){I(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await n.renameSession(g.workspaceId,g.id,g.path,g.name)}else{if(!n.deleteSession){I(v,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await n.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 n.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 n.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"&&_s(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 n.updateConfig(S));return}else if(x==="/api/prompt-queue"){let S=g,_=S.action;if(typeof S.id!="string"||S.id.length>100||!Number.isSafeInteger(S.revision)||S.revision<1||!_||typeof _!="object"||!["edit","remove","steer"].includes(_.kind)||_.kind==="edit"&&(typeof _.text!="string"||_.text.length>32e3)){I(v,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let C=n.snapshot();if(S.sessionId!==C.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(_.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(_.kind==="steer"&&C.interactions?.length){I(v,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!n.updateQueuedPrompt){I(v,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(C.cwd,async()=>n.updateQueuedPrompt(g.sessionId,S.id,S.revision,_))}else if(x==="/api/message"){let S="delivery"in g?g.delivery:void 0;if(S!==void 0&&S!=="steer"&&S!=="followUp"){I(v,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let _="attachments"in g?g.attachments:[];if(!Array.isArray(_)||_.length>ms||_.some(q=>typeof q!="string")||new Set(_).size!==_.length){I(v,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let C=_.map(q=>f.get(q));if(C.some(q=>!q||q.sessionId!==g.sessionId)){I(v,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in g)||typeof g.text!="string"||!g.text.trim()&&_.length===0||g.text.length>32e3){I(v,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let U=n.snapshot();if(g.sessionId!==U.sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{Oe(U,g.text,S)}catch(q){I(v,409,{error:q.message});return}let ke=C,Be=[g.text.trim(),...ke.map(q=>`\u9644\u4EF6 ${JSON.stringify(q.name)}\uFF1A${q.path}`)].filter(Boolean).join(`
38
+ `);if(this.validateText(c),this.entries.reduce((l,p)=>l+At(p),0)-At(s)+At({text:c,images:s.images})>64*1024*1024)throw new oe("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");s.text=c,s.revision++,delete s.error,this.changed();return}await this.deliver(s,i)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,t){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var f=class extends Error{code;status;reason;constructor(e,t,r={}){super(t),this.name="HostedPluginError",this.code=e,this.status=r.status,this.reason=r.reason}};function X(n){let e=n&&typeof n=="object"?n:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:n instanceof Error?n.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var je=n=>n.code==="ENOENT";var Qs=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function ai(n,e,t,r){if(!n)throw new f("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return n.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new f("invalid_input","Expected plugin request object",{status:400});let i=t;if(e==="/api/hosted-plugins/views"){if(r?.draining&&!["poll","pollMany","change","ack","close","reconcile","status","cancel-initialization"].includes(String(i.operation)))throw new f("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(i.operation!=="pollMany")return n.views(i);if(!Array.isArray(i.views)||!i.views.length||i.views.length>64||i.views.some(s=>!s||typeof s!="object"||Array.isArray(s)||s.operation!=="poll"))throw new f("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(i.views.map(async s=>{try{return{reply:await n.views({...s,operation:"poll",immediate:!0})}}catch(o){return{failure:cr(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(r?.draining)throw new f("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof i.id!="string"||!/^[a-f0-9-]{36}$/.test(i.id)||i.decision!=="allow"&&i.decision!=="deny")throw new f("invalid_input","Invalid approval decision",{status:400});if(!n.decide)throw new f("hosted_unavailable","Approvals are not available in this runtime",{status:503});return n.decide(i.id,i.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new f("host_restarting","Host is updating; secret changes are fenced",{status:409});if(i.auth!==void 0){if(!n.secretAuth)throw new f("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(i.auth==="start"&&typeof i.pluginId=="string"&&i.pluginId.length<=214&&typeof i.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(i.name))return n.secretAuth({phase:"start",pluginId:i.pluginId,name:i.name});if((i.auth==="poll"||i.auth==="cancel")&&typeof i.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(i.deviceId))return n.secretAuth({phase:i.auth,deviceId:i.deviceId});throw new f("invalid_input","Invalid sign-in request",{status:400})}if(typeof i.pluginId!="string"||i.pluginId.length>214||typeof i.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(i.name)||!(i.value===null||typeof i.value=="string"&&i.value.length>=1&&i.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(i.value)))throw new f("invalid_input","Invalid secret request",{status:400});if(!n.secret)throw new f("hosted_unavailable","Secrets are not available in this runtime",{status:503});return n.secret(i.pluginId,i.name,i.value)}if(typeof i.pluginId!="string"||i.pluginId.length>214)throw new f("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(r?.draining)throw new f("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof i.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(i.operation)||i.version!==void 0&&(typeof i.version!="string"||!/^\d+\.\d+\.\d+$/.test(i.version)))throw new f("invalid_input","Invalid plugin management request",{status:400});if(i.downloadId!==void 0&&(typeof i.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(i.downloadId))||i.operation==="cancel-download"&&!i.downloadId)throw new f("invalid_input","Exact download identity required",{status:400});if(i.reopenEditors!==void 0&&typeof i.reopenEditors!="boolean")throw new f("invalid_input","Invalid editor reopen consent",{status:400});if(i.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(i.updatePolicy)||i.operation==="policy"&&(typeof i.updatePolicy!="string"||i.updatePolicy==="pinned"&&!i.version))throw new f("invalid_input","Invalid update policy or missing exact pin",{status:400});return n.manage({pluginId:i.pluginId,operation:i.operation,...typeof i.downloadId=="string"?{downloadId:i.downloadId}:{},...typeof i.updatePolicy=="string"?{updatePolicy:i.updatePolicy}:{},...typeof i.version=="string"?{version:i.version}:{},...typeof i.reopenEditors=="boolean"?{reopenEditors:i.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof i.sessionId!="string"||!i.sessionId||i.sessionId.length>200||!Number.isSafeInteger(i.generation)||Number(i.generation)<1||typeof i.action!="string"||!/^[\w.-]{1,80}$/.test(i.action))throw new f("invalid_input","Invalid plugin action request",{status:400});if(i.viewToken!==void 0&&(typeof i.viewToken!="string"||i.viewToken.length>200)||i.mountId!==void 0&&(typeof i.mountId!="string"||i.mountId.length>200))throw new f("invalid_input","Invalid view flush capability",{status:400});return n.action({sessionId:i.sessionId,pluginId:i.pluginId,generation:Number(i.generation),action:i.action,input:i.input??{},...typeof i.viewToken=="string"?{viewToken:i.viewToken}:{},...typeof i.mountId=="string"?{mountId:i.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new f("invalid_route","Unknown hosted plugin route",{status:404})}function cr(n){let e=X(n);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","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 Zs}from"node:fs/promises";import{join as eo}from"node:path";async function to(n){try{let e=JSON.parse(await Zs(eo(n,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await Zs(eo(n,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let s of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!s||typeof s!="object"))for(let o of[s.file,...Array.isArray(s.css)?s.css:[],...Array.isArray(s.assets)?s.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let i={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(s=>[`/${s}`,{path:s,type:i[s.split(".").pop()]}]))}catch{return{}}}import{access as Pd,readFile as no,realpath as pr,rename as _w,rm as Tw,writeFile as Aw}from"node:fs/promises";import{dirname as dr,join as De,resolve as Id,sep as io}from"node:path";import{createRequire as Sd}from"node:module";var kd=/^(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 Te(n){let e=typeof n=="string"&&kd.exec(n);if(!e||e[0]!==n)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||r.some(i=>/^\d+$/.test(i)&&i.length>1&&i[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:r}}function he(n,e){let t=Te(n),r=Te(e);for(let i=0;i<3;i++)if(t.core[i]!==r.core[i])return t.core[i]>r.core[i]?1:-1;if(!t.prerelease.length||!r.prerelease.length)return+!t.prerelease.length-+!r.prerelease.length;for(let i=0;i<Math.max(t.prerelease.length,r.prerelease.length);i++){let s=t.prerelease[i],o=r.prerelease[i];if(s===void 0||o===void 0)return s===void 0?-1:1;if(s===o)continue;let a=/^\d+$/.test(s),c=/^\d+$/.test(o);return a!==c?a?-1:1:a&&s.length!==o.length?s.length>o.length?1:-1:s>o?1:-1}return 0}function ro(n){try{return Te(n).prerelease.length===0}catch{return!1}}function lr(n){try{return Te(n),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(n)}catch{return!1}}var $e=1;async function ot(n,e){let t=Sd(De(n,"package.json"));for(let r of t.resolve.paths(e)??[]){let i=De(r,e);try{if(JSON.parse(await no(De(i,"package.json"),"utf8")).name===e)return await pr(i)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function ci(n,e){if(he(e?.version,e?.version),e.desktopProtocolVersion!==$e||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await pr(Id(dr(e.launcher),"..")),r=await pr(De(n,"pi-web","releases")),i=dr(dr(t));if(await pr(e.launcher)!==De(t,"bin","pi-webapp.mjs")||dr(i)!==r||!i.startsWith(r+io)||!i.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(i.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let s=JSON.parse(await no(De(t,"package.json"),"utf8"));if(s.name!=="pi-webapp"||s.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(s.piWebappDesktopProtocol!==$e)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 ot(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(i+io))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let a=De(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,a,De(t,"dist","extension.js"),De(t,"web","dist","index.html")].map(c=>Pd(c))),e.fallbackVersion!==void 0&&Te(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:a,desktopProtocolVersion:$e,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var Cd={"/":{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(n,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:n.getHeader("X-Request-ID"),operationId:n.getHeader("X-Operation-ID")}),n.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),n.end(JSON.stringify(t))}function Nd(n,e){let t=n.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let r=Buffer.from(t.slice(7),"utf8");return r.length===e.length&&Ed(r,e)}async function oo(n,e=64*1024){let t=0,r=[];for await(let i of n){let s=Buffer.isBuffer(i)?i:Buffer.from(i);if(t+=s.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(s)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function Dd(n){let e=0,t=[];for await(let r of n){let i=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=i.length,e>sr)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(i)}return Buffer.concat(t)}async function Od(n,e=0){await new Promise((r,i)=>{n.once("error",i),n.listen(e,"127.0.0.1",()=>{n.off("error",i),r()})});let t=n.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function ao(n,e,t=new _e,r={}){t.setState({piVersion:Rd});let i=process.env.PI_WEBAPP_RESTART_TOKEN,s=i&&/^[A-Za-z0-9_-]{32}$/.test(i)?i:so(24).toString("base64url"),o=Buffer.from(s),a=Os(),c=new Set,l=new rr(r.pluginSettingsFile??di(Ad(),"pi-web","plugins.json"));try{await l.load()}catch(k){throw await t.close(),k}let p=new ir(xs(),l),u=async()=>await n.plugins?.()??{plugins:[],errors:[]},h=()=>({type:"plugin_state",disabled:p.plugins.filter(k=>!l.enabled(k.metadata.id)).map(k=>k.metadata.id)}),w=()=>{for(let k of c)k.write(`${JSON.stringify(h())}
39
+ `)},v=new Map,m=new or((k,y)=>t.capture(k,y)),b=k=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(k.sessionId),idle:k.idle,model:k.model,thinkingLevel:k.thinkingLevel,messageCount:k.messages.length}),P="",S=!1,_=!1,C={...Cd,...await to(e)};for(let k of await _d(di(e,"assets")).catch(()=>[])){let y=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(k);if(!y)continue;let $={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};C[`/assets/${k}`]={path:`assets/${k}`,type:$[y[1]]}}let H=Td(async(k,y)=>{let $=so(18).toString("base64"),ye=le=>typeof le=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(le),ve=ye(k.headers["x-request-id"])?k.headers["x-request-id"]:li(),Q={requestId:ve,operationId:ye(k.headers["x-operation-id"])?k.headers["x-operation-id"]:void 0};y.setHeader("X-Request-ID",ve),Q.operationId&&y.setHeader("X-Operation-ID",Q.operationId);let x="/",lc=performance.now(),ce=(le,g,E)=>{let N=!Ge(le)&&zn(x)?Ce(le,"Agent or provider operation failed"):le,U=t.capture(N,{...Q,route:x,method:k.method,status:g,stage:"http"});I(y,g,{error:E,errorId:U,errorReported:t.enabled,errorCode:Ge(le)?"validation_error":"unexpected_error"})};y.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...Q,route:x,method:k.method,status:y.statusCode,durationMs:Math.round(performance.now()-lc)})});try{y.setHeader("X-Content-Type-Options","nosniff"),y.setHeader("Referrer-Policy","no-referrer"),y.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${$}'; 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(k.url??"/",P).pathname}catch{I(y,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let le=C[x];if(k.method==="GET"&&le){try{let g=await xd(di(e,le.path));y.writeHead(200,{"Content-Type":le.type,"Cache-Control":"no-store"}),y.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${$}">`):g)}catch(g){ce(g,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let g=await n.hosted?.asset(x);if(!g){I(y,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}y.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),y.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),y.end(g.bytes)}catch{I(y,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(k.method==="GET"&&x.startsWith("/plugins/")){try{let g=await n.pluginAsset?.(k.url??x);if(!g){I(y,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}y.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),y.end(g.bytes)}catch(g){ce(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(y,404,{error:"\u672A\u627E\u5230"});return}if(!Nd(k,o)){I(y,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(k.method==="GET"&&x==="/api/hosted-plugins"){try{I(y,200,await ai(n.hosted,x,void 0))}catch(g){let E=cr(g);I(y,E.status,E.body)}return}if(k.method==="POST"&&Qs.includes(x)){if(k.headers.origin!==void 0&&k.headers.origin!==P){I(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){I(y,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let g;try{g=await oo(k,2*1024*1024)}catch(E){I(y,E instanceof Error&&E.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{I(y,200,await ai(n.hosted,x,g,{draining:S}))}catch(E){let T=cr(E);I(y,T.status,T.body)}return}if(k.method==="GET"&&x==="/api/telemetry/config"){I(y,200,t.config.browser);return}if(k.method==="GET"&&x==="/api/update/version"){try{I(y,200,{current:await n.selfUpdate?.runningVersion()??null,desktopProtocolVersion:$e,...n.selfUpdate?.launcherIdentity?{launcher:n.selfUpdate.launcherIdentity(),desktopHandoffProtocol:n.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){ce(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(k.method==="GET"&&x==="/api/update"){try{I(y,200,await n.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){ce(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(k.method==="GET"&&x==="/api/image"){let g=new URL(k.url??x,P),E=g.searchParams.get("sessionId")??"",T=g.searchParams.get("messageId")??"",N=Number(g.searchParams.get("index"));if(!E||E!==n.snapshot().sessionId||!T||!Number.isInteger(N)||N<0||N>100){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let U=n.image?.(E,T,N);if(!U||!["image/png","image/jpeg","image/webp","image/gif"].includes(U.mimeType)){I(y,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}y.writeHead(200,{"Content-Type":U.mimeType,"Cache-Control":"private, no-store"}),y.end(U.data);return}if(k.method==="POST"&&x==="/api/attachment"){if(k.headers.origin!==void 0&&k.headers.origin!==P){I(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let g=new URL(k.url??x,P),E=g.searchParams.get("sessionId"),T=g.searchParams.get("name");try{if(!E||!T||T.length>1024||E!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(k.headers["content-length"]??0)>sr){I(y,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let N=await js(E,T,k.headers["content-type"]??"application/octet-stream",await Dd(k));if(E!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}v.set(N.id,N),I(y,201,{id:N.id,name:N.name,bytes:N.bytes})}catch(N){ce(N,400,N instanceof Error?N.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(k.method==="GET"&&x==="/api/session"){try{let g=n.snapshot();b(g),I(y,200,g)}catch(g){ce(g,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/plugin-management"){try{I(y,200,p.inventory(await u()))}catch(g){ce(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/plugins"){try{I(y,200,p.catalog(await u()))}catch(g){ce(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/providers"){try{I(y,200,await n.providers?.()??[])}catch(g){ce(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/provider/models"){let g=new URL(k.url??x,P).searchParams.get("providerId")??"";try{if(!g||!n.providerModels){I(y,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(y,200,await n.providerModels(g))}catch(E){ce(E,400,E instanceof Error?E.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/provider/login/active"){I(y,200,{active:m.getActive()??null});return}if(k.method==="GET"&&x==="/api/provider/login"){let g=new URL(k.url??x,P).searchParams.get("id")??"",E=m.get(g);I(y,E?200:404,E??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(k.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{I(y,200,x==="/api/models"?await n.models():x==="/api/config"?await n.config():x==="/api/commands"?n.commands?.()??[]:await n.workspaces())}catch(g){ce(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(k.method==="GET"&&x==="/api/directory/capability"){I(y,200,{kind:a});return}if(k.method==="GET"&&x==="/api/events"){let g;try{g=n.snapshot(),b(g)}catch(E){ce(E,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}y.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),c.add(y),y.write(`${JSON.stringify({type:"snapshot",session:g})}
40
+ `),y.on("close",()=>c.delete(y));return}if(k.method==="POST"&&[...p.routes,"/api/desktop/handoff","/api/plugin-management","/api/plugin-interaction","/api/plugin-action","/api/update","/api/update/channel","/api/update/cancel","/api/message","/api/prompt-queue","/api/attachment/remove","/api/abort","/api/resume","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/config","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/provider/models","/api/provider/logout","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/session/rename","/api/session/delete","/api/directory/list","/api/directory/create","/api/directory/pick"].includes(x)){if(k.headers.origin!==void 0&&k.headers.origin!==P){I(y,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!k.headers["content-type"]?.startsWith("application/json")){I(y,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}try{let g;try{g=await oo(k,x==="/api/plugin-action"?544*1024:64*1024)}catch(E){if(E instanceof Error&&E.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"){I(y,413,{error:E.message});return}if(E instanceof SyntaxError||Ge(E)){I(y,400,{error:"\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548"});return}throw E}if(x==="/api/desktop/handoff"){let E=g;if(!E||typeof E.nonce!="string"||typeof E.requestId!="string"){I(y,400,{error:"\u4EA4\u63A5\u8EAB\u4EFD\u65E0\u6548"});return}if(!n.selfUpdate?.requestLauncherHandoff){I(y,409,{error:"\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u91CD\u8BD5\u542F\u52A8\u5668\u4EA4\u63A5"});return}if(S||_||m.getActive()){I(y,409,{error:"\u66F4\u65B0\u3001\u767B\u5F55\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D"});return}let T=p.restartBlocker()??p.restartConfirmations()[0];if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length||T){I(y,409,{error:T??"\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}S=!0;try{await n.selfUpdate.requestLauncherHandoff(E.nonce,E.requestId)}catch(N){throw S=!1,N}I(y,202,{accepted:!0,protocol:1,requestId:E.requestId});return}if(typeof g!="object"||g===null||!("sessionId"in g)||typeof g.sessionId!="string"){I(y,400,{error:"\u7F3A\u5C11\u4F1A\u8BDD\u6807\u8BC6"});return}if(S&&x!=="/api/update/cancel"){I(y,409,{error:"\u66F4\u65B0\u6B63\u5728\u5B89\u88C5\u6216\u91CD\u542F\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(x==="/api/plugin-management"){let E=g;if(typeof E.id!="string"||E.id.length>200||typeof E.enabled!="boolean"||typeof E.expected!="string"){I(y,400,{error:"\u63D2\u4EF6\u5F00\u5173\u53C2\u6570\u65E0\u6548"});return}let T=()=>{if(n.snapshot().sessionId!==g.sessionId)throw new Z("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length)throw new Z("\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u7A7A\u95F2\u540E\u4FEE\u6539\u5168\u5C40\u63D2\u4EF6\u5F00\u5173")};try{await p.toggle(E.id,E.enabled,E.expected,T),I(y,200,p.inventory(await u()))}catch(N){if(N instanceof Z)I(y,N.status,{error:N.message});else throw N}finally{w()}return}if(p.mutating&&x!=="/api/abort"){I(y,409,{error:"\u63D2\u4EF6\u914D\u7F6E\u6B63\u5728\u4FDD\u5B58\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}if(await p.dispatch({path:x,body:g,res:y,snapshot:()=>n.snapshot(),busyWorkspaces:()=>n.busyGitWorkspaces?.()??[],json:(E,T)=>I(y,E,T)}))return;if(x==="/api/plugin-interaction"){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("requestId"in g)||typeof g.requestId!="string"||g.requestId.length>200||!n.resolvePluginInteraction||!("value"in g)){I(y,400,{error:"\u63D2\u4EF6\u4EA4\u4E92\u54CD\u5E94\u65E0\u6548"});return}await p.coordinateStart(n.snapshot().cwd,async()=>n.resolvePluginInteraction(g.sessionId,g.pluginId,g.requestId,g.value)),I(y,200,{accepted:!0});return}if(x==="/api/plugin-action"){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("pluginId"in g)||typeof g.pluginId!="string"||g.pluginId.length>200||!("action"in g)||typeof g.action!="string"||g.action.length>100){I(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u65E0\u6548"});return}if(p.plugins.some(N=>N.metadata.id===g.pluginId)){let N=p.actionRoute(g.pluginId,g.action);if(!N){I(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u5B58\u5728"});return}let U="input"in g?g.input:{};if(!U||typeof U!="object"||Array.isArray(U)){I(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u53C2\u6570\u65E0\u6548"});return}await p.dispatch({path:N,body:{...U,sessionId:g.sessionId},res:y,snapshot:()=>n.snapshot(),busyWorkspaces:()=>n.busyGitWorkspaces?.()??[],json:(Ie,ze)=>I(y,Ie,Ie>=200&&Ie<300?{value:ze}:ze)});return}if(!n.invokePluginAction){I(y,400,{error:"\u63D2\u4EF6\u52A8\u4F5C\u4E0D\u53EF\u7528"});return}let T=await p.coordinateStart(n.snapshot().cwd,async()=>n.invokePluginAction(g.sessionId,g.pluginId,g.action,"input"in g?g.input:void 0));I(y,200,{value:T});return}if(x==="/api/update/channel"){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("channel"in g)||g.channel!=="stable"&&g.channel!=="alpha"){I(y,400,{error:"\u66F4\u65B0\u901A\u9053\u65E0\u6548"});return}if(!n.selfUpdate?.setChannel){I(y,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u5148\u5347\u7EA7"});return}I(y,200,await n.selfUpdate.setChannel(g.channel));return}if(x==="/api/update/cancel"){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!n.selfUpdate?.cancel){I(y,409,{error:"\u5F53\u524D\u540E\u53F0\u4E0D\u652F\u6301\u53D6\u6D88\u66F4\u65B0"});return}await n.selfUpdate.cancel(),I(y,200,{cancelled:!0,dataPreserved:!0});return}if(x==="/api/update"){if(_){I(y,409,{error:"\u66F4\u65B0\u4E0B\u8F7D\u548C\u9A8C\u8BC1\u6B63\u5728\u8FDB\u884C\u4E2D"});return}if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!n.snapshot().idle){I(y,409,{error:"\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}if(!n.selfUpdate){I(y,409,{error:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"});return}let E=p.restartBlocker();if((n.busyGitWorkspaces?.()??[]).length||E){I(y,409,{error:E??"\u8BF7\u7B49\u5F85\u6240\u6709\u804A\u5929\u4EFB\u52A1\u7ED3\u675F\u540E\u518D\u5347\u7EA7"});return}let T=g,N="channel"in T||"version"in T||"allowDowngrade"in T;if(N&&(T.channel!=="stable"&&T.channel!=="alpha"||typeof T.version!="string"||T.allowDowngrade!==void 0&&typeof T.allowDowngrade!="boolean")){I(y,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}if(T.force!==void 0&&typeof T.force!="boolean"){I(y,400,{error:"\u66F4\u65B0\u53C2\u6570\u65E0\u6548"});return}let U=T.force===!0,Ie=q=>I(y,409,{error:q.join("\uFF1B"),reason:"update_confirm_required"}),ze=p.restartConfirmations();if(ze.length&&!U){Ie(ze);return}_=!0;let kt;try{kt=await n.selfUpdate.prepare(N?{channel:T.channel,version:T.version,allowDowngrade:T.allowDowngrade}:void 0);let q=p.restartBlocker();if(!n.snapshot().idle||(n.busyGitWorkspaces?.()??[]).length||q)throw new Error(q??"\u4E0B\u8F7D\u5B8C\u6210\uFF1B\u5F53\u524D\u804A\u5929\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u7ED3\u675F\u4EFB\u52A1\u540E\u518D\u5347\u7EA7");let un=p.restartConfirmations();if(un.length&&!U){Ie(un);return}U&&await p.releaseForRestart(),S=!0;try{await n.selfUpdate.requestRestart(kt,{force:U})}catch(fn){let hn=fn?.code;if(!U&&(hn==="view_barrier"||hn==="drain_pending")){S=!1,Ie(["\u90E8\u5206\u63D2\u4EF6\u89C6\u56FE\u672A\u786E\u8BA4\u4FDD\u5B58\uFF08\u672A\u4FDD\u5B58\u5185\u5BB9\u4F1A\u4FDD\u7559\u5728\u63D2\u4EF6\u89C6\u56FE\u6062\u590D\u8BB0\u5F55\u4E2D\uFF09\uFF0C\u63D2\u4EF6\u540E\u53F0\u4EFB\u52A1\u4E5F\u53EF\u80FD\u88AB\u4E2D\u65AD"]);return}throw fn}}catch(q){throw S=!1,q}finally{_=!1}I(y,202,{accepted:!0,version:kt.version});return}if(x==="/api/provider/custom"){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("provider"in g)||!oi(g.provider)||!n.addCustomProvider){I(y,400,{error:"\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u65E0\u6548"});return}await n.addCustomProvider(g.sessionId,g.provider),I(y,201,{accepted:!0});return}if(x==="/api/provider/models"||x==="/api/provider/logout"){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!("providerId"in g)||typeof g.providerId!="string"){I(y,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}if(x==="/api/provider/models"){if(!("change"in g)||!Vs(g.change)||!n.updateProviderModel){I(y,400,{error:"\u6A21\u578B\u53C2\u6570\u65E0\u6548"});return}await n.updateProviderModel(g.sessionId,g.providerId,g.change)}else{if(!n.logoutProvider){I(y,400,{error:"\u65E0\u6CD5\u79FB\u9664\u8BA4\u8BC1"});return}await n.logoutProvider(g.sessionId,g.providerId)}I(y,200,{accepted:!0});return}if(x.startsWith("/api/provider/login")){if(g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(x==="/api/provider/login"){if(!("providerId"in g)||typeof g.providerId!="string"||!("method"in g)||g.method!=="api_key"&&g.method!=="oauth"||!n.loginProvider||!n.providers){I(y,400,{error:"\u767B\u5F55\u65B9\u5F0F\u65E0\u6548"});return}if(!(await n.providers()).some(U=>U.id===g.providerId&&U.methods.includes(g.method))){I(y,400,{error:"\u63D0\u4F9B\u65B9\u4E0D\u652F\u6301\u6B64\u767B\u5F55\u65B9\u5F0F"});return}let T="initialSecret"in g?g.initialSecret:void 0;if(T!==void 0&&(g.method!=="api_key"||typeof T!="string"||!T.trim()||T.length>16384)){I(y,400,{error:"API Key \u65E0\u6548"});return}let N=m.start(g.providerId,g.method,n.loginProvider,T,Q);I(y,202,{id:N.id});return}if(!("id"in g)||typeof g.id!="string"){I(y,400,{error:"\u767B\u5F55\u6D41\u7A0B\u65E0\u6548"});return}if(x==="/api/provider/login/cancel"){I(y,m.cancel(g.id)?202:404,{accepted:!0});return}if(!("value"in g)||typeof g.value!="string"||g.value.length>16384||!m.respond(g.id,g.value)){I(y,400,{error:"\u767B\u5F55\u8F93\u5165\u65E0\u6548"});return}I(y,202,{accepted:!0});return}if(x==="/api/attachment/remove"){if(!("id"in g)||typeof g.id!="string"||g.sessionId!==n.snapshot().sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u9644\u4EF6\u65E0\u6548"});return}v.get(g.id)?.sessionId===g.sessionId&&v.delete(g.id),I(y,202,{accepted:!0});return}if(x==="/api/directory/pick"){if(a!=="native"){I(y,409,{error:"\u672C\u5730\u76EE\u5F55\u9009\u62E9\u5668\u4E0D\u53EF\u7528"});return}let E=new AbortController;y.once("close",()=>E.abort()),I(y,200,{path:await Hs(E.signal)});return}if(x==="/api/directory/list"){if("path"in g&&(typeof g.path!="string"||g.path.length>4096)){I(y,400,{error:"\u76EE\u5F55\u8DEF\u5F84\u65E0\u6548"});return}I(y,200,await Ns("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(y,400,{error:"\u6587\u4EF6\u5939\u540D\u79F0\u6216\u8DEF\u5F84\u65E0\u6548"});return}I(y,200,{path:await Ds(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(y,400,{error:"\u5DE5\u4F5C\u533A\u8DEF\u5F84\u65E0\u6548"});return}await n.addWorkspace(g.path,g.create),I(y,202,{accepted:!0});return}if(x==="/api/workspace/select"||x==="/api/workspace/remove"||x==="/api/workspace/new-session"){if(!("id"in g)||typeof g.id!="string"){I(y,400,{error:"\u5DE5\u4F5C\u533A\u65E0\u6548"});return}x==="/api/workspace/select"?await n.selectWorkspace(g.id):x==="/api/workspace/new-session"?await n.newSessionInWorkspace(g.id):await n.removeWorkspace(g.id),I(y,202,{accepted:!0});return}if(x==="/api/session/select"){if(!("workspaceId"in g)||typeof g.workspaceId!="string"||!("id"in g)||typeof g.id!="string"||!("path"in g)||typeof g.path!="string"){I(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}await n.selectSession(g.workspaceId,g.id,g.path),I(y,202,{accepted:!0});return}if(x==="/api/session/rename"||x==="/api/session/delete"){if(!("workspaceId"in g)||typeof g.workspaceId!="string"||!("id"in g)||typeof g.id!="string"||!("path"in g)||typeof g.path!="string"||g.path.length>4096){I(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(x==="/api/session/rename"){if(!("name"in g)||typeof g.name!="string"){I(y,400,{error:"\u4F1A\u8BDD\u65E0\u6548"});return}if(!n.renameSession){I(y,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u91CD\u547D\u540D\u4F1A\u8BDD"});return}await n.renameSession(g.workspaceId,g.id,g.path,g.name)}else{if(!n.deleteSession){I(y,501,{error:"\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u5220\u9664\u4F1A\u8BDD"});return}await n.deleteSession(g.workspaceId,g.id,g.path)}I(y,202,{accepted:!0});return}if(x==="/api/thinking-level"){if(!("level"in g)||typeof g.level!="string"){I(y,400,{error:"\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548"});return}await n.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(y,400,{error:"\u6A21\u578B\u65E0\u6548"});return}await n.setModel(g.sessionId,g.provider,g.id)}else if(x==="/api/config"){let E=g;if(!["packages","extensions","skills"].includes(E.kind)||!["global","project"].includes(E.scope)||!["add","remove"].includes(E.action)||typeof E.value!="string"||!E.value.trim()||E.value.length>2048){I(y,400,{error:"\u914D\u7F6E\u9879\u65E0\u6548"});return}if(E.action==="add"&&E.kind!=="packages"&&Js(E.value)){I(y,400,{error:"npm \u6216 Git \u6765\u6E90\u8BF7\u5728\u300C\u5305\u300D\u4E2D\u6DFB\u52A0\uFF1B\u6269\u5C55\u548C\u6280\u80FD\u53EA\u63A5\u53D7\u6587\u4EF6\u6216\u76EE\u5F55\u8DEF\u5F84"});return}I(y,200,await n.updateConfig(E));return}else if(x==="/api/prompt-queue"){let E=g,T=E.action;if(typeof E.id!="string"||E.id.length>100||!Number.isSafeInteger(E.revision)||E.revision<1||!T||typeof T!="object"||!["edit","remove","steer"].includes(T.kind)||T.kind==="edit"&&(typeof T.text!="string"||T.text.length>32e3)){I(y,400,{error:"\u961F\u5217\u64CD\u4F5C\u65E0\u6548"});return}let N=n.snapshot();if(E.sessionId!==N.sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(T.kind==="steer"&&N.idle){I(y,409,{error:"\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1"});return}if(T.kind==="steer"&&N.interactions?.length){I(y,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!n.updateQueuedPrompt){I(y,409,{error:"\u8BF7\u91CD\u8F7D Pi \u4EE5\u542F\u7528\u961F\u5217\u64CD\u4F5C"});return}await p.coordinateStart(N.cwd,async()=>n.updateQueuedPrompt(g.sessionId,E.id,E.revision,T))}else if(x==="/api/message"){let E="delivery"in g?g.delivery:void 0;if(E!==void 0&&E!=="steer"&&E!=="followUp"){I(y,400,{error:"\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548"});return}let T="attachments"in g?g.attachments:[];if(!Array.isArray(T)||T.length>Ws||T.some(q=>typeof q!="string")||new Set(T).size!==T.length){I(y,400,{error:"\u9644\u4EF6\u65E0\u6548\u6216\u8FC7\u591A"});return}let N=T.map(q=>v.get(q));if(N.some(q=>!q||q.sessionId!==g.sessionId)){I(y,400,{error:"\u9644\u4EF6\u4E0D\u53EF\u7528"});return}if(!("text"in g)||typeof g.text!="string"||!g.text.trim()&&T.length===0||g.text.length>32e3){I(y,400,{error:"\u6D88\u606F\u65E0\u6548\u6216\u8FC7\u957F"});return}let U=n.snapshot();if(g.sessionId!==U.sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}try{Me(U,g.text,E)}catch(q){I(y,409,{error:q.message});return}let Ie=N,ze=[g.text.trim(),...Ie.map(q=>`\u9644\u4EF6 ${JSON.stringify(q.name)}\uFF1A${q.path}`)].filter(Boolean).join(`
37
41
 
38
- `),bt=await Promise.all(ke.filter(q=>["image/png","image/jpeg","image/webp","image/gif"].includes(q.mediaType)).map(ys));ne.operationId??=ii(),v.setHeader("X-Operation-ID",ne.operationId),t.breadcrumb("send",{...ne,attachmentCount:ke.length}),await p.coordinateStart(U.cwd,async()=>n.send(g.sessionId,Be,bt,ne,S));for(let q of _)f.delete(q)}else if(x==="/api/compact"){if(!n.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await n.compact(g.sessionId)}else if(x==="/api/resume"){let S=n.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(!n.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");ne.operationId??=ii(),v.setHeader("X-Operation-ID",ne.operationId),t.breadcrumb("resume",{...ne}),await p.coordinateStart(S.cwd,async()=>n.resume(g.sessionId,ne))}else x==="/api/abort"?await n.abort(g.sessionId):await n.newSession(g.sessionId);I(v,202,{accepted:!0})}catch(g){if(g instanceof oe){I(v,g.status,{error:g.message});return}let S=p.requestFailure(g);if(S){I(v,S.status,S.body);return}let _=g instanceof Error?g.message:"\u8BF7\u6C42\u5931\u8D25";ce(g,_==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,_)}return}I(v,404,{error:"\u672A\u627E\u5230"})}catch(le){v.headersSent?(t.capture(le,{...ne,route:x,stage:"http_stream"}),v.end()):ce(le,500,"\u8BF7\u6C42\u5931\u8D25")}}),R=Number(process.env.PI_WEBAPP_RESTART_PORT),Y;try{Y=await od(M,Number.isInteger(R)&&R>0&&R<65536&&i===s?R:0)}catch(b){throw t.capture(b,{stage:"listen"}),await t.close(),b}return P=`http://127.0.0.1:${Y}`,{protocolVersion:7,buildId:Ie,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:`${P}/#${s}`,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[$,we]of f)we.sessionId!==b.session.sessionId&&f.delete($);let v=`${JSON.stringify(b)}
39
- `;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})}
40
- `);a.clear();let v;try{await new Promise(($,we)=>{M.close(ye=>ye?we(ye):$()),v=setTimeout(()=>M.closeAllConnections(),50).unref()})}finally{clearTimeout(v),await t.close()}}}}import{getSupportedThinkingLevels as ad}from"@earendil-works/pi-ai";var At="pi-webapp/paused",si="pi-webapp/resume";function ot(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(t.type==="custom_message"&&t.customType===si)return!1;if(t.type==="custom"&&t.customType===At)return!0;if(t.type==="message"){if(t.message.role==="user")return!1;if(t.message.role==="assistant"){if(t.message.stopReason==="aborted")return!0;if(t.message.stopReason==="stop"||t.message.stopReason==="length"||t.message.stopReason==="error")return!1}}}return!1}function oi(n,e){let t=[],r;for(let i of n){if(i.type==="message"&&(r=i.id),i.type!=="custom")continue;let s=e.find(o=>i.customType.startsWith(`${o}/`));if(s){try{if(JSON.stringify(i.data).length>128*1024)continue}catch{continue}t.push({id:i.id,pluginId:s,kind:i.customType,data:i.data,timestamp:i.timestamp,...r?{afterMessageId:r}:{}})}}return t}function qe(n){return typeof n=="string"?[{kind:"text",text:n}]:n.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function Rt(n){if(n.type==="custom_message")return n.display?{id:n.id,role:"notice",timestamp:n.timestamp,blocks:qe(n.content)}:null;if(n.type!=="message")return null;let{message:e}=n;return e.role==="user"||e.role==="assistant"?{id:n.id,role:e.role,timestamp:n.timestamp,blocks:qe(e.content),...e.role==="assistant"?{...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{},usage:{input:e.usage.input,output:e.usage.output,cacheRead:e.usage.cacheRead,cacheWrite:e.usage.cacheWrite,...e.usage.reasoning===void 0?{}:{reasoning:e.usage.reasoning},totalTokens:e.usage.totalTokens,cost:e.usage.cost.total},model:`${e.provider}/${e.model}`}:{}}:e.role==="toolResult"?{id:n.id,role:"tool",timestamp:n.timestamp,blocks:qe(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function cr(n,e){let t=n?.trim();if(t)return t;let r=e.find(s=>s.role==="user");return _t(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function Vs(n,e,t=[]){let r=n.sessionManager.getBranch().flatMap(i=>{let s=Rt(i);return s?[s]:[]});return{schemaVersion:1,sessionId:n.sessionManager.getSessionId(),cwd:n.cwd,name:cr(e,r),model:n.model?`${n.model.provider}/${n.model.id}`:null,thinkingLevel:n.thinkingLevel??null,thinkingLevels:n.model?ad(n.model):["off"],idle:n.isIdle(),paused:ot(n.sessionManager.getBranch()),contextUsage:n.getContextUsage()??null,messages:r,pluginEntries:oi(n.sessionManager.getBranch(),t)}}import{randomUUID as ai}from"node:crypto";import{mkdir as Us,readFile as cd,realpath as ci,rename as ld,rm as dd,stat as li,writeFile as pd}from"node:fs/promises";import{basename as Bs,dirname as ud,isAbsolute as Ls,join as fd}from"node:path";var Ct=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 Ge(n){try{let e=await ci(n);return(await li(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function _e(n){let e=await Ge(n);if(e===null)throw new Ct;return e}var lr=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await cd(this.file,"utf8")),t,r=[];if(Array.isArray(e)?t=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(t=e.items,r=e.hiddenPaths),!Array.isArray(t)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=t.filter(i=>typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.path=="string"&&typeof i.title=="string"),this.hiddenPaths=r.filter(i=>typeof i=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(t=>t.id===e)}async add(e,t=!1){if(!Ls(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await Us(e,{recursive:!0});let r=await ci(e);if(!(await li(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let i=this.hiddenPaths.filter(a=>a!==r),s=this.items.find(a=>a.path===r);if(s)return i.length!==this.hiddenPaths.length&&(await this.save(this.items,i),this.hiddenPaths=i),s;let o={id:ai(),path:r,title:Bs(r)||r},c=[o,...this.items];return await this.save(c,i),this.items=c,this.hiddenPaths=i,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter(Ls).map(async r=>{try{let i=await ci(r);return(await li(i)).isDirectory()?i:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),i=[];for(let o of t)r.has(o)||(r.add(o),i.push({id:ai(),path:o,title:Bs(o)||o}));if(i.length===0)return;let s=[...this.items,...i];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let t=this.get(e);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),i=[...new Set([...this.hiddenPaths,t.path])];await this.save(r,i),this.items=r,this.hiddenPaths=i})}mutate(e){let t=this.mutationChain.then(e,e);return this.mutationChain=t.then(()=>{},()=>{}),t}async save(e,t){await Us(ud(this.file),{recursive:!0});let r=`${this.file}.${ai()}.tmp`;try{await pd(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await ld(r,this.file)}catch(i){throw await dd(r,{force:!0}),i}}};function zs(n){return fd(n,"pi-web","workspaces.json")}import{createAgentSession as ip,createEventBus as np,DefaultResourceLoader as sp,getAgentDir as op,SessionManager as Dt,VERSION as fr}from"@earendil-works/pi-coding-agent";var hd="pi-webapp:interaction-open:v1",gd="pi-webapp:interaction-accept:v1",qs="pi-webapp:interaction-settle:v1",md="pi-webapp:interaction-cancel:v1";var at=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,r){this.bus=e,this.accepts=t,this.changed=r,this.detach=[e.on(hd,i=>{!wd(i)||!t(i)||this.requests.has(i.requestId)||(this.requests.set(i.requestId,i),e.emit(gd,{requestId:i.requestId}),r())}),e.on(md,i=>{let s=i,o=this.requests.get(s?.requestId);o&&o.sessionId===s.sessionId&&o.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,r,i){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==t||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(qs,{requestId:r,value:i}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(qs,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function wd(n){if(!n||typeof n!="object")return!1;let e=n;for(let t of["requestId","sessionId","pluginId","kind"])if(typeof e[t]!="string"||!e[t]||e[t].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function Je(n){return typeof n=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(n)&&n.length<=512&&!n.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function je(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&Je(e.backend.entry)&&/\.m?js$/.test(e.backend.entry)&&!!e.frontend&&Je(e.frontend.document)&&/\.html$/.test(e.frontend.document)&&Je(e.frontend.controller)&&/\.html$/.test(e.frontend.controller)&&Je(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 yd=1,vd="pi-webapp:action:v1",bd="pi-webapp:action-response:v1",dr="pi-webapp:plugin-changed:v1";function Gs(n){if(!n||typeof n!="object")return!1;let e=n;return e.apiVersion===yd&&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 pr(n,e,t=15e3,r){return new Promise((i,s)=>{let o=!1,c=(u,w)=>{o||(o=!0,clearTimeout(l),a(),r?.removeEventListener("abort",p),u?s(u):i(w))},a=n.on(bd,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(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{n.emit(vd,e)}catch(u){c(u instanceof Error?u:new Error(String(u)))}})}import{realpath as ap}from"node:fs/promises";import{readFile as di,realpath as Ys,stat as Qs}from"node:fs/promises";import{createHash as kd}from"node:crypto";import{dirname as Js,isAbsolute as Pd,join as pi,parse as Id,resolve as Sd,sep as Ed,delimiter as xd}from"node:path";import{DefaultPackageManager as _d,getAgentDir as Td,SettingsManager as Ad}from"@earendil-works/pi-coding-agent";async function Ks(n,e){let t=await di(n),r=e?await di(e):void 0;if(t.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let i=kd("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:i}}function Rd(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(xd).filter(Boolean).map(n=>Sd(n))}async function Cd(n){let e=Js(n);for(;e!==Id(e).root;)try{return await Qs(pi(e,"package.json")),e}catch{e=Js(e)}return null}async function Xs(n,e){let t=await Ys(pi(n,e));if(!t.startsWith(n+Ed))throw new Error("Asset escapes package root");let r=await Qs(t);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return t}var Ke=class n{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=Rd()){let i=Ad.create(e,void 0,{projectTrusted:t}),s=new _d({cwd:e,agentDir:Td(),settingsManager:i}),o=await s.resolve(async()=>"skip"),c=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},a=new Set;for(let m of[...o.extensions,...c.extensions]){if(!m.enabled)continue;let f=await Cd(m.path);f&&a.add(f)}for(let m of r)Pd(m)&&a.add(m);let l=[],p=[],u=[],w=new Set;for(let m of a)try{let f=await Ys(m),y=JSON.parse(await di(pi(f,"package.json"),"utf8"));if(y.piWebapp===void 0)continue;if(typeof y.name!="string"||!y.name)throw new Error("Missing package name");if(!Gs(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 k=await Xs(f,y.piWebapp.client),P=y.piWebapp.style?await Xs(f,y.piWebapp.style):void 0;w.add(y.name),l.push({id:y.name,root:f,manifest:y.piWebapp,clientPath:k,stylePath:P,...await Ks(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 n(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 Ks(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let t=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(t.pathname);if(!r)return null;let i;try{i=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(c=>c.id===i);if(!s||t.searchParams.has("v")&&t.searchParams.get("v")!==s.revision)return null;let o=r[2]==="client.js"?s.clientBytes:s.styleBytes;return o?{bytes:o,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as Nd}from"node:fs/promises";import{SessionManager as Dd}from"@earendil-works/pi-coding-agent";async function ct(n,e){let t=await _e(n),r=e??await Dd.listAll(),i=await Promise.all(r.map(async s=>s.cwd!==""&&await Nd(s.cwd).catch(()=>null)===t));return r.filter((s,o)=>i[o])}var Xe=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))}},Zs=new WeakMap;function eo(n,e,t,r=5e3,i=()=>{}){let s=Zs.get(n);if(s)return s;let o=(async()=>{let c;try{await Promise.race([n.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((a,l)=>{c=setTimeout(()=>l(new Error("Plugin shutdown timed out")),r)})])}catch(a){t(a instanceof Error?a.message:String(a))}finally{clearTimeout(c);try{i()}finally{n.dispose()}}})();return Zs.set(n,o),o}function ur(n){let t=[...n].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
41
- `);return{customType:si,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?`
42
+ `),kt=await Promise.all(Ie.filter(q=>["image/png","image/jpeg","image/webp","image/gif"].includes(q.mediaType)).map($s));Q.operationId??=li(),y.setHeader("X-Operation-ID",Q.operationId),t.breadcrumb("send",{...Q,attachmentCount:Ie.length}),await p.coordinateStart(U.cwd,async()=>n.send(g.sessionId,ze,kt,Q,E));for(let q of T)v.delete(q)}else if(x==="/api/compact"){if(!n.compact)throw new Error("\u5F53\u524D\u4F1A\u8BDD\u4E0D\u652F\u6301\u538B\u7F29");await n.compact(g.sessionId)}else if(x==="/api/resume"){let E=n.snapshot();if(g.sessionId!==E.sessionId){I(y,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}if(!E.idle){I(y,409,{error:"Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F"});return}if(!E.paused){I(y,409,{error:"\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1"});return}if(E.interactions?.length){I(y,409,{error:"\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279"});return}if(!n.resume)throw new Error("\u5F53\u524D\u670D\u52A1\u4E0D\u652F\u6301\u7EE7\u7EED\uFF0C\u8BF7\u91CD\u8F7D Pi");Q.operationId??=li(),y.setHeader("X-Operation-ID",Q.operationId),t.breadcrumb("resume",{...Q}),await p.coordinateStart(E.cwd,async()=>n.resume(g.sessionId,Q))}else x==="/api/abort"?await n.abort(g.sessionId):await n.newSession(g.sessionId);I(y,202,{accepted:!0})}catch(g){if(g instanceof oe){I(y,g.status,{error:g.message});return}let E=p.requestFailure(g);if(E){I(y,E.status,E.body);return}let T=g instanceof Error?g.message:"\u8BF7\u6C42\u5931\u8D25";ce(g,T==="\u4F1A\u8BDD\u5DF2\u5207\u6362"?409:400,T)}return}I(y,404,{error:"\u672A\u627E\u5230"})}catch(le){y.headersSent?(t.capture(le,{...Q,route:x,stage:"http_stream"}),y.end()):ce(le,500,"\u8BF7\u6C42\u5931\u8D25")}}),A=Number(process.env.PI_WEBAPP_RESTART_PORT),K;try{K=await Od(H,Number.isInteger(A)&&A>0&&A<65536&&i===s?A:0)}catch(k){throw t.capture(k,{stage:"listen"}),await t.close(),k}return P=`http://127.0.0.1:${K}`,{protocolVersion:7,buildId:Ee,runPluginTool:(k,y,$,ye,ve,Q)=>p.runAgentAction(k,y,$,ye,ve,Q),reportError(k,y){return t.capture(k,y)},breadcrumb(k,y){t.breadcrumb(k,y)},url:`${P}/#${s}`,publish(k){if(k.type==="snapshot"&&b(k.session),k.type==="error"&&!k.errorCode&&(k={...k,errorCode:"unexpected_error",errorId:t.capture(new Error("Agent execution failed"),{stage:"agent",requestId:k.requestId,operationId:k.operationId})}),k.type==="error"&&(k={...k,errorReported:k.errorReported??t.enabled}),k.type==="snapshot")for(let[$,ye]of v)ye.sessionId!==k.session.sessionId&&v.delete($);let y=`${JSON.stringify(k)}
43
+ `;for(let $ of c)$.write(y)},async close(k){m.close(),await p.close();for(let $ of c)$.end(`${JSON.stringify({type:"shutdown",reconnect:k?.reconnect??S})}
44
+ `);c.clear();let y;try{await new Promise(($,ye)=>{H.close(ve=>ve?ye(ve):$()),y=setTimeout(()=>H.closeAllConnections(),50).unref()})}finally{clearTimeout(y),await t.close()}}}}import{getSupportedThinkingLevels as Hd}from"@earendil-works/pi-ai";var Rt="pi-webapp/paused",pi="pi-webapp/resume";function at(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(t.type==="custom_message"&&t.customType===pi)return!1;if(t.type==="custom"&&t.customType===Rt)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 ui(n,e){let t=[],r;for(let i of n){if(i.type==="message"&&(r=i.id),i.type!=="custom")continue;let s=e.find(o=>i.customType.startsWith(`${o}/`));if(s){try{if(JSON.stringify(i.data).length>128*1024)continue}catch{continue}t.push({id:i.id,pluginId:s,kind:i.customType,data:i.data,timestamp:i.timestamp,...r?{afterMessageId:r}:{}})}}return t}function Je(n){return typeof n=="string"?[{kind:"text",text:n}]:n.flatMap(e=>e.type==="text"?[{kind:"text",text:e.text}]:e.type==="thinking"?[{kind:"thinking",text:e.thinking}]:e.type==="image"?[{kind:"image",text:"\u56FE\u7247\u9644\u4EF6"}]:e.type==="toolCall"?[{kind:"toolCall",text:JSON.stringify(e.arguments??{}),toolName:e.name,toolCallId:e.id}]:[])}function Ct(n){if(n.type==="custom_message")return n.display?{id:n.id,role:"notice",timestamp:n.timestamp,blocks:Je(n.content)}:null;if(n.type!=="message")return null;let{message:e}=n;return e.role==="user"||e.role==="assistant"?{id:n.id,role:e.role,timestamp:n.timestamp,blocks: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:n.id,role:"tool",timestamp:n.timestamp,blocks:Je(e.content),isError:e.isError,toolCallId:e.toolCallId,toolName:e.toolName}:null}function ur(n,e){let t=n?.trim();if(t)return t;let r=e.find(s=>s.role==="user");return Tt(r?.blocks.find(s=>s.kind==="text")?.text??"").text.replace(/\s+/g," ").trim().slice(0,50)}function co(n,e,t=[]){let r=n.sessionManager.getBranch().flatMap(i=>{let s=Ct(i);return s?[s]:[]});return{schemaVersion:1,sessionId:n.sessionManager.getSessionId(),cwd:n.cwd,name:ur(e,r),model:n.model?`${n.model.provider}/${n.model.id}`:null,thinkingLevel:n.thinkingLevel??null,thinkingLevels:n.model?Hd(n.model):["off"],idle:n.isIdle(),paused:at(n.sessionManager.getBranch()),contextUsage:n.getContextUsage()??null,messages:r,pluginEntries:ui(n.sessionManager.getBranch(),t)}}import{randomUUID as fi}from"node:crypto";import{mkdir as lo,readFile as Md,realpath as hi,rename as Wd,rm as jd,stat as gi,writeFile as $d}from"node:fs/promises";import{basename as po,dirname as Fd,isAbsolute as uo,join as Ld}from"node:path";var Nt=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(n){try{let e=await hi(n);return(await gi(e)).isDirectory()?e:null}catch(e){let t=e.code;if(t==="ENOENT"||t==="ENOTDIR")return null;throw e}}async function Ae(n){let e=await Ke(n);if(e===null)throw new Nt;return e}var fr=class{items=[];hiddenPaths=[];mutationChain=Promise.resolve();file;constructor(e){this.file=e}async load(){try{let e=JSON.parse(await Md(this.file,"utf8")),t,r=[];if(Array.isArray(e)?t=e:e&&typeof e=="object"&&"version"in e&&e.version===2&&"items"in e&&"hiddenPaths"in e&&(t=e.items,r=e.hiddenPaths),!Array.isArray(t)||!Array.isArray(r))throw new Error("\u5DE5\u4F5C\u533A\u8BB0\u5F55\u65E0\u6548");this.items=t.filter(i=>typeof i=="object"&&i!==null&&typeof i.id=="string"&&typeof i.path=="string"&&typeof i.title=="string"),this.hiddenPaths=r.filter(i=>typeof i=="string")}catch(e){if(e.code!=="ENOENT")throw e}}list(){return[...this.items]}get(e){return this.items.find(t=>t.id===e)}async add(e,t=!1){if(!uo(e)||e.includes("\0"))throw new Error("\u8BF7\u8F93\u5165\u5B8C\u6574\u7684\u76EE\u5F55\u8DEF\u5F84");t&&await lo(e,{recursive:!0});let r=await hi(e);if(!(await gi(r)).isDirectory())throw new Error("\u8DEF\u5F84\u4E0D\u662F\u76EE\u5F55");return this.mutate(async()=>{let i=this.hiddenPaths.filter(c=>c!==r),s=this.items.find(c=>c.path===r);if(s)return i.length!==this.hiddenPaths.length&&(await this.save(this.items,i),this.hiddenPaths=i),s;let o={id:fi(),path:r,title:po(r)||r},a=[o,...this.items];return await this.save(a,i),this.items=a,this.hiddenPaths=i,o})}async discover(e){let t=(await Promise.all([...new Set(e)].filter(uo).map(async r=>{try{let i=await hi(r);return(await gi(i)).isDirectory()?i:null}catch{return null}}))).filter(r=>r!==null);await this.mutate(async()=>{let r=new Set([...this.items.map(o=>o.path),...this.hiddenPaths]),i=[];for(let o of t)r.has(o)||(r.add(o),i.push({id:fi(),path:o,title:po(o)||o}));if(i.length===0)return;let s=[...this.items,...i];await this.save(s,this.hiddenPaths),this.items=s})}async remove(e){await this.mutate(async()=>{let t=this.get(e);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=this.items.filter(s=>s.id!==e),i=[...new Set([...this.hiddenPaths,t.path])];await this.save(r,i),this.items=r,this.hiddenPaths=i})}mutate(e){let t=this.mutationChain.then(e,e);return this.mutationChain=t.then(()=>{},()=>{}),t}async save(e,t){await lo(Fd(this.file),{recursive:!0});let r=`${this.file}.${fi()}.tmp`;try{await $d(r,JSON.stringify({version:2,items:e,hiddenPaths:t},null,2),{mode:384}),await Wd(r,this.file)}catch(i){throw await jd(r,{force:!0}),i}}};function fo(n){return Ld(n,"pi-web","workspaces.json")}import{createAgentSession as Tp,createEventBus as Ap,DefaultResourceLoader as Rp,getAgentDir as Cp,SessionManager as Ot,VERSION as yr}from"@earendil-works/pi-coding-agent";var ho="pi-webapp:interaction-open:v1",go="pi-webapp:interaction-accept:v1",mi="pi-webapp:interaction-settle:v1",mo="pi-webapp:interaction-cancel:v1",wi=class extends Error{};function hr(n,e,t,r=300){return new Promise((i,s)=>{let o=!1,a,c=(h,w)=>{o||(o=!0,clearTimeout(a),p(),u(),t?.removeEventListener("abort",l),h?s(h):i(w))},l=()=>{n.emit(mo,e),c(new Error("Interaction cancelled"))},p=n.on(go,h=>{h?.requestId===e.requestId&&clearTimeout(a)}),u=n.on(mi,h=>{let w=h;w?.requestId===e.requestId&&c(w.error?new Error(w.error):null,w.value)});a=setTimeout(()=>c(new wi("No Web interaction host")),r),t?.addEventListener("abort",l,{once:!0}),t?.aborted?l():n.emit(ho,e)})}var ct=class{bus;accepts;changed;requests=new Map;detach;constructor(e,t,r){this.bus=e,this.accepts=t,this.changed=r,this.detach=[e.on(ho,i=>{!Ud(i)||!t(i)||this.requests.has(i.requestId)||(this.requests.set(i.requestId,i),e.emit(go,{requestId:i.requestId}),r())}),e.on(mo,i=>{let s=i,o=this.requests.get(s?.requestId);o&&o.sessionId===s.sessionId&&o.pluginId===s.pluginId&&(this.requests.delete(s.requestId),r())})]}pending(e){return[...this.requests.values()].filter(t=>t.sessionId===e)}resolve(e,t,r,i){let s=this.requests.get(r);if(!s||s.sessionId!==e||s.pluginId!==t||!this.accepts(s))throw new Error("Interaction expired or session changed");this.requests.delete(r),this.bus.emit(mi,{requestId:r,value:i}),this.changed()}cancelAll(e="Session changed"){for(let t of this.requests.values())this.bus.emit(mi,{requestId:t.requestId,error:e});this.requests.clear(),this.changed()}dispose(){for(let e of this.detach)e();this.cancelAll("Interaction host unloaded")}};function Ud(n){if(!n||typeof n!="object")return!1;let e=n;for(let t of["requestId","sessionId","pluginId","kind"])if(typeof e[t]!="string"||!e[t]||e[t].length>200)return!1;try{return JSON.stringify(e.data).length<=128*1024}catch{return!1}}function Xe(n){return typeof n=="string"&&/^\.\/dist\/[A-Za-z0-9_./-]+$/.test(n)&&n.length<=512&&!n.slice(2).split("/").some(e=>!e||e==="."||e==="..")}function Fe(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n;return e.apiVersion===2&&e.runtimeProtocol===1&&typeof e.hostRange=="string"&&e.hostRange.length>0&&!!e.backend&&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 Vd=1,Bd="pi-webapp:action:v1",zd="pi-webapp:action-response:v1",gr="pi-webapp:plugin-changed:v1";function wo(n){if(!n||typeof n!="object")return!1;let e=n;return e.apiVersion===Vd&&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 mr(n,e,t=15e3,r){return new Promise((i,s)=>{let o=!1,a=(u,h)=>{o||(o=!0,clearTimeout(l),c(),r?.removeEventListener("abort",p),u?s(u):i(h))},c=n.on(zd,u=>{let h=u;h?.requestId===e.requestId&&a(h.ok?null:new Error(h.error??"Plugin action failed"),h.value)}),l=setTimeout(()=>a(new Error(`Plugin action timed out: ${e.pluginId}/${e.action}`)),t),p=()=>a(new Error("Plugin action runtime unloaded"));if(r?.addEventListener("abort",p,{once:!0}),r?.aborted)p();else try{n.emit(Bd,e)}catch(u){a(u instanceof Error?u:new Error(String(u)))}})}import{realpath as Np}from"node:fs/promises";import{readFile as yi,realpath as ko,stat as Po}from"node:fs/promises";import{createHash as qd}from"node:crypto";import{dirname as yo,isAbsolute as Gd,join as vi,parse as Jd,resolve as Kd,sep as Xd,delimiter as Yd}from"node:path";import{DefaultPackageManager as Qd,getAgentDir as Zd,SettingsManager as ep}from"@earendil-works/pi-coding-agent";async function vo(n,e){let t=await yi(n),r=e?await yi(e):void 0;if(t.length>8*1024*1024||(r?.length??0)>8*1024*1024)throw new Error("Plugin asset exceeds 8 MB");let i=qd("sha256").update(t).update("\0").update(r??"").digest("hex");return{clientBytes:t,styleBytes:r,revision:i}}function tp(){return(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Yd).filter(Boolean).map(n=>Kd(n))}async function rp(n){let e=yo(n);for(;e!==Jd(e).root;)try{return await Po(vi(e,"package.json")),e}catch{e=yo(e)}return null}async function bo(n,e){let t=await ko(vi(n,e));if(!t.startsWith(n+Xd))throw new Error("Asset escapes package root");let r=await Po(t);if(!r.isFile()||r.size>8*1024*1024)throw new Error("Plugin asset is not a regular file under 8 MB");return t}var Ye=class n{plugins;errors;extensionRoots;constructor(e,t,r){this.plugins=e,this.errors=t,this.extensionRoots=r}static async discover(e,t,r=tp()){let i=ep.create(e,void 0,{projectTrusted:t}),s=new Qd({cwd:e,agentDir:Zd(),settingsManager:i}),o=await s.resolve(async()=>"skip"),a=r.length?await s.resolveExtensionSources(r,{temporary:!0}):{extensions:[]},c=new Set;for(let w of[...o.extensions,...a.extensions]){if(!w.enabled)continue;let v=await rp(w.path);v&&c.add(v)}for(let w of r)Gd(w)&&c.add(w);let l=[],p=[],u=[],h=new Set;for(let w of c)try{let v=await ko(w),m=JSON.parse(await yi(vi(v,"package.json"),"utf8"));if(m.piWebapp===void 0)continue;if(typeof m.name!="string"||!m.name)throw new Error("Missing package name");if(!wo(m.piWebapp))throw new Error("Unsupported piWebapp manifest or asset path");if(h.has(m.name))throw new Error(`Duplicate plugin id: ${m.name}`);let b=await bo(v,m.piWebapp.client),P=m.piWebapp.style?await bo(v,m.piWebapp.style):void 0;h.add(m.name),l.push({id:m.name,root:v,manifest:m.piWebapp,clientPath:b,stylePath:P,...await vo(b,P)}),u.push(v)}catch(v){p.push(`${w}: ${v instanceof Error?v.message:String(v)}`)}return l.sort((w,v)=>w.id.localeCompare(v.id)),new n(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 vo(e.clientPath,e.stylePath))}view(){return{plugins:this.plugins.map(e=>({id:e.id,client:`/plugins/${encodeURIComponent(e.id)}/client.js?v=${e.revision}`,...e.stylePath?{style:`/plugins/${encodeURIComponent(e.id)}/client.css?v=${e.revision}`}:{}})),errors:this.errors}}async asset(e){let t=new URL(e,"http://localhost"),r=/^\/plugins\/([^/]+)\/(client\.js|client\.css)$/.exec(t.pathname);if(!r)return null;let i;try{i=decodeURIComponent(r[1])}catch{return null}let s=this.plugins.find(a=>a.id===i);if(!s||t.searchParams.has("v")&&t.searchParams.get("v")!==s.revision)return null;let o=r[2]==="client.js"?s.clientBytes:s.styleBytes;return o?{bytes:o,type:r[2]==="client.js"?"text/javascript; charset=utf-8":"text/css; charset=utf-8"}:null}};import{realpath as ip}from"node:fs/promises";import{SessionManager as np}from"@earendil-works/pi-coding-agent";async function lt(n,e){let t=await Ae(n),r=e??await np.listAll(),i=await Promise.all(r.map(async s=>s.cwd!==""&&await ip(s.cwd).catch(()=>null)===t));return r.filter((s,o)=>i[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))}},Io=new WeakMap;function So(n,e,t,r=5e3,i=()=>{}){let s=Io.get(n);if(s)return s;let o=(async()=>{let a;try{await Promise.race([n.extensionRunner.emit({type:"session_shutdown",reason:e}),new Promise((c,l)=>{a=setTimeout(()=>l(new Error("Plugin shutdown timed out")),r)})])}catch(c){t(c instanceof Error?c.message:String(c))}finally{clearTimeout(a);try{i()}finally{n.dispose()}}})();return Io.set(n,o),o}function wr(n){let t=[...n].reverse().find(r=>r.role==="assistant")?.blocks.filter(r=>r.kind==="text").map(r=>r.text).join(`
45
+ `);return{customType:pi,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?`
42
46
  Already displayed assistant text (reference data):
43
- ${JSON.stringify(t)}`:"")}}import{createHash as Od}from"node:crypto";import{readFile as ro,realpath as to,writeFile as Hd,unlink as Md}from"node:fs/promises";import{basename as Wd,dirname as ui,extname as jd,isAbsolute as $d,join as io,parse as Fd,relative as Vd,sep as Ud}from"node:path";import{DefaultPackageManager as no,getAgentDir as so,SettingsManager as oo}from"@earendil-works/pi-coding-agent";var Nt=new Map;async function Bd(n){let e=ui(n);for(;e!==Fd(e).root;){try{let t=JSON.parse(await ro(io(e,"package.json"),"utf8"));if(typeof t.name=="string")return t.name}catch{}e=ui(e)}return null}function Ld(n,e){let t=Vd(n,e);return t===""||t!==".."&&!t.startsWith(`..${Ud}`)&&!$d(t)}async function ao(n,e,t){let r=oo.create(n,void 0,{projectTrusted:t}),s=await new no({cwd:n,agentDir:so(),settingsManager:r}).resolve(async()=>"skip"),o=await Promise.all(e.map(l=>to(l))),c=new Set;for(let l of s.extensions){if(!l.enabled||l.path.startsWith("builtin:"))continue;let p=await to(l.path);await Bd(p)!=="pi-webapp"&&(o.some(u=>Ld(u,p))||c.add(p))}let a=await zd(n,o);return{paths:[...a.paths,...c],release:a.release}}async function zd(n,e){let r=await new no({cwd:n,agentDir:so(),settingsManager:oo.create(n)}).resolveExtensionSources([...e],{temporary:!0}),i=[],s=[],o=async()=>{for(let a of i.splice(0)){let l=(Nt.get(a)??1)-1;l?Nt.set(a,l):(Nt.delete(a),await Md(a).catch(()=>{}))}},c=new Set;try{for(let a of r.extensions){if(!a.enabled||c.has(a.path))continue;c.add(a.path);let l=jd(a.path);if(![".js",".mjs"].includes(l)){s.push(a.path);continue}let p=await ro(a.path),u=Od("sha256").update(p).digest("hex"),w=io(ui(a.path),`.pi-web-runtime-${Wd(a.path,l)}-${u}${l}`);await Hd(w,p,{flag:"wx"}).catch(m=>{if(m.code!=="EEXIST")throw m}),Nt.set(w,(Nt.get(w)??0)+1),i.push(w),s.push(w)}return{paths:s,release:o}}catch(a){throw await o(),a}}import{createHash as qd}from"node:crypto";var fi={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"}},$e=n=>n!==null&&typeof n=="object"?n:void 0,Gd=[{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 lo(n,e){let t=n instanceof Error?n:$e(n)?.error instanceof Error?$e(n).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},i=(p,u,w)=>{Object.assign(r,{failureKind:p,errorCode:u,errorSummary:w.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete r.summaryOmittedReason},s=$e(t)?.code;if(typeof s=="string"&&fi[s]){let p=fi[s];return i(p.kind,s,`${s}: ${p.summary}`),r}let o=t?.message??"";if(!t){let p=$e(n)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(u=>{let w=$e(u);return w?.type==="text"&&typeof w.text=="string"?[w.text.length>16384?`${w.text.slice(0,8192)}
47
+ ${JSON.stringify(t)}`:"")}}import{createHash as sp}from"node:crypto";import{readFile as xo,realpath as Eo,writeFile as op,unlink as ap}from"node:fs/promises";import{basename as cp,dirname as bi,extname as lp,isAbsolute as dp,join as _o,parse as pp,relative as up,sep as fp}from"node:path";import{DefaultPackageManager as To,getAgentDir as Ao,SettingsManager as Ro}from"@earendil-works/pi-coding-agent";var Dt=new Map;async function hp(n){let e=bi(n);for(;e!==pp(e).root;){try{let t=JSON.parse(await xo(_o(e,"package.json"),"utf8"));if(typeof t.name=="string")return t.name}catch{}e=bi(e)}return null}function gp(n,e){let t=up(n,e);return t===""||t!==".."&&!t.startsWith(`..${fp}`)&&!dp(t)}async function Co(n,e,t){let r=Ro.create(n,void 0,{projectTrusted:t}),s=await new To({cwd:n,agentDir:Ao(),settingsManager:r}).resolve(async()=>"skip"),o=await Promise.all(e.map(l=>Eo(l))),a=new Set;for(let l of s.extensions){if(!l.enabled||l.path.startsWith("builtin:"))continue;let p=await Eo(l.path);await hp(p)!=="pi-webapp"&&(o.some(u=>gp(u,p))||a.add(p))}let c=await mp(n,o);return{paths:[...c.paths,...a],release:c.release}}async function mp(n,e){let r=await new To({cwd:n,agentDir:Ao(),settingsManager:Ro.create(n)}).resolveExtensionSources([...e],{temporary:!0}),i=[],s=[],o=async()=>{for(let c of i.splice(0)){let l=(Dt.get(c)??1)-1;l?Dt.set(c,l):(Dt.delete(c),await ap(c).catch(()=>{}))}},a=new Set;try{for(let c of r.extensions){if(!c.enabled||a.has(c.path))continue;a.add(c.path);let l=lp(c.path);if(![".js",".mjs"].includes(l)){s.push(c.path);continue}let p=await xo(c.path),u=sp("sha256").update(p).digest("hex"),h=_o(bi(c.path),`.pi-web-runtime-${cp(c.path,l)}-${u}${l}`);await op(h,p,{flag:"wx"}).catch(w=>{if(w.code!=="EEXIST")throw w}),Dt.set(h,(Dt.get(h)??0)+1),i.push(h),s.push(h)}return{paths:s,release:o}}catch(c){throw await o(),c}}import{createHash as wp}from"node:crypto";var ki={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=n=>n!==null&&typeof n=="object"?n:void 0,yp=[{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 Do(n,e){let t=n instanceof Error?n:Le(n)?.error instanceof Error?Le(n).error:void 0,r={failureKind:"unknown",summaryOmitted:!0,summaryOmittedReason:"unrecognized_diagnostic",originalStackAvailable:!!t?.stack,level:"error"},i=(p,u,h)=>{Object.assign(r,{failureKind:p,errorCode:u,errorSummary:h.slice(0,512),summaryOmitted:!1,level:t?"error":"warning"}),delete r.summaryOmittedReason},s=Le(t)?.code;if(typeof s=="string"&&ki[s]){let p=ki[s];return i(p.kind,s,`${s}: ${p.summary}`),r}let o=t?.message??"";if(!t){let p=Le(n)?.content;Array.isArray(p)&&(o=p.slice(0,8).flatMap(u=>{let h=Le(u);return h?.type==="text"&&typeof h.text=="string"?[h.text.length>16384?`${h.text.slice(0,8192)}
44
48
  [truncated]
45
- ${w.text.slice(-8192)}`:w.text]:[]}).join(`
46
- `))}let c=e==="bash"||e==="powershell",a=o.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(c){let p=a.match(/^Command exited with code (-?\d{1,10})$/),u=a.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return i("process_exit","nonzero_exit",a),r.exitCode=Number(p[1]),r;if(u&&Number.isFinite(Number(u[1]))&&Number(u[1])>0)return i("timeout","timeout",a),r.timeoutMs=Number(u[1])*1e3,r;if(a==="Command aborted")return i("cancelled","cancelled",a),r}let l=o.slice(0,8192).split(/\r?\n/,1)[0]??"";if(o==="Operation aborted"||t?.name==="AbortError")i("cancelled","cancelled","Operation aborted");else if(o==="Tool execution was blocked")i("blocked","blocked",o);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(o))i("not_found","ENOENT","Working directory does not exist");else if(!c||!o.includes(`
47
- `)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=fi[p[1]],w=l.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);i(u.kind,p[1],`${p[1]}: ${u.summary}${w?`; operation=${w[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))i("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(l)||l==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(l))i("validation","invalid_arguments",l.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(o))i("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=Gd.find(w=>w.pattern.test(o));u&&i("validation",u.code,u.summary)}}return r}var Jd=256;function co(n,e,t){n.delete(e),n.set(e,t),n.size>Jd&&n.delete(n.keys().next().value)}var lt=class{options;pending=new Map;completed=new Map;constructor(e){this.options=e}enabled(){return this.options.enabled()?!0:(this.clear(),!1)}identity(e){return{toolName:Xt.has(e.toolName)?e.toolName:"custom",...Xt.has(e.toolName)?{}:{toolId:qd("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,t){try{this.options.breadcrumb(e,t)}catch{}}start(e,t={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let r=e.toolName==="bash"||e.toolName==="powershell"?$e(e.args)?.timeout:void 0,i=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,s={...Pe(t),...this.identity(e),stage:"tool"};co(this.pending,e.toolCallId,{context:s,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:i}),this.breadcrumb("tool_start",s)}catch{}}end(e,t={}){this.finish(e,t,"tool_execution_end")}message(e,t={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},t,"message_end")}catch{}}finish(e,t,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let i=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),co(this.completed,e.toolCallId,!0);let s={...i?.context??{...Pe(t),...this.identity(e),stage:"tool"},diagnosticSource:r};if(i&&(s.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-i.started)),i.timeoutMs!==void 0&&(s.timeoutMs=i.timeoutMs)),!e.isError){this.breadcrumb("tool_end",s);return}let o=e.result instanceof Error?e.result:$e(e.result)?.error instanceof Error?$e(e.result).error:void 0,c=i?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:lo(e.result,e.toolName);if(Object.assign(s,c,{code:"tool_failed"}),this.breadcrumb(c.failureKind==="cancelled"?"tool_cancelled":c.failureKind==="blocked"?"tool_blocked":"tool_failed",s),c.failureKind==="cancelled"||c.failureKind==="blocked")return;let a;o?a=po(o,e.toolName):(a=new Error(`${s.toolName}: ${c.failureKind} (${c.errorCode??"unknown"})`),a.name="ToolResultFailure",a.stack=void 0),this.options.capture(a,s)}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 po(n,e,t=0){let r=lo(n,e),i=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return i.name=n.name,i.stack=n.stack?`${i.name}: ${i.message}
49
+ ${h.text.slice(-8192)}`:h.text]:[]}).join(`
50
+ `))}let a=e==="bash"||e==="powershell",c=o.slice(-8192).trimEnd().split(/\r?\n/).at(-1)??"";if(a){let p=c.match(/^Command exited with code (-?\d{1,10})$/),u=c.match(/^Command timed out after (\d+(?:\.\d+)?) seconds$/);if(p&&Number.isSafeInteger(Number(p[1]))&&Number(p[1])!==0)return i("process_exit","nonzero_exit",c),r.exitCode=Number(p[1]),r;if(u&&Number.isFinite(Number(u[1]))&&Number(u[1])>0)return i("timeout","timeout",c),r.timeoutMs=Number(u[1])*1e3,r;if(c==="Command aborted")return i("cancelled","cancelled",c),r}let l=o.slice(0,8192).split(/\r?\n/,1)[0]??"";if(o==="Operation aborted"||t?.name==="AbortError")i("cancelled","cancelled","Operation aborted");else if(o==="Tool execution was blocked")i("blocked","blocked",o);else if(/^Working directory does not exist: [^\n]+\nCannot execute (?:bash|powershell) commands\.$/.test(o))i("not_found","ENOENT","Working directory does not exist");else if(!a||!o.includes(`
51
+ `)||/^Validation failed for tool\b/.test(l)){let p=l.match(/^(ENOENT|ENOTDIR|EACCES|EPERM|ETIMEDOUT|EINVAL):/);if(p){let u=ki[p[1]],h=l.match(/, (open|access|stat|lstat|scandir|spawn|read|write|rename|mkdir|unlink)\s/);i(u.kind,p[1],`${p[1]}: ${u.summary}${h?`; operation=${h[1]}`:""}`)}else if(/^Tool [^\r\n]+ not found$/.test(o))i("not_found","tool_not_found","Tool not found");else if(/^Validation failed for tool\b/.test(l)||l==="Edit tool input is invalid. edits must contain at least one replacement."||/^Invalid timeout:/.test(l))i("validation","invalid_arguments",l.startsWith("Invalid timeout:")?"Invalid timeout argument":"Invalid tool arguments");else if(/^Offset \d+ is beyond end of file \(\d+ lines total\)$/.test(o))i("validation","invalid_arguments","Read offset is beyond end of file");else if(e==="edit"){let u=yp.find(h=>h.pattern.test(o));u&&i("validation",u.code,u.summary)}}return r}var vp=256;function No(n,e,t){n.delete(e),n.set(e,t),n.size>vp&&n.delete(n.keys().next().value)}var dt=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:wp("sha256").update(e.toolName).digest("hex").slice(0,16)},toolCallId:this.options.anonymize(`tool-call:${e.toolCallId}`)}}breadcrumb(e,t){try{this.options.breadcrumb(e,t)}catch{}}start(e,t={}){try{if(!this.enabled()||this.pending.has(e.toolCallId)||this.completed.has(e.toolCallId))return;let r=e.toolName==="bash"||e.toolName==="powershell"?Le(e.args)?.timeout:void 0,i=typeof r=="number"&&r>0&&Number.isFinite(r*1e3)?r*1e3:void 0,s={...Se(t),...this.identity(e),stage:"tool"};No(this.pending,e.toolCallId,{context:s,started:(this.options.now??performance.now.bind(performance))(),cancelled:!1,timeoutMs:i}),this.breadcrumb("tool_start",s)}catch{}}end(e,t={}){this.finish(e,t,"tool_execution_end")}message(e,t={}){try{if(!this.enabled()||!e.isError)return;this.finish({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,result:{content:e.content}},t,"message_end")}catch{}}finish(e,t,r){try{if(!this.enabled()||this.completed.has(e.toolCallId))return;let i=this.pending.get(e.toolCallId);this.pending.delete(e.toolCallId),No(this.completed,e.toolCallId,!0);let s={...i?.context??{...Se(t),...this.identity(e),stage:"tool"},diagnosticSource:r};if(i&&(s.durationMs=Math.max(0,Math.round((this.options.now??performance.now.bind(performance))()-i.started)),i.timeoutMs!==void 0&&(s.timeoutMs=i.timeoutMs)),!e.isError){this.breadcrumb("tool_end",s);return}let o=e.result instanceof Error?e.result:Le(e.result)?.error instanceof Error?Le(e.result).error:void 0,a=i?.cancelled&&!o?{failureKind:"cancelled",errorCode:"cancelled",level:"warning",originalStackAvailable:!1,summaryOmitted:!0,summaryOmittedReason:"cancelled"}:Do(e.result,e.toolName);if(Object.assign(s,a,{code:"tool_failed"}),this.breadcrumb(a.failureKind==="cancelled"?"tool_cancelled":a.failureKind==="blocked"?"tool_blocked":"tool_failed",s),a.failureKind==="cancelled"||a.failureKind==="blocked")return;let c;o?c=Oo(o,e.toolName):(c=new Error(`${s.toolName}: ${a.failureKind} (${a.errorCode??"unknown"})`),c.name="ToolResultFailure",c.stack=void 0),this.options.capture(c,s)}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 Oo(n,e,t=0){let r=Do(n,e),i=new Error(r.errorSummary??"Tool exception (diagnostic text unavailable)");return i.name=n.name,i.stack=n.stack?`${i.name}: ${i.message}
48
52
  ${n.stack.split(`
49
53
  `).slice(1).join(`
50
- `)}`:void 0,t<3&&n.cause instanceof Error&&(i.cause=po(n.cause,e,t+1)),nt(i)}import{randomUUID as ho}from"node:crypto";import{randomUUID as Kd}from"node:crypto";import{EnvHttpProxyAgent as Xd,getGlobalDispatcher as iy,setGlobalDispatcher as ny}from"undici";var uo=n=>({httpProxy:n.http_proxy??n.HTTP_PROXY??n.all_proxy??n.ALL_PROXY??"",httpsProxy:n.https_proxy??n.HTTPS_PROXY??n.all_proxy??n.ALL_PROXY??"",noProxy:n.no_proxy??n.NO_PROXY??""});function Yd(n,e){let t=uo(n),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let i=t.noProxy.toLowerCase();if(i==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),o=r.hostname.toLowerCase();return!i.split(/[,\s]/).filter(Boolean).some(c=>{let a=c.match(/^(.+):(\d+)$/),l=(a?.[1]??c).replace(/^\*?\./,"");return(!a||Number(a[2])===s)&&(o===l||o.endsWith("."+l))})}function Qd(n){let e=uo(n);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new Xd(e)}function hi({env:n=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:r=!1}={}){let i,s=new Set,o=t===globalThis.fetch,c=(p,u)=>{try{e(p,u)}catch{}},a=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let w={requestId:Kd(),phase:"headers",proxied:o&&Yd(n,p)},m=r?void 0:i,f=!1,y=u?.signal??(p instanceof Request?p.signal:void 0),k=()=>P(),P=()=>{y?.removeEventListener("abort",k),!f&&r&&(f=!0,a(m).catch(()=>{}))},E;try{o?(m??=Qd(n),s.add(m),r||(i=m),E=await t(p,{...u,dispatcher:m})):E=await t(p,u)}catch(R){throw c(R,w),P(),R}if(E.ok||c(void 0,{...w,status:E.status}),!E.body)return P(),E;let T=E.body.getReader();y?.addEventListener("abort",k,{once:!0}),y?.aborted&&P();let D=new ReadableStream({async pull(R){try{let Y=await T.read();Y.done?(R.close(),T.releaseLock(),P()):R.enqueue(Y.value)}catch(Y){c(Y,{...w,phase:"body"}),R.error(Y),T.releaseLock(),P()}},async cancel(R){try{await T.cancel(R)}finally{T.releaseLock(),P()}}}),M=new Response(D,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(M,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),M},close:async()=>{await Promise.all([...s].map(a))}}}var fo=(n,e)=>hi({autoClose:!0}).fetch(n,e);var Zd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),ep=n=>typeof n=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(n)?n:void 0;function gi(n,e={}){let t=[],r=new Set,i=(a,l=0)=>{if(!a||l>4||r.has(a)||t.length>=8)return;r.add(a);let p=ep(a.code);if(t.push({name:Zd.has(a.name)?a.name:"Error",...p?{code:p}:{}}),i(a.cause,l+1),a instanceof AggregateError)for(let u of a.errors.slice(0,4))i(u,l+1)};i(n);let s=t.flatMap(a=>a.code?[a.code]:[]),o=e.stage==="model_admission"||s.some(a=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(a))?"lifecycle":s.some(a=>/CERT|TLS|SSL/.test(a))?"tls":s.some(a=>/^PROXY_/.test(a))||e.proxied&&s.some(a=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(a))?"proxy":s.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":s.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:ho(),requestId:c(e.requestId)??ho(),...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 go({env:n=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return hi({env:n,fetchRequest:t,onFailure:(r,i)=>e(gi(r,{...i,stage:i.phase==="body"?"model_stream":"model_headers"}))})}function tp(n){let e={...process.env,...n};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])n&&t.toUpperCase()in n&&!(t in n)&&delete e[t];return e}var rp=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function mo(n,e,t=()=>{}){let r=n.agent.streamFunction;n.agent.streamFunction=async(i,s,o)=>{if(!rp.has(i.api))return r(i,s,o);let c=t(),a=go({env:tp(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...c?{operationId:c}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await r(i,s,{...o,fetch:a.fetch});return l.result().finally(()=>a.close()).catch(()=>{}),l}catch(l){throw await a.close(),l}}}function dt(n,e,t){try{n()}catch(r){let i=gi(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...i})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:i.errorId,requestId:i.requestId,stage:i.stage,code:"hosted_admission_blocked",networkKind:i.kind,networkStage:i.stage,causeCodes:i.causes.flatMap(s=>s.code?[s.code]:[]).join(",")})}catch{}throw r}}var cp=["read","grep","find","ls"],wo=200,hr=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Xe;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,r=()=>!1,i=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},c=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=r,this.reportError=i,this.onSessionsChanged=o,this.customTools=c,this.offHosted=a?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return s.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{s.enabled()&&s.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return s.enabled()?s.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let r=await _e(e),i=t==="continue"?this.selectedByWorkspace.get(r):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.sessionId):void 0;if(i){if(i.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(i);return}if(typeof t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(t==="new")s=Dt.create(r);else if(t==="continue"){let c=(await ct(r))[0];s=c?Dt.open(c.path):Dt.create(r)}else s="sessionManager"in t?t.sessionManager:Dt.open(t.sessionFile);if(await ap(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(s.getSessionId());if(o){if(o.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(r,s,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await _e(e));return!t||!this.blank(t)?!1:(this.activate(t),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:t,cwd:r,prompts:i}=e,s=t.sessionManager.getBranch(),o=s.flatMap(c=>{let a=Rt(c);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:r,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!i.sending,name:cr(t.sessionManager.getSessionName(),o),modified:s.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=>Rt(t)?.role==="user")}rename(e,t){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.session.setSessionName(t),!0}discard(e){return this.queue.run(async()=>{let t=this.runtimes.get(e);if(!t||t.closing)return null;if(t.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!t.session.isIdle||t.prompts.sending||t.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=this.active===t,i=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),r&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:i,cwd:t.cwd,wasActive:r}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,r,i){let s=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${i}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,t,r,i){let s=this.runtimes.get(t.getSessionId()),o=await Ke.discover(e,this.isProjectTrusted(e)),c=np(),a=await ao(e,o.extensionRoots,this.isProjectTrusted(e)),l=new sp({cwd:e,agentDir:op(),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 ip({cwd:e,sessionManager:t,model:w,resourceLoader:l,customTools:this.customTools}),f=new lt({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,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:f,streaming:null,prompts:null,detached:i?{owner:i,events:[],seq:0,lastText:"",restoreTools:null}:void 0};y.prompts=s?.prompts??new He(()=>{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,mo(m,b=>{y.networkDiagnostic=b},()=>y.operation?.operationId);let k=b=>this.publishFor(y,b),P=y.detached,E=(b,v)=>{P&&(P.events.push({seq:++P.seq,type:b,...v===void 0?{}:{text:v}}),P.events.length>wo&&P.events.splice(0,P.events.length-wo))};y.interactions=new at(c,b=>!y.closing&&b.sessionId===m.sessionManager.getSessionId()&&o.has(b.pluginId),()=>k({type:"snapshot",session:this.snapshotOf(y)}));let T=0,D=c.on(dr,()=>k({type:"snapshot",session:this.snapshotOf(y)})),M=m.subscribe(b=>{if(P&&!y.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(`
51
- `)),b.type==="agent_settled"&&E("turn_end",P.lastText)),!this.disposed&&!y.closing){let v={...y.operation,session:this.telemetry.anonymize(m.sessionManager.getSessionId()),piVersion:fr,model:m.model?`${m.model.provider}/${m.model.id}`:null,thinkingLevel:m.thinkingLevel};if(b.type==="agent_start"&&(y.activityId++,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:fr,...$?{networkKind:$.kind,networkStage:$.stage,causeCodes:$.causes.flatMap(ye=>ye.code?[ye.code]:[]).join(","),requestId:$.requestId}:{}})??$?.errorId;k({type:"error",message:b.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:we,inTranscript:!0,...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:qe(b.message.content)},Date.now()-T>=60&&(T=Date.now(),k({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,k({type:"stream",message:null})),k({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=()=>{D(),M()},y.releaseHosted=this.hosted?.adapter.attach(m);let R=[],Y=!0;if(await m.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Y&&R.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,R.length)throw new Error(R.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");y.detached&&(y.detached.restoreTools=m.getActiveToolNames(),m.setActiveToolsByName(cp)),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 eo(e.session,t,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:r,catalog:i}=e,s=t.sessionManager.getBranch().flatMap(o=>{let c=Rt(o);return c?[c]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:cr(t.sessionManager.getSessionName(),s),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:ot(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:oi(t.sessionManager.getBranch(),i.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=t.session.extensionRunner,i=await pr(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||r!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),i}resolveInteraction(e,t,r,i){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,r,i)}async send(e,t=[],r,i){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(Oe(this.snapshot(),e,i),i==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,t,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,t,r,i)}async prompt(e,t,r,i,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),i,this.reportError),Oe({...this.snapshotOf(e),idle:e.session.isIdle},t,s);let o=e.session,c=o.isIdle;c&&(e.operation=i,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...i,piVersion:fr});let a=!1,l,p,u=new Promise((w,m)=>{l=w,p=m});o.prompt(t,{images:r,streamingBehavior:s,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(Ae(w,"Agent response failed"),{...i,stage:"agent",code:"agent_failed",piVersion:fr});this.publishFor(e,{type:"error",message:w instanceof Error?w.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:m,...i})}});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&&!ot(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,r,i)=>this.prompt(e,t,r,i))}async updateQueuedPrompt(e,t,r){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&i.session.isIdle)throw new oe("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await i.prompts.update(e,t,r,(s,o,c)=>this.prompt(i,s,o,c,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(At),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=t.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!ot(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!ot(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=ur(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let c=this.reportError(Ae(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:c,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=r.session.modelRuntime.getModel(e,t);if(!i)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(i),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}createDetached(e,t,r){return this.queue.run(async()=>{this.ensureAvailable();let i=await _e(e),s=Dt.create(i);return await this.replace(i,s,"new",t),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,r){let i=this.detachedRuntime(e);if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&i.detached.restoreTools&&(i.session.setActiveToolsByName(i.detached.restoreTools),i.detached.restoreTools=null),!i.session.isIdle||i.prompts.length>0){i.prompts.enqueue(t,[],void 0),this.scheduleQueued(i);return}await this.prompt(i,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(i=>i.seq>t),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as lp,mkdir as dp,rename as pp,unlink as up}from"node:fs/promises";import{basename as fp,join as yo}from"node:path";var hp=n=>yo(n,"pi-web","trash");async function vo(n,e){let t=hp(e);await dp(t,{recursive:!0});let r=yo(t,`${Date.now()}_${fp(n)}`);try{await pp(n,r)}catch(i){let s=i.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw i;await lp(n,r),await up(n)}return r}import{basename as mi,dirname as gp}from"node:path";function bo(n,e){let t=r=>e[r].map(i=>({name:r==="skills"&&mi(i.path).toLowerCase()==="skill.md"?mi(gp(i.path)):mi(i.path),path:i.path,source:i.metadata.source,scope:i.metadata.scope,enabled:i.enabled}));return{packages:n.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as mp}from"node:child_process";var wp=(n,e)=>new Promise((t,r)=>{mp(n,[...e],{windowsHide:!0},i=>{i?r(i):t()})});async function wi(n,e=process.platform,t=process.env,r=wp){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let i=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return i===null?!1:(await r(i,[n]),!0)}import{execFile as ou}from"node:child_process";import{randomUUID as Hi}from"node:crypto";import{existsSync as zo}from"node:fs";import{access as au,mkdir as Mt,mkdtemp as cu,readFile as Ve,realpath as lu,rename as qo,rm as Go,writeFile as Jo}from"node:fs/promises";import{join as G}from"node:path";import{createHash as bi}from"node:crypto";import{readdir as Ep,realpath as xo,rename as xp,stat as _p}from"node:fs/promises";import{join as Fe}from"node:path";import{constants as yi}from"node:fs";import{DatabaseSync as yp}from"node:sqlite";import{lstat as Io,mkdir as vp,open as Ot,rename as bp,unlink as So}from"node:fs/promises";import{dirname as kp,join as ko,resolve as Pp}from"node:path";import{randomUUID as Ip}from"node:crypto";import{setTimeout as Sp}from"node:timers/promises";async function Z(n){await vp(n,{recursive:!0,mode:448});let e=await Io(n);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function X(n,e){let t;try{t=await Ot(n,yi.O_RDONLY|yi.O_NONBLOCK|(yi.O_NOFOLLOW??0))}catch(r){if(Me(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new h("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<i.length;){let o=await t.read(i,s,i.length-s,s);if(!o.bytesRead)break;s+=o.bytesRead}if(s>e||s!==r.size)throw new h("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function ee(n,e=2*1024*1024){let t=await X(n,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 he(n){let e=await X(n,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 ${n}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new h("gc_recovery_required",`Invalid journal ${n}; original bytes preserved`);return t}async function W(n,e){let t=`${n}.${Ip()}.tmp`,r=await Ot(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await bp(t,n);let i;try{i=await Ot(kp(n),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await So(t).catch(()=>{})}}var Eo='{"version":2,"mechanism":"sqlite-exclusive"}',Po=n=>n.toString("utf8")===Eo,gr=new Set;async function vi(n,e,t=0){await Z(n);let r=ko(n,`${e}.lock`),i=ko(n,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new h(s,"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 Ot(i,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await Io(i);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 yp(i,{allowExtension:!1}),p=Pp(i),u=Date.now()+t,w=!1;try{for(;;){if(!gr.has(p))try{l.exec("BEGIN EXCLUSIVE"),gr.add(p),w=!0;break}catch(y){if(y.errcode!==5)throw y}if(Date.now()>=u)throw new h(s,"Another host owns this plugin storage; wait for it to stop before retrying");await Sp(10)}let f=await X(r,4096);if(f===null){let y;try{y=await Ot(r,"wx",384),await y.writeFile(Eo),await y.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await y?.close()}f=await X(r,4096)}if(f===null||!Po(f))throw o()}catch(f){throw l.close(),w&&gr.delete(p),f}let m=!1;return async()=>{if(m)return;let f=await X(r,4096);if(f===null||!Po(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await So(r),l.close(),gr.delete(p),m=!0}}async function te(n,e,t=2e3){let r=await vi(n,"transaction",t);try{return await e()}finally{await r()}}var mr=n=>Fe(n,"host-pair"),Tp=n=>bi("sha256").update(JSON.stringify(n)).digest("hex"),Ap=10*6e4;async function Rp(n){let e=bi("sha256"),t=0,r=0;async function i(s){let o=(await Ep(Fe(n,s),{withFileTypes:!0})).sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(let c of o){if(!s&&c.name==="node_modules")continue;let a=s?`${s}/${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 i(a);continue}let l=await X(Fe(n,a),64*1024*1024);if(!l||(r+=l.length)>256*1024*1024)throw new h("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,bi("sha256").update(l).digest("hex")]))}}return await i(""),e.digest("hex")}async function ki(n,e){let t=await xo(e),r=Fe(e,"dist","hosted-worker.js");if(await xo(r)!==Fe(t,"dist","hosted-worker.js"))throw new h("host_pair_required","Candidate worker must remain inside the staged host");let i=await X(Fe(e,"package.json"),512*1024);if(!i)throw new h("host_pair_required","Candidate package metadata missing");let s=JSON.parse(i.toString("utf8")),o=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==n||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(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(r,32*1024*1024);if(!c)throw new h("host_pair_required","Candidate worker missing");return Tp([i.toString("base64"),c.toString("base64"),await Rp(e)])}async function wr(n){await xp(n,`${n}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Cp=n=>n.schema===1&&/^[a-f0-9-]{36}$/.test(n.id)&&typeof n.version=="string"&&typeof n.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(n.hostDigest)&&/^[a-f0-9]{64}$/.test(n.fingerprint)&&Array.isArray(n.selections)&&!n.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(n.selection&&(typeof n.selection.path!="string"||!/^[a-f0-9]{64}$/.test(n.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(n.phase);async function Pi(n){let e=Fe(mr(n),"intent.json"),t,r=!0;try{t=await he(e)}catch{t=null,r=!1}if(!r||t&&!Cp(t))return await wr(e),null;if(t){let{lifecyclePhase:i,...s}=t,o=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await _p(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());t={...s,updatedAt:o,phase:s.phase==="selected"&&i==="restart-requested"?"restart-requested":s.phase==="reconciled"&&i==="cancelled"?"cancelled":s.phase==="reconciled"&&i==="required-action"?"required-action":s.phase}}return t}async function yr(n,e){let{lifecyclePhase:t,...r}={...e,selections:[],updatedAt:new Date().toISOString()},i=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await W(Fe(mr(n),"intent.json"),i)}var Ii=n=>n&&["selecting","selected","restart-requested"].includes(n.phase),_o=(n,e=Date.now())=>!!n&&!!Ii(n)&&e-Date.parse(n.updatedAt??"")<Ap;import{promisify as du}from"node:util";import{realpathSync as Ro,statSync as Np}from"node:fs";import{basename as Dp,delimiter as Op,dirname as To,join as Si,resolve as Hp}from"node:path";function Ao(n){if(!n)return null;try{let e=Ro(n);return Dp(e)==="npm-cli.js"&&Np(e).isFile()?e:null}catch{return null}}function Mp({execPath:n=process.execPath,env:e=process.env}={}){let t=Ao(e.npm_execpath);if(t)return t;let r=new Set([To(n)]);try{r.add(To(Ro(n)))}catch{}let i=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of i.split(Op).filter(Boolean))r.add(Hp(s));for(let s of r)for(let o of[Si(s,"node_modules","npm","bin","npm-cli.js"),Si(s,"..","lib","node_modules","npm","bin","npm-cli.js"),Si(s,"npm")]){let c=Ao(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(n){return{file:process.execPath,args:[Mp(),...n]}}import{randomUUID as Wp}from"node:crypto";import{mkdir as Oo,readFile as jp,rename as xi,rm as $p,unlink as sv,writeFile as Fp}from"node:fs/promises";import{isAbsolute as No,join as Ht}from"node:path";var _i=1,Vp=1440*6e4,vr=n=>Ht(n,"pi-web","upgrade"),Ti=n=>Ht(vr(n),"candidate.json"),Up=n=>Ht(vr(n),"transaction.json"),Do=n=>Ht(vr(n),"history"),Ho=/^[a-f0-9-]{36}$/i;async function Bp(n,e){let t=`${n}.${Wp()}.tmp`;try{await Fp(t,e,{mode:384}),await xi(t,n)}finally{await $p(t,{force:!0})}}var Lp=(n,e)=>Bp(n,JSON.stringify(e));async function Ei(n,e){await xi(n,`${n}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function Mo(n,e,t=()=>!1){let r;try{r=JSON.parse(await jp(n,"utf8"))}catch(i){return i?.code==="ENOENT"||await Ei(n,"invalid"),null}return e(r)?t(r)?(await Ei(n,"expired"),null):r:(await Ei(n,"invalid"),null)}function Wo(n){if(!n||typeof n!="object"||n.schema!==_i||!Ho.test(n.id??""))return!1;try{xe(n.version)}catch{return!1}return typeof n.launcher=="string"&&No(n.launcher)&&typeof n.packageRoot=="string"&&No(n.packageRoot)&&["stable","alpha"].includes(n.channel)&&typeof n.downgrade=="boolean"&&!Number.isNaN(Date.parse(n.createdAt??""))}async function br(n,e=Date.now()){return Mo(Ti(n),Wo,t=>e-Date.parse(t.createdAt)>Vp)}async function jo(n,e){let t={schema:_i,createdAt:new Date().toISOString(),...e};if(!Wo(t))throw new Error("Invalid upgrade candidate");return await Oo(vr(n),{recursive:!0,mode:448}),await Lp(Ti(n),t),t}async function Ai(n,e,t){let r=await br(n);!r||e&&r.id!==e||(await Oo(Do(n),{recursive:!0,mode:448}),await xi(Ti(n),Ht(Do(n),`${r.id}-candidate-${t}.json`)).catch(i=>{if(i?.code!=="ENOENT")throw i}))}var zp=["selected","committed","rolled-back"];function qp(n){return!!n&&typeof n=="object"&&n.schema===_i&&Ho.test(n.id??"")&&zp.includes(n.phase)&&typeof n.version=="string"&&typeof n.from=="string"&&!Number.isNaN(Date.parse(n.updatedAt??""))}async function $o(n){return Mo(Up(n),qp)}import{readFile as Gp,rename as Jp,writeFile as Kp,unlink as Xp}from"node:fs/promises";import{join as Yp}from"node:path";import{randomUUID as Qp}from"node:crypto";var Ri=1,Fo=n=>Yp(n,"pi-web","launcher-handoff.json");function Vo(n){return n?.protocol===Ri&&typeof n.nonce=="string"&&n.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(n.requestId)&&Number.isSafeInteger(n.pid)&&n.pid>0&&["requested","draining","stopped","refused","failed"].includes(n.phase)}async function Ci(n){try{let e=JSON.parse(await Gp(Fo(n),"utf8"));if(!Vo(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 Zp(n,e){let t=`${n}.${Qp()}.tmp`;try{await Kp(t,JSON.stringify(e),{mode:384}),await Jp(t,n)}finally{await Xp(t).catch(()=>{})}}async function Uo(n,e){if(!Vo(e))throw new Error("Invalid launcher handoff receipt");await Zp(Fo(n),e)}import{execFile as eu}from"node:child_process";import{cp as tu,readFile as Ni,realpath as ru,rm as iu}from"node:fs/promises";import{join as pt,sep as nu}from"node:path";import{promisify as su}from"node:util";var Bo=su(eu),Di=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Oi(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=n;return Di.map(t=>{let r=e[t];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${r}`})}async function kr(n){return Promise.all(Di.map(async e=>{let t=await st(n,e),r=JSON.parse(await Ni(pt(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Lo(n,e){let t=JSON.parse(await Ni(pt(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=t.peerDependencies===void 0?await kr(n):Oi(t.peerDependencies);if(JSON.stringify(await kr(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let i=await st(n,"node-pty"),s=await st(e,"node-pty"),o=await ru(pt(e,"../.."));if(i===s||!s.startsWith(o+nu))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 Ni(pt(u,"package.json"),"utf8")).version;if(await c(i)!==await c(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await iu(s,{recursive:!0,force:!0}),await tu(i,s,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await Bo(process.execPath,[pt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await st(e,Di[0]),{stdout:p}=await Bo(process.execPath,[pt(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:a,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}var pu=du(ou),Wt=n=>["committed","cancelled","failed"].includes(n);function Ko(n){let e=n.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function uu(n,e){try{let t=Co(n),{stdout:r}=await pu(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(t){let r=t;throw new Error(r.stderr?.trim()||r.message)}}var Pr=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??uu,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let r=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return kr(this.packageRoot);let i=JSON.parse(r),s=Array.isArray(i)&&i.length===1?i[0]:i;return Oi(s)},this.verifyPackage=e.verifyPackage??Lo,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?Ri:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!Wt(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let i=G(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await Ve(i,"utf8")),o=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let c=await Ci(this.agentDir);if(c?.nonce===e&&["requested","draining"].includes(c.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let a,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(a=await this.beforeRestart(),!o(JSON.parse(await Ve(i,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:s.pid,phase:"requested"};try{await Uo(this.agentDir,p),l=!0}catch(u){let w=await Ci(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 Ve(G(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return xe(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();if(!t||Wt(t.phase)||t.id===this.ownTransaction)return e;if(t.version===e&&["selecting","selected","restart-requested"].includes(t.phase))await this.record({...t,phase:"committed",message:"Selected version is running"});else if(t.phase==="restart-requested"){let r=await $o(this.agentDir);await this.record({...t,phase:"failed",message:r?.id===t.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Ai(this.agentDir,t.id,"superseded"),await this.record({...t,phase:"failed",message:`Interrupted while ${t.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return G(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await he(this.transactionPath)}catch{return await wr(this.transactionPath),null}return e?e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||typeof e.selectionPath!="string"?(await wr(this.transactionPath),null):e:null}async record(e){if(await Mt(G(this.agentDir,"pi-web"),{recursive:!0}),await W(this.transactionPath,e),Wt(e.phase)){let t=G(this.agentDir,"pi-web","update-history");await Mt(t,{recursive:!0}),await W(G(t,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),t=await br(this.agentDir);t&&(!e||t.id===e.id)&&await Ai(this.agentDir,t.id,"cancelled"),e&&!Wt(e.phase)&&await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0}get preferencePath(){return G(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await Ve(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${Hi()}.tmp`;try{await Mt(G(this.agentDir,"pi-web"),{recursive:!0}),await Jo(t,JSON.stringify({channel:e}),{mode:384}),await qo(t,this.preferencePath)}finally{this.savingPreference=!1,await Go(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=zo(G(this.packageRoot,".git")),i={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(i.launcher=this.launcherIdentity(),i.launcherHandoff={supported:i.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(i.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction();if(s&&!Wt(s.phase)?i.recovery={version:s.version,phase:s.phase,canCancel:s.phase!=="restart-requested"}:s?.phase==="failed"&&s.message&&(i.lastFailure={version:s.version,message:s.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...i,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...i,canRestart:!1,reason:i.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?i.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":i.canRestart||(i.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&i.canRestart&&(i.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let o=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),c=Array.isArray(o)&&o.length===1?o[0]:o,a=t==="alpha"?c:{latest:c};if(!a||!Hs(a.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let l=a.latest;if(t==="alpha"&&a.alpha!==void 0){if(!sr(a.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");fe(a.alpha,l)>0&&(l=a.alpha)}if(i.latest=l,i.downgrade=fe(l,e)<0,i.available=t==="stable"?fe(l,e)!==0:fe(l,e)>0,i.available&&this.pluginWarnings){let p=await this.pluginWarnings(l).catch(()=>[]);p.length&&(i.pluginWarnings=p)}this.desktopManaged&&i.downgrade&&!this.desktopReleaseChannels&&fe(l,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(i.canRestart=!1,i.requiresDesktopUpgrade=!0,i.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(o){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`)}return i}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(zo(G(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=G(this.agentDir,"pi-web","releases");await Mt(r,{recursive:!0});let i=await cu(G(await lu(r),`${t.latest}-`)),s=G(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Hi(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=o.id,await this.record(o);try{let c=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...c,"--prefix",i,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let a=G(i,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:a},await this.record(o);let l=JSON.parse(await Ve(G(a,"package.json"),"utf8"));if(l.name!=="pi-webapp"||l.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await Ve(G(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&Ko(l)!==Ko(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let u=G(a,"bin","pi-webapp.mjs");return await Promise.all([u,G(a,"dist","extension.js"),G(a,"web","dist","index.html")].map(w=>au(w))),this.desktopManaged&&(await ri(this.agentDir,{version:t.latest,launcher:u,desktopProtocolVersion:We}),await this.verifyPackage(this.packageRoot,a)),await this.prefetchPlugins?.(t.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await jo(this.agentDir,{id:o.id,version:t.latest,launcher:u,packageRoot:a,channel:t.channel??"stable",downgrade:!!t.downgrade}),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={id:o.id,update:{version:t.latest,launcher:u},channel:t.channel??"stable"},{version:t.latest,launcher:u}}catch(c){await Go(i,{recursive:!0,force:!0});let a=(c instanceof Error?c.message:String(c)).slice(0,500);throw await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${a}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),c}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:t=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let i,s=!1,o=G(this.agentDir,"pi-web","launcher.restart");try{if(i=await this.beforeRestart?.(t),(await br(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let c=await this.transaction();c?.id===r.id&&await this.record({...c,phase:"restart-requested"});try{if(JSON.parse(await Ve(o,"utf8"))?.nonce!==this.launcherNonce){let l=G(this.agentDir,"pi-web","restart-history");await Mt(l,{recursive:!0,mode:448}),await qo(o,G(l,`stale-${Hi()}.json`))}}catch{}try{await Jo(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(a){try{let l=JSON.parse(await Ve(o,"utf8"));s=l.nonce===this.launcherNonce&&l.candidate===r.id}catch{}if(!s)throw a}this.restartPending=!0}catch(c){if(s){this.restartPending=!0;return}let a=await this.transaction();throw a?.id===r.id&&a.phase==="restart-requested"&&await this.record({...a,phase:"prepared"}),i&&await i(),c}}};import{createHash as Da,randomUUID as gh}from"node:crypto";import{randomUUID as Lf}from"node:crypto";import{join as Ki}from"node:path";import{randomUUID as Qo}from"node:crypto";import{randomUUID as fu}from"node:crypto";function Xo(n){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof n[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let r=`__pi_web_contract_${fu().replaceAll("-","")}`,i;try{if(i=n.getActiveTools(),!Array.isArray(i))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{n.registerTool(s),n.setActiveTools([...i,r]),(n.getAllTools().find(c=>c.name===r)?.exposure!=="hidden"||n.getActiveTools().includes(r))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};n.registerTool({...s,parameters:o}),n.getAllTools().find(c=>c.name===r)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{n.setActiveTools(i)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var hu;function Yo(){return hu??=gu().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function gu(){let{createAgentSession:n,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:i,rm:s}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:c}=await import("node:path"),a=await i(c(o(),"pi-sdk-contract-")),l,p=[],u=0,w=0,m=!1,f=!1;try{let y=(M,R,Y)=>({name:M,label:M,description:"Inert host SDK contract check",exposure:R,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:[M=>{M.on("tool_call",R=>{if(R.toolName==="__contract_direct"&&(m=!!R.parentToolCallId),R.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let R of["hidden","model-only"])M.registerTool(y(`__contract_${R.replace("-","_")}`,R,async()=>(w++,k())));M.registerTool(y("__contract_protected","direct",async()=>(w++,k()))),M.registerTool(y("__contract_direct","direct",async()=>(u++,k()))),M.registerTool(y("__contract_driver","direct",async(R,Y,b,v,$)=>{let we=await $.executeTool("__contract_hidden",{}),ye=await $.executeTool("__contract_model_only",{}),ne=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!we.isError||!ye.isError)&&p.push("nested-tool-exposure"),(ne.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,k()}))}]});await P.reload(),{session:l}=await n({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 T=0;l.agent.streamFunction=async M=>{let R=T++===0,Y={role:"assistant",api:M.api,provider:M.provider,model:M.id,timestamp:Date.now(),content:R?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:R?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},b=r();return b.push({type:"start",partial:Y}),b.push({type:"done",reason:R?"toolUse":"stop",message:Y}),b.end(Y),b};let D;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((M,R)=>{D=setTimeout(()=>R(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(D)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await s(a,{recursive:!0,force:!0})}}var Ir=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??=Yo().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,i)=>{t=setTimeout(()=>i(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let r=this.install(e,t);r.ready=!0;try{this.publish(r)}catch(i){throw this.release(r),i}return()=>this.release(r)}install(e,t){let r={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let i=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{i(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),i(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),i(e.on("tool_call",s=>{let o=r.owned.get(s.toolName);if(!o)return;let c=this.descriptors.get(o)?.find(a=>a.name===s.toolName);if(!c||!this.allowed(r,o,c,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),i(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),i(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let t=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(r=>{r.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(r){throw this.release(t),r}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,r,i=!1){let s=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!i||s.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(i=>i.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(t);this.validateChange(e,r),this.descriptors.set(e,r);for(let i of this.bindings)i.ready&&this.publish(i)}validateChange(e,t){for(let i of this.bindings)if(i.compatible!==!1)for(let[s,o]of i.owned)this.assertOwner(i,o,s);let r=new Set;for(let i of t){if(!i.name||!i.action||!i.parameters||i.parameters.type!=="object"||r.has(i.name))throw new Error("Invalid hosted tool descriptor");r.add(i.name);for(let[s,o]of this.descriptors)if(s!==e&&o.some(c=>c.name===i.name))throw new Error(`Hosted tool ownership conflict: ${i.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,i.name)}}assertOwner(e,t,r){let i=e.owned.get(r);if(i&&i!==t)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(o=>o.name===r);if(s&&(!i||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=Xo(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,i]of e.owned)this.assertOwner(e,i,r);for(let[r,i]of this.descriptors)for(let s of i)this.assertOwner(e,r,s.name);let t=new Set;for(let[r,i]of this.descriptors)for(let s of i){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;t.add(s.name);let o=this.service.policy(r,e.scope),c=o.exposure??"direct",a=!o.allowNested&&c==="direct"?"model-only":c,l={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:a,execute:async(p,u,w)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:Qo(),scope:{...e.scope},kind:"tool",action:s.action,input:u},w)}};e.pi.registerTool(l),e.definitions.set(s.name,l)}for(let r of e.owned.keys())if(!t.has(r)){let i={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:mu};e.pi.registerTool(i),e.definitions.set(r,i)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let i=e.definitions.get(r);return!i||i.exposure==="direct"||i.exposure==="model-only"}))}async invokeAction(e,t,r,i,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(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:Qo(),scope:t,kind:"action",action:r,input:i},s)}};async function mu(){throw new Error("Hosted tool unavailable")}import{randomBytes as wf,randomUUID as yf,timingSafeEqual as vf}from"node:crypto";import{join as be}from"node:path";var wu=30,Zo=/^[a-z][a-z0-9-]{0,63}$/,yu=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,jt=n=>{throw new h("invalid_package",n)},Mi=(n,e)=>n===void 0?[]:!Array.isArray(n)||n.length>32?jt(`Invalid ${e} declaration`):n;function ut(n){let e=n&&typeof n=="object"?n:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),r=t.has("secrets")?Mi(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&Zo.test(a)?a:jt("Invalid secret name")}):[],i=e.network,s=t.has("network")?Mi(i?.hosts,"network").map(c=>typeof c=="string"&&yu.test(c)?c:jt("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Mi(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!Zo.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<wu||a.intervalSec>86400?jt("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&jt("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:o,sessions:t.has("sessions")}}import{lookup as vu}from"node:dns/promises";import{isIP as bu}from"node:net";var ku=new Set(["GET","POST","PATCH","PUT","DELETE"]),Pu=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),Iu=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Sr=(n,e)=>{throw new h("network_denied",n,{status:403,reason:e})};function Su(n){let e=n.toLowerCase().replace(/^::ffff:/,"");if(bu(e)===4){let[t,r]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&r===254||t===172&&r>=16&&r<=31||t===192&&r===168||t===100&&r>=64&&r<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function ea(n,e,t,r,i){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new h("invalid_input","Invalid network request");let o;try{o=new URL(s.url)}catch{throw new h("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Sr("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Sr("Host is not declared by the plugin","host");let c=(s.method??"GET").toUpperCase();if(!ku.has(c))throw new h("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new h("invalid_input","Invalid body");let a={};for(let[E,T]of Object.entries(s.headers??{})){if(typeof T!="string"||Pu.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(T))throw new h("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=T}let l=null;if(s.secret!==void 0){if(t.includes(s.secret)||Sr("Secret is not declared by the plugin","secret"),l=await i.secrets.get(n,s.secret),!l)throw new h("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(i.resolve??(async E=>(await vu(E,{all:!0})).map(T=>T.address)))(o.hostname);(!p.length||p.some(Su))&&Sr("Host resolves to a non-public address","address");let u=i.timeoutMs??2e4,w=i.maxResponseBytes??2*1024*1024,m=await(i.fetch??fetch)(o,{method:c,headers:a,body:s.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 k=Buffer.concat(f).toString("utf8"),P={};return m.headers.forEach((E,T)=>{Iu.has(T.toLowerCase())&&(P[T.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:m.status,headers:P,body:k}}var Er=(n,e,t)=>{if(typeof n!="string"||!n||n.length>e)throw new h("invalid_input",`Invalid ${t}`);return n};async function ta(n,e,t,r,i,s){let o=i&&typeof i=="object"&&!Array.isArray(i)?i:{};if(r==="sessions.create"){if(o.mode!=="plan")throw new h("invalid_input","Plugin sessions must start in plan mode");if(n.activeCount(e)>=s)throw new h("quota_exceeded","Too many active plugin sessions",{status:429});return n.create({pluginId:e,cwd:t,title:Er(o.title,200,"title"),prompt:Er(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=Er(o.sessionId,200,"sessionId");if(n.ownerOf(c)!==e)throw new h("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new h("invalid_input","Invalid mode");return await n.send(c,Er(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await n.release(c),{ok:!0};case"sessions.abort":return await n.abort(c),{ok:!0};case"sessions.events":return n.events(c,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new h("method_denied","Unknown sessions method")}}var Eu=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),xr=class{options;constructor(e){this.options=e}handles(e){return Eu.has(e)}async call(e,t,r,i,s){let o=ut(t);if(i==="network.fetch"){if(!o.networkHosts.length)throw new h("capability_denied","Plugin did not declare network access",{status:403});return ea(e,o.networkHosts,o.secrets,s,this.options)}if(!o.sessions||!this.options.sessions)throw new h("capability_denied","Sessions capability is unavailable",{status:403});return ta(this.options.sessions,e,r.scope.cwd,i,s,this.options.maxActiveSessions??3)}};var _r=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let r=this.deps.setInterval??((i,s)=>{let o=setInterval(i,s);return o.unref(),o});this.timers.set(e,t.map(i=>r(()=>{this.tick(e,i)},i.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])t(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let r=`${e}\0${t.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,t),!0}catch(i){return this.deps.onError?.(e,t,i),!1}finally{this.running.delete(r)}}};import{createHash as Bi,timingSafeEqual as Gu}from"node:crypto";import{lstat as ua,mkdtemp as Ui,readdir as Ju,readFile as Ku,realpath as Xu,rename as Yu,rm as Ue,writeFile as Qu}from"node:fs/promises";import{tmpdir as Zu}from"node:os";import{join as L}from"node:path";import{gunzipSync as Nu}from"node:zlib";import{mkdir as Du,writeFile as Ou}from"node:fs/promises";import{dirname as Hu,join as Mu}from"node:path";import{constants as Wi}from"node:fs";import{lstat as na,open as xu,readdir as ra,realpath as sa}from"node:fs/promises";import{createHash as _u}from"node:crypto";import{join as oa,relative as Tu,resolve as Au,sep as Ru}from"node:path";var J={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},Cu={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=n=>_u("sha256").update(n).digest("hex");function V(n){throw new h("invalid_package",n)}async function Ye(n,e,t){let r=e.split("/");(!r.length||r.some(c=>!c||c==="."||c===".."||!/^[\w.-]+$/.test(c)))&&V("Invalid resource path");let i=n;for(let c=0;c<r.length;c++){i=oa(i,r[c]);let a=await na(i);(a.isSymbolicLink()||(c<r.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&V("Links and non-regular package files are forbidden")}let s=await sa(i);(s!==Au(n,e)||Tu(n,s).startsWith(`..${Ru}`))&&V("Resource escapes package root");let o=await xu(i,Wi.O_RDONLY|Wi.O_NONBLOCK|(Wi.O_NOFOLLOW??0));try{let c=await o.stat();(!c.isFile()||c.nlink!==1||c.size>t)&&V("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)&&V("Package resource changed during read"),a.subarray(0,l)}finally{await o.close()}}function ia(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return V("Invalid package JSON")}}async function Qe(n,e){let t=await sa(n);(await na(n)).isSymbolicLink()&&V("Package root cannot be a symlink");let r=ia(await Ye(t,"package.json",J.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&V("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&V("Invalid package version"),je(r.piWebapp)||V("Unsupported hosted manifest"),r.type!=="module"&&V("Hosted package must declare ESM module type");for(let u of await ra(t,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&V("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&V("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let w=r[u];w&&(typeof w!="object"||Object.keys(w).length>0)&&V("Hosted packages must contain all runtime dependencies")}let i=r.piWebapp,s=ia(await Ye(t,i.resourcesManifest.slice(2),J.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>J.files)&&V("Invalid resource manifest");let o=new Map,c=0;for(let u of s.files){(!u||typeof u!="object")&&V("Invalid resource entry");let w=u,m={...w,path:typeof w.path=="string"&&w.path.startsWith("./")?w.path.slice(2):w.path};(!Je(`./${m.path}`)||typeof m.sha256!="string"||!/^[a-f0-9]{64}$/.test(m.sha256)||!Number.isSafeInteger(m.bytes)||m.bytes<0||o.has(m.path))&&V("Invalid or duplicate resource");let f=m.path.split(".").at(-1);Cu[f]?.includes(m.mime)||V("Unsupported resource MIME");let y=f==="js"||f==="mjs"?J.js:f==="css"?J.css:f==="woff"||f==="woff2"?J.font:J.other;(m.bytes>y||(c+=m.bytes)>J.total)&&V("Resource budget exceeded");let k=await Ye(t,m.path,y);(k.length!==m.bytes||B(k)!==m.sha256)&&V("Resource integrity mismatch"),o.set(m.path,Object.freeze({...m}))}for(let u of[i.backend.entry,i.frontend.document,i.frontend.controller])o.has(u.slice(2))||V("Entrypoint is absent from resource manifest");let a=0;async function l(u,w=0){w>16&&V("Package directory nesting limit exceeded");for(let m of await ra(oa(t,u),{withFileTypes:!0})){++a>J.files*2&&V("Too many package entries");let f=`${u}/${m.name}`;(m.isSymbolicLink()||!m.isDirectory()&&!m.isFile())&&V("Invalid archive member"),m.isDirectory()?await l(f,w+1):f!==i.resourcesManifest.slice(2)&&!o.has(f)&&V("Undeclared distribution asset")}}await l("dist");let p=B(JSON.stringify({id:r.name,version:r.version,manifest:i,resources:[...o.values()].sort((u,w)=>u.path.localeCompare(w.path))}));return{id:r.name,version:r.version,root:t,manifest:i,resources:o,digest:p}}async function aa(n,e,t){if(t!==n.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Je(`./${r}`))return null;let i=n.resources.get(r);if(!i||r===n.manifest.backend.entry.slice(2))return null;let s=await Ye(n.root,r,i.bytes);if(s.length!==i.bytes||B(s)!==i.sha256)throw new h("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:i.mime}}var Tr=64*1024*1024,Wu=J.total+J.files*2048,F=n=>{throw new h("invalid_archive",n)};function ft(n){let e=n.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?n:n.subarray(0,e))}catch{return F("Archive has invalid UTF-8 paths")}}function ca(n){let e=ft(n).trim();if(!/^[0-7]+$/.test(e))return F("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:F("Archive number exceeds limits")}function ju(n){let e=n.endsWith("/")?n.slice(0,-1):n;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return F("Archive must have one package root");let t=e.slice(8);return t.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?F("Archive path is not a safe relative package path"):t}function $u(n){let e={},t=0;for(;t<n.length;){let r=n.indexOf(32,t);if(r<0)return F("Invalid PAX header");let i=n.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(i))return F("Invalid PAX record length");let s=Number(i),o=t+s;if(o>n.length||o<=r+2||n[o-1]!==10)return F("Truncated PAX record");let c=ft(n.subarray(r+1,o-1)),a=c.indexOf("=");if(a<1)return F("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 F("Unsupported PAX feature");e[l]=p,t=o}return e}function Fu(n){if(!n.length||n.length>Tr)return F("Compressed archive exceeds budget");let e;try{e=Nu(n,{maxOutputLength:Wu})}catch{return F("Invalid or oversized gzip archive")}let t=[],r=new Set,i=0,s=0,o=0,c=0,a=null,l=!1;for(;i+512<=e.length;){let u=e.subarray(i,i+512);if(i+=512,u.every(D=>D===0)){if(a||e.subarray(i).some(D=>D!==0))return F("Unexpected archive data after end marker");l=!0;break}if(++c>J.files*2)return F("Too many archive headers");let w=0;for(let D=0;D<512;D++)w+=D>=148&&D<156?32:u[D];if(ca(u.subarray(148,156))!==w)return F("Invalid tar header checksum");let m=ft(u.subarray(257,263));if(m&&m!=="ustar"&&m!=="ustar ")return F("Unsupported tar format");let f=u[156],y=ft(u.subarray(345,500)),k=(y?y+"/":"")+ft(u.subarray(0,100)),P=ca(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 F("Invalid PAX size");P=Number(a.size)}if(!Number.isSafeInteger(P)||P<0||P>J.total||i+P>e.length)return F("Truncated or oversized tar member");let E=e.subarray(i,i+P);if(i+=Math.ceil(P/512)*512,f===120){if(a||P>8192)return F("Oversized or chained PAX header");a=$u(E);continue}if(a=null,f!==0&&f!==48&&f!==53)return F("Links and special archive members are forbidden");let T=f===53;if(T&&P!==0||ft(u.subarray(157,257)))return F("Invalid archive link or directory");if(k=ju(k),!k&&!T)return F("Invalid package root member");if(r.has(k))return F("Duplicate archive member");if(r.add(k),++s>J.files||(o+=P)>J.total)return F("Unpacked archive exceeds budget");t.push({path:k,data:E,directory:T})}if(!l||!r.has("package.json"))return F("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 F("Archive file/directory collision")}return t}async function ji(n,e){let t=Fu(n);for(let r of t){if(!r.path)continue;let i=Mu(e,r.path);await Du(r.directory?i:Hu(i),{recursive:!0,mode:448}),r.directory||await Ou(i,r.data,{flag:"wx",mode:384})}}import{lstat as Vu,mkdir as Uu,readdir as Bu,realpath as Lu,writeFile as zu}from"node:fs/promises";import{dirname as qu,join as $i}from"node:path";async function la(n,e){let t=await Lu(n),r=await Ye(t,"package.json",J.other),i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new h("invalid_package","package.json is not valid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw new h("invalid_package","package.json must be an object");let s=[],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 Bu($i(t,w),{withFileTypes:!0})){let y=`${w}/${f.name}`;if(++o>J.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 k=await Ye(t,y,J.js);if((c+=k.length)>J.total)throw new h("invalid_package","Resource budget exceeded");let P=$i(e,y);await Uu(qu(P),{recursive:!0,mode:448}),await zu(P,k,{flag:"wx",mode:384}),s.push([y,B(k)])}}let l;try{l=await Vu($i(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}=i;return s.sort((w,m)=>w[0].localeCompare(m[0])),{contentHash:B(JSON.stringify({package:u,files:s})),packageJson:i}}function ve(n){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(n);return!e||e[0]!==n||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Se(n,e){let t=ve(n),r=ve(e);if(!t||!r)throw new h("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function da(n){let e=ve(n);if(e)return e;if(!sr(n))return null;let[t,r]=n.split("-alpha."),i=ve(t),s=Number(r);return i&&Number.isSafeInteger(s)?{...i,alpha:s}:null}function Fi(n){return!!da(n)}function ht(n,e){if(!Fi(n)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(i=>!i.trim()))return!1;let r=[];for(let i of t){let s=i.trim().split(/\s+/),o=!0;for(let c of s){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&da(a[2]);if(!a||!l)return!1;let p=a[2],u=fe(n,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&&fe(n,`${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&&fe(n,`${w}-0`)<0;break}}}r.push(o)}return r.some(Boolean)}var Ne=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 ge(n,e=Ne){let t=e.find(r=>r.id===n);if(!t)throw new h("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Vi(n,e,t){let r=n.piWebapp;return n.name===e.id&&!!ve(n.version)&&!n.deprecated&&je(r)&&ht(t,r.hostRange)&&e.requiredCapabilities.every(i=>r.capabilities.includes(i))}function pa(n,e,t,r,i){if(!n||typeof n!="object"||!("versions"in n)||!n.versions||typeof n.versions!="object"||Array.isArray(n.versions))throw new h("registry_invalid","Invalid registry version catalog");let s=Object.entries(n.versions);if(s.length>1e4)throw new h("registry_invalid","Registry version catalog exceeds budget");let c=s.flatMap(([a,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===a&&Vi(p,e,t)&&(!i||a===i)&&(!r||Se(a,r)>=0)?[p]:[]}).sort((a,l)=>Se(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 ef(n,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 r=Buffer.from(t[1],"base64"),i=Bi("sha512").update(n).digest();if(r.length!==i.length||!Gu(r,i))throw new h("integrity_mismatch","Downloaded package failed integrity verification")}var gt=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Fi(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??Ne,this.fetcher=e.fetch??fo}async index(){let e=await ee(L(this.root,"installed.json"));if(!e){if(await X(L(this.root,"installed.json"),2*1024*1024))throw new h("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new h("invalid_storage","Invalid plugin installation index");for(let[t,r]of Object.entries(e.versions))if(this.catalog.some(i=>i.id===t)){if(!Array.isArray(r)||r.length>16||new Set(r.map(i=>i.version)).size!==r.length)throw new h("invalid_storage","Invalid installed version list");for(let i of r)this.validateRecord(t,i)}return e}validateRecord(e,t){if(!t||!ve(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 L(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await he(L(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(s=>!["schema","pluginId","next"].includes(s)))throw new h("invalid_storage","Invalid install journal");ge(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let i=e.versions[t.pluginId]?.find(s=>s.version===t.next.version);if(i&&i.digest!==t.next.digest)throw new h("invalid_storage","Conflicting installation journal");await Ue(L(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=L(this.root,"staging");await Z(r);for(let i of await Ju(r)){if(!/^stage-[A-Za-z0-9]+$/.test(i)||(await ua(L(r,i))).isSymbolicLink())throw new h("invalid_storage","Invalid abandoned staging directory");await Ue(L(r,i),{recursive:!0})}return e}async recoverCollection(e){let t=L(this.root,"gc-journal.json"),r=await he(t);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new h("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");ge(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let i=r.records.filter(s=>e.versions[r.pluginId]?.some(o=>o.directory===s.directory));if(i.length&&i.length!==r.records.length)throw new h("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!i.length){await Z(L(this.root,"versions")),await Z(L(this.root,"versions",B(r.pluginId)));for(let s of r.records)await Ue(this.path(s),{recursive:!0,force:!0})}await Ue(t)}async collect(e,t){return ge(e,this.catalog),te(this.root,async()=>{let r=await this.recoverLocked(),i=r.versions[e]??[],s=new Set(await t()),o=i.at(-1);o&&s.add(o.version);let c=i.filter(a=>!s.has(a.version));return await this.removeLocked(e,r,c),c.map(a=>a.version)})}async removeLocked(e,t,r){r.length&&(await Z(L(this.root,"versions")),await Z(L(this.root,"versions",B(e))),await W(L(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),t.versions[e]=(t.versions[e]??[]).filter(i=>!r.some(s=>s.directory===i.directory)),t.revision++,await W(L(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return te(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let r;try{r=new URL(e)}catch{throw new h("registry_denied","Invalid registry URL")}let i=new URL(t.registry);if(r.protocol!=="https:"||r.origin!==i.origin||r.username||r.password||r.hash||r.search)throw new h("registry_denied","Only the official registry origin is permitted");return r}async download(e,t,r,i="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw r?.aborted?r.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?`${i}_not_found`:"download_failed",`Registry ${i} 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(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.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 s.throwIfAborted(),Buffer.concat(a)}catch(u){throw r?.aborted?r.reason:u instanceof h?u:new h("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await c.cancel().catch(()=>{}),c.releaseLock()}}async check(e,t,r,i){let s=ge(e,this.catalog);if(r&&!ve(r))throw new h("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),c,a=await this.download(o,8*1024*1024,i,"metadata");try{c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{throw new h("registry_invalid","Invalid registry metadata JSON")}return pa(c,s,this.hostVersion,t,r)}async install(e,t,r){let i=ge(e,this.catalog);if(!Vi(t,i,this.hostVersion))throw new h("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(t.dist.tarball,i),Tr,r);return this.installArchive(e,s,t.dist.integrity,t.version,r)}async installArchive(e,t,r,i,s){let o=ge(e,this.catalog);if(!ve(i))throw new h("invalid_version","Choose an exact stable version");if(t.length>Tr)throw new h("download_too_large","Package archive exceeds budget");return ef(t,r),te(this.root,async()=>{let c=await this.recoverLocked();s?.throwIfAborted();let a=await Ui(L(this.root,"staging","stage-"));try{await ji(t,a),s?.throwIfAborted();let l=await Qe(a,e);if(l.version!==i||!je(l.manifest)||!ht(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(p=>l.manifest.capabilities.includes(p)))throw new h("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,c,a,l,r,s)}finally{await Ue(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,r,i,s,o){let c=t.versions[e]?.find(u=>u.version===i.version);if(c&&c.digest!==i.digest)throw new h("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:i.version,digest:i.digest,integrity:s,directory:`${B(e)}/${i.version}-${i.digest}`,installedAt:new Date().toISOString()};if(await Z(L(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 W(L(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await ua(l),p=!0}catch(u){if(!Me(u))throw u}if(p){if((await Qe(l,e)).digest!==i.digest)throw new h("resource_changed","Installed package content was modified")}else await Yu(r,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await W(L(this.root,"installed.json"),t)),await Ue(L(this.root,"install-journal.json")),{...i,root:await Xu(l)}}async installDevArchive(e,t,r){ge(e,this.catalog);let i=await Ku(t),s="sha512-"+Bi("sha512").update(i).digest("base64"),o=await Ui(L(Zu(),"pi-dev-archive-"));try{await ji(i,o);let c=(await Qe(o,e)).version;return await this.installArchive(e,i,s,c,r)}finally{await Ue(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,r){let i=ge(e,this.catalog);return te(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let o=await Ui(L(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await la(t,o);r?.throwIfAborted();let l=L(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],w=s.versions[e]??[],m=u?.contentHash===c?w.find(R=>R.version===u.version):void 0;if(m){let R=await Qe(this.path(m),e);if(R.digest!==m.digest)throw new h("resource_changed","Installed package integrity changed");return R}let f=typeof a.version=="string"?ve(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(R=>ve(R.version)).filter(R=>R&&R.major===f.major&&R.minor===f.minor).map(R=>R.patch)),k=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),y+1),P=`${f.major}.${f.minor}.${k}`;await Qu(L(o,"package.json"),JSON.stringify({...a,version:P},null,2),{flag:"wx",mode:384});let E=await Qe(o,e);if(!ht(this.hostVersion,E.manifest.hostRange))throw new h("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let T=i.requiredCapabilities.filter(R=>!E.manifest.capabilities.includes(R));if(T.length)throw new h("incompatible_plugin",`Package lacks required capabilities: ${T.join(", ")}`);let D="sha512-"+Bi("sha512").update(c).digest("base64"),M=await this.commitStaged(e,s,o,E,D,r);return p[e]={contentHash:c,version:P},await W(l,p),M}finally{await Ue(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=ge(e,this.catalog);return te(this.root,async()=>{let i=await this.recoverLocked(),s=i.versions[e]?.find(c=>c.version===t);if(!s)throw new h("not_installed","Plugin version is not installed");let o=await Qe(this.path(s),e);if(o.digest!==s.digest)throw new h("resource_changed","Installed package integrity changed");if(!ht(this.hostVersion,o.manifest.hostRange)||!r.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){ge(e,this.catalog),await te(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,r,s)})}};import{lstat as Ar,mkdir as tf,open as fa,realpath as ha,readdir as Li,link as rf,rename as nf,unlink as Ze,copyFile as sf,rm as of}from"node:fs/promises";import{dirname as af,isAbsolute as ga,join as O,relative as ma,resolve as cf,sep as zi,win32 as lf}from"node:path";import{randomUUID as qi}from"node:crypto";var $t=192*1024*1024,Ft=512*1024,ya=n=>typeof n=="string"&&/^[a-f0-9-]{36}$/.test(n);function df(n){if(!n||typeof n!="object"||Array.isArray(n))throw new h("invalid_input","Expected object input");return n}function wa(n){if(typeof n!="string"||!/^[\w.-]{1,160}$/.test(n)||n==="."||n==="..")throw new h("invalid_input","Invalid state key");return n}function Vt(n){if(n&&(!ya(n.stateRef)||typeof n.version!="string"||!Number.isSafeInteger(n.generation)||n.generation<1||!Number.isSafeInteger(n.schema)||n.schema<1||typeof n.enabled!="boolean"||typeof n.operationId!="string"))throw new h("invalid_storage","Invalid active plugin record");return n}var et=class{root;pluginId;legacy;checkpoint;constructor(e,t,r,i){this.root=O(e,B(t)),this.pluginId=t,this.legacy=r,this.checkpoint=i}active(){return ee(O(this.root,"active.json")).then(Vt)}async recover(){return te(this.root,async()=>{let e=await this.active(),t=await he(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");Vt(t.next),Vt(t.before);let r=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,c)=>o===null||c===null?o===c:["version","generation","stateRef","schema","enabled","operationId"].every(a=>o[a]===c[a]))(e,r==="committed"?t.next:t.before))throw new h("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await W(O(this.root,"previous.json"),s),r==="committed"){let o=await he(O(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(c=>["version","stateRef"].includes(c))&&await Ze(O(this.root,"fork.json"))}return await Ze(O(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return te(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new h("stale_generation","Plugin activation changed concurrently");let i=await he(O(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).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 s=Vt({...t,generation:e+1,operationId:qi()});await Z(O(this.root,"states")),await Z(O(this.root,"states",s.stateRef)),await W(O(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await W(O(this.root,"active.json"),s)}catch(o){if((await this.active())?.operationId!==s.operationId)throw o}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await W(O(this.root,"previous.json"),r),await Ze(O(this.root,"transition.json")),await Ze(O(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return te(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=qi(),i=O(this.root,"states",r);if(await he(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 W(O(this.root,"fork.json"),{version:1,stateRef:r}),await Z(i);let s=O(this.root,"states",t.stateRef);for(let o of await Li(s)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await X(O(s,o),$t))throw new h("invalid_storage","Missing state file");await sf(O(s,o),O(i,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return te(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await X(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(),r=Vt(await he(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 i=[t,r].filter(l=>!!l),s=O(this.root,"states");await Z(s);let o=await Li(s),c=new Set(i.map(l=>l.stateRef));for(let l of o){if(!ya(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(s,l),u=await Ar(p);if(!u.isDirectory()||u.isSymbolicLink())throw new h("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let w of await Li(p)){let m=await Ar(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),$t);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(k=>!["requestId","inputHash","nextHash","committed"].includes(k))||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(i);for(let l of o)c.has(l)||await of(O(s,l),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let r=await this.active();if(!r||r.generation!==e||t&&!r.enabled)throw new h("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new h("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,r,i="session"){if(i!=="session"&&i!=="workspace")throw new h("invalid_input","Invalid state scope");let s=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return O(this.root,"states",e.stateRef,`${B(s+":state:"+r)}.json`)}async call(e,t,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new h("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=df(r);return te(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(s,e,wa(i.key),i.scope),$t);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(s,e,wa(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new h("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new h("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>$t)throw new h("state_too_large","Plugin state exceeds limit");let a=await ee(o,$t);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)!==i.expectedRevision)throw new h("revision_conflict","Plugin state changed concurrently");let p={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await W(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?Ft:i.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:B(a)}:null}case"workspace.commit":return this.commitFile(s,e,i);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,r=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||ga(t)||lf.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let i=await ha(e),s=cf(i,t),o=ma(i,s);if(!o||o===".."||o.startsWith(`..${zi}`)||ga(o))throw new h("invalid_path","Workspace path escapes root");let c=i,a=o.split(zi);for(let p=0;p<a.length;p++){c=O(c,a[p]);let u;try{u=await Ar(c)}catch(w){if(!Me(w))throw w;if(p<a.length-1){if(!r||ma(i,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await tf(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Ar(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 ha(af(s));if(l!==i&&!l.startsWith(i+zi))throw new h("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,r){if(typeof r.text!="string"||Buffer.byteLength(r.text)>Ft||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new h("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,r.path,!0),o=O(this.root,"states",e.stateRef,`${B(this.scopeKey(t)+":file:"+t.requestId+":"+String(r.path))}.json`),c=B(JSON.stringify(r)),a=B(r.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 fa(`${i}.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(i,Ft),m=w?B(w):null;if(l&&m===a)return{hash:a};if(l?.committed||m!==r.expectedHash)throw new h("file_conflict","Workspace file already exists or changed externally");await W(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=O(s,`.plugin-${qi()}.tmp`);let f=await fa(u,"wx",384);try{await f.writeFile(r.text),await f.sync()}finally{await f.close()}if((await this.fileTarget(t.scope.cwd,r.path)).parent!==s)throw new h("file_conflict","Workspace directory changed during save");let k=await X(i,Ft);if((k?B(k):null)!==r.expectedHash)throw new h("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await rf(u,i)}catch(P){throw P.code==="EEXIST"?new h("file_conflict","Workspace file was created concurrently"):P}await Ze(u),u=void 0}else await nf(u,i),u=void 0;return await W(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await Ze(u).catch(()=>{}),await p.close(),await Ze(`${i}.lock`)}}};import{randomUUID as gf}from"node:crypto";import{fork as pf}from"node:child_process";import{randomUUID as uf}from"node:crypto";import{join as ff}from"node:path";import{EventEmitter as hf}from"node:events";var va=192*1024*1024,Ut=class n{child;pending=new Map;events=new hf;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,r,i){this.package=e,this.generation=t,this.broker=i;let s={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(s[o]=process.env[o]);this.child=pf(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new 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,r,i,s=1e4){let o=new n(e,t,r,i);try{await o.request("initialize",{entry:ff(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},s);let c=await o.request("describe",void 0,s);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,s),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>va){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let i=this.pending.get(r.id);if(!i)return;if(clearTimeout(i.timer),this.pending.delete(r.id),!i.expired){let s=r.error;r.ok===!0?i.resolve(r.value):i.reject(new h(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let i=this.pending.get(r.invocationId);try{if(!i?.invocation||i.expired)throw new h("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(i.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:K(s)})}}}request(e,t,r=3e4,i){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 s=i?.requestId??uf();if(this.pending.has(s))return Promise.reject(new h("duplicate_request","An identical request is still running"));let o={type:"request",id:s,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>va?Promise.reject(new h("message_too_large","Plugin request exceeds limit")):new Promise((c,a)=>{let l=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),a(new h("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:c,reject:a,timer:l,invocation:i,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(s),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 r=()=>{clearTimeout(i),this.events.off("idle",r),t(!0)},i=setTimeout(()=>{this.events.off("idle",r),t(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new 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(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var mf={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Rr=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,r=mf,i){this.broker=e,this.workerEntry=t,this.hooks=r,this.capabilities=i}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await vi(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,r)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,r):this.broker.call(e,t,r);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new 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 r;try{if(r=(await this.broker.recover()).active,r&&r.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 i=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let o=null,c=!1,a=!1;try{if(o=await Ut.start(e,i+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(t))throw new h("drain_pending","Plugin calls are still running; switch deferred without killing them");if(a=!0,await this.hooks.freeze(),s&&!await s.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=r?await this.broker.forkState(i):gf(),p=await this.broker.activate(i,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});c=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await s?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw c||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,t=!1){return this.serialize(async()=>{let r=this.worker,i=this.phaseValue,s=await this.broker.active(),o=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))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 Ut.start(r.package,r.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(a){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),a}}};this.phaseValue="draining";try{let a=async l=>{try{await l()}catch(p){if(!t)throw p}};await a(async()=>{if(r&&!await r.waitForIdle(e))throw new h("drain_pending","Plugin work is still draining; current host retained")}),await a(()=>this.hooks.freeze()),await a(async()=>{if(r&&!await r.waitForIdle(e))throw new h("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(a){try{await o(),this.phaseValue=i,await this.hooks.resume()}catch(l){throw this.phaseValue="failed",l}throw a}let c=!1;return()=>this.serialize(async()=>{c||(await o(),this.phaseValue=i,await this.hooks.resume(),c=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,r;try{r=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!r){if(t)throw this.phaseValue="failed",new 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&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let i=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin still has in-flight work; not killed");if(s=!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(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=i,s&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new 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(i){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),i}})}};import{readFile as ba}from"node:fs/promises";var Cr=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;constructor(e){this.options=e,this.installer=new gt({root:be(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new xr(e.capabilities):void 0;this.scheduler=new _r({invoke:async(r,i)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:yf(),scope:s,kind:"action",action:i.action,input:{schedule:i.id}})},onError:(r,i,s)=>e.onScheduleError?.(r,i.id,s),...e.scheduleTimers});for(let r of this.installer.catalog){let i=new et(be(e.root,"data"),r.id,e.legacy?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new Rr(i,e.workerEntry,{validateCandidate:o=>s.validateCandidate?.(o),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async o=>{if(o.enabled){let c=await this.installer.load(r.id,o.version);this.packages.set(r.id,c),this.assetTokens.set(r.id,wf(24).toString("base64url"));try{this.scheduler.start(r.id,ut(c.manifest).schedules)}catch(a){this.scheduler.stop(r.id),this.errors.set(r.id,K(a))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return t?i=>this.installer.installDevDirectory(e,t,i):r?i=>this.installer.installDevArchive(e,r,i):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){ge(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 r=(this.operations.get(e)??Promise.resolve()).then(t,t);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),i=>{this.errors.set(e,K(i))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,r=!1){return this.options.lifecycle?this.options.lifecycle(e,t,r):t()}async policies(){let e=await ee(be(this.options.root,"policies","policies.json"));if(!e){if(await X(be(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,r]of Object.entries(e))if(this.installer.catalog.some(i=>i.id===t)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new h("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await ee(be(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await te(be(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await W(be(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,r,i){try{let s=await this.installer.check(e,t,r,i),o=!t||Se(s.version,t)>0;return o?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:s.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:K(s).code,message:K(s).message}),s}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new h("invalid_input","Invalid plugin update policy");await te(be(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await W(be(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return te(mr(this.options.root),async()=>{let e=await Pi(this.options.root);if(!e)return{intent:e,admitted:!1};if(!Ii(e))return e.phase==="required-action"&&await yr(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await ki(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await ki(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await ba(this.options.workerEntry)).equals(await ba(be(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(t){return await yr(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${K(t).message}; data retained`}),{intent:e,admitted:!1}}return await yr(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await te(be(this.options.root,"policies"),async()=>{let t=await this.policies();await W(be(this.options.root,"policies","policies.json"),t)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let t of this.installer.catalog){let r=this.supervisor(t.id),i=await r.broker.active();if(i?.enabled)try{let s=await this.compatiblePackage(t.id,i.version);await this.lifecycle(t.id,()=>r.replace(s)),this.packages.set(t.id,s),e||await this.collectSettled(t.id)}catch(s){let o=K(s),c=["runtime_owned","storage_busy"].includes(o.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(t.id,{...o,message:`Plugin unavailable: startup failed (${o.code}): ${o.message}; data retained. ${c}`})}}}async compatiblePackage(e,t){try{return await this.installer.load(e,t)}catch(r){if(K(r).code!=="incompatible_plugin")throw r;let i=((await this.installer.inventory()).versions[e]??[]).map(s=>s.version).filter(s=>s!==t).sort((s,o)=>Se(o,s));for(let s of i)try{return await this.installer.load(e,s)}catch{}throw r}}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let o=this.supervisor(s.id),c=await o.broker.active(),a=this.packages.get(s.id),l=(e.versions[s.id]??[]).map(p=>p.version).sort((p,u)=>Se(u,p));return{id:s.id,name:s.name,description:s.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[s.id]?.updatePolicy??"notify",pinnedVersion:t[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...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(s.id)}/${this.assetTokens.get(s.id)}/${a.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,r,i){return this.serialize(e,async()=>{let s=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],c=o.map(l=>l.version).sort((l,p)=>Se(p,l))[0],a=await(async()=>{switch(t){case"check":return this.isDevPlugin(e)?{version:c??null,dev:!0}:{version:(await this.check(e,c,void 0,i)).version};case"install":{let l=this.devSource(e);if(l){let w=await l(i);return await this.recordDevSync(e,w.version),{installed:!0,version:w.version}}let p=await this.check(e,c,r,i),u=await this.installer.install(e,p,i);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:u.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:u.version}}case"enable":{let l=r??c;if(!l)throw new h("not_installed","Install the plugin first");let p=await this.installer.load(e,l),u=await this.lifecycle(e,()=>s.replace(p));return u.pending||this.packages.set(e,p),u}case"retry":{let l=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!c)throw new h("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let f=await l(i),y=await s.broker.active();if(await this.recordDevSync(e,f.version),!y?.enabled)return{installed:!0,enabled:!1,version:f.version};if(y.version===f.version&&!s.pendingVersion)return{unchanged:!0,version:f.version};let k=await this.lifecycle(e,()=>s.replace(f));return k.pending||this.packages.set(e,f),k}let p=await this.check(e,c,r,i),u=await s.broker.active();if(p.version===c&&(!u?.enabled||u.version===c)&&!s.pendingVersion)return{unchanged:!0,version:c};let w=p.version===c?await this.installer.load(e,c):await this.installer.install(e,p,i);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version: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,()=>s.replace(w));return m.pending||this.packages.set(e,w),m}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new h("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=K(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async r=>this.installer.collect(e,async()=>{let i=(await this.policies())[e];return[...r.map(s=>s.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...i?.pinnedVersion?[i.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new h("stale_generation","Reconnect the plugin view before editing",{status:409})):i.invoke(r)}flush(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new h("stale_generation","Flush generation changed",{status:409})):i.flushAction(r)}async asset(e,t,r){let i=this.packages.get(e);if(!i)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(i.version,(s.get(i.version)??0)+1);try{return await aa(i,r,t)}finally{let o=s.get(i.version)-1;o?s.set(i.version,o):s.delete(i.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let r;try{r=decodeURIComponent(t[1])}catch{return null}let i=this.assetTokens.get(r),s=Buffer.from(t[2]);return!i||s.length!==Buffer.byteLength(i)||!vf(s,Buffer.from(i))?null:this.asset(r,t[3],t[4])}async reconcileHostUpgrade(){if(_o(await Pi(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),r=!0;for(let i of this.installer.catalog){let s=e.versions[i.id];if(s?.length)try{let o=await this.supervisor(i.id).broker.active(),c=o?.enabled?o.version:s.map(l=>l.version).sort((l,p)=>Se(p,l))[0];try{await this.installer.load(i.id,c);continue}catch(l){if(K(l).code!=="incompatible_plugin")throw l}let a=await this.manage(i.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(r=!1)}catch(o){r=!1;let c=K(o);this.errors.set(i.id,c),await this.recordCheck(i.id,{status:"failed",code:c.code,message:c.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,t){let r=new gt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),i=await this.installer.inventory();for(let s of this.installer.catalog){let o=(i.versions[s.id]??[]).map(l=>l.version).sort((l,p)=>Se(p,l)),c=await this.supervisor(s.id).broker.active();if(!o.length||this.isDevPlugin(s.id))continue;let a=!1;for(let l of new Set([...c?.enabled?[c.version]:[],...o]))try{await r.load(s.id,l),a=!0;break}catch{}if(!a)try{let l=await r.check(s.id,o[0],void 0,t),p=await r.install(s.id,l,t);await this.recordCheck(s.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(l){t?.throwIfAborted();let p=K(l);await this.recordCheck(s.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let t=new gt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),i=[];for(let s of this.installer.catalog){let o=r.versions[s.id],c=await this.supervisor(s.id).broker.active();if(!c?.enabled)continue;if(!o?.length){i.push({pluginId:s.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let a=[c.version,...o.map(u=>u.version).sort((u,w)=>Se(w,u))],l=!1,p="";for(let u of new Set(a))try{await t.load(s.id,u),l=!0;break}catch(w){p||=K(w).message}l||i.push({pluginId:s.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return i}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],r=async()=>{let i=await Promise.allSettled(t.map(o=>o()));this.closing=!1;let s=i.find(o=>o.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let i of this.supervisors.values())t.push(await i.suspendForRestart(void 0,e));return r}catch(i){throw await r(),i}}};import{randomUUID as bf}from"node:crypto";var N=n=>Object.assign(new Error(n),{status:409,code:"view_barrier"}),Bt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,t,r=2e4,i=15e3,s=12e4){this.pluginId=e,this.generation=t,this.pollMs=r,this.freezeMs=i,this.staleMs=s}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&r.scope.ownerId===t.ownerId&&r.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||t.ownerId!==r.scope.ownerId||t.workspaceId!==r.scope.workspaceId||t.sessionId!==r.identity.sessionId)throw N("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw N("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,t,r=++this.sequence){return e.commands.push({id:r,type:t,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw N("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw N("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw N("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw N("Invalid registration capability");let o=e.viewToken??bf();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw N("View initialization was cancelled; register a new document identity");let c=this.views.get(o);if(c){if(!this.sameScope(c,e,t)||c.kind!==e.kind)throw N("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw N("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw N("Invalid view capability");let r=this.views.get(e.viewToken),i=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,t))throw N("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw N("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let o=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:o}}}if(r&&this.sameScope(r,e,t)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw N("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw N("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&i&&this.sameScope(i,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!i){if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");if(this.switching)throw N("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,t))throw N("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw N("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw N("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw N("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(N("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw N("Invalid acknowledgement");let o=r.commands.find(c=>c.id===e.commandId);if(!o)throw N("Unknown command acknowledgement");r.commands=r.commands.filter(c=>c.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(N(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw N("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw N("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw N("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw N("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw N("Invalid poll cursor");if(r.waiter)throw N("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw N("Invalid poll mode");return!e.immediate&&!r.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),r.waiter=void 0,o()}r.waiter=a}),{viewToken:r.token,commands:r.commands.filter(o=>o.id>e.after)}}default:throw N("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw N("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(r=>r.activeActions||r.kind!=="controller"&&!r.frozen&&(r.busy||!this.immediate&&["editor","workspace"].includes(r.kind)));throw N(`Close editors before updating; old version retained. Pending views: ${t.map(r=>`${r.kind}:${r.identity.mountId}${r.activeActions?` (action in flight x${r.activeActions})`:r.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let i=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>i(),reject:s=>i(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));i(N(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||i()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw N("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(N("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(N("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var kf="@chengzhiyi/pi-excalidraw",Pf={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"}}},If="@chengzhiyi/pi-github",Sf={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"}}},ka=new Map([[kf,Pf],[If,Sf]]);function Gi(n,e){let t=n.get(e);if(!t)throw new h("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as Ef}from"node:crypto";var xf="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"}),_f="Ov23limJmKiuu8cOP83E";function Ji(n,e,t=process.env){if(n==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||_f,scope:"repo",createUrl:xf}}var Tf="https://github.com/login/device/code",Af="https://github.com/login/oauth/access_token",Rf=8,Nr=class{flows=new Map;fetcher;now;constructor(e=(r,i)=>fetch(r,{...i,signal:i.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new h("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let i=await r.json().catch(()=>null);if(!i||typeof i!="object"||!r.ok&&!("error"in i))throw new h("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return i}async start(e,t,r){if(!r.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>=Rf)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let i=await this.post(Tf,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:o,verification_uri:c}=i,a=Number(i.expires_in),l=Math.max(Number(i.interval)||5,1);if(typeof s!="string"||typeof o!="string"||typeof c!="string"||!c.startsWith("https://github.com/")||!Number.isFinite(a))throw new h("oauth_failed",typeof i.error_description=="string"?i.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=Ef();return this.flows.set(p,{pluginId:e,name:t,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+a*1e3,interval:l,nextPoll:this.now()+l*1e3}),{deviceId:p,userCode:o,verificationUri:c,interval:l,expiresIn:a}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let r=await this.post(Af,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:t.pluginId,name:t.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return t.interval+=5,t.nextPoll=this.now()+t.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as Ia,readFileSync as Sa,statSync as Cf}from"node:fs";import{lstat as Nf,readdir as Df,writeFile as Of,mkdir as Hf,rename as Mf}from"node:fs/promises";import{delimiter as Wf,dirname as jf,isAbsolute as $f,join as tt,resolve as Lt}from"node:path";var Pa="@chengzhiyi/pi-github",Hr={[Pa]:{id:Pa,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"]}},Ea=()=>Object.keys(Hr).join(", ");function Ff(n=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,r=[],i="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let s of(n??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=s.lastIndexOf("="),c=s.slice(0,o),a=s.slice(o+1),l=Hr[c],p=o<1?`entry "${s}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?Ia(Lt(a))?null:`archive not found: ${Lt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Ea()})`;if(p){r.push({level:"error",source:i,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,Lt(a))}return{catalog:e,archives:t,notices:r}}var xa=n=>tt(n,"pi-web","hosted-dev.json"),_a=n=>tt(n,"pi-web","hosted-dev-status.json");function Vf(n,e,t=process.cwd()){let r=[],i=[],s=(n.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(Wf).map(c=>c.trim()).filter(Boolean);for(let c of s)r.push({path:Lt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=s.length>0;if(e&&Ia(e)){o=!0;try{let c=JSON.parse(Sa(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"||!$f(l)?i.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):r.push({path:Lt(l),source:e})}catch(c){i.push({level:"error",source:e,message:`cannot read dev configuration: ${c instanceof Error?c.message:String(c)}`})}}return{specs:r,notices:i,configured:o}}function Uf(n){let e=(i,s)=>({notice:{level:"error",source:n.source,...s?{pluginId:s}:{},message:`${n.path}: ${i}`}}),t;try{t=Cf(n.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(Sa(tt(n.path,"package.json"),"utf8"))}catch(i){return e(i.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof r.name!="string"?e("package.json has no name"):Hr[r.name]?je(r.piWebapp)?{pluginId:r.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name):e(`unknown plugin id "${r.name}" (known: ${Ea()})`)}var Dr=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=Ff(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let t=Vf(this.env,this.configPath,this.cwd),r=[],i=new Map,s=new Map;for(let o of t.specs){let c=Uf(o);if(c.notice){r.push(c.notice);continue}let a=c.pluginId;if(i.has(a)){r.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${i.get(a)}`});continue}if(this.archives.has(a)&&r.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${a}; the dev directory wins`}),!this.catalog.some(l=>l.id===a)){if(!e){r.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: ${a} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}this.catalog.push(Hr[a])}i.set(a,o.path),s.set(a,o.source)}for(let o of[...this.roots.keys()])i.has(o)||this.roots.delete(o);for(let[o,c]of i)this.roots.set(o,c);this.rootSource.clear();for(let[o,c]of s)this.rootSource.set(o,c);return this.fileNotices=t.notices,this.rootNotices=r,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Or=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${K(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,r]of e){let i=this.roots.get(t);(!i||i.root!==r)&&(i={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,i));let s=await Bf(r);if(s===null){this.set(t,i,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),i.seen=void 0;continue}if(s!==i.seen){i.seen=s;continue}s===i.applied||this.stopped||await this.apply(t,i,s)}await this.publish()}set(e,t,r,i={}){let s=t.state!==r||t.message!==i.message||t.version!==i.version;t.state=r,t.message=i.message,t.code=i.code,t.version=i.version??t.version,s&&(t.at=new Date().toISOString(),this.log(`${e}: ${r}${i.version?` ${i.version}`:""}${i.message?` \u2014 ${i.message}`:""}`))}async apply(e,t,r){this.set(e,t,"switching");try{let s=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=r,s?.installed?s.pendingVersion?this.set(e,t,"pending",{version:s.version,message:`Waiting for editors to close before switching to ${s.pendingVersion}`}):this.set(e,t,"synced",{version:s.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(i){let s=K(i);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(s.code)||(t.applied=r),s.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:s.code,message:`${s.message} (${s.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let i=Object.fromEntries([...this.roots].map(([c,a])=>[c,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(c=>c.id),plugins:i,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let o=`${r}.${process.pid}.tmp`;try{await Hf(jf(r),{recursive:!0}),await Of(o,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await Mf(o,r)}catch{}}};async function Bf(n){let e=[],t=async(r,i)=>{let s=await Nf(r);e.push(`${i}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await t(tt(n,"package.json"),"package.json");let r=async(i,s,o)=>{if(!(o>16||e.length>8192))for(let c of(await Df(i,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await r(tt(i,c.name),`${s}/${c.name}`,o+1):await t(tt(i,c.name),`${s}/${c.name}`)};if(await r(tt(n,"dist"),"dist",0),!e.some(i=>i.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function zf(n){try{return[...ut(n).secrets]}catch{return[]}}var Mr=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Nr;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??ka,e.dev?.enabled&&(this.devWatcher=new Or({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let r=await this.inventory();return r.plugins.find(i=>i.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):r}}})),this.adapter=new Ir({policy:(t,r)=>{let i=e.policy?.(t,r);return{...i,enabled:!this.recovery.has(t)&&this.manager.tools.some(s=>s.pluginId===t)&&i?.enabled!==!1}},invoke:async(t,r,i)=>{i?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(c=>c.pluginId===t);if(!s)throw new h("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,s.generation,r);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Cr({...e,lifecycle:(t,r,i)=>this.lifecycle(t,r,i),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(Gi(this.trusted,t).tools).length)throw new h("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,r),this.adapter.validateChange(t,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async r=>{try{let i=r.enabled?this.manager.tools.find(s=>s.pluginId===t)?.descriptors:[];if(!i)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,i),r.enabled){let s=await this.manager.installer.load(t,r.version);this.documents.set(t,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:zf(s.manifest)})}else this.documents.delete(t);this.adapter.change(t,i),await this.coordinator(t).committed(r),e.changed?.(),this.recovery.delete(t)}catch(i){throw this.recovery.set(t,i),await this.coordinator(t).committed(r).catch(()=>{}),i}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,r,i)=>{let s=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!s)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(r))throw new h("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return i===null?await s.delete(t,r):await s.set(t,r,i),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let r=this.options.capabilities?.secrets;if(!r)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 s=this.documents.get(t.pluginId)?.secrets.includes(t.name)?Ji(t.pluginId,t.name):void 0;if(!s)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,s)}let i=await this.deviceFlows.poll(t.deviceId);return i.status!=="granted"?{status:i.status}:(await r.set(i.pluginId,i.name,i.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,r)=>{if(!this.options.approvals)throw new h("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,r),this.inventory()},action:(t,r)=>this.action(t,r?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new h("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let r=t,i=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(i))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let r=Gi(this.trusted,e);for(let i of t)if(!Object.hasOwn(r.tools,i.name)||r.tools[i.name]!==i.action||i.readonly!==r.readonlyActions.includes(i.action))throw new 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 r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||t&&(r.cwd!==t.cwd||r.workspaceId!==t.workspaceId))throw new h("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let r=this.manager.tools.find(i=>i.pluginId===e);if(!r||r.generation!==t)throw new h("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,t=!1){let r=this.queue.then(async()=>{if(this.closing&&!t)throw new h("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,t,r=!1){let i=this.switches.then(async()=>{if(this.closing&&!r)throw new h("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await t();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new et(Ki(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new h("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=i.catch(()=>{}),i.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let t,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(i=>{t=setTimeout(()=>i(!1),e),t.unref?.()})])}finally{clearTimeout(t)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Ne)try{let t=await new et(Ki(this.options.root,"data"),e.id).active();this.views.set(e.id,new Bt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new Bt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Ki(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await Z(this.options.root),await W(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Ne)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,r=new Map;for(let i of e.plugins){let s=i.enabled?this.documents.get(i.id)?.secrets??[]:[];t&&s.length&&r.set(i.id,await Promise.all(s.map(async o=>{let c=Ji(i.id,o);return{name:o,configured:await t.has(i.id,o),...c?{signIn:c.clientId?"browser":"token-page",...c.createUrl?{createUrl:c.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(i=>({pluginId:i.id,name:i.name,official:i.official,installed:i.installed,enabled:i.enabled,description:i.description,...r.has(i.id)?{secrets:r.get(i.id)}:{},icon:(this.options.catalog??Ne).find(s=>s.id===i.id)?.icon,hasRetainedData:i.activeVersion!==null,phase:this.recovery.has(i.id)?"reconnect-required":i.phase,updatePolicy:i.updatePolicy,pinnedVersion:i.pinnedVersion,updateDiagnostic:i.updateDiagnostic,...i.enabled&&i.activeVersion?{version:i.activeVersion}:i.version?{version:i.version}:{},...i.availableVersion?{availableVersion:i.availableVersion}:{},...i.pendingVersion?{pendingVersion:i.pendingVersion}:{},...i.generation!==null?{generation:i.generation}:{},...this.recovery.has(i.id)||i.error?{error:this.recovery.get(i.id)instanceof Error?this.recovery.get(i.id).message:i.error?.message??"Recovery required",errorCode:this.recovery.has(i.id)?"reconnect_required":i.error?.code}:{},...i.enabled&&i.assetBase&&this.documents.has(i.id)&&this.trusted.has(i.id)?{documentUrl:i.assetBase+this.documents.get(i.id).document,controllerUrl:i.assetBase+this.documents.get(i.id).controller,contribution:structuredClone(this.trusted.get(i.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new h("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.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 r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new h("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let i=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||i&&typeof i=="object"&&"reconnectRequired"in i&&i.reconnectRequired)throw new h("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new h("action_denied","Action is not reviewed by this host",{status:403});let i=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:Lf(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);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,{...s,kind:"action"})}finally{i()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let s of this.views.values())s.allowImmediateReopen(!0);let t=await this.manager.suspendForRestart(e),r=!1,i=async()=>{if(!r)try{await t(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(t){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),t}finally{for(let t of this.views.values())t.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as qf,readdir as Gf,unlink as Jf}from"node:fs/promises";import{join as mt}from"node:path";import{randomUUID as Kf}from"node:crypto";var Xi="hosted-migration.json";function Ta(n,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:i}=t.scope,s=mt(n,B(JSON.stringify([r,i])));await Z(n),await Z(s);let o=mt(s,"scope.lock"),c;try{c=await qf(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:Kf()}));let a=await ee(mt(s,Xi));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Gf(s),p=[];for(let w of l){if(w==="scope.lock"||w==="focus.json"||w===Xi||/^[\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(mt(s,w),3*512*1024);if(!m||m.version!==1||m.cwd!==r||m.sessionId!==i||!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(mt(s,"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 W(mt(s,Xi),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Jf(o)}}}import{join as nh}from"node:path";import{randomUUID as Xf}from"node:crypto";var Yf=6e4,Wr=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:r,title:i})=>({id:e,pluginId:t,sessionId:r,title:i}))}async authorize(e,t){let r=this.entries.get(t);if(r&&r.pluginId!==e)throw new h("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new h("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<Yf?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:Xf(),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 r=[...this.entries.values()].find(i=>i.id===e&&i.status==="pending");if(!r)throw new h("unknown_approval","No such pending approval",{status:404});r.status=t?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as Qf,readFile as Zf,rename as eh,writeFile as th}from"node:fs/promises";import{randomUUID as rh,createHash as ih}from"node:crypto";import{join as Aa}from"node:path";var jr=class{dir;queue=Promise.resolve();constructor(e){this.dir=Aa(e,"secrets")}file=e=>Aa(this.dir,`${ih("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Zf(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Me(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(r=>r!==null)}set(e,t,r){return this.mutate(e,i=>{i[t]=r})}delete(e,t){return this.mutate(e,r=>{delete r[t]})}mutate(e,t){return this.serialize(async()=>{let r=await this.read(e);t(r),await Qf(this.dir,{recursive:!0,mode:448});let i=`${this.file(e)}.${rh()}.tmp`;await th(i,JSON.stringify(r),{mode:384}),await eh(i,this.file(e))})}};function Ra(n,e){let t=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:i,title:s,prompt:o}){let c=await n.createDetached(i,r,s);try{await n.sendDetached(c,o,!1)}catch(a){throw await n.releaseDetached(c),a}return{sessionId:c}},ownerOf:r=>n.detachedOwner(r),activeCount:r=>n.detachedCount(r),async send(r,i,s){let o=n.detachedOwner(r);if(s==="execute"&&(!o||!await e(o,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await n.sendDetached(r,i,s==="execute")},abort:r=>n.abortDetached(r),release:r=>n.releaseDetached(r),async events(r,i){let s=n.detachedEvents(r,i);return{events:s.events.map(t),next:s.next}}}}var sh="scheduler";function Ca(n){let e=new Wr({describe:n.sessionTitle,changed:n.changed}),t=()=>{let i=n.sessions();if(!i)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return i},r={createDetached:(...i)=>t().createDetached(...i),detachedOwner:i=>n.sessions()?.detachedOwner(i)??null,detachedCount:i=>n.sessions()?.detachedCount(i)??0,sendDetached:(...i)=>t().sendDetached(...i),abortDetached:i=>t().abortDetached(i),releaseDetached:async i=>{e.forget(i),await t().releaseDetached(i)},detachedEvents:(...i)=>t().detachedEvents(...i)};return{approvals:e,capabilities:{secrets:new jr(nh(n.root,"capability-secrets")),sessions:Ra(r,(i,s)=>e.authorize(i,s))},scheduledScope:()=>{let i=n.activeWorkspace();if(!i)return null;try{return n.trustedScope(i,sh)}catch{return null}}}}async function oh(){for(let n of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=ir(n),t=new Ee({env:n,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:xt,buildId:Ie,browser:ir({}).browser}}async function Na(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let n=new Ee({monitor:!1});try{if(await n.ready,!n.enabled)throw new Error("Sentry verification transport is disabled");let e=n.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await n.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:xt,buildId:Ie}}finally{await n.close()}}var zt=vt(ch(ph(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),mh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[mh]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new He(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:De()}),re()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Xe,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Xe;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new He(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:De()}),re()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function $r(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var wh=null;function yh(){return wh??=uh.create({refreshOnCreate:!1})}var Fr=new Map;async function yt(){let n=await yh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Fr.keys())t.has(r)||(n.unregisterProvider(r),Fr.delete(r));for(let r of t){let i=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),o=i??s;!o||Fr.get(r)===o||(i?n.registerNativeProvider(i):s&&n.registerProvider(r,s),Fr.set(r,o))}return await n.refresh({allowNetwork:!1}),n}function ie(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():De()}function De(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...Vs(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 rn(n,e,t,r,i){let s=de(n);Oe({...De(),idle:s.isIdle()},e,i);let o=s.isIdle();o&&dt(()=>d.hosted?.adapter.assertAdmission(),r,(c,a)=>d.bridge?.reportError?.(c,a)),o&&(d.operation=r);try{let c=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===n)await d.replacementContext.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:i});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:i})}d.current?.sessionManager.getSessionId()===n&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:De()})}catch(c){throw o&&(d.operation=void 0),c}}function Zi(){let n=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!n||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==n||d.tuiAgentError)return!1;let r=De();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!r.paused&&!r.interactions.length};d.tuiPrompts.schedule(t,(r,i,s)=>rn(n,r,i,s))}function se(n){if(ie().sessionId!==n)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function Wa(){let n=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=ie(),i=d.current?De():null,s=await Ge(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=i?await Ge(i.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await tn.listAll(),a=d.workspaceSessions?.retainedSessions()??[];i&&o&&a.push({sessionId:i.sessionId,cwd:o,path:null,name:i.name,modified:i.messages.at(-1)?.timestamp??new Date().toISOString(),idle:i.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&i.idle&&d.tuiPrompts.length===0&&!i.messages.some(p=>p.role==="user")});let l=(await Promise.all(n.map(async p=>{let w=(await ct(p.path,c).catch(m=>(m instanceof Ct?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=w.findIndex(k=>k.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===s&&!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:n,activeId:e,sessions:l}}var Oa=0;async function re(){if(!d.bridge)return;let n=++Oa;try{let e=await Wa();n===Oa&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function en(n,e=!1){let t=d.workspaces?.get(n);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await _e(t.path),!e&&d.current&&t.path===await Ge(d.current.cwd)&&!d.workspaceSessions?.hasWorkspace(t.path))d.selected="tui",d.activeWorkspaceId=n,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:ie()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await d.workspaceSessions.reuseBlank(t.path))&&await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=n,d.bridge?.publish({type:"snapshot",session:ie()})}await re()}async function Ha(n,e,t){let r=d.workspaces?.get(n);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let i=await _e(r.path);if(d.workspaceSessions?.hasSession(i,e)||d.current?.sessionManager.getSessionId()===e&&await Ge(d.current.cwd)===i)return r;if(!(await ct(i)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function de(n){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==n)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function ae(n){d.current=n,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:ie()})}function ja(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let n=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!n)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return fh.create(n,void 0,{projectTrusted:e})}async function $a(){let n=ja(),e=i=>({packages:(i.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:i.extensions??[],skills:i.skills??[]}),t=new Ma({cwd:ie().cwd,agentDir:me(),settingsManager:n}),r=bo(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:n.isProjectTrusted(),global:e(n.getGlobalSettings()),project:e(n.getProjectSettings()),installed:r}}async function vh(n){se(n.sessionId);let e=d.selected==="tui"?de(n.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=ja();if(n.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=n.value.trim(),i=n.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(n.kind==="packages"){let s=new Ma({cwd:ie().cwd,agentDir:me(),settingsManager:t});n.action==="add"?await s.installAndPersist(r,{local:n.scope==="project"}):await s.removeAndPersist(r,{local:n.scope==="project"})}else if(n.kind==="extensions"){let s=i.extensions??[],o=n.action==="add"?[...new Set([...s,r])]:s.filter(c=>c!==r);n.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let s=i.skills??[],o=n.action==="add"?[...new Set([...s,r])]:s.filter(c=>c!==r);n.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&ae(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await $a()}function Vr(n,e=wi){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=Yi(a);return{cwd:p,sessionId:l,workspaceId:Da("sha256").update(p).digest("hex")}},r=wt(me(),"pi-web","hosted"),i=new Dr({configPath:xa(me())});d.hosted??=new Mr({root:r,...i.enabled?{dev:i,devStatusPath:_a(me())}:{},...i.catalog.length?{catalog:[...Ne,...i.catalog],devArchives:i.archives,devRoots:i.roots}:{},...Ca({root:r,sessions:()=>d.workspaceSessions,activeWorkspace:()=>d.workspaceSessions?.path??null,trustedScope:t,sessionTitle:a=>d.workspaceSessions?.retainedSessions().find(l=>l.sessionId===a)?.name,changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(lh(vt(zt,"../../package.json"),"utf8")).version,packageRoot:vt(zt,"../.."),workerEntry:vt(zt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${Da("sha256").update(me()).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:()=>Ta(wt(me(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Zi),d.pi=n,d.tools?.clear(),d.tools=new lt({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(a,l)=>d.bridge?.reportError?.(a,l),breadcrumb:(a,l)=>d.bridge?.breadcrumb?.(a,l),anonymize:a=>d.telemetry?.session(a)??"unavailable"});let s=a=>({...d.operation,session:d.telemetry?.session(a.sessionManager.getSessionId()),piVersion:Qi,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new at(n.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=n.events.on(dr,()=>{d.selected==="tui"&&d.current&&ae(d.current)})};o(),n.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(n,t(l.cwd,l.sessionManager.getSessionId())),d.hosted&&!await d.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new He(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:De()}),re()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Ke.discover(l.cwd,l.isProjectTrusted?.()??!1);if(d.current!==l)return;d.tuiCatalog=p}d.replacementSessionId!==l.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),ae(l),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(l.cwd).then(async p=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==l.sessionManager.getSessionId()||(d.activeWorkspaceId=p.id,await re())}).catch(p=>{d.bridge?.publish({type:"error",message:p instanceof Error?p.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(p,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&l.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,c(l).catch(p=>{l.ui.notify(p instanceof Error?p.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),n.on("agent_start",(a,l)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",s(l)),ae(l),re()}),n.on("agent_end",(a,l)=>ae(l)),n.on("agent_settled",(a,l)=>{d.bridge?.breadcrumb?.("agent_end",s(l)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Zi(),ae(l),re()}),n.on("tool_execution_start",(a,l)=>{d.tools?.start(a,s(l))}),n.on("tool_execution_end",(a,l)=>{d.tools?.end(a,s(l))}),n.on("model_select",(a,l)=>ae(l)),n.on("thinking_level_select",(a,l)=>ae(l)),n.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:Qi});d.selected==="tui"&&d.bridge?.publish({type:"error",message:a.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:p,inTranscript:!0,...d.operation})}a.message.role==="toolResult"&&d.tools?.message(a.message,s(l)),a.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&a.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),ae(l),re()}),n.on("session_info_changed",(a,l)=>ae(l)),n.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:qe(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}))}),n.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 Ee;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=n,d.tuiCatalog=await Ke.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new lr(zs(me())),await d.workspaces.load());try{await d.workspaces.discover((await tn.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!==Ie||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 Ee}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 hr(f=>{d.selected==="sdk"&&d.bridge?.publish(f)},()=>d.current?.model,f=>{try{return!!d.current&&Yi(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"},()=>{re()},[],{adapter:d.hosted.adapter,scope:t}),w&&await d.workspaceSessions.open(w.path,{sessionManager:w.sessionManager});let m={hosted:d.hosted?.handlers,selfUpdate:new Pr({agentDir:me(),packageRoot:vt(zt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:f=>d.hosted.manager.hostUpdateWarnings(f),prefetchPlugins:(f,y)=>d.hosted.manager.prefetchForHost(f,y),beforeRestart:f=>d.hosted.prepareRestart(f)}),snapshot:ie,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(Yi(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=$r();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>$r()?.asset(f)??null,async invokePluginAction(f,y,k,P){if(se(f),!$r()?.has(y))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,T=d.tuiGeneration,D=d.workspaceSessions?.session,M={requestId:gh(),sessionId:f,pluginId:y,action:k,input:P},R=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(M):await pr(d.pi.events,M,15e3,d.tuiWaitController.signal);if(se(f),E!==d.selected||(E==="tui"?T!==d.tuiGeneration:D!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&ae(d.current),R},async resolvePluginInteraction(f,y,k,P){if(se(f),!$r()?.has(y))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(f,y,k,P):d.interactions.resolve(f,y,k,P)},image(f,y,k){se(f);let E=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(D=>D.id===y);if(E?.type!=="message"||E.message.role!=="user"||!Array.isArray(E.message.content))return null;let T=E.message.content[k];return T?.type!=="image"?null:{data:Buffer.from(T.data,"base64"),mimeType:T.mimeType}},async workspaces(){return Wa()},async addWorkspace(f,y){let k=await d.workspaces.add(f,y);try{await en(k.id,!0)}catch(P){throw await re(),P}},async selectWorkspace(f){await en(f)},async newSessionInWorkspace(f){await en(f,!0)},async removeWorkspace(f){if(f===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(f),await re()},async selectSession(f,y,k){let P=d.workspaces?.get(f);if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await _e(P.path),y===d.current?.sessionManager.getSessionId()&&P.path===await Ge(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:ie()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===y&&d.workspaceSessions.path===P.path)return;if(d.workspaceSessions?.hasSession(P.path,y))await d.workspaceSessions.open(P.path,{sessionId:y});else{if(!(await ct(P.path)).some(T=>T.id===y&&T.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:ie()})}await re()},async renameSession(f,y,k,P){let E=P.replace(/\s+/g," ").trim();if(E.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await Ha(f,y,k),d.current?.sessionManager.getSessionId()===y&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(y,E)||tn.open(k).appendSessionInfo(E),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===y&&d.bridge?.publish({type:"snapshot",session:ie()}),await re()},async deleteSession(f,y,k){let P=await Ha(f,y,k);if(d.current?.sessionManager.getSessionId()===y)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(y)??null,T=E?.path??(k||null);T&&await vo(T,me()),E?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(P.path,"new"),d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:ie()})),await re()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let f=d.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let y=f.scopedModels?.map(k=>`${k.model.provider}/${k.model.id}`)??[];return f.modelRegistry.getAvailable().filter(k=>y.length===0||y.includes(`${k.provider}/${k.id}`)).map(k=>({provider:k.provider,id:k.id,name:k.name}))},async providers(){let f=await yt(),y=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:y.has(k.id),methods:[k.auth.apiKey?.login?"api_key":null,k.auth.oauth?"oauth":null].filter(P=>P!==null)}))},async providerModels(f){let y=await yt();return Es(wt(me(),"models.json"),f,y)},async updateProviderModel(f,y,k){if(se(f),d.selected==="tui"?!de(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=ie().model;if(k.action==="remove"&&P===`${y}/${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===`${y}/${k.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let E=await yt();await xs(wt(me(),"models.json"),y,k,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 T=k.action==="save"?k.model.id:k.action==="base_url"&&P?.startsWith(`${y}/`)?P.slice(y.length+1):null;if(T&&P===`${y}/${T}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(y,T)}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 D=de(f),M=D.modelRegistry.find(y,T);if(!M||!d.pi||!await d.pi.setModel(M))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");ae(D)}},async logoutProvider(f,y){if(se(f),d.selected==="tui"?!de(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 yt();if(!(await k.listCredentials()).some(P=>P.providerId===y))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await k.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,k){let P=await yt();await P.login(f,y,vs(f,y,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,y){if(se(f),d.selected==="tui"?!de(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 yt();if(k.getProvider(y.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await bs(wt(me(),"models.json"),y),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(se(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:ie()});return}let y=de(f);if(!y.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");y.compact()},async setModel(f,y,k){if(se(f),d.selected==="sdk"){await d.workspaceSessions.setModel(y,k);return}let P=de(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(y,k);if(!E||!P.modelRegistry.getAvailable().some(T=>T.provider===y&&T.id===k))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(E))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");ae(P)},async setThinkingLevel(f,y){if(se(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:ie()});return}let P=de(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||!hh(P.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(P)},config:$a,updateConfig:vh,async send(f,y,k=[],P,E){if(se(f),d.selected==="sdk"){await d.workspaceSessions.send(y,k,P,E);return}let T=de(f);if(Oe(De(),y,E),E==="followUp"&&(!T.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(y,k,P),Zi();return}if(T.isIdle()&&d.tuiPrompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await rn(f,y,k,P,E)},async updateQueuedPrompt(f,y,k,P){if(se(f),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(y,k,P);return}if(P.kind==="steer"&&de(f).isIdle())throw new oe("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(y,k,P,(E,T,D)=>rn(f,E,T,D,"steer"))},async abort(f){if(se(f),d.selected==="sdk")await d.workspaceSessions.stop();else{let y=de(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(At),y.abort()}},async resume(f,y){if(se(f),d.selected==="sdk"){await d.workspaceSessions.resume(y);return}let k=de(f);if(dt(()=>d.hosted?.adapter.assertAdmission(),y,(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=y;try{d.pi.sendMessage(ur(ie().messages),{triggerTurn:!0})}catch(P){throw d.operation=void 0,P}},async newSession(f){if(se(f),d.selected==="sdk"){let P=d.workspaces?.get(d.activeWorkspaceId??"");if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(P.path)||await d.workspaceSessions.open(P.path,"new"),await re();return}let y=de(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:ie()}),await re();return}if((await d.commandContext.newSession({withSession:async P=>{d.commandContext=P,d.replacementContext=P,d.replacementSessionId=P.sessionManager.getSessionId(),d.current=P}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await re()}};m.addWorkspace=d.lifecycle.wrap(m.addWorkspace),m.selectWorkspace=d.lifecycle.wrap(m.selectWorkspace),m.newSessionInWorkspace=d.lifecycle.wrap(m.newSessionInWorkspace),m.removeWorkspace=d.lifecycle.wrap(m.removeWorkspace),m.selectSession=d.lifecycle.wrap(m.selectSession),m.renameSession=d.lifecycle.wrap(m.renameSession),m.deleteSession=d.lifecycle.wrap(m.deleteSession),m.newSession=d.lifecycle.wrap(m.newSession),m.updateConfig=d.lifecycle.wrap(m.updateConfig),d.bridge=await Fs(m,zt,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(ah).filter(Boolean))try{u.push(dh(wt(vt(m),"dist"),(f,y)=>{let k=String(y??"");["client.js","client.css"].includes(k)&&(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:Qi}),d.bridge||(await d.telemetry?.close(),d.telemetry=null),l}};n.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(a,l)=>c(l)}),n.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")}}}),n.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 t0=Vr;export{t0 as default,oh as verifySentryDisabledRelease,Na as verifySentryNodeRelease};
54
+ `)}`:void 0,t<3&&n.cause instanceof Error&&(i.cause=Oo(n.cause,e,t+1)),st(i)}import{randomUUID as Wo}from"node:crypto";import{randomUUID as bp}from"node:crypto";import{EnvHttpProxyAgent as kp,getGlobalDispatcher as Fy,setGlobalDispatcher as Ly}from"undici";var Ho=n=>({httpProxy:n.http_proxy??n.HTTP_PROXY??n.all_proxy??n.ALL_PROXY??"",httpsProxy:n.https_proxy??n.HTTPS_PROXY??n.all_proxy??n.ALL_PROXY??"",noProxy:n.no_proxy??n.NO_PROXY??""});function Pp(n,e){let t=Ho(n),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let i=t.noProxy.toLowerCase();if(i==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),o=r.hostname.toLowerCase();return!i.split(/[,\s]/).filter(Boolean).some(a=>{let c=a.match(/^(.+):(\d+)$/),l=(c?.[1]??a).replace(/^\*?\./,"");return(!c||Number(c[2])===s)&&(o===l||o.endsWith("."+l))})}function Ip(n){let e=Ho(n);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new kp(e)}function Pi({env:n=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:r=!1}={}){let i,s=new Set,o=t===globalThis.fetch,a=(p,u)=>{try{e(p,u)}catch{}},c=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let h={requestId:bp(),phase:"headers",proxied:o&&Pp(n,p)},w=r?void 0:i,v=!1,m=u?.signal??(p instanceof Request?p.signal:void 0),b=()=>P(),P=()=>{m?.removeEventListener("abort",b),!v&&r&&(v=!0,c(w).catch(()=>{}))},S;try{o?(w??=Ip(n),s.add(w),r||(i=w),S=await t(p,{...u,dispatcher:w})):S=await t(p,u)}catch(A){throw a(A,h),P(),A}if(S.ok||a(void 0,{...h,status:S.status}),!S.body)return P(),S;let _=S.body.getReader();m?.addEventListener("abort",b,{once:!0}),m?.aborted&&P();let C=new ReadableStream({async pull(A){try{let K=await _.read();K.done?(A.close(),_.releaseLock(),P()):A.enqueue(K.value)}catch(K){a(K,{...h,phase:"body"}),A.error(K),_.releaseLock(),P()}},async cancel(A){try{await _.cancel(A)}finally{_.releaseLock(),P()}}}),H=new Response(C,{status:S.status,statusText:S.statusText,headers:S.headers});return Object.defineProperties(H,{url:{value:S.url},redirected:{value:S.redirected},type:{value:S.type}}),H},close:async()=>{await Promise.all([...s].map(c))}}}var Mo=(n,e)=>Pi({autoClose:!0}).fetch(n,e);var Sp=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),Ep=n=>typeof n=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(n)?n:void 0;function Ii(n,e={}){let t=[],r=new Set,i=(c,l=0)=>{if(!c||l>4||r.has(c)||t.length>=8)return;r.add(c);let p=Ep(c.code);if(t.push({name:Sp.has(c.name)?c.name:"Error",...p?{code:p}:{}}),i(c.cause,l+1),c instanceof AggregateError)for(let u of c.errors.slice(0,4))i(u,l+1)};i(n);let s=t.flatMap(c=>c.code?[c.code]:[]),o=e.stage==="model_admission"||s.some(c=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(c))?"lifecycle":s.some(c=>/CERT|TLS|SSL/.test(c))?"tls":s.some(c=>/^PROXY_/.test(c))||e.proxied&&s.some(c=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(c))?"proxy":s.some(c=>/TIMEOUT|ETIMEDOUT/.test(c))||t.some(c=>/TimeoutError$/.test(c.name))?"timeout":t.some(c=>c.name==="AbortError"||c.code==="ABORT_ERR"||c.code==="UND_ERR_ABORTED")?"cancelled":s.some(c=>/ENOTFOUND|EAI_AGAIN/.test(c))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",a=c=>typeof c=="string"&&/^[\w-]{1,80}$/.test(c)?c:void 0;return{errorId:Wo(),requestId:a(e.requestId)??Wo(),...a(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:o,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:t}}function jo({env:n=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return Pi({env:n,fetchRequest:t,onFailure:(r,i)=>e(Ii(r,{...i,stage:i.phase==="body"?"model_stream":"model_headers"}))})}function xp(n){let e={...process.env,...n};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])n&&t.toUpperCase()in n&&!(t in n)&&delete e[t];return e}var _p=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function $o(n,e,t=()=>{}){let r=n.agent.streamFunction;n.agent.streamFunction=async(i,s,o)=>{if(!_p.has(i.api))return r(i,s,o);let a=t(),c=jo({env:xp(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...a?{operationId:a}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await r(i,s,{...o,fetch:c.fetch});return l.result().finally(()=>c.close()).catch(()=>{}),l}catch(l){throw await c.close(),l}}}function pt(n,e,t){try{n()}catch(r){let i=Ii(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...i})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:i.errorId,requestId:i.requestId,stage:i.stage,code:"hosted_admission_blocked",networkKind:i.kind,networkStage:i.stage,causeCodes:i.causes.flatMap(s=>s.code?[s.code]:[]).join(",")})}catch{}throw r}}var Dp=["read","grep","find","ls"],Op=n=>Object.values(de).includes(n),Fo=200,vr=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,r=()=>!1,i=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},a=[],c){this.hosted=c,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=r,this.reportError=i,this.onSessionsChanged=o,this.customTools=a,this.offHosted=c?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return s.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{s.enabled()&&s.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return s.enabled()?s.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let r=await Ae(e),i=t==="continue"?this.selectedByWorkspace.get(r):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.sessionId):void 0;if(i){if(i.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(i);return}if(typeof t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(t==="new")s=Ot.create(r);else if(t==="continue"){let a=(await lt(r))[0];s=a?Ot.open(a.path):Ot.create(r)}else s="sessionManager"in t?t.sessionManager:Ot.open(t.sessionFile);if(await Np(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(s.getSessionId());if(o){if(o.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(r,s,t==="new"?"new":"resume")})}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:r,prompts:i}=e,s=t.sessionManager.getBranch(),o=s.flatMap(a=>{let c=Ct(a);return c?[c]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:r,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!i.sending,name:ur(t.sessionManager.getSessionName(),o),modified:s.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=>Ct(t)?.role==="user")}rename(e,t){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.session.setSessionName(t),!0}discard(e){return this.queue.run(async()=>{let t=this.runtimes.get(e);if(!t||t.closing)return null;if(t.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!t.session.isIdle||t.prompts.sending||t.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=this.active===t,i=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),r&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:i,cwd:t.cwd,wasActive:r}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,r,i){let s=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${i}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,t,r,i){let s=this.runtimes.get(t.getSessionId()),o=await Ye.discover(e,this.isProjectTrusted(e)),a=Ap(),c=await Co(e,o.extensionRoots,this.isProjectTrusted(e)),l=new Rp({cwd:e,agentDir:Cp(),noExtensions:!0,additionalExtensionPaths:c.paths,eventBus:a,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(k=>`${k.path}: ${k.error}`).join("; "));let h=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:w}=await Tp({cwd:e,sessionManager:t,model:h,resourceLoader:l,customTools:this.customTools}),v=new dt({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(k,y)=>this.telemetry.breadcrumb(k,y),anonymize:k=>this.telemetry.anonymize(k)}),m={session:w,cwd:e,catalog:o,bus:a,generation:++this.generation,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:c.release,tools:v,streaming:null,prompts:null,detached:i?{owner:i,events:[],seq:0,lastText:"",restoreTools:null}:void 0};m.prompts=s?.prompts??new We(()=>{let k=this.runtimes.get(t.getSessionId())??m;this.publishFor(k,{type:"snapshot",session:this.snapshotOf(k)}),!this.disposed&&!k.closing&&this.onSessionsChanged()}),p=m,$o(w,k=>{m.networkDiagnostic=k},()=>m.operation?.operationId);let b=k=>this.publishFor(m,k),P=m.detached,S=(k,y)=>{P&&(P.events.push({seq:++P.seq,type:k,...y===void 0?{}:{text:y}}),P.events.length>Fo&&P.events.splice(0,P.events.length-Fo))};m.interactions=new ct(a,k=>!m.closing&&k.sessionId===w.sessionManager.getSessionId()&&(o.has(k.pluginId)||Op(k.pluginId)),()=>b({type:"snapshot",session:this.snapshotOf(m)}));let _=0,C=a.on(gr,()=>b({type:"snapshot",session:this.snapshotOf(m)})),H=w.subscribe(k=>{if(P&&!m.closing&&(k.type==="message_end"&&k.message.role==="assistant"&&(k.message.stopReason==="error"?S("error",k.message.errorMessage??"Agent response failed"):P.lastText=k.message.content.flatMap(y=>y.type==="text"?[y.text]:[]).join(`
55
+ `)),k.type==="agent_settled"&&S("turn_end",P.lastText)),!this.disposed&&!m.closing){let y={...m.operation,session:this.telemetry.anonymize(w.sessionManager.getSessionId()),piVersion:yr,model:w.model?`${w.model.provider}/${w.model.id}`:null,thinkingLevel:w.thinkingLevel};if(k.type==="agent_start"&&(m.activityId++,this.telemetry.breadcrumb("agent_start",y)),k.type==="tool_execution_start"&&v.start(k,y),k.type==="tool_execution_end"&&v.end(k,y),k.type==="message_end"&&k.message.role==="assistant"&&k.message.stopReason==="error"){m.agentErrorReported=!0;let $=m.networkDiagnostic,ye=this.reportError(new Error("Agent response failed"),{...m.operation,stage:"agent",code:"agent_failed",piVersion:yr,...$?{networkKind:$.kind,networkStage:$.stage,causeCodes:$.causes.flatMap(ve=>ve.code?[ve.code]:[]).join(","),requestId:$.requestId}:{}})??$?.errorId;b({type:"error",message:k.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:ye,inTranscript:!0,...m.operation})}k.type==="message_end"&&k.message.role==="toolResult"&&v.message(k.message,y),k.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",y),v.clear(),m.operation=void 0)}k.type==="message_update"&&k.message.role==="assistant"&&(m.streaming={id:"stream",role:"assistant",timestamp:new Date(k.message.timestamp).toISOString(),blocks:Je(k.message.content)},Date.now()-_>=60&&(_=Date.now(),b({type:"stream",message:m.streaming}))),k.type==="agent_settled"&&this.scheduleQueued(m),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(k.type)&&((k.type==="message_end"&&k.message.role==="assistant"||k.type==="agent_settled")&&(m.streaming=null,b({type:"stream",message:null})),b({type:"snapshot",session:this.snapshotOf(m)}),!this.disposed&&!m.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(k.type)&&this.onSessionsChanged())});m.detach=()=>{C(),H()},m.releaseHosted=this.hosted?.adapter.attach(w);let A=[],K=!0;if(await w.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:k=>{K&&A.push(k.error),this.diagnostic(m,o.plugins.find(y=>k.extensionPath.startsWith(y.root+"/"))?.id??k.extensionPath,k.event??"runtime",k.error)}}),K=!1,A.length)throw new Error(A.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");m.detached&&(m.detached.restoreTools=w.getActiveToolNames(),w.setActiveToolsByName(Dp)),this.runtimes.set(w.sessionManager.getSessionId(),m),p=null,m.detached?this.onSessionsChanged():this.activate(m)}catch(u){throw this.hosted?.adapter.releasePending(t.getSessionId()),p?await this.close(p,"quit"):(a.clear(),await c.release()),u}}async close(e,t){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await So(e.session,t,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:r,catalog:i}=e,s=t.sessionManager.getBranch().flatMap(o=>{let a=Ct(o);return a?[a]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:ur(t.sessionManager.getSessionName(),s),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:at(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:ui(t.sessionManager.getBranch(),i.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=t.session.extensionRunner,i=await mr(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||r!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),i}requestInteraction(e,t){let r=this.runtimes.get(e.sessionId);return this.disposed||!r||r.closing?Promise.reject(new Error("\u4F1A\u8BDD\u4E0D\u53EF\u7528")):hr(r.bus,e,t)}resolveInteraction(e,t,r,i){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,r,i)}async send(e,t=[],r,i){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(Me(this.snapshot(),e,i),i==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,t,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,t,r,i)}async prompt(e,t,r,i,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");pt(()=>this.hosted?.adapter.assertAdmission(),i,this.reportError),Me({...this.snapshotOf(e),idle:e.session.isIdle},t,s);let o=e.session,a=o.isIdle;a&&(e.operation=i,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...i,piVersion:yr});let c=!1,l,p,u=new Promise((h,w)=>{l=h,p=w});o.prompt(t,{images:r,streamingBehavior:s,preflightResult:h=>{h&&(c=!0,l())}}).then(()=>{c||l()}).catch(h=>{if(!c)p(h);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let w=this.reportError(Ce(h,"Agent response failed"),{...i,stage:"agent",code:"agent_failed",piVersion:yr});this.publishFor(e,{type:"error",message:h instanceof Error?h.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:w,...i})}});try{await u}catch(h){throw a&&(e.operation=void 0),h}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!at(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,r,i)=>this.prompt(e,t,r,i))}async updateQueuedPrompt(e,t,r){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&i.session.isIdle)throw new oe("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await i.prompts.update(e,t,r,(s,o,a)=>this.prompt(i,s,o,a,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Rt),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");pt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=t.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!at(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!at(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=wr(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let a=this.reportError(Ce(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:a,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=r.session.modelRuntime.getModel(e,t);if(!i)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(i),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}createDetached(e,t,r){return this.queue.run(async()=>{this.ensureAvailable();let i=await Ae(e),s=Ot.create(i);return await this.replace(i,s,"new",t),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,r){let i=this.detachedRuntime(e);if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&i.detached.restoreTools&&(i.session.setActiveToolsByName(i.detached.restoreTools),i.detached.restoreTools=null),!i.session.isIdle||i.prompts.length>0){i.prompts.enqueue(t,[],void 0),this.scheduleQueued(i);return}await this.prompt(i,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(i=>i.seq>t),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as Hp,mkdir as Mp,rename as Wp,unlink as jp}from"node:fs/promises";import{basename as $p,join as Lo}from"node:path";var Fp=n=>Lo(n,"pi-web","trash");async function Uo(n,e){let t=Fp(e);await Mp(t,{recursive:!0});let r=Lo(t,`${Date.now()}_${$p(n)}`);try{await Wp(n,r)}catch(i){let s=i.code;if(s==="ENOENT")return null;if(s!=="EXDEV")throw i;await Hp(n,r),await jp(n)}return r}import{basename as Si,dirname as Lp}from"node:path";function Vo(n,e){let t=r=>e[r].map(i=>({name:r==="skills"&&Si(i.path).toLowerCase()==="skill.md"?Si(Lp(i.path)):Si(i.path),path:i.path,source:i.metadata.source,scope:i.metadata.scope,enabled:i.enabled}));return{packages:n.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as Up}from"node:child_process";var Vp=(n,e)=>new Promise((t,r)=>{Up(n,[...e],{windowsHide:!0},i=>{i?r(i):t()})});async function Ei(n,e=process.platform,t=process.env,r=Vp){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let i=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return i===null?!1:(await r(i,[n]),!0)}import{execFile as Nu}from"node:child_process";import{randomUUID as Vi}from"node:crypto";import{existsSync as ha}from"node:fs";import{access as Du,mkdir as Wt,mkdtemp as Ou,readFile as Ve,realpath as Hu,rename as ga,rm as ma,writeFile as wa}from"node:fs/promises";import{join as G}from"node:path";import{createHash as Ti}from"node:crypto";import{readdir as Yp,realpath as Ko,rename as Qp,stat as Zp}from"node:fs/promises";import{join as Ue}from"node:path";import{constants as xi}from"node:fs";import{DatabaseSync as Bp}from"node:sqlite";import{lstat as qo,mkdir as zp,open as Ht,rename as qp,unlink as Go}from"node:fs/promises";import{dirname as Gp,join as Bo,resolve as Jp}from"node:path";import{randomUUID as Kp}from"node:crypto";import{setTimeout as Xp}from"node:timers/promises";async function ee(n){await zp(n,{recursive:!0,mode:448});let e=await qo(n);if(!e.isDirectory()||e.isSymbolicLink())throw new f("invalid_storage","Plugin storage must be a real directory")}async function Y(n,e){let t;try{t=await Ht(n,xi.O_RDONLY|xi.O_NONBLOCK|(xi.O_NOFOLLOW??0))}catch(r){if(je(r))return null;throw r}try{let r=await t.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new f("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<i.length;){let o=await t.read(i,s,i.length-s,s);if(!o.bytesRead)break;s+=o.bytesRead}if(s>e||s!==r.size)throw new f("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function te(n,e=2*1024*1024){let t=await Y(n,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new f("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function ge(n){let e=await Y(n,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new f("gc_recovery_required",`Invalid journal ${n}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new f("gc_recovery_required",`Invalid journal ${n}; original bytes preserved`);return t}async function W(n,e){let t=`${n}.${Kp()}.tmp`,r=await Ht(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await qp(t,n);let i;try{i=await Ht(Gp(n),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await Go(t).catch(()=>{})}}var Jo='{"version":2,"mechanism":"sqlite-exclusive"}',zo=n=>n.toString("utf8")===Jo,br=new Set;async function _i(n,e,t=0){await ee(n);let r=Bo(n,`${e}.lock`),i=Bo(n,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new f(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),a;try{a=await Ht(i,"wx",384)}catch(v){if(v.code!=="EEXIST")throw v}finally{await a?.close()}let c=await qo(i);if(!c.isFile()||c.isSymbolicLink()||c.nlink!==1||c.size>1024*1024)throw new f("invalid_storage","Ownership database must be a small, single-link regular file");let l=new Bp(i,{allowExtension:!1}),p=Jp(i),u=Date.now()+t,h=!1;try{for(;;){if(!br.has(p))try{l.exec("BEGIN EXCLUSIVE"),br.add(p),h=!0;break}catch(m){if(m.errcode!==5)throw m}if(Date.now()>=u)throw new f(s,"Another host owns this plugin storage; wait for it to stop before retrying");await Xp(10)}let v=await Y(r,4096);if(v===null){let m;try{m=await Ht(r,"wx",384),await m.writeFile(Jo),await m.sync()}catch(b){if(b.code!=="EEXIST")throw b}finally{await m?.close()}v=await Y(r,4096)}if(v===null||!zo(v))throw o()}catch(v){throw l.close(),h&&br.delete(p),v}let w=!1;return async()=>{if(w)return;let v=await Y(r,4096);if(v===null||!zo(v))throw new f("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Go(r),l.close(),br.delete(p),w=!0}}async function re(n,e,t=2e3){let r=await _i(n,"transaction",t);try{return await e()}finally{await r()}}var kr=n=>Ue(n,"host-pair"),eu=n=>Ti("sha256").update(JSON.stringify(n)).digest("hex"),tu=10*6e4;async function ru(n){let e=Ti("sha256"),t=0,r=0;async function i(s){let o=(await Yp(Ue(n,s),{withFileTypes:!0})).sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(let a of o){if(!s&&a.name==="node_modules")continue;let c=s?`${s}/${a.name}`:a.name;if(a.isSymbolicLink()||!a.isFile()&&!a.isDirectory())throw new f("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new f("host_pair_required","Candidate package resource budget exceeded");if(a.isDirectory()){await i(c);continue}let l=await Y(Ue(n,c),64*1024*1024);if(!l||(r+=l.length)>256*1024*1024)throw new f("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([c,Ti("sha256").update(l).digest("hex")]))}}return await i(""),e.digest("hex")}async function Ai(n,e){let t=await Ko(e),r=Ue(e,"dist","hosted-worker.js");if(await Ko(r)!==Ue(t,"dist","hosted-worker.js"))throw new f("host_pair_required","Candidate worker must remain inside the staged host");let i=await Y(Ue(e,"package.json"),512*1024);if(!i)throw new f("host_pair_required","Candidate package metadata missing");let s=JSON.parse(i.toString("utf8")),o=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==n||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(c=>o.capabilities.includes(c)))throw new f("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let a=await Y(r,32*1024*1024);if(!a)throw new f("host_pair_required","Candidate worker missing");return eu([i.toString("base64"),a.toString("base64"),await ru(e)])}async function Pr(n){await Qp(n,`${n}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var iu=n=>n.schema===1&&/^[a-f0-9-]{36}$/.test(n.id)&&typeof n.version=="string"&&typeof n.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(n.hostDigest)&&/^[a-f0-9]{64}$/.test(n.fingerprint)&&Array.isArray(n.selections)&&!n.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(n.selection&&(typeof n.selection.path!="string"||!/^[a-f0-9]{64}$/.test(n.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(n.phase);async function Ri(n){let e=Ue(kr(n),"intent.json"),t,r=!0;try{t=await ge(e)}catch{t=null,r=!1}if(!r||t&&!iu(t))return await Pr(e),null;if(t){let{lifecyclePhase:i,...s}=t,o=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await Zp(e).then(a=>a.mtime.toISOString(),()=>new Date(0).toISOString());t={...s,updatedAt:o,phase:s.phase==="selected"&&i==="restart-requested"?"restart-requested":s.phase==="reconciled"&&i==="cancelled"?"cancelled":s.phase==="reconciled"&&i==="required-action"?"required-action":s.phase}}return t}async function Ir(n,e){let{lifecyclePhase:t,...r}={...e,selections:[],updatedAt:new Date().toISOString()},i=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await W(Ue(kr(n),"intent.json"),i)}var Ci=n=>n&&["selecting","selected","restart-requested"].includes(n.phase),Xo=(n,e=Date.now())=>!!n&&!!Ci(n)&&e-Date.parse(n.updatedAt??"")<tu;import{promisify as Mu}from"node:util";import{realpathSync as Zo,statSync as nu}from"node:fs";import{basename as su,delimiter as ou,dirname as Yo,join as Ni,resolve as au}from"node:path";function Qo(n){if(!n)return null;try{let e=Zo(n);return su(e)==="npm-cli.js"&&nu(e).isFile()?e:null}catch{return null}}function cu({execPath:n=process.execPath,env:e=process.env}={}){let t=Qo(e.npm_execpath);if(t)return t;let r=new Set([Yo(n)]);try{r.add(Yo(Zo(n)))}catch{}let i=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of i.split(ou).filter(Boolean))r.add(au(s));for(let s of r)for(let o of[Ni(s,"node_modules","npm","bin","npm-cli.js"),Ni(s,"..","lib","node_modules","npm","bin","npm-cli.js"),Ni(s,"npm")]){let a=Qo(o);if(a)return a}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function ea(n){return{file:process.execPath,args:[cu(),...n]}}import{randomUUID as lu}from"node:crypto";import{mkdir as ia,readFile as du,rename as Oi,rm as pu,unlink as Vv,writeFile as uu}from"node:fs/promises";import{isAbsolute as ta,join as Mt}from"node:path";var Hi=1,fu=1440*6e4,Sr=n=>Mt(n,"pi-web","upgrade"),Mi=n=>Mt(Sr(n),"candidate.json"),hu=n=>Mt(Sr(n),"transaction.json"),ra=n=>Mt(Sr(n),"history"),na=/^[a-f0-9-]{36}$/i;async function gu(n,e){let t=`${n}.${lu()}.tmp`;try{await uu(t,e,{mode:384}),await Oi(t,n)}finally{await pu(t,{force:!0})}}var mu=(n,e)=>gu(n,JSON.stringify(e));async function Di(n,e){await Oi(n,`${n}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function sa(n,e,t=()=>!1){let r;try{r=JSON.parse(await du(n,"utf8"))}catch(i){return i?.code==="ENOENT"||await Di(n,"invalid"),null}return e(r)?t(r)?(await Di(n,"expired"),null):r:(await Di(n,"invalid"),null)}function oa(n){if(!n||typeof n!="object"||n.schema!==Hi||!na.test(n.id??""))return!1;try{Te(n.version)}catch{return!1}return typeof n.launcher=="string"&&ta(n.launcher)&&typeof n.packageRoot=="string"&&ta(n.packageRoot)&&["stable","alpha"].includes(n.channel)&&typeof n.downgrade=="boolean"&&!Number.isNaN(Date.parse(n.createdAt??""))}async function Er(n,e=Date.now()){return sa(Mi(n),oa,t=>e-Date.parse(t.createdAt)>fu)}async function aa(n,e){let t={schema:Hi,createdAt:new Date().toISOString(),...e};if(!oa(t))throw new Error("Invalid upgrade candidate");return await ia(Sr(n),{recursive:!0,mode:448}),await mu(Mi(n),t),t}async function Wi(n,e,t){let r=await Er(n);!r||e&&r.id!==e||(await ia(ra(n),{recursive:!0,mode:448}),await Oi(Mi(n),Mt(ra(n),`${r.id}-candidate-${t}.json`)).catch(i=>{if(i?.code!=="ENOENT")throw i}))}var wu=["selected","committed","rolled-back"];function yu(n){return!!n&&typeof n=="object"&&n.schema===Hi&&na.test(n.id??"")&&wu.includes(n.phase)&&typeof n.version=="string"&&typeof n.from=="string"&&!Number.isNaN(Date.parse(n.updatedAt??""))}async function ca(n){return sa(hu(n),yu)}import{readFile as vu,rename as bu,writeFile as ku,unlink as Pu}from"node:fs/promises";import{join as Iu}from"node:path";import{randomUUID as Su}from"node:crypto";var ji=1,la=n=>Iu(n,"pi-web","launcher-handoff.json");function da(n){return n?.protocol===ji&&typeof n.nonce=="string"&&n.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(n.requestId)&&Number.isSafeInteger(n.pid)&&n.pid>0&&["requested","draining","stopped","refused","failed"].includes(n.phase)}async function $i(n){try{let e=JSON.parse(await vu(la(n),"utf8"));if(!da(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 Eu(n,e){let t=`${n}.${Su()}.tmp`;try{await ku(t,JSON.stringify(e),{mode:384}),await bu(t,n)}finally{await Pu(t).catch(()=>{})}}async function pa(n,e){if(!da(e))throw new Error("Invalid launcher handoff receipt");await Eu(la(n),e)}import{execFile as xu}from"node:child_process";import{cp as _u,readFile as Fi,realpath as Tu,rm as Au}from"node:fs/promises";import{join as ut,sep as Ru}from"node:path";import{promisify as Cu}from"node:util";var ua=Cu(xu),Li=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Ui(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=n;return Li.map(t=>{let r=e[t];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${r}`})}async function xr(n){return Promise.all(Li.map(async e=>{let t=await ot(n,e),r=JSON.parse(await Fi(ut(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function fa(n,e){let t=JSON.parse(await Fi(ut(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=t.peerDependencies===void 0?await xr(n):Ui(t.peerDependencies);if(JSON.stringify(await xr(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let i=await ot(n,"node-pty"),s=await ot(e,"node-pty"),o=await Tu(ut(e,"../.."));if(i===s||!s.startsWith(o+Ru))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let a=async u=>JSON.parse(await Fi(ut(u,"package.json"),"utf8")).version;if(await a(i)!==await a(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await Au(s,{recursive:!0,force:!0}),await _u(i,s,{recursive:!0});let c={...process.env};delete c.NODE_OPTIONS,delete c.NODE_PATH,delete c.ELECTRON_RUN_AS_NODE,await ua(process.execPath,[ut(e,"desktop","check-pty.cjs")],{cwd:e,env:c,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await ot(e,Li[0]),{stdout:p}=await ua(process.execPath,[ut(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:c,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}var Wu=Mu(Nu),jt=n=>["committed","cancelled","failed"].includes(n);function ya(n){let e=n.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function ju(n,e){try{let t=ea(n),{stdout:r}=await Wu(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(t){let r=t;throw new Error(r.stderr?.trim()||r.message)}}var _r=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??ju,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let r=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return xr(this.packageRoot);let i=JSON.parse(r),s=Array.isArray(i)&&i.length===1?i[0]:i;return Ui(s)},this.verifyPackage=e.verifyPackage??fa,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?ji:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!jt(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let i=G(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await Ve(i,"utf8")),o=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let a=await $i(this.agentDir);if(a?.nonce===e&&["requested","draining"].includes(a.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let c,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(c=await this.beforeRestart(),!o(JSON.parse(await Ve(i,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:s.pid,phase:"requested"};try{await pa(this.agentDir,p),l=!0}catch(u){let h=await $i(this.agentDir).catch(()=>null);if(l=h?.nonce===e&&h?.requestId===t&&["requested","draining","stopped"].includes(h.phase),!l)throw u}this.restartPending=!0}finally{!l&&c&&await c()}}async current(){let e=JSON.parse(await Ve(G(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Te(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();if(!t||jt(t.phase)||t.id===this.ownTransaction)return e;if(t.version===e&&["selecting","selected","restart-requested"].includes(t.phase))await this.record({...t,phase:"committed",message:"Selected version is running"});else if(t.phase==="restart-requested"){let r=await ca(this.agentDir);await this.record({...t,phase:"failed",message:r?.id===t.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Wi(this.agentDir,t.id,"superseded"),await this.record({...t,phase:"failed",message:`Interrupted while ${t.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return G(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await ge(this.transactionPath)}catch{return await Pr(this.transactionPath),null}return e?e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||typeof e.selectionPath!="string"?(await Pr(this.transactionPath),null):e:null}async record(e){if(await Wt(G(this.agentDir,"pi-web"),{recursive:!0}),await W(this.transactionPath,e),jt(e.phase)){let t=G(this.agentDir,"pi-web","update-history");await Wt(t,{recursive:!0}),await W(G(t,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),t=await Er(this.agentDir);t&&(!e||t.id===e.id)&&await Wi(this.agentDir,t.id,"cancelled"),e&&!jt(e.phase)&&await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0}get preferencePath(){return G(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await Ve(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${Vi()}.tmp`;try{await Wt(G(this.agentDir,"pi-web"),{recursive:!0}),await wa(t,JSON.stringify({channel:e}),{mode:384}),await ga(t,this.preferencePath)}finally{this.savingPreference=!1,await ma(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=ha(G(this.packageRoot,".git")),i={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(i.launcher=this.launcherIdentity(),i.launcherHandoff={supported:i.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(i.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction();if(s&&!jt(s.phase)?i.recovery={version:s.version,phase:s.phase,canCancel:s.phase!=="restart-requested"}:s?.phase==="failed"&&s.message&&(i.lastFailure={version:s.version,message:s.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...i,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...i,canRestart:!1,reason:i.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?i.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":i.canRestart||(i.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&i.canRestart&&(i.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let o=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),a=Array.isArray(o)&&o.length===1?o[0]:o,c=t==="alpha"?a:{latest:a};if(!c||!ro(c.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let l=c.latest;if(t==="alpha"&&c.alpha!==void 0){if(!lr(c.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");he(c.alpha,l)>0&&(l=c.alpha)}if(i.latest=l,i.downgrade=he(l,e)<0,i.available=t==="stable"?he(l,e)!==0:he(l,e)>0,i.available&&this.pluginWarnings){let p=await this.pluginWarnings(l).catch(()=>[]);p.length&&(i.pluginWarnings=p)}this.desktopManaged&&i.downgrade&&!this.desktopReleaseChannels&&he(l,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(i.canRestart=!1,i.requiresDesktopUpgrade=!0,i.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(o){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${o instanceof Error?o.message:String(o)}`)}return i}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(ha(G(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=G(this.agentDir,"pi-web","releases");await Wt(r,{recursive:!0});let i=await Ou(G(await Hu(r),`${t.latest}-`)),s=G(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:Vi(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=o.id,await this.record(o);try{let a=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...a,"--prefix",i,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let c=G(i,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:c},await this.record(o);let l=JSON.parse(await Ve(G(c,"package.json"),"utf8"));if(l.name!=="pi-webapp"||l.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await Ve(G(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&ya(l)!==ya(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let u=G(c,"bin","pi-webapp.mjs");return await Promise.all([u,G(c,"dist","extension.js"),G(c,"web","dist","index.html")].map(h=>Du(h))),this.desktopManaged&&(await ci(this.agentDir,{version:t.latest,launcher:u,desktopProtocolVersion:$e}),await this.verifyPackage(this.packageRoot,c)),await this.prefetchPlugins?.(t.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await aa(this.agentDir,{id:o.id,version:t.latest,launcher:u,packageRoot:c,channel:t.channel??"stable",downgrade:!!t.downgrade}),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={id:o.id,update:{version:t.latest,launcher:u},channel:t.channel??"stable"},{version:t.latest,launcher:u}}catch(a){await ma(i,{recursive:!0,force:!0});let c=(a instanceof Error?a.message:String(a)).slice(0,500);throw await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${c}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),a}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:t=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let i,s=!1,o=G(this.agentDir,"pi-web","launcher.restart");try{if(i=await this.beforeRestart?.(t),(await Er(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let a=await this.transaction();a?.id===r.id&&await this.record({...a,phase:"restart-requested"});try{if(JSON.parse(await Ve(o,"utf8"))?.nonce!==this.launcherNonce){let l=G(this.agentDir,"pi-web","restart-history");await Wt(l,{recursive:!0,mode:448}),await ga(o,G(l,`stale-${Vi()}.json`))}}catch{}try{await wa(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(c){try{let l=JSON.parse(await Ve(o,"utf8"));s=l.nonce===this.launcherNonce&&l.candidate===r.id}catch{}if(!s)throw c}this.restartPending=!0}catch(a){if(s){this.restartPending=!0;return}let c=await this.transaction();throw c?.id===r.id&&c.phase==="restart-requested"&&await this.record({...c,phase:"prepared"}),i&&await i(),a}}};import{createHash as rc,randomUUID as Lh}from"node:crypto";import{randomUUID as mh}from"node:crypto";import{join as nn}from"node:path";import{randomUUID as ka}from"node:crypto";import{randomUUID as $u}from"node:crypto";function va(n){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof n[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let r=`__pi_web_contract_${$u().replaceAll("-","")}`,i;try{if(i=n.getActiveTools(),!Array.isArray(i))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{n.registerTool(s),n.setActiveTools([...i,r]),(n.getAllTools().find(a=>a.name===r)?.exposure!=="hidden"||n.getActiveTools().includes(r))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};n.registerTool({...s,parameters:o}),n.getAllTools().find(a=>a.name===r)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{n.setActiveTools(i)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var Fu;function ba(){return Fu??=Lu().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function Lu(){let{createAgentSession:n,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:i,rm:s}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:a}=await import("node:path"),c=await i(a(o(),"pi-sdk-contract-")),l,p=[],u=0,h=0,w=!1,v=!1;try{let m=(H,A,K)=>({name:H,label:H,description:"Inert host SDK contract check",exposure:A,parameters:{type:"object",properties:{}},execute:K}),b=()=>({content:[],details:void 0}),P=new e({cwd:c,agentDir:c,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[H=>{H.on("tool_call",A=>{if(A.toolName==="__contract_direct"&&(w=!!A.parentToolCallId),A.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let A of["hidden","model-only"])H.registerTool(m(`__contract_${A.replace("-","_")}`,A,async()=>(h++,b())));H.registerTool(m("__contract_protected","direct",async()=>(h++,b()))),H.registerTool(m("__contract_direct","direct",async()=>(u++,b()))),H.registerTool(m("__contract_driver","direct",async(A,K,k,y,$)=>{let ye=await $.executeTool("__contract_hidden",{}),ve=await $.executeTool("__contract_model_only",{}),Q=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!ye.isError||!ve.isError)&&p.push("nested-tool-exposure"),(Q.isError||u!==1)&&p.push("nested-tool-execution"),(!x.isError||h!==0)&&p.push("nested-tool-permission-guard"),w||p.push("nested-parent-identity"),v=!0,b()}))}]});await P.reload(),{session:l}=await n({cwd:c,agentDir:c,sessionManager:t.inMemory(c),resourceLoader:P}),await l.bindExtensions({mode:"print"});let S=l.modelRuntime.getModels("openai")[0];if(!S)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(S);let _=0;l.agent.streamFunction=async H=>{let A=_++===0,K={role:"assistant",api:H.api,provider:H.provider,model:H.id,timestamp:Date.now(),content:A?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:A?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},k=r();return k.push({type:"start",partial:K}),k.push({type:"done",reason:A?"toolUse":"stop",message:K}),k.end(K),k};let C;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((H,A)=>{C=setTimeout(()=>A(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(C)}return v||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await s(c,{recursive:!0,force:!0})}}var Tr=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??=ba().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,i)=>{t=setTimeout(()=>i(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let r=this.install(e,t);r.ready=!0;try{this.publish(r)}catch(i){throw this.release(r),i}return()=>this.release(r)}install(e,t){let r={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let i=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{i(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),i(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),i(e.on("tool_call",s=>{let o=r.owned.get(s.toolName);if(!o)return;let a=this.descriptors.get(o)?.find(c=>c.name===s.toolName);if(!a||!this.allowed(r,o,a,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),i(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),i(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let t=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(r=>{r.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(r){throw this.release(t),r}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,r,i=!1){let s=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!i||s.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(i=>i.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(t);this.validateChange(e,r),this.descriptors.set(e,r);for(let i of this.bindings)i.ready&&this.publish(i)}validateChange(e,t){for(let i of this.bindings)if(i.compatible!==!1)for(let[s,o]of i.owned)this.assertOwner(i,o,s);let r=new Set;for(let i of t){if(!i.name||!i.action||!i.parameters||i.parameters.type!=="object"||r.has(i.name))throw new Error("Invalid hosted tool descriptor");r.add(i.name);for(let[s,o]of this.descriptors)if(s!==e&&o.some(a=>a.name===i.name))throw new Error(`Hosted tool ownership conflict: ${i.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,i.name)}}assertOwner(e,t,r){let i=e.owned.get(r);if(i&&i!==t)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(o=>o.name===r);if(s&&(!i||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=va(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,i]of e.owned)this.assertOwner(e,i,r);for(let[r,i]of this.descriptors)for(let s of i)this.assertOwner(e,r,s.name);let t=new Set;for(let[r,i]of this.descriptors)for(let s of i){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;t.add(s.name);let o=this.service.policy(r,e.scope),a=o.exposure??"direct",c=!o.allowNested&&a==="direct"?"model-only":a,l={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:c,execute:async(p,u,h)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:ka(),scope:{...e.scope},kind:"tool",action:s.action,input:u},h)}};e.pi.registerTool(l),e.definitions.set(s.name,l)}for(let r of e.owned.keys())if(!t.has(r)){let i={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:Uu};e.pi.registerTool(i),e.definitions.set(r,i)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let i=e.definitions.get(r);return!i||i.exposure==="direct"||i.exposure==="model-only"}))}async invokeAction(e,t,r,i,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(a=>a.scope.sessionId===t.sessionId&&a.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:ka(),scope:t,kind:"action",action:r,input:i},s)}};async function Uu(){throw new Error("Hosted tool unavailable")}import{randomBytes as Vf,randomUUID as Bf,timingSafeEqual as zf}from"node:crypto";import{join as Pe}from"node:path";var Vu=30,Pa=/^[a-z][a-z0-9-]{0,63}$/,Bu=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,$t=n=>{throw new f("invalid_package",n)},Bi=(n,e)=>n===void 0?[]:!Array.isArray(n)||n.length>32?$t(`Invalid ${e} declaration`):n;function ft(n){let e=n&&typeof n=="object"?n:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(a=>typeof a=="string"):[]),r=t.has("secrets")?Bi(e.secrets,"secrets").map(a=>{let c=a?.name;return typeof c=="string"&&Pa.test(c)?c:$t("Invalid secret name")}):[],i=e.network,s=t.has("network")?Bi(i?.hosts,"network").map(a=>typeof a=="string"&&Bu.test(a)?a:$t("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Bi(e.schedules,"schedules").map(a=>{let c=a;return!c||typeof c.id!="string"||!Pa.test(c.id)||typeof c.action!="string"||!/^[\w.-]{1,80}$/.test(c.action)||!Number.isSafeInteger(c.intervalSec)||c.intervalSec<Vu||c.intervalSec>86400?$t("Invalid schedule declaration"):{id:c.id,intervalSec:c.intervalSec,action:c.action}}):[];return new Set(o.map(a=>a.id)).size!==o.length&&$t("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:o,sessions:t.has("sessions")}}import{lookup as zu}from"node:dns/promises";import{isIP as qu}from"node:net";var Gu=new Set(["GET","POST","PATCH","PUT","DELETE"]),Ju=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),Ku=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Ar=(n,e)=>{throw new f("network_denied",n,{status:403,reason:e})};function Xu(n){let e=n.toLowerCase().replace(/^::ffff:/,"");if(qu(e)===4){let[t,r]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&r===254||t===172&&r>=16&&r<=31||t===192&&r===168||t===100&&r>=64&&r<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function Ia(n,e,t,r,i){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new f("invalid_input","Invalid network request");let o;try{o=new URL(s.url)}catch{throw new f("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Ar("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Ar("Host is not declared by the plugin","host");let a=(s.method??"GET").toUpperCase();if(!Gu.has(a))throw new f("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new f("invalid_input","Invalid body");let c={};for(let[S,_]of Object.entries(s.headers??{})){if(typeof _!="string"||Ju.has(S.toLowerCase())||!/^[\w-]{1,64}$/.test(S)||/[\r\n]/.test(_))throw new f("invalid_input",`Header not allowed: ${S.slice(0,64)}`);c[S]=_}let l=null;if(s.secret!==void 0){if(t.includes(s.secret)||Ar("Secret is not declared by the plugin","secret"),l=await i.secrets.get(n,s.secret),!l)throw new f("secret_missing","Secret has not been configured",{status:412});c.Authorization=`Bearer ${l}`}let p=await(i.resolve??(async S=>(await zu(S,{all:!0})).map(_=>_.address)))(o.hostname);(!p.length||p.some(Xu))&&Ar("Host resolves to a non-public address","address");let u=i.timeoutMs??2e4,h=i.maxResponseBytes??2*1024*1024,w=await(i.fetch??fetch)(o,{method:a,headers:c,body:s.body,redirect:"manual",signal:AbortSignal.timeout(u)}),v=[],m=0;if(w.body)for await(let S of w.body){if(m+=S.byteLength,m>h)throw new f("response_too_large","Network response exceeds limit",{status:502});v.push(Buffer.from(S))}let b=Buffer.concat(v).toString("utf8"),P={};return w.headers.forEach((S,_)=>{Ku.has(_.toLowerCase())&&(P[_.toLowerCase()]=S)}),l&&(b=b.split(l).join("[redacted]")),{status:w.status,headers:P,body:b}}var Rr=(n,e,t)=>{if(typeof n!="string"||!n||n.length>e)throw new f("invalid_input",`Invalid ${t}`);return n};async function Sa(n,e,t,r,i,s){let o=i&&typeof i=="object"&&!Array.isArray(i)?i:{};if(r==="sessions.create"){if(o.mode!=="plan")throw new f("invalid_input","Plugin sessions must start in plan mode");if(n.activeCount(e)>=s)throw new f("quota_exceeded","Too many active plugin sessions",{status:429});return n.create({pluginId:e,cwd:t,title:Rr(o.title,200,"title"),prompt:Rr(o.prompt,64*1024,"prompt"),mode:"plan"})}let a=Rr(o.sessionId,200,"sessionId");if(n.ownerOf(a)!==e)throw new f("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new f("invalid_input","Invalid mode");return await n.send(a,Rr(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await n.release(a),{ok:!0};case"sessions.abort":return await n.abort(a),{ok:!0};case"sessions.events":return n.events(a,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new f("method_denied","Unknown sessions method")}}var Yu=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),Cr=class{options;constructor(e){this.options=e}handles(e){return Yu.has(e)}async call(e,t,r,i,s){let o=ft(t);if(i==="network.fetch"){if(!o.networkHosts.length)throw new f("capability_denied","Plugin did not declare network access",{status:403});return Ia(e,o.networkHosts,o.secrets,s,this.options)}if(!o.sessions||!this.options.sessions)throw new f("capability_denied","Sessions capability is unavailable",{status:403});return Sa(this.options.sessions,e,r.scope.cwd,i,s,this.options.maxActiveSessions??3)}};var Nr=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let r=this.deps.setInterval??((i,s)=>{let o=setInterval(i,s);return o.unref(),o});this.timers.set(e,t.map(i=>r(()=>{this.tick(e,i)},i.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])t(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let r=`${e}\0${t.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,t),!0}catch(i){return this.deps.onError?.(e,t,i),!1}finally{this.running.delete(r)}}};import{createHash as Yi,timingSafeEqual as bf}from"node:crypto";import{lstat as Ha,mkdtemp as Xi,readdir as kf,readFile as Pf,realpath as If,rename as Sf,rm as Be,writeFile as Ef}from"node:fs/promises";import{tmpdir as xf}from"node:os";import{join as B}from"node:path";import{gunzipSync as sf}from"node:zlib";import{mkdir as of,writeFile as af}from"node:fs/promises";import{dirname as cf,join as lf}from"node:path";import{constants as zi}from"node:fs";import{lstat as _a,open as Qu,readdir as Ea,realpath as Ta}from"node:fs/promises";import{createHash as Zu}from"node:crypto";import{join as Aa,relative as ef,resolve as tf,sep as rf}from"node:path";var J={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},nf={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"]},V=n=>Zu("sha256").update(n).digest("hex");function L(n){throw new f("invalid_package",n)}async function Ze(n,e,t){let r=e.split("/");(!r.length||r.some(a=>!a||a==="."||a===".."||!/^[\w.-]+$/.test(a)))&&L("Invalid resource path");let i=n;for(let a=0;a<r.length;a++){i=Aa(i,r[a]);let c=await _a(i);(c.isSymbolicLink()||(a<r.length-1?!c.isDirectory():!c.isFile()||c.nlink!==1))&&L("Links and non-regular package files are forbidden")}let s=await Ta(i);(s!==tf(n,e)||ef(n,s).startsWith(`..${rf}`))&&L("Resource escapes package root");let o=await Qu(i,zi.O_RDONLY|zi.O_NONBLOCK|(zi.O_NOFOLLOW??0));try{let a=await o.stat();(!a.isFile()||a.nlink!==1||a.size>t)&&L("Oversized or non-regular package file");let c=Buffer.alloc(Math.min(a.size+1,t+1)),l=0;for(;l<c.length;){let p=await o.read(c,l,c.length-l,l);if(!p.bytesRead)break;l+=p.bytesRead}return(l>t||l!==a.size)&&L("Package resource changed during read"),c.subarray(0,l)}finally{await o.close()}}function xa(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return L("Invalid package JSON")}}async function et(n,e){let t=await Ta(n);(await _a(n)).isSymbolicLink()&&L("Package root cannot be a symlink");let r=xa(await Ze(t,"package.json",J.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&L("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&L("Invalid package version"),Fe(r.piWebapp)||L("Unsupported hosted manifest"),r.type!=="module"&&L("Hosted package must declare ESM module type");for(let u of await Ea(t,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&L("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&L("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let h=r[u];h&&(typeof h!="object"||Object.keys(h).length>0)&&L("Hosted packages must contain all runtime dependencies")}let i=r.piWebapp,s=xa(await Ze(t,i.resourcesManifest.slice(2),J.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>J.files)&&L("Invalid resource manifest");let o=new Map,a=0;for(let u of s.files){(!u||typeof u!="object")&&L("Invalid resource entry");let h=u,w={...h,path:typeof h.path=="string"&&h.path.startsWith("./")?h.path.slice(2):h.path};(!Xe(`./${w.path}`)||typeof w.sha256!="string"||!/^[a-f0-9]{64}$/.test(w.sha256)||!Number.isSafeInteger(w.bytes)||w.bytes<0||o.has(w.path))&&L("Invalid or duplicate resource");let v=w.path.split(".").at(-1);nf[v]?.includes(w.mime)||L("Unsupported resource MIME");let m=v==="js"||v==="mjs"?J.js:v==="css"?J.css:v==="woff"||v==="woff2"?J.font:J.other;(w.bytes>m||(a+=w.bytes)>J.total)&&L("Resource budget exceeded");let b=await Ze(t,w.path,m);(b.length!==w.bytes||V(b)!==w.sha256)&&L("Resource integrity mismatch"),o.set(w.path,Object.freeze({...w}))}for(let u of[i.backend.entry,i.frontend.document,i.frontend.controller])o.has(u.slice(2))||L("Entrypoint is absent from resource manifest");let c=0;async function l(u,h=0){h>16&&L("Package directory nesting limit exceeded");for(let w of await Ea(Aa(t,u),{withFileTypes:!0})){++c>J.files*2&&L("Too many package entries");let v=`${u}/${w.name}`;(w.isSymbolicLink()||!w.isDirectory()&&!w.isFile())&&L("Invalid archive member"),w.isDirectory()?await l(v,h+1):v!==i.resourcesManifest.slice(2)&&!o.has(v)&&L("Undeclared distribution asset")}}await l("dist");let p=V(JSON.stringify({id:r.name,version:r.version,manifest:i,resources:[...o.values()].sort((u,h)=>u.path.localeCompare(h.path))}));return{id:r.name,version:r.version,root:t,manifest:i,resources:o,digest:p}}async function Ra(n,e,t){if(t!==n.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Xe(`./${r}`))return null;let i=n.resources.get(r);if(!i||r===n.manifest.backend.entry.slice(2))return null;let s=await Ze(n.root,r,i.bytes);if(s.length!==i.bytes||V(s)!==i.sha256)throw new f("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:i.mime}}var Dr=64*1024*1024,df=J.total+J.files*2048,F=n=>{throw new f("invalid_archive",n)};function ht(n){let e=n.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?n:n.subarray(0,e))}catch{return F("Archive has invalid UTF-8 paths")}}function Ca(n){let e=ht(n).trim();if(!/^[0-7]+$/.test(e))return F("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:F("Archive number exceeds limits")}function pf(n){let e=n.endsWith("/")?n.slice(0,-1):n;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return F("Archive must have one package root");let t=e.slice(8);return t.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?F("Archive path is not a safe relative package path"):t}function uf(n){let e={},t=0;for(;t<n.length;){let r=n.indexOf(32,t);if(r<0)return F("Invalid PAX header");let i=n.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(i))return F("Invalid PAX record length");let s=Number(i),o=t+s;if(o>n.length||o<=r+2||n[o-1]!==10)return F("Truncated PAX record");let a=ht(n.subarray(r+1,o-1)),c=a.indexOf("=");if(c<1)return F("Invalid PAX record");let l=a.slice(0,c),p=a.slice(c+1);if(Object.hasOwn(e,l)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(l))return F("Unsupported PAX feature");e[l]=p,t=o}return e}function ff(n){if(!n.length||n.length>Dr)return F("Compressed archive exceeds budget");let e;try{e=sf(n,{maxOutputLength:df})}catch{return F("Invalid or oversized gzip archive")}let t=[],r=new Set,i=0,s=0,o=0,a=0,c=null,l=!1;for(;i+512<=e.length;){let u=e.subarray(i,i+512);if(i+=512,u.every(C=>C===0)){if(c||e.subarray(i).some(C=>C!==0))return F("Unexpected archive data after end marker");l=!0;break}if(++a>J.files*2)return F("Too many archive headers");let h=0;for(let C=0;C<512;C++)h+=C>=148&&C<156?32:u[C];if(Ca(u.subarray(148,156))!==h)return F("Invalid tar header checksum");let w=ht(u.subarray(257,263));if(w&&w!=="ustar"&&w!=="ustar ")return F("Unsupported tar format");let v=u[156],m=ht(u.subarray(345,500)),b=(m?m+"/":"")+ht(u.subarray(0,100)),P=Ca(u.subarray(124,136));if(c&&(c.path!==void 0&&(b=c.path),c.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(c.size))return F("Invalid PAX size");P=Number(c.size)}if(!Number.isSafeInteger(P)||P<0||P>J.total||i+P>e.length)return F("Truncated or oversized tar member");let S=e.subarray(i,i+P);if(i+=Math.ceil(P/512)*512,v===120){if(c||P>8192)return F("Oversized or chained PAX header");c=uf(S);continue}if(c=null,v!==0&&v!==48&&v!==53)return F("Links and special archive members are forbidden");let _=v===53;if(_&&P!==0||ht(u.subarray(157,257)))return F("Invalid archive link or directory");if(b=pf(b),!b&&!_)return F("Invalid package root member");if(r.has(b))return F("Duplicate archive member");if(r.add(b),++s>J.files||(o+=P)>J.total)return F("Unpacked archive exceeds budget");t.push({path:b,data:S,directory:_})}if(!l||!r.has("package.json"))return F("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 h=u.path.split("/");for(let w=1;w<h.length;w++)if(p.has(h.slice(0,w).join("/")))return F("Archive file/directory collision")}return t}async function qi(n,e){let t=ff(n);for(let r of t){if(!r.path)continue;let i=lf(e,r.path);await of(r.directory?i:cf(i),{recursive:!0,mode:448}),r.directory||await af(i,r.data,{flag:"wx",mode:384})}}import{lstat as hf,mkdir as gf,readdir as mf,realpath as wf,writeFile as yf}from"node:fs/promises";import{dirname as vf,join as Gi}from"node:path";async function Na(n,e){let t=await wf(n),r=await Ze(t,"package.json",J.other),i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new f("invalid_package","package.json is not valid JSON")}if(!i||typeof i!="object"||Array.isArray(i))throw new f("invalid_package","package.json must be an object");let s=[],o=0,a=0;async function c(h,w){if(w>16)throw new f("invalid_package","Package directory nesting limit exceeded");for(let v of await mf(Gi(t,h),{withFileTypes:!0})){let m=`${h}/${v.name}`;if(++o>J.files)throw new f("invalid_package","Too many package entries");if(v.isDirectory()){await c(m,w+1);continue}if(!v.isFile())throw new f("invalid_package",`Links and non-regular files are forbidden: ${m}`);let b=await Ze(t,m,J.js);if((a+=b.length)>J.total)throw new f("invalid_package","Resource budget exceeded");let P=Gi(e,m);await gf(vf(P),{recursive:!0,mode:448}),await yf(P,b,{flag:"wx",mode:384}),s.push([m,V(b)])}}let l;try{l=await hf(Gi(t,"dist"))}catch(h){throw h.code==="ENOENT"?new f("dist_missing","dist/ does not exist yet; build the plugin first"):h}if(!l.isDirectory())throw new f("invalid_package","dist must be a real directory");await c("dist",0);let{version:p,...u}=i;return s.sort((h,w)=>h[0].localeCompare(w[0])),{contentHash:V(JSON.stringify({package:u,files:s})),packageJson:i}}function ke(n){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(n);return!e||e[0]!==n||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function xe(n,e){let t=ke(n),r=ke(e);if(!t||!r)throw new f("invalid_version","Only exact stable semantic versions are supported");return t.major-r.major||t.minor-r.minor||t.patch-r.patch}function Da(n){let e=ke(n);if(e)return e;if(!lr(n))return null;let[t,r]=n.split("-alpha."),i=ke(t),s=Number(r);return i&&Number.isSafeInteger(s)?{...i,alpha:s}:null}function Ji(n){return!!Da(n)}function gt(n,e){if(!Ji(n)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(i=>!i.trim()))return!1;let r=[];for(let i of t){let s=i.trim().split(/\s+/),o=!0;for(let a of s){let c=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(a),l=c&&Da(c[2]);if(!c||!l)return!1;let p=c[2],u=he(n,p);switch(c[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&&he(n,`${l.major}.${l.minor+1}.0-0`)<0;break;case"^":{let h=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&he(n,`${h}-0`)<0;break}}}r.push(o)}return r.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(n,e=Oe){let t=e.find(r=>r.id===n);if(!t)throw new f("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Ki(n,e,t){let r=n.piWebapp;return n.name===e.id&&!!ke(n.version)&&!n.deprecated&&Fe(r)&&gt(t,r.hostRange)&&e.requiredCapabilities.every(i=>r.capabilities.includes(i))}function Oa(n,e,t,r,i){if(!n||typeof n!="object"||!("versions"in n)||!n.versions||typeof n.versions!="object"||Array.isArray(n.versions))throw new f("registry_invalid","Invalid registry version catalog");let s=Object.entries(n.versions);if(s.length>1e4)throw new f("registry_invalid","Registry version catalog exceeds budget");let a=s.flatMap(([c,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===c&&Ki(p,e,t)&&(!i||c===i)&&(!r||xe(c,r)>=0)?[p]:[]}).sort((c,l)=>xe(l.version,c.version))[0];if(!a)throw new f("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!a.dist||typeof a.dist.tarball!="string"||typeof a.dist.integrity!="string")throw new f("registry_invalid","Release is missing its immutable tarball integrity");return a}function _f(n,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new f("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),i=Yi("sha512").update(n).digest();if(r.length!==i.length||!bf(r,i))throw new f("integrity_mismatch","Downloaded package failed integrity verification")}var mt=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Ji(e.hostVersion))throw new f("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Oe,this.fetcher=e.fetch??Mo}async index(){let e=await te(B(this.root,"installed.json"));if(!e){if(await Y(B(this.root,"installed.json"),2*1024*1024))throw new f("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new f("invalid_storage","Invalid plugin installation index");for(let[t,r]of Object.entries(e.versions))if(this.catalog.some(i=>i.id===t)){if(!Array.isArray(r)||r.length>16||new Set(r.map(i=>i.version)).size!==r.length)throw new f("invalid_storage","Invalid installed version list");for(let i of r)this.validateRecord(t,i)}return e}validateRecord(e,t){if(!t||!ke(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${V(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new f("invalid_storage","Invalid installed plugin record")}path(e){return B(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await ge(B(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(s=>!["schema","pluginId","next"].includes(s)))throw new f("invalid_storage","Invalid install journal");me(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let i=e.versions[t.pluginId]?.find(s=>s.version===t.next.version);if(i&&i.digest!==t.next.digest)throw new f("invalid_storage","Conflicting installation journal");await Be(B(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=B(this.root,"staging");await ee(r);for(let i of await kf(r)){if(!/^stage-[A-Za-z0-9]+$/.test(i)||(await Ha(B(r,i))).isSymbolicLink())throw new f("invalid_storage","Invalid abandoned staging directory");await Be(B(r,i),{recursive:!0})}return e}async recoverCollection(e){let t=B(this.root,"gc-journal.json"),r=await ge(t);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new f("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");me(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let i=r.records.filter(s=>e.versions[r.pluginId]?.some(o=>o.directory===s.directory));if(i.length&&i.length!==r.records.length)throw new f("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!i.length){await ee(B(this.root,"versions")),await ee(B(this.root,"versions",V(r.pluginId)));for(let s of r.records)await Be(this.path(s),{recursive:!0,force:!0})}await Be(t)}async collect(e,t){return me(e,this.catalog),re(this.root,async()=>{let r=await this.recoverLocked(),i=r.versions[e]??[],s=new Set(await t()),o=i.at(-1);o&&s.add(o.version);let a=i.filter(c=>!s.has(c.version));return await this.removeLocked(e,r,a),a.map(c=>c.version)})}async removeLocked(e,t,r){r.length&&(await ee(B(this.root,"versions")),await ee(B(this.root,"versions",V(e))),await W(B(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),t.versions[e]=(t.versions[e]??[]).filter(i=>!r.some(s=>s.directory===i.directory)),t.revision++,await W(B(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return re(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let r;try{r=new URL(e)}catch{throw new f("registry_denied","Invalid registry URL")}let i=new URL(t.registry);if(r.protocol!=="https:"||r.origin!==i.origin||r.username||r.password||r.hash||r.search)throw new f("registry_denied","Only the official registry origin is permitted");return r}async download(e,t,r,i="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw r?.aborted?r.reason:new f("registry_unreachable",u instanceof Error?u.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new f(o.status===404?`${i}_not_found`:"download_failed",`Registry ${i} request failed (${o.status})`);if(o.url&&new URL(o.url).origin!==e.origin)throw new f("registry_denied","Registry redirect is forbidden");let a=o.body.getReader(),c=[],l=0,p=()=>{a.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new f("download_too_large","Registry response exceeds budget");for(;;){let u=await a.read();if(u.done)break;if(l+=u.value.length,l>t)throw new f("download_too_large","Registry response exceeds budget");c.push(Buffer.from(u.value))}return s.throwIfAborted(),Buffer.concat(c)}catch(u){throw r?.aborted?r.reason:u instanceof f?u:new f("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await a.cancel().catch(()=>{}),a.releaseLock()}}async check(e,t,r,i){let s=me(e,this.catalog);if(r&&!ke(r))throw new f("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),a,c=await this.download(o,8*1024*1024,i,"metadata");try{a=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c))}catch{throw new f("registry_invalid","Invalid registry metadata JSON")}return Oa(a,s,this.hostVersion,t,r)}async install(e,t,r){let i=me(e,this.catalog);if(!Ki(t,i,this.hostVersion))throw new f("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(t.dist.tarball,i),Dr,r);return this.installArchive(e,s,t.dist.integrity,t.version,r)}async installArchive(e,t,r,i,s){let o=me(e,this.catalog);if(!ke(i))throw new f("invalid_version","Choose an exact stable version");if(t.length>Dr)throw new f("download_too_large","Package archive exceeds budget");return _f(t,r),re(this.root,async()=>{let a=await this.recoverLocked();s?.throwIfAborted();let c=await Xi(B(this.root,"staging","stage-"));try{await qi(t,c),s?.throwIfAborted();let l=await et(c,e);if(l.version!==i||!Fe(l.manifest)||!gt(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(p=>l.manifest.capabilities.includes(p)))throw new f("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,a,c,l,r,s)}finally{await Be(c,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,r,i,s,o){let a=t.versions[e]?.find(u=>u.version===i.version);if(a&&a.digest!==i.digest)throw new f("version_replaced","An installed immutable version cannot be replaced with different content");let c={version:i.version,digest:i.digest,integrity:s,directory:`${V(e)}/${i.version}-${i.digest}`,installedAt:new Date().toISOString()};if(await ee(B(this.root,"versions",V(e))),!a&&(t.versions[e]?.length??0)>=16)throw new f("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await W(B(this.root,"install-journal.json"),{schema:1,pluginId:e,next:c});let l=this.path(c),p=!1;try{await Ha(l),p=!0}catch(u){if(!je(u))throw u}if(p){if((await et(l,e)).digest!==i.digest)throw new f("resource_changed","Installed package content was modified")}else await Sf(r,l);return o?.throwIfAborted(),a||(t.versions[e]=[...t.versions[e]??[],c],t.revision++,await W(B(this.root,"installed.json"),t)),await Be(B(this.root,"install-journal.json")),{...i,root:await If(l)}}async installDevArchive(e,t,r){me(e,this.catalog);let i=await Pf(t),s="sha512-"+Yi("sha512").update(i).digest("base64"),o=await Xi(B(xf(),"pi-dev-archive-"));try{await qi(i,o);let a=(await et(o,e)).version;return await this.installArchive(e,i,s,a,r)}finally{await Be(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,r){let i=me(e,this.catalog);return re(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let o=await Xi(B(this.root,"staging","stage-"));try{let{contentHash:a,packageJson:c}=await Na(t,o);r?.throwIfAborted();let l=B(this.root,"dev-sources.json"),p=await te(l)??{},u=p[e],h=s.versions[e]??[],w=u?.contentHash===a?h.find(A=>A.version===u.version):void 0;if(w){let A=await et(this.path(w),e);if(A.digest!==w.digest)throw new f("resource_changed","Installed package integrity changed");return A}let v=typeof c.version=="string"?ke(c.version):null;if(!v)throw new f("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let m=Math.max(-1,...h.map(A=>ke(A.version)).filter(A=>A&&A.major===v.major&&A.minor===v.minor).map(A=>A.patch)),b=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),m+1),P=`${v.major}.${v.minor}.${b}`;await Ef(B(o,"package.json"),JSON.stringify({...c,version:P},null,2),{flag:"wx",mode:384});let S=await et(o,e);if(!gt(this.hostVersion,S.manifest.hostRange))throw new f("incompatible_plugin",`Package hostRange ${S.manifest.hostRange} does not include host ${this.hostVersion}`);let _=i.requiredCapabilities.filter(A=>!S.manifest.capabilities.includes(A));if(_.length)throw new f("incompatible_plugin",`Package lacks required capabilities: ${_.join(", ")}`);let C="sha512-"+Yi("sha512").update(a).digest("base64"),H=await this.commitStaged(e,s,o,S,C,r);return p[e]={contentHash:a,version:P},await W(l,p),H}finally{await Be(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let r=me(e,this.catalog);return re(this.root,async()=>{let i=await this.recoverLocked(),s=i.versions[e]?.find(a=>a.version===t);if(!s)throw new f("not_installed","Plugin version is not installed");let o=await et(this.path(s),e);if(o.digest!==s.digest)throw new f("resource_changed","Installed package integrity changed");if(!gt(this.hostVersion,o.manifest.hostRange)||!r.requiredCapabilities.every(a=>o.manifest.capabilities.includes(a)))throw new f("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){me(e,this.catalog),await re(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,r,s)})}};import{lstat as Or,mkdir as Tf,open as Ma,realpath as Wa,readdir as Qi,link as Af,rename as Rf,unlink as tt,copyFile as Cf,rm as Nf}from"node:fs/promises";import{dirname as Df,isAbsolute as ja,join as O,relative as $a,resolve as Of,sep as Zi,win32 as Hf}from"node:path";import{randomUUID as en}from"node:crypto";var Ft=192*1024*1024,Lt=512*1024,La=n=>typeof n=="string"&&/^[a-f0-9-]{36}$/.test(n);function Mf(n){if(!n||typeof n!="object"||Array.isArray(n))throw new f("invalid_input","Expected object input");return n}function Fa(n){if(typeof n!="string"||!/^[\w.-]{1,160}$/.test(n)||n==="."||n==="..")throw new f("invalid_input","Invalid state key");return n}function Ut(n){if(n&&(!La(n.stateRef)||typeof n.version!="string"||!Number.isSafeInteger(n.generation)||n.generation<1||!Number.isSafeInteger(n.schema)||n.schema<1||typeof n.enabled!="boolean"||typeof n.operationId!="string"))throw new f("invalid_storage","Invalid active plugin record");return n}var rt=class{root;pluginId;legacy;checkpoint;constructor(e,t,r,i){this.root=O(e,V(t)),this.pluginId=t,this.legacy=r,this.checkpoint=i}active(){return te(O(this.root,"active.json")).then(Ut)}async recover(){return re(this.root,async()=>{let e=await this.active(),t=await ge(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 f("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ut(t.next),Ut(t.before);let r=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,a)=>o===null||a===null?o===a:["version","generation","stateRef","schema","enabled","operationId"].every(c=>o[c]===a[c]))(e,r==="committed"?t.next:t.before))throw new f("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await W(O(this.root,"previous.json"),s),r==="committed"){let o=await ge(O(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(a=>["version","stateRef"].includes(a))&&await tt(O(this.root,"fork.json"))}return await tt(O(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,t){return re(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new f("stale_generation","Plugin activation changed concurrently");let i=await ge(O(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(o=>!["version","stateRef"].includes(o))))throw new f("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=Ut({...t,generation:e+1,operationId:en()});await ee(O(this.root,"states")),await ee(O(this.root,"states",s.stateRef)),await W(O(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await W(O(this.root,"active.json"),s)}catch(o){if((await this.active())?.operationId!==s.operationId)throw o}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await W(O(this.root,"previous.json"),r),await tt(O(this.root,"transition.json")),await tt(O(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return re(this.root,async()=>{let t=await this.assertGeneration(e,!1),r=en(),i=O(this.root,"states",r);if(await ge(O(this.root,"fork.json")))throw new f("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await W(O(this.root,"fork.json"),{version:1,stateRef:r}),await ee(i);let s=O(this.root,"states",t.stateRef);for(let o of await Qi(s)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new f("invalid_storage","Unexpected state file");if(!await Y(O(s,o),Ft))throw new f("invalid_storage","Missing state file");await Cf(O(s,o),O(i,o))}return await this.checkpoint?.("forked"),r})}async collect(e){return re(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await Y(O(this.root,l),2*1024*1024))throw new f("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),r=Ut(await ge(O(this.root,"previous.json")));if(!t&&await Y(O(this.root,"active.json"),2*1024*1024))throw new f("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,r].filter(l=>!!l),s=O(this.root,"states");await ee(s);let o=await Qi(s),a=new Set(i.map(l=>l.stateRef));for(let l of o){if(!La(l))throw new f("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(s,l),u=await Or(p);if(!u.isDirectory()||u.isSymbolicLink())throw new f("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let h of await Qi(p)){let w=await Or(O(p,h));if(!/^[a-f0-9]{64}\.json$/.test(h)||!w.isFile()||w.isSymbolicLink()||w.nlink!==1)throw new f("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!a.has(l)){let v=await te(O(p,h),Ft);if(!v)throw new f("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(v,"committed")){let m=v;if(Object.keys(m).some(b=>!["requestId","inputHash","nextHash","committed"].includes(b))||m.committed!==!0||!/^[a-f0-9]{64}$/.test(m.inputHash)||!/^[a-f0-9]{64}$/.test(m.nextHash)||typeof m.requestId!="string")throw new f("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(v).some(m=>!["revision","schema","value","requestId","inputHash"].includes(m)))throw new f("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(v)}}}}for(let l of a)if(!o.includes(l))throw new f("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let c=await e(i);for(let l of o)a.has(l)||await Nf(O(s,l),{recursive:!0,force:!0});return c})}async assertGeneration(e,t=!0){let r=await this.active();if(!r||r.generation!==e||t&&!r.enabled)throw new f("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new f("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,r,i="session"){if(i!=="session"&&i!=="workspace")throw new f("invalid_input","Invalid state scope");let s=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return O(this.root,"states",e.stateRef,`${V(s+":state:"+r)}.json`)}async call(e,t,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new f("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=Mf(r);return re(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await te(this.statePath(s,e,Fa(i.key),i.scope),Ft);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(s,e,Fa(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new f("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new f("invalid_input","State value must be JSON serializable");let a=JSON.stringify(i);if(Buffer.byteLength(a)>Ft)throw new f("state_too_large","Plugin state exceeds limit");let c=await te(o,Ft);c&&this.validateState(c);let l=V(a);if(c?.requestId===e.requestId&&c.inputHash===l)return{revision:c.revision,schema:c.schema,value:c.value};if((c?.revision??0)!==i.expectedRevision)throw new f("revision_conflict","Plugin state changed concurrently");let p={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await W(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,i.path),a=i.maxBytes===void 0?Lt:i.maxBytes;if(!Number.isSafeInteger(a)||a<=0||a>Lt)throw new f("invalid_input","Invalid workspace read limit");let c=await Y(o,a);return c?{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:V(c)}:null}case"workspace.commit":return this.commitFile(s,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new f("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new f("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,r=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||ja(t)||Hf.isAbsolute(t))throw new f("invalid_path","Use a workspace-relative .excalidraw path");let i=await Wa(e),s=Of(i,t),o=$a(i,s);if(!o||o===".."||o.startsWith(`..${Zi}`)||ja(o))throw new f("invalid_path","Workspace path escapes root");let a=i,c=o.split(Zi);for(let p=0;p<c.length;p++){a=O(a,c[p]);let u;try{u=await Or(a)}catch(h){if(!je(h))throw h;if(p<c.length-1){if(!r||$a(i,a)!=="diagrams")throw new f("invalid_path","Workspace directory does not exist");try{await Tf(a,{mode:448})}catch(w){if(w.code!=="EEXIST")throw w}u=await Or(a)}}if(u&&(u.isSymbolicLink()||(p<c.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new f("invalid_path","Workspace path contains a link or non-regular file")}let l=await Wa(Df(s));if(l!==i&&!l.startsWith(i+Zi))throw new f("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,r){if(typeof r.text!="string"||Buffer.byteLength(r.text)>Lt||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new f("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,r.path,!0),o=O(this.root,"states",e.stateRef,`${V(this.scopeKey(t)+":file:"+t.requestId+":"+String(r.path))}.json`),a=V(JSON.stringify(r)),c=V(r.text),l=await te(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==a||l.nextHash!==c))throw new f("duplicate_request","Request ID was reused with different content");let p;try{p=await Ma(`${i}.lock`,"wx",384)}catch(h){throw h.code==="EEXIST"?new f("file_busy","Workspace file is locked; original file preserved"):h}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let h=await Y(i,Lt),w=h?V(h):null;if(l&&w===c)return{hash:c};if(l?.committed||w!==r.expectedHash)throw new f("file_conflict","Workspace file already exists or changed externally");await W(o,{requestId:t.requestId,inputHash:a,nextHash:c,committed:!1}),u=O(s,`.plugin-${en()}.tmp`);let v=await Ma(u,"wx",384);try{await v.writeFile(r.text),await v.sync()}finally{await v.close()}if((await this.fileTarget(t.scope.cwd,r.path)).parent!==s)throw new f("file_conflict","Workspace directory changed during save");let b=await Y(i,Lt);if((b?V(b):null)!==r.expectedHash)throw new f("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),r.expectedHash===null){try{await Af(u,i)}catch(P){throw P.code==="EEXIST"?new f("file_conflict","Workspace file was created concurrently"):P}await tt(u),u=void 0}else await Rf(u,i),u=void 0;return await W(o,{requestId:t.requestId,inputHash:a,nextHash:c,committed:!0}),{hash:c}}finally{u&&await tt(u).catch(()=>{}),await p.close(),await tt(`${i}.lock`)}}};import{randomUUID as Lf}from"node:crypto";import{fork as Wf}from"node:child_process";import{randomUUID as jf}from"node:crypto";import{join as $f}from"node:path";import{EventEmitter as Ff}from"node:events";var Ua=192*1024*1024,Vt=class n{child;pending=new Map;events=new Ff;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,r,i){this.package=e,this.generation=t,this.broker=i;let s={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(s[o]=process.env[o]);this.child=Wf(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new f("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,t,r,i,s=1e4){let o=new n(e,t,r,i);try{await o.request("initialize",{entry:$f(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},s);let a=await o.request("describe",void 0,s);if(!a||!Array.isArray(a.tools)||a.tools.length>128)throw new f("invalid_tools","Invalid hosted tool catalog");let c=new Set;for(let l of a.tools){if(!l||typeof l.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(l.name)||c.has(l.name)||typeof l.label!="string"||typeof l.description!="string"||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!l.parameters||typeof l.parameters!="object"||Array.isArray(l.parameters)||l.parameters.type!=="object")throw new f("invalid_tools","Invalid or duplicate tool descriptor");c.add(l.name)}return o.tools=structuredClone(a.tools),await o.request("health",void 0,s),o}catch(a){throw await o.dispose(),a}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>Ua){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let i=this.pending.get(r.id);if(!i)return;if(clearTimeout(i.timer),this.pending.delete(r.id),!i.expired){let s=r.error;r.ok===!0?i.resolve(r.value):i.reject(new f(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let i=this.pending.get(r.invocationId);try{if(!i?.invocation||i.expired)throw new f("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(i.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:X(s)})}}}request(e,t,r=3e4,i){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new f("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new f("worker_busy","Too many plugin requests"));let s=i?.requestId??jf();if(this.pending.has(s))return Promise.reject(new f("duplicate_request","An identical request is still running"));let o={type:"request",id:s,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>Ua?Promise.reject(new f("message_too_large","Plugin request exceeds limit")):new Promise((a,c)=>{let l=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),c(new f("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:a,reject:c,timer:l,invocation:i,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(s),c(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new f("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,t,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(t=>{let r=()=>{clearTimeout(i),this.events.off("idle",r),t(!0)},i=setTimeout(()=>{this.events.off("idle",r),t(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new f("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let t=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var Uf={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Hr=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,r=Uf,i){this.broker=e,this.workerEntry=t,this.hooks=r,this.capabilities=i}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await _i(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,r)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new f("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,r):this.broker.call(e,t,r);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new f("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new f("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new f("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new f("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(l){throw this.worker||await this.releaseOwnership?.(),l}let i=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let o=null,a=!1,c=!1;try{if(o=await Vt.start(e,i+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(t))throw new f("drain_pending","Plugin calls are still running; switch deferred without killing them");if(c=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(t))throw new f("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new f("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let l=r?await this.broker.forkState(i):Lf(),p=await this.broker.activate(i,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});a=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await s?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw a||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",c&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,t=!1){return this.serialize(async()=>{let r=this.worker,i=this.phaseValue,s=await this.broker.active(),o=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))throw await this.releaseOwnership?.(),this.phaseValue="failed",new f("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Vt.start(r.package,r.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{let c=async l=>{try{await l()}catch(p){if(!t)throw p}};await c(async()=>{if(r&&!await r.waitForIdle(e))throw new f("drain_pending","Plugin work is still draining; current host retained")}),await c(()=>this.hooks.freeze()),await c(async()=>{if(r&&!await r.waitForIdle(e))throw new f("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(c){try{await o(),this.phaseValue=i,await this.hooks.resume()}catch(l){throw this.phaseValue="failed",l}throw c}let a=!1;return()=>this.serialize(async()=>{a||(await o(),this.phaseValue=i,await this.hooks.resume(),a=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,r;try{r=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!r){if(t)throw this.phaseValue="failed",new f("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let i=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(t&&!await t.waitForIdle(e))throw new f("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new f("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=i,s&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new f("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new f("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(i){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),i}})}};import{readFile as Va}from"node:fs/promises";var Mr=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;constructor(e){this.options=e,this.installer=new mt({root:Pe(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new Cr(e.capabilities):void 0;this.scheduler=new Nr({invoke:async(r,i)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:Bf(),scope:s,kind:"action",action:i.action,input:{schedule:i.id}})},onError:(r,i,s)=>e.onScheduleError?.(r,i.id,s),...e.scheduleTimers});for(let r of this.installer.catalog){let i=new rt(Pe(e.root,"data"),r.id,e.legacy?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new Hr(i,e.workerEntry,{validateCandidate:o=>s.validateCandidate?.(o),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async o=>{if(o.enabled){let a=await this.installer.load(r.id,o.version);this.packages.set(r.id,a),this.assetTokens.set(r.id,Vf(24).toString("base64url"));try{this.scheduler.start(r.id,ft(a.manifest).schedules)}catch(c){this.scheduler.stop(r.id),this.errors.set(r.id,X(c))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return t?i=>this.installer.installDevDirectory(e,t,i):r?i=>this.installer.installDevArchive(e,r,i):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){me(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new f("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new f("manager_closed","Plugin manager is shutting down"));let r=(this.operations.get(e)??Promise.resolve()).then(t,t);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),i=>{this.errors.set(e,X(i))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,r=!1){return this.options.lifecycle?this.options.lifecycle(e,t,r):t()}async policies(){let e=await te(Pe(this.options.root,"policies","policies.json"));if(!e){if(await Y(Pe(this.options.root,"policies","policies.json"),2*1024*1024))throw new f("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,r]of Object.entries(e))if(this.installer.catalog.some(i=>i.id===t)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new f("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await te(Pe(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await re(Pe(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await W(Pe(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,r,i){try{let s=await this.installer.check(e,t,r,i),o=!t||xe(s.version,t)>0;return o?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:s.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:X(s).code,message:X(s).message}),s}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new f("invalid_input","Invalid plugin update policy");await re(Pe(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await W(Pe(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return re(kr(this.options.root),async()=>{let e=await Ri(this.options.root);if(!e)return{intent:e,admitted:!1};if(!Ci(e))return e.phase==="required-action"&&await Ir(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await Ai(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Ai(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Va(this.options.workerEntry)).equals(await Va(Pe(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(t){return await Ir(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${X(t).message}; data retained`}),{intent:e,admitted:!1}}return await Ir(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await re(Pe(this.options.root,"policies"),async()=>{let t=await this.policies();await W(Pe(this.options.root,"policies","policies.json"),t)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let t of this.installer.catalog){let r=this.supervisor(t.id),i=await r.broker.active();if(i?.enabled)try{let s=await this.compatiblePackage(t.id,i.version);await this.lifecycle(t.id,()=>r.replace(s)),this.packages.set(t.id,s),e||await this.collectSettled(t.id)}catch(s){let o=X(s),a=["runtime_owned","storage_busy"].includes(o.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(t.id,{...o,message:`Plugin unavailable: startup failed (${o.code}): ${o.message}; data retained. ${a}`})}}}async compatiblePackage(e,t){try{return await this.installer.load(e,t)}catch(r){if(X(r).code!=="incompatible_plugin")throw r;let i=((await this.installer.inventory()).versions[e]??[]).map(s=>s.version).filter(s=>s!==t).sort((s,o)=>xe(o,s));for(let s of i)try{return await this.installer.load(e,s)}catch{}throw r}}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let o=this.supervisor(s.id),a=await o.broker.active(),c=this.packages.get(s.id),l=(e.versions[s.id]??[]).map(p=>p.version).sort((p,u)=>xe(u,p));return{id:s.id,name:s.name,description:s.description,official:!0,installed:!!l.length,installedVersions:l,version:l[0]??null,activeVersion:a?.version??null,enabled:a?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[s.id]?.updatePolicy??"notify",pinnedVersion:t[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...c&&o.phase==="active"?{digest:c.digest,document:c.manifest.frontend.document.slice(2),controller:c.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${c.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,r,i){return this.serialize(e,async()=>{let s=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],a=o.map(l=>l.version).sort((l,p)=>xe(p,l))[0],c=await(async()=>{switch(t){case"check":return this.isDevPlugin(e)?{version:a??null,dev:!0}:{version:(await this.check(e,a,void 0,i)).version};case"install":{let l=this.devSource(e);if(l){let h=await l(i);return await this.recordDevSync(e,h.version),{installed:!0,version:h.version}}let p=await this.check(e,a,r,i),u=await this.installer.install(e,p,i);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:u.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:u.version}}case"enable":{let l=r??a;if(!l)throw new f("not_installed","Install the plugin first");let p=await this.installer.load(e,l),u=await this.lifecycle(e,()=>s.replace(p));return u.pending||this.packages.set(e,p),u}case"retry":{let l=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!a)throw new f("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let v=await l(i),m=await s.broker.active();if(await this.recordDevSync(e,v.version),!m?.enabled)return{installed:!0,enabled:!1,version:v.version};if(m.version===v.version&&!s.pendingVersion)return{unchanged:!0,version:v.version};let b=await this.lifecycle(e,()=>s.replace(v));return b.pending||this.packages.set(e,v),b}let p=await this.check(e,a,r,i),u=await s.broker.active();if(p.version===a&&(!u?.enabled||u.version===a)&&!s.pendingVersion)return{unchanged:!0,version:a};let h=p.version===a?await this.installer.load(e,a):await this.installer.install(e,p,i);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:h.version,message:"Selected compatible release installed; activation may wait for editors"}),!u?.enabled)return{installed:!0,enabled:!1,version:h.version};let w=await this.lifecycle(e,()=>s.replace(h));return w.pending||this.packages.set(e,h),w}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new f("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=X(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),c})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async r=>this.installer.collect(e,async()=>{let i=(await this.policies())[e];return[...r.map(s=>s.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...i?.pinnedVersion?[i.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new f("stale_generation","Reconnect the plugin view before editing",{status:409})):i.invoke(r)}flush(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new f("stale_generation","Flush generation changed",{status:409})):i.flushAction(r)}async asset(e,t,r){let i=this.packages.get(e);if(!i)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(i.version,(s.get(i.version)??0)+1);try{return await Ra(i,r,t)}finally{let o=s.get(i.version)-1;o?s.set(i.version,o):s.delete(i.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let r;try{r=decodeURIComponent(t[1])}catch{return null}let i=this.assetTokens.get(r),s=Buffer.from(t[2]);return!i||s.length!==Buffer.byteLength(i)||!zf(s,Buffer.from(i))?null:this.asset(r,t[3],t[4])}async reconcileHostUpgrade(){if(Xo(await Ri(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),r=!0;for(let i of this.installer.catalog){let s=e.versions[i.id];if(s?.length)try{let o=await this.supervisor(i.id).broker.active(),a=o?.enabled?o.version:s.map(l=>l.version).sort((l,p)=>xe(p,l))[0];try{await this.installer.load(i.id,a);continue}catch(l){if(X(l).code!=="incompatible_plugin")throw l}let c=await this.manage(i.id,"update");c&&typeof c=="object"&&"pending"in c&&c.pending&&(r=!1)}catch(o){r=!1;let a=X(o);this.errors.set(i.id,a),await this.recordCheck(i.id,{status:"failed",code:a.code,message:a.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,t){let r=new mt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),i=await this.installer.inventory();for(let s of this.installer.catalog){let o=(i.versions[s.id]??[]).map(l=>l.version).sort((l,p)=>xe(p,l)),a=await this.supervisor(s.id).broker.active();if(!o.length||this.isDevPlugin(s.id))continue;let c=!1;for(let l of new Set([...a?.enabled?[a.version]:[],...o]))try{await r.load(s.id,l),c=!0;break}catch{}if(!c)try{let l=await r.check(s.id,o[0],void 0,t),p=await r.install(s.id,l,t);await this.recordCheck(s.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(l){t?.throwIfAborted();let p=X(l);await this.recordCheck(s.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let t=new mt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),i=[];for(let s of this.installer.catalog){let o=r.versions[s.id],a=await this.supervisor(s.id).broker.active();if(!a?.enabled)continue;if(!o?.length){i.push({pluginId:s.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let c=[a.version,...o.map(u=>u.version).sort((u,h)=>xe(h,u))],l=!1,p="";for(let u of new Set(c))try{await t.load(s.id,u),l=!0;break}catch(h){p||=X(h).message}l||i.push({pluginId:s.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return i}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],r=async()=>{let i=await Promise.allSettled(t.map(o=>o()));this.closing=!1;let s=i.find(o=>o.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let i of this.supervisors.values())t.push(await i.suspendForRestart(void 0,e));return r}catch(i){throw await r(),i}}};import{randomUUID as qf}from"node:crypto";var D=n=>Object.assign(new Error(n),{status:409,code:"view_barrier"}),Bt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,t,r=2e4,i=15e3,s=12e4){this.pluginId=e,this.generation=t,this.pollMs=r,this.freezeMs=i,this.staleMs=s}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&r.scope.ownerId===t.ownerId&&r.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||t.ownerId!==r.scope.ownerId||t.workspaceId!==r.scope.workspaceId||t.sessionId!==r.identity.sessionId)throw D("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw D("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,t,r=++this.sequence){return e.commands.push({id:r,type:t,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw 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??qf();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw D("View initialization was cancelled; register a new document identity");let a=this.views.get(o);if(a){if(!this.sameScope(a,e,t)||a.kind!==e.kind)throw D("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(c=>c.scope.ownerId===t.ownerId&&c.identity.mountId===e.mountId))throw D("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw D("Invalid view capability");let r=this.views.get(e.viewToken),i=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,t))throw D("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw D("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let o=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:o}}}if(r&&this.sameScope(r,e,t)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw D("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw D("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&i&&this.sameScope(i,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!i){if(e.confirmation!=="discard-unconfirmed-edits")throw 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(!r||!this.sameScope(r,e,t))throw D("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw D("View already initialized; preserve its recovery record");this.retire(r);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");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(D("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw D("Invalid acknowledgement");let o=r.commands.find(a=>a.id===e.commandId);if(!o)throw D("Unknown command acknowledgement");r.commands=r.commands.filter(a=>a.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(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||r.activeActions)throw D("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw D("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw D("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw D("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw D("Invalid poll cursor");if(r.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&&!r.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let a=setTimeout(c,Math.min(25e3,Math.max(50,this.pollMs)));function c(){clearTimeout(a),r.waiter=void 0,o()}r.waiter=c}),{viewToken:r.token,commands:r.commands.filter(o=>o.id>e.after)}}default:throw D("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw D("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(r=>r.activeActions||r.kind!=="controller"&&!r.frozen&&(r.busy||!this.immediate&&["editor","workspace"].includes(r.kind)));throw D(`Close editors before updating; old version retained. Pending views: ${t.map(r=>`${r.kind}:${r.identity.mountId}${r.activeActions?` (action in flight x${r.activeActions})`:r.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let i=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>i(),reject:s=>i(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));i(D(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||i()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw 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 Gf="@chengzhiyi/pi-excalidraw",Jf={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"}}},Kf="@chengzhiyi/pi-github",Xf={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"}}},Ba=new Map([[Gf,Jf],[Kf,Xf]]);function tn(n,e){let t=n.get(e);if(!t)throw new f("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as Yf}from"node:crypto";var Qf="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"}),Zf="Ov23limJmKiuu8cOP83E";function rn(n,e,t=process.env){if(n==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||Zf,scope:"repo",createUrl:Qf}}var eh="https://github.com/login/device/code",th="https://github.com/login/oauth/access_token",rh=8,Wr=class{flows=new Map;fetcher;now;constructor(e=(r,i)=>fetch(r,{...i,signal:i.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new f("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let i=await r.json().catch(()=>null);if(!i||typeof i!="object"||!r.ok&&!("error"in i))throw new f("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return i}async start(e,t,r){if(!r.clientId)throw new f("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[u,h]of this.flows)h.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=rh)throw new f("oauth_busy","Too many sign-ins in progress",{status:429});let i=await this.post(eh,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:o,verification_uri:a}=i,c=Number(i.expires_in),l=Math.max(Number(i.interval)||5,1);if(typeof s!="string"||typeof o!="string"||typeof a!="string"||!a.startsWith("https://github.com/")||!Number.isFinite(c))throw new f("oauth_failed",typeof i.error_description=="string"?i.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=Yf();return this.flows.set(p,{pluginId:e,name:t,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+c*1e3,interval:l,nextPoll:this.now()+l*1e3}),{deviceId:p,userCode:o,verificationUri:a,interval:l,expiresIn:c}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let r=await this.post(th,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:t.pluginId,name:t.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return t.interval+=5,t.nextPoll=this.now()+t.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as qa,readFileSync as Ga,statSync as ih}from"node:fs";import{lstat as nh,readdir as sh,writeFile as oh,mkdir as ah,rename as ch}from"node:fs/promises";import{delimiter as lh,dirname as dh,isAbsolute as ph,join as it,resolve as zt}from"node:path";var za="@chengzhiyi/pi-github",Fr={[za]:{id:za,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"]}},Ja=()=>Object.keys(Fr).join(", ");function uh(n=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,r=[],i="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let s of(n??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=s.lastIndexOf("="),a=s.slice(0,o),c=s.slice(o+1),l=Fr[a],p=o<1?`entry "${s}" is not <id>=<path.tgz>`:l?c.endsWith(".tgz")?qa(zt(c))?null:`archive not found: ${zt(c)}`:`"${c}" is not a .tgz archive`:`unknown plugin id "${a}" (known: ${Ja()})`;if(p){r.push({level:"error",source:i,...l?{pluginId:a}:{},message:p});continue}e.push(l),t.set(a,zt(c))}return{catalog:e,archives:t,notices:r}}var Ka=n=>it(n,"pi-web","hosted-dev.json"),Xa=n=>it(n,"pi-web","hosted-dev-status.json");function fh(n,e,t=process.cwd()){let r=[],i=[],s=(n.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(lh).map(a=>a.trim()).filter(Boolean);for(let a of s)r.push({path:zt(t,a),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=s.length>0;if(e&&qa(e)){o=!0;try{let a=JSON.parse(Ga(e,"utf8")),c=a&&typeof a=="object"?a.roots:void 0;if(!Array.isArray(c))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let l of c)typeof l!="string"||!ph(l)?i.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):r.push({path:zt(l),source:e})}catch(a){i.push({level:"error",source:e,message:`cannot read dev configuration: ${a instanceof Error?a.message:String(a)}`})}}return{specs:r,notices:i,configured:o}}function hh(n){let e=(i,s)=>({notice:{level:"error",source:n.source,...s?{pluginId:s}:{},message:`${n.path}: ${i}`}}),t;try{t=ih(n.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(Ga(it(n.path,"package.json"),"utf8"))}catch(i){return e(i.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof r.name!="string"?e("package.json has no name"):Fr[r.name]?Fe(r.piWebapp)?{pluginId:r.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name):e(`unknown plugin id "${r.name}" (known: ${Ja()})`)}var jr=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=uh(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let t=fh(this.env,this.configPath,this.cwd),r=[],i=new Map,s=new Map;for(let o of t.specs){let a=hh(o);if(a.notice){r.push(a.notice);continue}let c=a.pluginId;if(i.has(c)){r.push({level:"error",pluginId:c,source:o.source,message:`${o.path}: plugin ${c} is already provided by ${i.get(c)}`});continue}if(this.archives.has(c)&&r.push({level:"warning",pluginId:c,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${c}; the dev directory wins`}),!this.catalog.some(l=>l.id===c)){if(!e){r.push({level:"warning",pluginId:c,source:o.source,message:`${o.path}: ${c} 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(Fr[c])}i.set(c,o.path),s.set(c,o.source)}for(let o of[...this.roots.keys()])i.has(o)||this.roots.delete(o);for(let[o,a]of i)this.roots.set(o,a);this.rootSource.clear();for(let[o,a]of s)this.rootSource.set(o,a);return this.fileNotices=t.notices,this.rootNotices=r,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},$r=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${X(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,r]of e){let i=this.roots.get(t);(!i||i.root!==r)&&(i={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,i));let s=await gh(r);if(s===null){this.set(t,i,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),i.seen=void 0;continue}if(s!==i.seen){i.seen=s;continue}s===i.applied||this.stopped||await this.apply(t,i,s)}await this.publish()}set(e,t,r,i={}){let s=t.state!==r||t.message!==i.message||t.version!==i.version;t.state=r,t.message=i.message,t.code=i.code,t.version=i.version??t.version,s&&(t.at=new Date().toISOString(),this.log(`${e}: ${r}${i.version?` ${i.version}`:""}${i.message?` \u2014 ${i.message}`:""}`))}async apply(e,t,r){this.set(e,t,"switching");try{let s=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=r,s?.installed?s.pendingVersion?this.set(e,t,"pending",{version:s.version,message:`Waiting for editors to close before switching to ${s.pendingVersion}`}):this.set(e,t,"synced",{version:s.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(i){let s=X(i);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(s.code)||(t.applied=r),s.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:s.code,message:`${s.message} (${s.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let i=Object.fromEntries([...this.roots].map(([a,c])=>[a,{root:c.root,state:c.state,version:c.version,message:c.message,code:c.code,at:c.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(a=>a.id),plugins:i,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let o=`${r}.${process.pid}.tmp`;try{await ah(dh(r),{recursive:!0}),await oh(o,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await ch(o,r)}catch{}}};async function gh(n){let e=[],t=async(r,i)=>{let s=await nh(r);e.push(`${i}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await t(it(n,"package.json"),"package.json");let r=async(i,s,o)=>{if(!(o>16||e.length>8192))for(let a of(await sh(i,{withFileTypes:!0})).sort((c,l)=>c.name.localeCompare(l.name)))a.isDirectory()?await r(it(i,a.name),`${s}/${a.name}`,o+1):await t(it(i,a.name),`${s}/${a.name}`)};if(await r(it(n,"dist"),"dist",0),!e.some(i=>i.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function wh(n){try{return[...ft(n).secrets]}catch{return[]}}var Lr=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Wr;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Ba,e.dev?.enabled&&(this.devWatcher=new $r({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let r=await this.inventory();return r.plugins.find(i=>i.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):r}}})),this.adapter=new Tr({policy:(t,r)=>{let i=e.policy?.(t,r);return{...i,enabled:!this.recovery.has(t)&&this.manager.tools.some(s=>s.pluginId===t)&&i?.enabled!==!1}},invoke:async(t,r,i)=>{i?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(a=>a.pluginId===t);if(!s)throw new f("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,s.generation,r);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Mr({...e,lifecycle:(t,r,i)=>this.lifecycle(t,r,i),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(tn(this.trusted,t).tools).length)throw new f("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,r),this.adapter.validateChange(t,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async r=>{try{let i=r.enabled?this.manager.tools.find(s=>s.pluginId===t)?.descriptors:[];if(!i)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,i),r.enabled){let s=await this.manager.installer.load(t,r.version);this.documents.set(t,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:wh(s.manifest)})}else this.documents.delete(t);this.adapter.change(t,i),await this.coordinator(t).committed(r),e.changed?.(),this.recovery.delete(t)}catch(i){throw this.recovery.set(t,i),await this.coordinator(t).committed(r).catch(()=>{}),i}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,r,i)=>{let s=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!s)throw new f("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(r))throw new f("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return i===null?await s.delete(t,r):await s.set(t,r,i),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let r=this.options.capabilities?.secrets;if(!r)throw new f("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let s=this.documents.get(t.pluginId)?.secrets.includes(t.name)?rn(t.pluginId,t.name):void 0;if(!s)throw new f("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,s)}let i=await this.deviceFlows.poll(t.deviceId);return i.status!=="granted"?{status:i.status}:(await r.set(i.pluginId,i.name,i.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,r)=>{if(!this.options.approvals)throw new f("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,r),this.inventory()},action:(t,r)=>this.action(t,r?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new f("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let r=t,i=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(i))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let r=tn(this.trusted,e);for(let i of t)if(!Object.hasOwn(r.tools,i.name)||r.tools[i.name]!==i.action||i.readonly!==r.readonlyActions.includes(i.action))throw new f("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new f("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||t&&(r.cwd!==t.cwd||r.workspaceId!==t.workspaceId))throw new f("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let r=this.manager.tools.find(i=>i.pluginId===e);if(!r||r.generation!==t)throw new f("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,t=!1){let r=this.queue.then(async()=>{if(this.closing&&!t)throw new f("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,t,r=!1){let i=this.switches.then(async()=>{if(this.closing&&!r)throw new f("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await t();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new rt(nn(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new f("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=i.catch(()=>{}),i.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let t,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(i=>{t=setTimeout(()=>i(!1),e),t.unref?.()})])}finally{clearTimeout(t)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Oe)try{let t=await new rt(nn(this.options.root,"data"),e.id).active();this.views.set(e.id,new Bt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new Bt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=nn(this.options.root,"host-version.json");(await te(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await ee(this.options.root),await W(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()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,r=new Map;for(let i of e.plugins){let s=i.enabled?this.documents.get(i.id)?.secrets??[]:[];t&&s.length&&r.set(i.id,await Promise.all(s.map(async o=>{let a=rn(i.id,o);return{name:o,configured:await t.has(i.id,o),...a?{signIn:a.clientId?"browser":"token-page",...a.createUrl?{createUrl:a.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(i=>({pluginId:i.id,name:i.name,official:i.official,installed:i.installed,enabled:i.enabled,description:i.description,...r.has(i.id)?{secrets:r.get(i.id)}:{},icon:(this.options.catalog??Oe).find(s=>s.id===i.id)?.icon,hasRetainedData:i.activeVersion!==null,phase:this.recovery.has(i.id)?"reconnect-required":i.phase,updatePolicy:i.updatePolicy,pinnedVersion:i.pinnedVersion,updateDiagnostic:i.updateDiagnostic,...i.enabled&&i.activeVersion?{version:i.activeVersion}:i.version?{version:i.version}:{},...i.availableVersion?{availableVersion:i.availableVersion}:{},...i.pendingVersion?{pendingVersion:i.pendingVersion}:{},...i.generation!==null?{generation:i.generation}:{},...this.recovery.has(i.id)||i.error?{error:this.recovery.get(i.id)instanceof Error?this.recovery.get(i.id).message:i.error?.message??"Recovery required",errorCode:this.recovery.has(i.id)?"reconnect_required":i.error?.code}:{},...i.enabled&&i.assetBase&&this.documents.has(i.id)&&this.trusted.has(i.id)?{documentUrl:i.assetBase+this.documents.get(i.id).document,controllerUrl:i.assetBase+this.documents.get(i.id).controller,contribution:structuredClone(this.trusted.get(i.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new f("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new f("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let t=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(t){if(this.downloads.has(e.pluginId))throw new f("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,t)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new f("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let i=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||i&&typeof i=="object"&&"reconnectRequired"in i&&i.reconnectRequired)throw new f("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new f("action_denied","Action is not reviewed by this host",{status:403});let i=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:mh(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new f("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new f("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{i()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let s of this.views.values())s.allowImmediateReopen(!0);let t=await this.manager.suspendForRestart(e),r=!1,i=async()=>{if(!r)try{await t(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(t){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),t}finally{for(let t of this.views.values())t.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as yh,readdir as vh,unlink as bh}from"node:fs/promises";import{join as wt}from"node:path";import{randomUUID as kh}from"node:crypto";var sn="hosted-migration.json";function Ya(n,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:i}=t.scope,s=wt(n,V(JSON.stringify([r,i])));await ee(n),await ee(s);let o=wt(s,"scope.lock"),a;try{a=await yh(o,"wx",384)}catch(c){throw c.code==="EEXIST"?new f("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):c}try{await a.writeFile(JSON.stringify({pid:process.pid,operationId:kh()}));let c=await te(wt(s,sn));if(c&&(c.version!==1||c.pluginId!==e))throw new f("invalid_storage","Legacy scope belongs to another migration");let l=await vh(s),p=[];for(let h of l){if(h==="scope.lock"||h==="focus.json"||h===sn||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(h))continue;if(!/^[\w-]{1,80}\.json$/.test(h))throw new f("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new f("invalid_storage","Too many legacy checkpoints");let w=await te(wt(s,h),3*512*1024);if(!w||w.version!==1||w.cwd!==r||w.sessionId!==i||!w.draft||h!==`${w.draft.id}.json`)throw new f("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(w.draft)}let u=await te(wt(s,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(h=>h.id===u)))throw new f("invalid_storage","Invalid legacy focused drawing");return c||await W(wt(s,sn),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await a.close(),await bh(o)}}}import{join as Rh}from"node:path";import{randomUUID as Ph}from"node:crypto";var Ih=6e4,Ur=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:r,title:i})=>({id:e,pluginId:t,sessionId:r,title:i}))}async authorize(e,t){let r=this.entries.get(t);if(r&&r.pluginId!==e)throw new f("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new f("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<Ih?new f("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:Ph(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new f("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,t){let r=[...this.entries.values()].find(i=>i.id===e&&i.status==="pending");if(!r)throw new f("unknown_approval","No such pending approval",{status:404});r.status=t?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as Sh,readFile as Eh,rename as xh,writeFile as _h}from"node:fs/promises";import{randomUUID as Th,createHash as Ah}from"node:crypto";import{join as Qa}from"node:path";var Vr=class{dir;queue=Promise.resolve();constructor(e){this.dir=Qa(e,"secrets")}file=e=>Qa(this.dir,`${Ah("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Eh(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!je(t))throw new f("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let t=this.queue.then(e,e);return this.queue=t.catch(()=>{}),t}async get(e,t){return(await this.read(e))[t]??null}has(e,t){return this.get(e,t).then(r=>r!==null)}set(e,t,r){return this.mutate(e,i=>{i[t]=r})}delete(e,t){return this.mutate(e,r=>{delete r[t]})}mutate(e,t){return this.serialize(async()=>{let r=await this.read(e);t(r),await Sh(this.dir,{recursive:!0,mode:448});let i=`${this.file(e)}.${Th()}.tmp`;await _h(i,JSON.stringify(r),{mode:384}),await xh(i,this.file(e))})}};function Za(n,e){let t=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:i,title:s,prompt:o}){let a=await n.createDetached(i,r,s);try{await n.sendDetached(a,o,!1)}catch(c){throw await n.releaseDetached(a),c}return{sessionId:a}},ownerOf:r=>n.detachedOwner(r),activeCount:r=>n.detachedCount(r),async send(r,i,s){let o=n.detachedOwner(r);if(s==="execute"&&(!o||!await e(o,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await n.sendDetached(r,i,s==="execute")},abort:r=>n.abortDetached(r),release:r=>n.releaseDetached(r),async events(r,i){let s=n.detachedEvents(r,i);return{events:s.events.map(t),next:s.next}}}}var Ch="scheduler";function ec(n){let e=new Ur({describe:n.sessionTitle,changed:n.changed}),t=()=>{let i=n.sessions();if(!i)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return i},r={createDetached:(...i)=>t().createDetached(...i),detachedOwner:i=>n.sessions()?.detachedOwner(i)??null,detachedCount:i=>n.sessions()?.detachedCount(i)??0,sendDetached:(...i)=>t().sendDetached(...i),abortDetached:i=>t().abortDetached(i),releaseDetached:async i=>{e.forget(i),await t().releaseDetached(i)},detachedEvents:(...i)=>t().detachedEvents(...i)};return{approvals:e,capabilities:{secrets:new Vr(Rh(n.root,"capability-secrets")),sessions:Za(r,(i,s)=>e.authorize(i,s))},scheduledScope:()=>{let i=n.activeWorkspace();if(!i)return null;try{return n.trustedScope(i,Ch)}catch{return null}}}}async function Nh(){for(let n of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=ar(n),t=new _e({env:n,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:_t,buildId:Ee,browser:ar({}).browser}}async function tc(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let n=new _e({monitor:!1});try{if(await n.ready,!n.enabled)throw new Error("Sentry verification transport is disabled");let e=n.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await n.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:_t,buildId:Ee}}finally{await n.close()}}var qt=bt(Oh(Wh(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 We(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:He()}),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 We(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:He()}),ie()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function Br(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var Vh=null;function Bh(){return Vh??=jh.create({refreshOnCreate:!1})}var zr=new Map;async function vt(){let n=await Bh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of zr.keys())t.has(r)||(n.unregisterProvider(r),zr.delete(r));for(let r of t){let i=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),o=i??s;!o||zr.get(r)===o||(i?n.registerNativeProvider(i):s&&n.registerProvider(r,s),zr.set(r,o))}return await n.refresh({allowNetwork:!1}),n}function ne(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():He()}function He(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...co(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 pn(n,e,t,r,i){let s=pe(n);Me({...He(),idle:s.isIdle()},e,i);let o=s.isIdle();o&&pt(()=>d.hosted?.adapter.assertAdmission(),r,(a,c)=>d.bridge?.reportError?.(a,c)),o&&(d.operation=r);try{let a=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===n)await d.replacementContext.sendUserMessage(a,{expandPromptTemplates:!0,deliverAs:i});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(a,{expandPromptTemplates:!0,deliverAs:i})}d.current?.sessionManager.getSessionId()===n&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:He()})}catch(a){throw o&&(d.operation=void 0),a}}function cn(){let n=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!n||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==n||d.tuiAgentError)return!1;let r=He();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!r.paused&&!r.interactions.length};d.tuiPrompts.schedule(t,(r,i,s)=>pn(n,r,i,s))}function se(n){if(ne().sessionId!==n)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function oc(){let n=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=ne(),i=d.current?He():null,s=await Ke(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=i?await Ke(i.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,a=await dn.listAll(),c=d.workspaceSessions?.retainedSessions()??[];i&&o&&c.push({sessionId:i.sessionId,cwd:o,path:null,name:i.name,modified:i.messages.at(-1)?.timestamp??new Date().toISOString(),idle:i.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&i.idle&&d.tuiPrompts.length===0&&!i.messages.some(p=>p.role==="user")});let l=(await Promise.all(n.map(async p=>{let h=(await lt(p.path,a).catch(w=>(w instanceof Nt?p.available=!1:d.bridge?.reportError?.(w,{stage:"workspace_sessions"}),[]))).map(w=>({id:w.id,workspaceId:p.id,path:w.path,name:w.name||w.firstMessage?.slice(0,50)||"",modified:w.modified.toISOString(),idle:!0}));for(let w of c.filter(v=>v.cwd===p.path)){if(w.blank&&w.sessionId!==t.sessionId)continue;let v=h.findIndex(b=>b.id===w.sessionId),m={id:w.sessionId,workspaceId:p.id,path:w.path??h[v]?.path??null,name:w.name,modified:w.modified,idle:w.idle};v<0?h.unshift(m):h[v]=m}return p.path===s&&!h.some(w=>w.id===t.sessionId)&&h.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),h}))).flat();return{items:n,activeId:e,sessions:l}}var ic=0;async function ie(){if(!d.bridge)return;let n=++ic;try{let e=await oc();n===ic&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function ln(n,e=!1){let t=d.workspaces?.get(n);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=n,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:ne()});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=n,d.bridge?.publish({type:"snapshot",session:ne()})}await ie()}async function nc(n,e,t){let r=d.workspaces?.get(n);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let i=await Ae(r.path);if(d.workspaceSessions?.hasSession(i,e)||d.current?.sessionManager.getSessionId()===e&&await Ke(d.current.cwd)===i)return r;if(!(await lt(i)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function pe(n){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==n)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function ae(n){d.current=n,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:ne()})}function ac(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let n=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!n)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return $h.create(n,void 0,{projectTrusted:e})}async function cc(){let n=ac(),e=i=>({packages:(i.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:i.extensions??[],skills:i.skills??[]}),t=new sc({cwd:ne().cwd,agentDir:we(),settingsManager:n}),r=Vo(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:n.isProjectTrusted(),global:e(n.getGlobalSettings()),project:e(n.getProjectSettings()),installed:r}}async function zh(n){se(n.sessionId);let e=d.selected==="tui"?pe(n.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=ac();if(n.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=n.value.trim(),i=n.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(n.kind==="packages"){let s=new sc({cwd:ne().cwd,agentDir:we(),settingsManager:t});n.action==="add"?await s.installAndPersist(r,{local:n.scope==="project"}):await s.removeAndPersist(r,{local:n.scope==="project"})}else if(n.kind==="extensions"){let s=i.extensions??[],o=n.action==="add"?[...new Set([...s,r])]:s.filter(a=>a!==r);n.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let s=i.skills??[],o=n.action==="add"?[...new Set([...s,r])]:s.filter(a=>a!==r);n.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&ae(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await cc()}function qr(n,e=Ei){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=(l,p)=>{let u=on(l);return{cwd:u,sessionId:p,workspaceId:rc("sha256").update(u).digest("hex")}},r=yt(we(),"pi-web","hosted"),i=new jr({configPath:Ka(we())});d.hosted??=new Lr({root:r,...i.enabled?{dev:i,devStatusPath:Xa(we())}:{},...i.catalog.length?{catalog:[...Oe,...i.catalog],devArchives:i.archives,devRoots:i.roots}:{},...ec({root:r,sessions:()=>d.workspaceSessions,activeWorkspace:()=>d.workspaceSessions?.path??null,trustedScope:t,sessionTitle:l=>d.workspaceSessions?.retainedSessions().find(p=>p.sessionId===l)?.name,changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(Hh(bt(qt,"../../package.json"),"utf8")).version,packageRoot:bt(qt,"../.."),workerEntry:bt(qt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${rc("sha256").update(we()).digest("hex")}`,resolveSession:l=>{let p=d.current;if(p?.sessionManager.getSessionId()===l)return t(p.cwd,l);let u=d.workspaceSessions?.hostedScope(l);return u?t(u.cwd,l):null},legacy:()=>Ya(yt(we(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(cn),d.pi=n;let s=Es({async run(...l){if(!d.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return d.bridge.runPluginTool(...l)},async ask(l,p){if(d.pi&&l.sessionId===d.current?.sessionManager.getSessionId())return hr(d.pi.events,l,p);if(!d.workspaceSessions)throw new Error("The Web workbench is not open");return d.workspaceSessions.requestInteraction(l,p)}});for(let l of s)n.registerTool(l);d.tools?.clear(),d.tools=new dt({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(l,p)=>d.bridge?.reportError?.(l,p),breadcrumb:(l,p)=>d.bridge?.breadcrumb?.(l,p),anonymize:l=>d.telemetry?.session(l)??"unavailable"});let o=l=>({...d.operation,session:d.telemetry?.session(l.sessionManager.getSessionId()),piVersion:an,model:l.model?`${l.model.provider}/${l.model.id}`:null,thinkingLevel:l.thinkingLevel});d.interactions?.dispose(),d.interactions=new ct(n.events,l=>!!d.bridge&&l.sessionId===d.current?.sessionManager.getSessionId()&&(!!d.tuiCatalog?.has(l.pluginId)||Object.values(de).includes(l.pluginId)),()=>{d.current&&d.selected==="tui"&&ae(d.current)});let a=()=>{d.stopChanged?.(),d.stopChanged=n.events.on(gr,()=>{d.selected==="tui"&&d.current&&ae(d.current)})};a(),n.on("session_start",async(l,p)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,a(),d.current=p,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(n,t(p.cwd,p.sessionManager.getSessionId())),d.hosted&&!await d.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),d.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(d.tuiPrompts=new We(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:He()}),ie()}),d.tuiPromptSessionId=p.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let u=await Ye.discover(p.cwd,p.isProjectTrusted?.()??!1);if(d.current!==p)return;d.tuiCatalog=u}d.replacementSessionId!==p.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),ae(p),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(p.cwd).then(async u=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(d.activeWorkspaceId=u.id,await ie())}).catch(u=>{d.bridge?.publish({type:"error",message:u instanceof Error?u.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(u,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,c(p).catch(u=>{p.ui.notify(u instanceof Error?u.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),n.on("agent_start",(l,p)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",o(p)),ae(p),ie()}),n.on("agent_end",(l,p)=>ae(p)),n.on("agent_settled",(l,p)=>{d.bridge?.breadcrumb?.("agent_end",o(p)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,cn(),ae(p),ie()}),n.on("tool_execution_start",(l,p)=>{d.tools?.start(l,o(p))}),n.on("tool_execution_end",(l,p)=>{d.tools?.end(l,o(p))}),n.on("model_select",(l,p)=>ae(p)),n.on("thinking_level_select",(l,p)=>ae(p)),n.on("message_end",(l,p)=>{if(l.message.role==="assistant"&&l.message.stopReason==="error"){d.tuiAgentError=!0;let u=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion:an});d.selected==="tui"&&d.bridge?.publish({type:"error",message:l.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:u,inTranscript:!0,...d.operation})}l.message.role==="toolResult"&&d.tools?.message(l.message,o(p)),l.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&l.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),ae(p),ie()}),n.on("session_info_changed",(l,p)=>ae(p)),n.on("message_update",(l,p)=>{if(d.current=p,l.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(l.message.timestamp).toISOString(),blocks:Je(l.message.content)},d.selected!=="tui"||d.bridge===null))return;let u=Date.now();u-d.lastStreamAt<60||(d.lastStreamAt=u,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),n.on("session_shutdown",async l=>{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,l.reason==="new"||l.reason==="resume"||l.reason==="fork"||l.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let p=d.bridge,u=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let h=d.workspaceSessions;d.workspaceSessions=null,await h?.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,p?await p.close():await u?.close()});let c=async l=>{d.telemetry??=new _e;try{d.current=l,d.commandContext="newSession"in l?l:null,d.pi=n,d.tuiCatalog=await Ye.discover(l.cwd,l.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new fr(fo(we())),await d.workspaces.load());try{await d.workspaces.discover((await dn.listAll()).map(h=>h.cwd))}catch(h){l.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${h instanceof Error?h.message:String(h)}`,"warning")}let p=await d.workspaces.add(l.cwd);if(d.selected==="tui"&&(d.activeWorkspaceId=p.id),d.bridge&&(d.bridge.protocolVersion!==7||d.bridge.buildId!==Ee||typeof d.bridge.reportError!="function"||typeof d.bridge.runPluginTool!="function")){let h=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 h.close(),await d.telemetry.close(),d.telemetry=new _e}if(d.bridge===null){let h=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,w=h?.session&&h.path?{path:h.path,sessionManager:h.session.sessionManager}:null;h&&(await h.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new vr(m=>{d.selected==="sdk"&&d.bridge?.publish(m)},()=>d.current?.model,m=>{try{return!!d.current&&on(d.current.cwd)===m&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(m,b)=>d.bridge?.reportError?.(m,b),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(m,b)=>d.bridge?.breadcrumb?.(m,b),anonymize:m=>d.telemetry?.session(m)??"unavailable"},()=>{ie()},s,{adapter:d.hosted.adapter,scope:t}),w&&await d.workspaceSessions.open(w.path,{sessionManager:w.sessionManager});let v={hosted:d.hosted?.handlers,selfUpdate:new _r({agentDir:we(),packageRoot:bt(qt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:m=>d.hosted.manager.hostUpdateWarnings(m),prefetchPlugins:(m,b)=>d.hosted.manager.prefetchForHost(m,b),beforeRestart:m=>d.hosted.prepareRestart(m)}),snapshot:ne,busyGitWorkspaces:()=>{let m=(d.workspaceSessions?.retainedSessions()??[]).filter(b=>!b.idle).map(b=>b.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{m.push(on(d.current.cwd))}catch{m.push(d.current.cwd)}return m},plugins:async()=>{let m=Br();return await m?.refreshAssets(),m?.view()??{plugins:[],errors:[]}},pluginAsset:async m=>Br()?.asset(m)??null,async invokePluginAction(m,b,P,S){if(se(m),!Br()?.has(b))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let _=d.selected,C=d.tuiGeneration,H=d.workspaceSessions?.session,A={requestId:Lh(),sessionId:m,pluginId:b,action:P,input:S},K=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(A):await mr(d.pi.events,A,15e3,d.tuiWaitController.signal);if(se(m),_!==d.selected||(_==="tui"?C!==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),K},async resolvePluginInteraction(m,b,P,S){if(se(m),!Br()?.has(b))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(m,b,P,S):d.interactions.resolve(m,b,P,S)},image(m,b,P){se(m);let _=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(H=>H.id===b);if(_?.type!=="message"||_.message.role!=="user"||!Array.isArray(_.message.content))return null;let C=_.message.content[P];return C?.type!=="image"?null:{data:Buffer.from(C.data,"base64"),mimeType:C.mimeType}},async workspaces(){return oc()},async addWorkspace(m,b){let P=await d.workspaces.add(m,b);try{await ln(P.id,!0)}catch(S){throw await ie(),S}},async selectWorkspace(m){await ln(m)},async newSessionInWorkspace(m){await ln(m,!0)},async removeWorkspace(m){if(m===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(m),await ie()},async selectSession(m,b,P){let S=d.workspaces?.get(m);if(!S)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(S.path),b===d.current?.sessionManager.getSessionId()&&S.path===await Ke(d.current.cwd))d.selected="tui",d.activeWorkspaceId=m,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:ne()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===b&&d.workspaceSessions.path===S.path)return;if(d.workspaceSessions?.hasSession(S.path,b))await d.workspaceSessions.open(S.path,{sessionId:b});else{if(!(await lt(S.path)).some(C=>C.id===b&&C.path===P))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(S.path,{sessionFile:P})}d.selected="sdk",d.activeWorkspaceId=m,d.bridge?.publish({type:"snapshot",session:ne()})}await ie()},async renameSession(m,b,P,S){let _=S.replace(/\s+/g," ").trim();if(_.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await nc(m,b,P),d.current?.sessionManager.getSessionId()===b&&d.pi?d.pi.setSessionName(_):d.workspaceSessions?.rename(b,_)||dn.open(P).appendSessionInfo(_),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===b&&d.bridge?.publish({type:"snapshot",session:ne()}),await ie()},async deleteSession(m,b,P){let S=await nc(m,b,P);if(d.current?.sessionManager.getSessionId()===b)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 _=await d.workspaceSessions?.discard(b)??null,C=_?.path??(P||null);C&&await Uo(C,we()),_?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(S.path,"new"),d.selected="sdk",d.activeWorkspaceId=m,d.bridge?.publish({type:"snapshot",session:ne()})),await ie()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let m=d.current;if(!m)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let b=m.scopedModels?.map(P=>`${P.model.provider}/${P.model.id}`)??[];return m.modelRegistry.getAvailable().filter(P=>b.length===0||b.includes(`${P.provider}/${P.id}`)).map(P=>({provider:P.provider,id:P.id,name:P.name}))},async providers(){let m=await vt(),b=new Set((await m.listCredentials()).map(P=>P.providerId));return m.getProviders().map(P=>({id:P.id,name:P.name,configured:m.getProviderAuthStatus(P.id).configured,storedCredential:b.has(P.id),methods:[P.auth.apiKey?.login?"api_key":null,P.auth.oauth?"oauth":null].filter(S=>S!==null)}))},async providerModels(m){let b=await vt();return qs(yt(we(),"models.json"),m,b)},async updateProviderModel(m,b,P){if(se(m),d.selected==="tui"?!pe(m).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=ne().model;if(P.action==="remove"&&S===`${b}/${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&&S===`${b}/${P.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let _=await vt();await Gs(yt(we(),"models.json"),b,P,_),await _.refresh({providers:[b],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[b],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[b],allowNetwork:!1});let C=P.action==="save"?P.model.id:P.action==="base_url"&&S?.startsWith(`${b}/`)?S.slice(b.length+1):null;if(C&&S===`${b}/${C}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(b,C)}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=pe(m),A=H.modelRegistry.find(b,C);if(!A||!d.pi||!await d.pi.setModel(A))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(m,b){if(se(m),d.selected==="tui"?!pe(m).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 vt();if(!(await P.listCredentials()).some(S=>S.providerId===b))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await P.logout(b),await d.current?.modelRegistry.refresh({providers:[b],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[b],allowNetwork:!1})},async loginProvider(m,b,P){let S=await vt();await S.login(m,b,Fs(m,b,P)),await S.refresh({providers:[m],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[m],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[m],allowNetwork:!1})},async addCustomProvider(m,b){if(se(m),d.selected==="tui"?!pe(m).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 vt();if(P.getProvider(b.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await Ls(yt(we(),"models.json"),b),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(m=>m.name!=="web"&&m.name!=="web-dev-reload").map(m=>({name:m.name,description:m.description})):[]},async compact(m){if(se(m),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:ne()});return}let b=pe(m);if(!b.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");b.compact()},async setModel(m,b,P){if(se(m),d.selected==="sdk"){await d.workspaceSessions.setModel(b,P);return}let S=pe(m);if(!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let _=S.modelRegistry.find(b,P);if(!_||!S.modelRegistry.getAvailable().some(C=>C.provider===b&&C.id===P))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(_))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");ae(S)},async setThinkingLevel(m,b){if(se(m),!["off","minimal","low","medium","high","xhigh"].includes(b))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(d.selected==="sdk"){let _=d.workspaceSessions?.session;if(!_||!_.isIdle||!_.getAvailableThinkingLevels().includes(b))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");_.setThinkingLevel(b),d.bridge?.publish({type:"snapshot",session:ne()});return}let S=pe(m);if(!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!S.model||!Fh(S.model).includes(b))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(b),ae(S)},config:cc,updateConfig:zh,async send(m,b,P=[],S,_){if(se(m),d.selected==="sdk"){await d.workspaceSessions.send(b,P,S,_);return}let C=pe(m);if(Me(He(),b,_),_==="followUp"&&(!C.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(b,P,S),cn();return}if(C.isIdle()&&d.tuiPrompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await pn(m,b,P,S,_)},async updateQueuedPrompt(m,b,P,S){if(se(m),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(b,P,S);return}if(S.kind==="steer"&&pe(m).isIdle())throw new oe("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(b,P,S,(_,C,H)=>pn(m,_,C,H,"steer"))},async abort(m){if(se(m),d.selected==="sdk")await d.workspaceSessions.stop();else{let b=pe(m);if(b.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(Rt),b.abort()}},async resume(m,b){if(se(m),d.selected==="sdk"){await d.workspaceSessions.resume(b);return}let P=pe(m);if(pt(()=>d.hosted?.adapter.assertAdmission(),b,(S,_)=>d.bridge?.reportError?.(S,_)),!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=b;try{d.pi.sendMessage(wr(ne().messages),{triggerTurn:!0})}catch(S){throw d.operation=void 0,S}},async newSession(m){if(se(m),d.selected==="sdk"){let S=d.workspaces?.get(d.activeWorkspaceId??"");if(!S)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(S.path)||await d.workspaceSessions.open(S.path,"new"),await ie();return}let b=pe(m);if(!b.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(b.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:ne()}),await ie();return}if((await d.commandContext.newSession({withSession:async S=>{d.commandContext=S,d.replacementContext=S,d.replacementSessionId=S.sessionManager.getSessionId(),d.current=S}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await ie()}};v.addWorkspace=d.lifecycle.wrap(v.addWorkspace),v.selectWorkspace=d.lifecycle.wrap(v.selectWorkspace),v.newSessionInWorkspace=d.lifecycle.wrap(v.newSessionInWorkspace),v.removeWorkspace=d.lifecycle.wrap(v.removeWorkspace),v.selectSession=d.lifecycle.wrap(v.selectSession),v.renameSession=d.lifecycle.wrap(v.renameSession),v.deleteSession=d.lifecycle.wrap(v.deleteSession),v.newSession=d.lifecycle.wrap(v.newSession),v.updateConfig=d.lifecycle.wrap(v.updateConfig),d.bridge=await ao(v,qt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let h=[],w=null;for(let v of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(Dh).filter(Boolean))try{h.push(Mh(yt(bt(v),"dist"),(m,b)=>{let P=String(b??"");["client.js","client.css"].includes(P)&&(w&&clearTimeout(w),w=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(m){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${v}: ${String(m)}`})}d.stopPluginWatch=()=>{for(let v of h)v.close();w&&clearTimeout(w)}}let u=await e(d.bridge.url).catch(()=>!1);l.ui.notify(`pi-webapp: ${d.bridge.url}`,u?"info":"warning"),l.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw d.telemetry?.capture(p,{stage:"open_web",piVersion:an}),d.bridge||(await d.telemetry?.close(),d.telemetry=null),p}};n.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(l,p)=>c(p)}),n.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(l,p)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(l))throw new Error("Launcher stop receipt ID required");try{await d.hosted?.shutdown(),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:l,ok:!0})}`,"info")}catch(u){console.error("pi-webapp: plugin shutdown refused the stop request:",u),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:l,ok:!1})}`,"warning")}}}),n.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(l,p)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await p.waitForIdle(),await d.lifecycle.run(async()=>{let u=d.workspaceSessions?.session;u&&(await u.waitForIdle(),await d.workspaceSessions.reload()),await p.reload()}))}})}var LP=qr;export{LP as default,Nh as verifySentryDisabledRelease,tc as verifySentryNodeRelease};
52
56
 
53
- //# debugId=493c6a42-4fe5-4290-8ae9-a8d404360b8a
57
+ //# debugId=4bfba74a-9d1c-4bfc-bdd9-a7aeb8a78cad