pi-webapp 0.1.53-alpha.1 → 0.1.54-alpha.1

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 (31) hide show
  1. package/dist/extension.js +3 -3
  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 +41 -41
  6. package/web/dist/assets/{MarkdownText-CBiL97gk.js → MarkdownText-Caal7CQa.js} +4 -4
  7. package/web/dist/assets/{app-CRTzSso6.js → app-hks8V4Ne.js} +13 -13
  8. package/web/dist/assets/app.css +1 -1
  9. package/web/dist/assets/app.js +4 -4
  10. package/web/dist/assets/{code-editor-DeAOkPrq.js → code-editor-BBYUAKH0.js} +4 -4
  11. package/web/dist/assets/{dist-BNmsN76A.js → dist-AmrJVFAB.js} +2 -2
  12. package/web/dist/assets/{dist-to0Y4VHe.js → dist-B3WnulhR.js} +2 -2
  13. package/web/dist/assets/{dist-B5emzMvH.js → dist-Bimmlq2z.js} +2 -2
  14. package/web/dist/assets/{dist-ThlP4B0-.js → dist-CBx8VRGq.js} +2 -2
  15. package/web/dist/assets/{dist-Bp1qxOA-.js → dist-CODCpnJW.js} +2 -2
  16. package/web/dist/assets/{dist-y5XhVIrr.js → dist-CT8MVz6U.js} +2 -2
  17. package/web/dist/assets/{dist-C3T17C1Q.js → dist-CZjG3cBA.js} +2 -2
  18. package/web/dist/assets/{dist-ekmOAsAL.js → dist-D8Dfw8A3.js} +2 -2
  19. package/web/dist/assets/{dist-rREmcN_F.js → dist-D8df1aZS.js} +2 -2
  20. package/web/dist/assets/{dist-CYNv_x25.js → dist-DJYhX4BP.js} +2 -2
  21. package/web/dist/assets/{dist-DTjHomg3.js → dist-DnWEnPKO.js} +2 -2
  22. package/web/dist/assets/{graphql-BfvlZifS.js → graphql-ClixcZMM.js} +2 -2
  23. package/web/dist/assets/{http-CMFHpKAi.js → http-Bj2ogFVC.js} +2 -2
  24. package/web/dist/assets/{php-AbwdN8Ef.js → php-CsUDSQtt.js} +2 -2
  25. package/web/dist/assets/{plugin-kH2lR7pE.js → plugin-BqxLHLyt.js} +2 -2
  26. package/web/dist/assets/{plugin-CnTnCTg7.js → plugin-DBjzIJ41.js} +2 -2
  27. package/web/dist/assets/{plugin-Bfd7f_vy.js → plugin-DalAFVX9.js} +3 -3
  28. package/web/dist/assets/{rst-DPJzqmXX.js → rst-DolQ9Oyd.js} +2 -2
  29. package/web/dist/assets/{ruby-Hx9so-WR.js → ruby-BKs5tHLp.js} +2 -2
  30. package/web/dist/assets/{svelte-DLqN0QFL.js → svelte-C8HwmQtr.js} +2 -2
  31. package/web/dist/assets/{vue-XwJifyVN.js → vue-CmwBrdHT.js} +2 -2
package/dist/extension.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(){try{var s=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="458ba3da-fce1-440b-bce1-403e684ef316",s._sentryDebugIdIdentifier="sentry-dbid-458ba3da-fce1-440b-bce1-403e684ef316")}catch{}})();import{delimiter as ih,dirname as sh,join as wt,resolve as vt}from"node:path";import{readFileSync as nh,realpathSync as Yi,watch as oh}from"node:fs";import{fileURLToPath as ah}from"node:url";import{DefaultPackageManager as Oa,getAgentDir as me,ModelRuntime as ch,SessionManager as ts,SettingsManager as lh,VERSION as Qi}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as dh}from"@earendil-works/pi-ai";import{randomBytes as Mn,randomUUID as ii,timingSafeEqual as Gl}from"node:crypto";import{readFile as Jl,readdir as Kl}from"node:fs/promises";import{createServer as Xl}from"node:http";import{join as si}from"node:path";import{getAgentDir as Yl}from"@earendil-works/pi-coding-agent";import{isAbsolute as hc,relative as gc}from"node:path";var rt={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var os={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 $a}from"node:child_process";import{realpath as Fa}from"node:fs/promises";import{isAbsolute as as,relative as Va,sep as Ua,win32 as Ba}from"node:path";var T=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function W(s,e,t=2*1024*1024,r={}){let i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=$a("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,env:{...i,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new T("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}n(p);return}if(r.write){let 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 T("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 T("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):w==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new T("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new T("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new T(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(s){let e=await Fa(s),t;try{t=(await W(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(i){if(i instanceof T&&i.status===404)return{kind:"not-repository"};if(i instanceof T&&i.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw i}let r=Va(t,e).split(Ua).join("/");if(r===".."||r.startsWith("../")||as(r))throw new T("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function Le(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||as(s)||Ba.isAbsolute(s)||s.split("/").some(e=>!e||e==="."||e===".."))throw new T("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as rc}from"node:crypto";import{lstat as qr,realpath as ks}from"node:fs/promises";import{dirname as bs,isAbsolute as ic,relative as sc,resolve as It}from"node:path";import{lstat as Za}from"node:fs/promises";import{resolve as ec}from"node:path";import{createHash as La}from"node:crypto";import{constants as Ae}from"node:fs";import{open as Br,opendir as za,realpath as cs,stat as qt}from"node:fs/promises";import{isAbsolute as ds,relative as qa,resolve as Ga,sep as Ja,win32 as Ka}from"node:path";var Xa=1e3,Ya={bytes:512*1024,lines:1e4},Lr={bytes:5*1024*1024,lines:2e5},ps=8*1024*1024,Qa=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Ur=s=>La("sha256").update(s).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 ls(s,e){let t=qa(s,e);return t!==".."&&!t.startsWith(`..${Ja}`)&&!ds(t)}async function kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ds(e)||Ka.isAbsolute(e))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await cs(s),r=Ga(t,e);if(!ls(t,r))throw new H("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let i=await cs(r);if(!ls(t,i))throw new H("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return i}async function Gt(s){try{return await s()}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 us(s,e){return Gt(async()=>{let t=await kt(s,e),r=[],i=!1;for await(let n of await za(t)){if(n.name===".git")continue;if(r.length===Xa){i=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await qt(await kt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}r.push({name:n.name,path:o,kind:c})}return r.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Qa.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:r,truncated:i}})}function fs(s){if(s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(s.subarray(0,6).toString("ascii")))return"image/gif";if(s.subarray(0,4).toString("ascii")==="RIFF"&&s.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Pt(s,e,t=Ya){return Gt(async()=>{let r=await kt(s,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,Ae.O_RDONLY|Ae.O_NONBLOCK|(Ae.O_NOFOLLOW??0));try{let n=await i.stat();if(!n.isFile())throw new H("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let o={path:e,size:n.size},c=Buffer.alloc(16);await i.read(c,0,c.length,0);let a=fs(c),l=a?ps:t.bytes;if(n.size>l)return{...o,kind:"too-large",limit:l,unit:"bytes"};let p=Buffer.alloc(Math.min(n.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>n.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 hs(s,e){return Gt(async()=>{let t=await kt(s,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,Ae.O_RDONLY|Ae.O_NONBLOCK|(Ae.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>ps)throw new H("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(i.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await r.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>i.size)throw new H("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=fs(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 gs(s,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:n,lines:o}=Lr;if(i.length>n)throw new H(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${n/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(s,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,Ae.O_RDWR|Ae.O_NONBLOCK|(Ae.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>n)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 tc=1e3,ms=512*1024,ws=1e4;function ys(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function it(s){let e=await pe(s);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,i=await W(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=i.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);n.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);n.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(n.ahead=Number(P[1]),n.behind=Number(P[2]));continue}let l=a[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,u=0;for(let P=0;P<p;P++)u=a.indexOf(" ",u)+1;let w=ys(r,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!w)continue;if(n.entries.length===tc){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),y={path:w,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},k=m===void 0?void 0:ys(r,m);k&&(y.originalPath=k),n.entries.push(y)}return n}async function vs(s,e,t){if(Le(e),!["staged","unstaged","untracked"].includes(t))throw new T("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await it(s);if(r.kind!=="repository")throw new T("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i={path:e,area:t},n=r.entries.find(c=>c.path===e);if(!n)return{...i,kind:"empty"};if(n.conflict)return{...i,kind:"conflict"};if(n.submodule)return{...i,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...i,kind:"empty"};if(!(await Za(ec(s,e))).isFile())return{...i,kind:"unsupported"};let c=await Pt(s,e);if(c.kind==="too-large")return{...i,kind:"too-large"};if(c.kind!=="text")return{...i,kind:"binary"};if(!c.text)return{...i,kind:"empty"};let a=c.text.split(`
1
+ (function(){try{var s=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="0fbf3f22-b19a-42a0-ab5a-c11e8b3ab525",s._sentryDebugIdIdentifier="sentry-dbid-0fbf3f22-b19a-42a0-ab5a-c11e8b3ab525")}catch{}})();import{delimiter as ih,dirname as sh,join as wt,resolve as vt}from"node:path";import{readFileSync as nh,realpathSync as Yi,watch as oh}from"node:fs";import{fileURLToPath as ah}from"node:url";import{DefaultPackageManager as Oa,getAgentDir as me,ModelRuntime as ch,SessionManager as ts,SettingsManager as lh,VERSION as Qi}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as dh}from"@earendil-works/pi-ai";import{randomBytes as Mn,randomUUID as ii,timingSafeEqual as Gl}from"node:crypto";import{readFile as Jl,readdir as Kl}from"node:fs/promises";import{createServer as Xl}from"node:http";import{join as si}from"node:path";import{getAgentDir as Yl}from"@earendil-works/pi-coding-agent";import{isAbsolute as hc,relative as gc}from"node:path";var rt={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var os={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 $a}from"node:child_process";import{realpath as Fa}from"node:fs/promises";import{isAbsolute as as,relative as Va,sep as Ua,win32 as Ba}from"node:path";var T=class extends Error{status;reason;constructor(e,t=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=r}};function W(s,e,t=2*1024*1024,r={}){let i=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=$a("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,env:{...i,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new T("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}n(p);return}if(r.write){let 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 T("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 T("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):w==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new T("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new T("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new T(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(s){let e=await Fa(s),t;try{t=(await W(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(i){if(i instanceof T&&i.status===404)return{kind:"not-repository"};if(i instanceof T&&i.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw i}let r=Va(t,e).split(Ua).join("/");if(r===".."||r.startsWith("../")||as(r))throw new T("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:r?`${r}/`:""}}function Le(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||as(s)||Ba.isAbsolute(s)||s.split("/").some(e=>!e||e==="."||e===".."))throw new T("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as rc}from"node:crypto";import{lstat as qr,realpath as ks}from"node:fs/promises";import{dirname as bs,isAbsolute as ic,relative as sc,resolve as It}from"node:path";import{lstat as Za}from"node:fs/promises";import{resolve as ec}from"node:path";import{createHash as La}from"node:crypto";import{constants as Ae}from"node:fs";import{open as Br,opendir as za,realpath as cs,stat as qt}from"node:fs/promises";import{isAbsolute as ds,relative as qa,resolve as Ga,sep as Ja,win32 as Ka}from"node:path";var Xa=1e3,Ya={bytes:512*1024,lines:1e4},Lr={bytes:5*1024*1024,lines:2e5},ps=8*1024*1024,Qa=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Ur=s=>La("sha256").update(s).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 ls(s,e){let t=qa(s,e);return t!==".."&&!t.startsWith(`..${Ja}`)&&!ds(t)}async function kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ds(e)||Ka.isAbsolute(e))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await cs(s),r=Ga(t,e);if(!ls(t,r))throw new H("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let i=await cs(r);if(!ls(t,i))throw new H("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return i}async function Gt(s){try{return await s()}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 us(s,e){return Gt(async()=>{let t=await kt(s,e),r=[],i=!1;for await(let n of await za(t)){if(n.name===".git")continue;if(r.length===Xa){i=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await qt(await kt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}r.push({name:n.name,path:o,kind:c})}return r.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Qa.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:r,truncated:i}})}function fs(s){if(s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(s.subarray(0,6).toString("ascii")))return"image/gif";if(s.subarray(0,4).toString("ascii")==="RIFF"&&s.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Pt(s,e,t=Ya){return Gt(async()=>{let r=await kt(s,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,Ae.O_RDONLY|Ae.O_NONBLOCK|(Ae.O_NOFOLLOW??0));try{let n=await i.stat();if(!n.isFile())throw new H("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let o={path:e,size:n.size},c=Buffer.alloc(16);await i.read(c,0,c.length,0);let a=fs(c),l=a?ps:t.bytes;if(n.size>l)return{...o,kind:"too-large",limit:l,unit:"bytes"};let p=Buffer.alloc(Math.min(n.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>n.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 hs(s,e){return Gt(async()=>{let t=await kt(s,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,Ae.O_RDONLY|Ae.O_NONBLOCK|(Ae.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>ps)throw new H("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(i.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await r.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>i.size)throw new H("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=fs(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 gs(s,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:n,lines:o}=Lr;if(i.length>n)throw new H(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${n/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(s,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,Ae.O_RDWR|Ae.O_NONBLOCK|(Ae.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>n)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 tc=1e3,ms=512*1024,ws=1e4;function ys(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function it(s){let e=await pe(s);if(e.kind!=="repository")return e;let{root:t,scope:r}=e,i=await W(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=i.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);n.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);n.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(n.ahead=Number(P[1]),n.behind=Number(P[2]));continue}let l=a[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,u=0;for(let P=0;P<p;P++)u=a.indexOf(" ",u)+1;let w=ys(r,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!w)continue;if(n.entries.length===tc){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),y={path:w,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},k=m===void 0?void 0:ys(r,m);k&&(y.originalPath=k),n.entries.push(y)}return n}async function vs(s,e,t){if(Le(e),!["staged","unstaged","untracked"].includes(t))throw new T("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await it(s);if(r.kind!=="repository")throw new T("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let i={path:e,area:t},n=r.entries.find(c=>c.path===e);if(!n)return{...i,kind:"empty"};if(n.conflict)return{...i,kind:"conflict"};if(n.submodule)return{...i,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...i,kind:"empty"};if(!(await Za(ec(s,e))).isFile())return{...i,kind:"unsupported"};let c=await Pt(s,e);if(c.kind==="too-large")return{...i,kind:"too-large"};if(c.kind!=="text")return{...i,kind:"binary"};if(!c.text)return{...i,kind:"empty"};let a=c.text.split(`
2
2
  `),l=a.at(-1)==="";l&&a.pop();let p=`--- /dev/null
3
3
  +++ b/${e.replace(/[\r\n]/g," ")}
4
4
  @@ -0,0 +1,${a.length} @@
@@ -26,7 +26,7 @@ ${l.stack.split(`
26
26
  `).slice(1).join(`
27
27
  `)}`);let u=this.reportError(p,{...n,stage:"provider_login"});a.view={id:c,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:u}}}),{...a.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(n=>n.id===t))return!1;let i=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},i(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as kl}from"node:crypto";import{readFile as Pl,rename as Il,rm as Sl,stat as El,writeFile as xl,mkdir as _l}from"node:fs/promises";import{dirname as Al}from"node:path";var Tl=["openai-completions","openai-responses","anthropic-messages"];function ei(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!Tl.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 bn(s,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 Pl(s,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let r;if(t===void 0)r={providers:{}};else{try{r=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let i={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await _l(Al(s),{recursive:!0});let n=t===void 0?384:(await El(s)).mode&511,o=`${s}.pi-web-${kl(6).toString("hex")}.tmp`;try{await xl(o,`${JSON.stringify(i,null,2)}
28
28
  `,{mode:n,flag:"wx"}),await Il(o,s)}finally{await Sl(o,{force:!0})}}import{randomBytes as Rl}from"node:crypto";import{mkdir as Cl,readFile as Nl,rename as Dl,rm as Ol,stat as Hl,writeFile as Ml}from"node:fs/promises";import{dirname as jl}from"node:path";function kn(s){if(!s||s.length>2048)return!1;try{let e=new URL(s);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function Pn(s){if(!s||typeof s!="object")return!1;let e=s;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&In(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&kn(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function In(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let t of[e.contextWindow,e.maxTokens])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(t=>t==="text"||t==="image")&&new Set(e.input).size===e.input.length}async function Sn(s){let e;try{e=await Nl(s,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function Wl(s,e,t){await Cl(jl(s),{recursive:!0});let r=t===void 0?384:(await Hl(s)).mode&511,i=`${s}.pi-web-${Rl(6).toString("hex")}.tmp`;try{await Ml(i,`${JSON.stringify(e,null,2)}
29
- `,{mode:r,flag:"wx"}),await Dl(i,s)}finally{await Ol(i,{force:!0})}}async function En(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Sn(s),i=r.providers[e],n=new Set(i?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:i?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!i?.modelOverrides?.[o.id]}))}}async function xn(s,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i,existing:n}=await Sn(s),o={...i.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!kn(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(!In(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 Wl(s,i,n)}function _n(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as An,createHash as $l}from"node:crypto";import{fileURLToPath as Fl}from"node:url";var xt="pi-webapp@0.1.53-alpha.1+ebb31dc2b865046f68d1",Ie="ebb31dc2b865046f68d1";var Vl="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ir(s=process.env,e=console.warn){let t=r=>{let i={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:xt,buildId:Ie},n=s[`PI_WEB_SENTRY_${r}_DSN`]??s.PI_WEB_SENTRY_DSN??Vl;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return i;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...i,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),i}};return{browser:t("BROWSER"),node:t("NODE")}}var Ee=class{config;ready;reporter;client;salt=An(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=Fl(import.meta.url).replace(/\\/g,"/"),r=t.lastIndexOf("/src/"),i=r>=0?t.slice(0,r+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:i)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Ie,integrations:[],transport:e.transport??(r=>$s(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:Ws,sendClientReports:!1,dataCollection:{...Hs,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=An(16).toString("hex");return this.early.push({error:st(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 $l("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 Ql}from"@earendil-works/pi-coding-agent";function Oe(s,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(s.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!s.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Ul}from"node:crypto";function _t(s){let e=[],t=s;for(;;){let r=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!r||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(r[3]))break;let i;try{i=JSON.parse(r[2])}catch{break}e.unshift({name:i,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(i)}),t=t.slice(0,r.index)}return{text:t,attachments:e}}var At=s=>Buffer.byteLength(s.text)+s.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,n)=>i+At(n),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:Ul(),revision:1,text:e,images:t.map(i=>({...i})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new oe("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let r=this.entries.find(i=>i.id===e);if(!r||r.revision!==t)throw new oe("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new oe("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,t,r,i){let n=this.find(e,t);if(r.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(r.kind==="edit"){let o=_t(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),c].filter(Boolean).join(`
29
+ `,{mode:r,flag:"wx"}),await Dl(i,s)}finally{await Ol(i,{force:!0})}}async function En(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await Sn(s),i=r.providers[e],n=new Set(i?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:i?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!i?.modelOverrides?.[o.id]}))}}async function xn(s,e,t,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i,existing:n}=await Sn(s),o={...i.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!kn(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(!In(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 Wl(s,i,n)}function _n(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as An,createHash as $l}from"node:crypto";import{fileURLToPath as Fl}from"node:url";var xt="pi-webapp@0.1.54-alpha.1+1ce6da75dc710e389314",Ie="1ce6da75dc710e389314";var Vl="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ir(s=process.env,e=console.warn){let t=r=>{let i={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:xt,buildId:Ie},n=s[`PI_WEB_SENTRY_${r}_DSN`]??s.PI_WEB_SENTRY_DSN??Vl;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return i;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...i,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),i}};return{browser:t("BROWSER"),node:t("NODE")}}var Ee=class{config;ready;reporter;client;salt=An(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=Fl(import.meta.url).replace(/\\/g,"/"),r=t.lastIndexOf("/src/"),i=r>=0?t.slice(0,r+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:i)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Ie,integrations:[],transport:e.transport??(r=>$s(t.createTransport,r)),stackParser:t.defaultStackParser,beforeSend:Ws,sendClientReports:!1,dataCollection:{...Hs,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=An(16).toString("hex");return this.early.push({error:st(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 $l("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 Ql}from"@earendil-works/pi-coding-agent";function Oe(s,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(s.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!s.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Ul}from"node:crypto";function _t(s){let e=[],t=s;for(;;){let r=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!r||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(r[3]))break;let i;try{i=JSON.parse(r[2])}catch{break}e.unshift({name:i,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(i)}),t=t.slice(0,r.index)}return{text:t,attachments:e}}var At=s=>Buffer.byteLength(s.text)+s.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,n)=>i+At(n),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:Ul(),revision:1,text:e,images:t.map(i=>({...i})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new oe("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let r=this.entries.find(i=>i.id===e);if(!r||r.revision!==t)throw new oe("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new oe("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,t,r,i){let n=this.find(e,t);if(r.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(r.kind==="edit"){let o=_t(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[r.text.trim(),c].filter(Boolean).join(`
30
30
 
31
31
  `);if(this.validateText(a),this.entries.reduce((l,p)=>l+At(p),0)-At(n)+At({text:a,images:n.images})>64*1024*1024)throw new oe("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");n.text=a,n.revision++,delete n.error,this.changed();return}await this.deliver(n,i)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(r=>r!==e)}catch(r){throw e.status="queued",e.revision++,e.error=r instanceof Error?r.message:"\u53D1\u9001\u5931\u8D25",r}finally{this.changed()}}schedule(e,t){let r=this.entries[0];this.pumping||!r||r.status!=="queued"||r.error||!e()||(this.pumping=!0,r.status="sending",r.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){r.status="queued",r.revision++,this.changed();return}await this.deliver(r,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var 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(s){let e=s&&typeof s=="object"?s:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:s instanceof Error?s.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Me=s=>s.code==="ENOENT";var Tn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function ti(s,e,t,r){if(!s)throw new h("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return s.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new h("invalid_input","Expected plugin request object",{status:400});let 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 s.views(i);if(!Array.isArray(i.views)||!i.views.length||i.views.length>64||i.views.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.operation!=="poll"))throw new h("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(i.views.map(async n=>{try{return{reply:await s.views({...n,operation:"poll",immediate:!0})}}catch(o){return{failure:sr(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(!s.decide)throw new h("hosted_unavailable","Approvals are not available in this runtime",{status:503});return s.decide(i.id,i.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(r?.draining)throw new h("host_restarting","Host is updating; secret changes are fenced",{status:409});if(i.auth!==void 0){if(!s.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 s.secretAuth({phase:"start",pluginId:i.pluginId,name:i.name});if((i.auth==="poll"||i.auth==="cancel")&&typeof i.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(i.deviceId))return s.secretAuth({phase:i.auth,deviceId:i.deviceId});throw new 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(!s.secret)throw new h("hosted_unavailable","Secrets are not available in this runtime",{status:503});return s.secret(i.pluginId,i.name,i.value)}if(typeof i.pluginId!="string"||i.pluginId.length>214)throw new 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 s.manage({pluginId:i.pluginId,operation:i.operation,...typeof i.downloadId=="string"?{downloadId:i.downloadId}:{},...typeof i.updatePolicy=="string"?{updatePolicy:i.updatePolicy}:{},...typeof i.version=="string"?{version:i.version}:{},...typeof i.reopenEditors=="boolean"?{reopenEditors:i.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof i.sessionId!="string"||!i.sessionId||i.sessionId.length>200||!Number.isSafeInteger(i.generation)||Number(i.generation)<1||typeof i.action!="string"||!/^[\w.-]{1,80}$/.test(i.action))throw new 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 s.action({sessionId:i.sessionId,pluginId:i.pluginId,generation:Number(i.generation),action:i.action,input:i.input??{},...typeof i.viewToken=="string"?{viewToken:i.viewToken}:{},...typeof i.mountId=="string"?{mountId:i.mountId}:{}},r?.draining?{checkpointOnly:!0}:void 0)}throw new h("invalid_route","Unknown hosted plugin route",{status:404})}function sr(s){let e=K(s);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as Rn}from"node:fs/promises";import{join as Cn}from"node:path";async function Nn(s){try{let e=JSON.parse(await Rn(Cn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,r=await Rn(Cn(s,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let n of[...Object.values(e),{assets:Array.isArray(r)?r:[]}])if(!(!n||typeof n!="object"))for(let o of[n.file,...Array.isArray(n.css)?n.css:[],...Array.isArray(n.assets)?n.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let i={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(n=>[`/${n}`,{path:n,type:i[n.split(".").pop()]}]))}catch{return{}}}import{access as Ll,readFile as Hn,realpath as ar,rename as Fm,rm as Vm,writeFile as Um}from"node:fs/promises";import{dirname as or,join as Ce,resolve as zl,sep as On}from"node:path";import{createRequire as ql}from"node:module";var Bl=/^(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(s){let e=typeof s=="string"&&Bl.exec(s);if(!e||e[0]!==s)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),r=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||r.some(i=>/^\d+$/.test(i)&&i.length>1&&i[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:r}}function fe(s,e){let t=xe(s),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 n=t.prerelease[i],o=r.prerelease[i];if(n===void 0||o===void 0)return n===void 0?-1:1;if(n===o)continue;let c=/^\d+$/.test(n),a=/^\d+$/.test(o);return c!==a?c?-1:1:c&&n.length!==o.length?n.length>o.length?1:-1:n>o?1:-1}return 0}function Dn(s){try{return xe(s).prerelease.length===0}catch{return!1}}function nr(s){try{return xe(s),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(s)}catch{return!1}}var je=1;async function nt(s,e){let t=ql(Ce(s,"package.json"));for(let r of t.resolve.paths(e)??[]){let i=Ce(r,e);try{if(JSON.parse(await Hn(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(s,e){if(fe(e?.version,e?.version),e.desktopProtocolVersion!==je||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await ar(zl(or(e.launcher),"..")),r=await ar(Ce(s,"pi-web","releases")),i=or(or(t));if(await ar(e.launcher)!==Ce(t,"bin","pi-webapp.mjs")||or(i)!==r||!i.startsWith(r+On)||!i.slice(r.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(i.slice(r.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let n=JSON.parse(await Hn(Ce(t,"package.json"),"utf8"));if(n.name!=="pi-webapp"||n.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(n.piWebappDesktopProtocol!==je)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await nt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(i+On))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=>Ll(a))),e.fallbackVersion!==void 0&&xe(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:je,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}var Zl={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function I(s,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:s.getHeader("X-Request-ID"),operationId:s.getHeader("X-Operation-ID")}),s.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),s.end(JSON.stringify(t))}function ed(s,e){let t=s.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let r=Buffer.from(t.slice(7),"utf8");return r.length===e.length&&Gl(r,e)}async function jn(s,e=64*1024){let t=0,r=[];for await(let i of s){let n=Buffer.isBuffer(i)?i:Buffer.from(i);if(t+=n.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");r.push(n)}return JSON.parse(Buffer.concat(r).toString("utf8"))}async function td(s){let e=0,t=[];for await(let r of s){let i=Buffer.isBuffer(r)?r:Buffer.from(r);if(e+=i.length,e>tr)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(i)}return Buffer.concat(t)}async function rd(s,e=0){await new Promise((r,i)=>{s.once("error",i),s.listen(e,"127.0.0.1",()=>{s.off("error",i),r()})});let t=s.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function Wn(s,e,t=new Ee,r={}){t.setState({piVersion:Ql});let i=process.env.PI_WEBAPP_RESTART_TOKEN,n=i&&/^[A-Za-z0-9_-]{32}$/.test(i)?i:Mn(24).toString("base64url"),o=Buffer.from(n),c=fn(),a=new Set,l=new Qt(r.pluginSettingsFile??si(Yl(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new Zt(nn(),l),u=async()=>await s.plugins?.()??{plugins:[],errors:[]},w=()=>({type:"plugin_state",disabled:p.plugins.filter(b=>!l.enabled(b.metadata.id)).map(b=>b.metadata.id)}),m=()=>{for(let b of a)b.write(`${JSON.stringify(w())}
32
32
  `)},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,A=!1,D={...Zl,...await Nn(e)};for(let b of await Kl(si(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=Xl(async(b,v)=>{let $=Mn(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(),se={requestId:ye,operationId:we(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",ye),se.operationId&&v.setHeader("X-Operation-ID",se.operationId);let x="/",Wa=performance.now(),ce=(le,g,S)=>{let C=!ze(le)&&Ms(x)?Te(le,"Agent or provider operation failed"):le,U=t.capture(C,{...se,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",{...se,route:x,method:b.method,status:v.statusCode,durationMs:Math.round(performance.now()-Wa)})});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 Jl(si(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 s.hosted?.asset(x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),v.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),v.end(g.bytes)}catch{I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(b.method==="GET"&&x.startsWith("/plugins/")){try{let g=await s.pluginAsset?.(b.url??x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),v.end(g.bytes)}catch(g){ce(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(v,404,{error:"\u672A\u627E\u5230"});return}if(!ed(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(s.hosted,x,void 0))}catch(g){let S=sr(g);I(v,S.status,S.body)}return}if(b.method==="POST"&&Tn.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 jn(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(s.hosted,x,g,{draining:E}))}catch(S){let _=sr(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 s.selfUpdate?.runningVersion()??null,desktopProtocolVersion:je,...s.selfUpdate?.launcherIdentity?{launcher:s.selfUpdate.launcherIdentity(),desktopHandoffProtocol:s.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){ce(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{I(v,200,await s.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){ce(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/image"){let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId")??"",_=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==s.snapshot().sessionId||!_||!Number.isInteger(C)||C<0||C>100){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let U=s.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!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(b.headers["content-length"]??0)>tr){I(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await wn(S,_,b.headers["content-type"]??"application/octet-stream",await td(b));if(S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}f.set(C.id,C),I(v,201,{id:C.id,name:C.name,bytes:C.bytes})}catch(C){ce(C,400,C instanceof Error?C.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/session"){try{let g=s.snapshot();k(g),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 s.providers?.()??[])}catch(g){ce(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/models"){let g=new URL(b.url??x,P).searchParams.get("providerId")??"";try{if(!g||!s.providerModels){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(v,200,await s.providerModels(g))}catch(S){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 s.models():x==="/api/config"?await s.config():x==="/api/commands"?s.commands?.()??[]:await s.workspaces())}catch(g){ce(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/directory/capability"){I(v,200,{kind:c});return}if(b.method==="GET"&&x==="/api/events"){let g;try{g=s.snapshot(),k(g)}catch(S){ce(S,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}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})}
@@ -47,4 +47,4 @@ ${s.stack.split(`
47
47
  `)}`:void 0,t<3&&s.cause instanceof Error&&(i.cause=co(s.cause,e,t+1)),st(i)}import{randomUUID as uo}from"node:crypto";import{randomUUID as zd}from"node:crypto";import{EnvHttpProxyAgent as qd,getGlobalDispatcher as Zw,setGlobalDispatcher as ey}from"undici";var lo=s=>({httpProxy:s.http_proxy??s.HTTP_PROXY??s.all_proxy??s.ALL_PROXY??"",httpsProxy:s.https_proxy??s.HTTPS_PROXY??s.all_proxy??s.ALL_PROXY??"",noProxy:s.no_proxy??s.NO_PROXY??""});function Gd(s,e){let t=lo(s),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let i=t.noProxy.toLowerCase();if(i==="*")return!1;let n=Number(r.port)||(r.protocol==="https:"?443:80),o=r.hostname.toLowerCase();return!i.split(/[,\s]/).filter(Boolean).some(c=>{let a=c.match(/^(.+):(\d+)$/),l=(a?.[1]??c).replace(/^\*?\./,"");return(!a||Number(a[2])===n)&&(o===l||o.endsWith("."+l))})}function Jd(s){let e=lo(s);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new qd(e)}function hi({env:s=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:r=!1}={}){let i,n=new Set,o=t===globalThis.fetch,c=(p,u)=>{try{e(p,u)}catch{}},a=p=>p?p.close().finally(()=>n.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let w={requestId:zd(),phase:"headers",proxied:o&&Gd(s,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??=Jd(s),n.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 A=E.body.getReader();y?.addEventListener("abort",k,{once:!0}),y?.aborted&&P();let D=new ReadableStream({async pull(R){try{let Y=await A.read();Y.done?(R.close(),A.releaseLock(),P()):R.enqueue(Y.value)}catch(Y){c(Y,{...w,phase:"body"}),R.error(Y),A.releaseLock(),P()}},async cancel(R){try{await A.cancel(R)}finally{A.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([...n].map(a))}}}var po=(s,e)=>hi({autoClose:!0}).fetch(s,e);var Kd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),Xd=s=>typeof s=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(s)?s:void 0;function gi(s,e={}){let t=[],r=new Set,i=(a,l=0)=>{if(!a||l>4||r.has(a)||t.length>=8)return;r.add(a);let p=Xd(a.code);if(t.push({name:Kd.has(a.name)?a.name:"Error",...p?{code:p}:{}}),i(a.cause,l+1),a instanceof AggregateError)for(let u of a.errors.slice(0,4))i(u,l+1)};i(s);let n=t.flatMap(a=>a.code?[a.code]:[]),o=e.stage==="model_admission"||n.some(a=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(a))?"lifecycle":n.some(a=>/CERT|TLS|SSL/.test(a))?"tls":n.some(a=>/^PROXY_/.test(a))||e.proxied&&n.some(a=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(a))?"proxy":n.some(a=>/TIMEOUT|ETIMEDOUT/.test(a))||t.some(a=>/TimeoutError$/.test(a.name))?"timeout":t.some(a=>a.name==="AbortError"||a.code==="ABORT_ERR"||a.code==="UND_ERR_ABORTED")?"cancelled":n.some(a=>/ENOTFOUND|EAI_AGAIN/.test(a))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",c=a=>typeof a=="string"&&/^[\w-]{1,80}$/.test(a)?a:void 0;return{errorId:uo(),requestId:c(e.requestId)??uo(),...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 fo({env:s=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return hi({env:s,fetchRequest:t,onFailure:(r,i)=>e(gi(r,{...i,stage:i.phase==="body"?"model_stream":"model_headers"}))})}function Yd(s){let e={...process.env,...s};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])s&&t.toUpperCase()in s&&!(t in s)&&delete e[t];return e}var Qd=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function ho(s,e,t=()=>{}){let r=s.agent.streamFunction;s.agent.streamFunction=async(i,n,o)=>{if(!Qd.has(i.api))return r(i,n,o);let c=t(),a=fo({env:Yd(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...c?{operationId:c}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await r(i,n,{...o,fetch:a.fetch});return l.result().finally(()=>a.close()).catch(()=>{}),l}catch(l){throw await a.close(),l}}}function dt(s,e,t){try{s()}catch(r){let i=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(n=>n.code?[n.code]:[]).join(",")})}catch{}throw r}}var sp=["read","grep","find","ls"],go=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=()=>{},n={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},c=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=r,this.reportError=i,this.onSessionsChanged=o,this.customTools=c,this.offHosted=a?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return n.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{n.enabled()&&n.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return n.enabled()?n.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let r=await _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 n;if(t==="new")n=Dt.create(r);else if(t==="continue"){let c=(await ct(r))[0];n=c?Dt.open(c.path):Dt.create(r)}else n="sessionManager"in t?t.sessionManager:Dt.open(t.sessionFile);if(await ip(n.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(n.getSessionId());if(o){if(o.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(r,n,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await _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,n=t.sessionManager.getBranch(),o=n.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:n.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(t=>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 n=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${i}`;console.error(n),this.publishFor(e,{type:"error",message:n})}async replace(e,t,r,i){let n=this.runtimes.get(t.getSessionId()),o=await Ke.discover(e,this.isProjectTrusted(e)),c=ep(),a=await no(e,o.extensionRoots,this.isProjectTrusted(e)),l=new tp({cwd:e,agentDir:rp(),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 Zd({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=n?.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,ho(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>go&&P.events.splice(0,P.events.length-go))};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 A=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(`
48
48
  `)),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()-A>=60&&(A=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(),n&&(!n.session.isIdle||n.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(n&&await this.close(n,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");y.detached&&(y.detached.restoreTools=m.getActiveToolNames(),m.setActiveToolsByName(sp)),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 Qn(e.session,t,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:r,catalog:i}=e,n=t.sessionManager.getBranch().flatMap(o=>{let c=Rt(o);return c?[c]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:r,name:cr(t.sessionManager.getSessionName(),n),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:ot(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:n,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries: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 n=this.active;if(Oe(this.snapshot(),e,i),i==="followUp"&&(!n.session.isIdle||n.prompts.length>0)){n.prompts.enqueue(e,t,r),this.scheduleQueued(n);return}if(n.session.isIdle&&n.prompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(n,e,t,r,i)}async prompt(e,t,r,i,n){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),i,this.reportError),Oe({...this.snapshotOf(e),idle:e.session.isIdle},t,n);let o=e.session,c=o.isIdle;c&&(e.operation=i,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...i,piVersion:fr});let a=!1,l,p,u=new Promise((w,m)=>{l=w,p=m});o.prompt(t,{images:r,streamingBehavior:n,preflightResult:w=>{w&&(a=!0,l())}}).then(()=>{a||l()}).catch(w=>{if(!a)p(w);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let m=this.reportError(Te(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,(n,o,c)=>this.prompt(i,n,o,c,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Tt),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");dt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=t.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!ot(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!ot(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let n=ur(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(n,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let c=this.reportError(Te(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),n=Dt.create(i);return await this.replace(i,n,"new",t),this.runtimes.get(n.getSessionId()).session.setSessionName(r),n.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,r){let i=this.detachedRuntime(e);if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&i.detached.restoreTools&&(i.session.setActiveToolsByName(i.detached.restoreTools),i.detached.restoreTools=null),!i.session.isIdle||i.prompts.length>0){i.prompts.enqueue(t,[],void 0),this.scheduleQueued(i);return}await this.prompt(i,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(i=>i.seq>t),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as np,mkdir as op,rename as ap,unlink as cp}from"node:fs/promises";import{basename as lp,join as mo}from"node:path";var dp=s=>mo(s,"pi-web","trash");async function wo(s,e){let t=dp(e);await op(t,{recursive:!0});let r=mo(t,`${Date.now()}_${lp(s)}`);try{await ap(s,r)}catch(i){let n=i.code;if(n==="ENOENT")return null;if(n!=="EXDEV")throw i;await np(s,r),await cp(s)}return r}import{basename as mi,dirname as pp}from"node:path";function yo(s,e){let t=r=>e[r].map(i=>({name:r==="skills"&&mi(i.path).toLowerCase()==="skill.md"?mi(pp(i.path)):mi(i.path),path:i.path,source:i.metadata.source,scope:i.metadata.scope,enabled:i.enabled}));return{packages:s.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as up}from"node:child_process";var fp=(s,e)=>new Promise((t,r)=>{up(s,[...e],{windowsHide:!0},i=>{i?r(i):t()})});async function wi(s,e=process.platform,t=process.env,r=fp){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let i=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return i===null?!1:(await r(i,[s]),!0)}import{execFile as ru}from"node:child_process";import{randomUUID as Hi}from"node:crypto";import{existsSync as Bo}from"node:fs";import{access as iu,mkdir as Mt,mkdtemp as su,readFile as Ve,realpath as nu,rename as Lo,rm as zo,writeFile as qo}from"node:fs/promises";import{join as G}from"node:path";import{createHash as bi}from"node:crypto";import{readdir as kp,realpath as So,rename as Pp,stat as Ip}from"node:fs/promises";import{join as Fe}from"node:path";import{constants as yi}from"node:fs";import{DatabaseSync as hp}from"node:sqlite";import{lstat as ko,mkdir as gp,open as Ot,rename as mp,unlink as Po}from"node:fs/promises";import{dirname as wp,join as vo,resolve as yp}from"node:path";import{randomUUID as vp}from"node:crypto";import{setTimeout as bp}from"node:timers/promises";async function Z(s){await gp(s,{recursive:!0,mode:448});let e=await ko(s);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function X(s,e){let t;try{t=await Ot(s,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)),n=0;for(;n<i.length;){let o=await t.read(i,n,i.length-n,n);if(!o.bytesRead)break;n+=o.bytesRead}if(n>e||n!==r.size)throw new h("invalid_storage","Storage record changed during read");return i.subarray(0,n)}finally{await t.close()}}async function ee(s,e=2*1024*1024){let t=await X(s,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new h("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function he(s){let e=await X(s,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new h("gc_recovery_required",`Invalid journal ${s}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new h("gc_recovery_required",`Invalid journal ${s}; original bytes preserved`);return t}async function j(s,e){let t=`${s}.${vp()}.tmp`,r=await Ot(t,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await mp(t,s);let i;try{i=await Ot(wp(s),"r"),await i.sync()}catch(n){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(n.code??""))throw n}finally{await i?.close()}}finally{await Po(t).catch(()=>{})}}var Io='{"version":2,"mechanism":"sqlite-exclusive"}',bo=s=>s.toString("utf8")===Io,gr=new Set;async function vi(s,e,t=0){await Z(s);let r=vo(s,`${e}.lock`),i=vo(s,`${e}.ownership.sqlite`),n=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new h(n,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await Ot(i,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await ko(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 hp(i,{allowExtension:!1}),p=yp(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(n,"Another host owns this plugin storage; wait for it to stop before retrying");await bp(10)}let f=await X(r,4096);if(f===null){let y;try{y=await Ot(r,"wx",384),await y.writeFile(Io),await y.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await y?.close()}f=await X(r,4096)}if(f===null||!bo(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||!bo(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await Po(r),l.close(),gr.delete(p),m=!0}}async function te(s,e,t=2e3){let r=await vi(s,"transaction",t);try{return await e()}finally{await r()}}var mr=s=>Fe(s,"host-pair"),Sp=s=>bi("sha256").update(JSON.stringify(s)).digest("hex"),Ep=10*6e4;async function xp(s){let e=bi("sha256"),t=0,r=0;async function i(n){let o=(await kp(Fe(s,n),{withFileTypes:!0})).sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(let c of o){if(!n&&c.name==="node_modules")continue;let a=n?`${n}/${c.name}`:c.name;if(c.isSymbolicLink()||!c.isFile()&&!c.isDirectory())throw new h("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new h("host_pair_required","Candidate package resource budget exceeded");if(c.isDirectory()){await i(a);continue}let l=await X(Fe(s,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(s,e){let t=await So(e),r=Fe(e,"dist","hosted-worker.js");if(await So(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 n=JSON.parse(i.toString("utf8")),o=n.piWebappHostedRuntime;if(n.name!=="pi-webapp"||n.version!==s||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(a=>o.capabilities.includes(a)))throw new 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 Sp([i.toString("base64"),c.toString("base64"),await xp(e)])}async function wr(s){await Pp(s,`${s}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var _p=s=>s.schema===1&&/^[a-f0-9-]{36}$/.test(s.id)&&typeof s.version=="string"&&typeof s.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(s.hostDigest)&&/^[a-f0-9]{64}$/.test(s.fingerprint)&&Array.isArray(s.selections)&&!s.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(s.selection&&(typeof s.selection.path!="string"||!/^[a-f0-9]{64}$/.test(s.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(s.phase);async function Pi(s){let e=Fe(mr(s),"intent.json"),t,r=!0;try{t=await he(e)}catch{t=null,r=!1}if(!r||t&&!_p(t))return await wr(e),null;if(t){let{lifecyclePhase:i,...n}=t,o=typeof n.updatedAt=="string"&&!Number.isNaN(Date.parse(n.updatedAt))?n.updatedAt:await Ip(e).then(c=>c.mtime.toISOString(),()=>new Date(0).toISOString());t={...n,updatedAt:o,phase:n.phase==="selected"&&i==="restart-requested"?"restart-requested":n.phase==="reconciled"&&i==="cancelled"?"cancelled":n.phase==="reconciled"&&i==="required-action"?"required-action":n.phase}}return t}async function yr(s,e){let{lifecyclePhase:t,...r}={...e,selections:[],updatedAt:new Date().toISOString()},i=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await j(Fe(mr(s),"intent.json"),i)}var Ii=s=>s&&["selecting","selected","restart-requested"].includes(s.phase),Eo=(s,e=Date.now())=>!!s&&!!Ii(s)&&e-Date.parse(s.updatedAt??"")<Ep;import{promisify as ou}from"node:util";import{realpathSync as Ao,statSync as Ap}from"node:fs";import{basename as Tp,delimiter as Rp,dirname as xo,join as Si,resolve as Cp}from"node:path";function _o(s){if(!s)return null;try{let e=Ao(s);return Tp(e)==="npm-cli.js"&&Ap(e).isFile()?e:null}catch{return null}}function Np({execPath:s=process.execPath,env:e=process.env}={}){let t=_o(e.npm_execpath);if(t)return t;let r=new Set([xo(s)]);try{r.add(xo(Ao(s)))}catch{}let i=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of i.split(Rp).filter(Boolean))r.add(Cp(n));for(let n of r)for(let o of[Si(n,"node_modules","npm","bin","npm-cli.js"),Si(n,"..","lib","node_modules","npm","bin","npm-cli.js"),Si(n,"npm")]){let c=_o(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 To(s){return{file:process.execPath,args:[Np(),...s]}}import{randomUUID as Dp}from"node:crypto";import{mkdir as No,readFile as Op,rename as xi,rm as Hp,unlink as tv,writeFile as Mp}from"node:fs/promises";import{isAbsolute as Ro,join as Ht}from"node:path";var _i=1,jp=1440*6e4,vr=s=>Ht(s,"pi-web","upgrade"),Ai=s=>Ht(vr(s),"candidate.json"),Wp=s=>Ht(vr(s),"transaction.json"),Co=s=>Ht(vr(s),"history"),Do=/^[a-f0-9-]{36}$/i;async function $p(s,e){let t=`${s}.${Dp()}.tmp`;try{await Mp(t,e,{mode:384}),await xi(t,s)}finally{await Hp(t,{force:!0})}}var Fp=(s,e)=>$p(s,JSON.stringify(e));async function Ei(s,e){await xi(s,`${s}.${e}-${Date.now()}`).catch(t=>{if(t?.code!=="ENOENT")throw t})}async function Oo(s,e,t=()=>!1){let r;try{r=JSON.parse(await Op(s,"utf8"))}catch(i){return i?.code==="ENOENT"||await Ei(s,"invalid"),null}return e(r)?t(r)?(await Ei(s,"expired"),null):r:(await Ei(s,"invalid"),null)}function Ho(s){if(!s||typeof s!="object"||s.schema!==_i||!Do.test(s.id??""))return!1;try{xe(s.version)}catch{return!1}return typeof s.launcher=="string"&&Ro(s.launcher)&&typeof s.packageRoot=="string"&&Ro(s.packageRoot)&&["stable","alpha"].includes(s.channel)&&typeof s.downgrade=="boolean"&&!Number.isNaN(Date.parse(s.createdAt??""))}async function br(s,e=Date.now()){return Oo(Ai(s),Ho,t=>e-Date.parse(t.createdAt)>jp)}async function Mo(s,e){let t={schema:_i,createdAt:new Date().toISOString(),...e};if(!Ho(t))throw new Error("Invalid upgrade candidate");return await No(vr(s),{recursive:!0,mode:448}),await Fp(Ai(s),t),t}async function Ti(s,e,t){let r=await br(s);!r||e&&r.id!==e||(await No(Co(s),{recursive:!0,mode:448}),await xi(Ai(s),Ht(Co(s),`${r.id}-candidate-${t}.json`)).catch(i=>{if(i?.code!=="ENOENT")throw i}))}var Vp=["selected","committed","rolled-back"];function Up(s){return!!s&&typeof s=="object"&&s.schema===_i&&Do.test(s.id??"")&&Vp.includes(s.phase)&&typeof s.version=="string"&&typeof s.from=="string"&&!Number.isNaN(Date.parse(s.updatedAt??""))}async function jo(s){return Oo(Wp(s),Up)}import{readFile as Bp,rename as Lp,writeFile as zp,unlink as qp}from"node:fs/promises";import{join as Gp}from"node:path";import{randomUUID as Jp}from"node:crypto";var Ri=1,Wo=s=>Gp(s,"pi-web","launcher-handoff.json");function $o(s){return s?.protocol===Ri&&typeof s.nonce=="string"&&s.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(s.requestId)&&Number.isSafeInteger(s.pid)&&s.pid>0&&["requested","draining","stopped","refused","failed"].includes(s.phase)}async function Ci(s){try{let e=JSON.parse(await Bp(Wo(s),"utf8"));if(!$o(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 Kp(s,e){let t=`${s}.${Jp()}.tmp`;try{await zp(t,JSON.stringify(e),{mode:384}),await Lp(t,s)}finally{await qp(t).catch(()=>{})}}async function Fo(s,e){if(!$o(e))throw new Error("Invalid launcher handoff receipt");await Kp(Wo(s),e)}import{execFile as Xp}from"node:child_process";import{cp as Yp,readFile as Ni,realpath as Qp,rm as Zp}from"node:fs/promises";import{join as pt,sep as eu}from"node:path";import{promisify as tu}from"node:util";var Vo=tu(Xp),Di=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Oi(s){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=s;return 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(s){return Promise.all(Di.map(async e=>{let t=await nt(s,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 Uo(s,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(s):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 nt(s,"node-pty"),n=await nt(e,"node-pty"),o=await Qp(pt(e,"../.."));if(i===n||!n.startsWith(o+eu))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(n))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await Zp(n,{recursive:!0,force:!0}),await Yp(i,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await Vo(process.execPath,[pt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await nt(e,Di[0]),{stdout:p}=await Vo(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 au=ou(ru),jt=s=>["committed","cancelled","failed"].includes(s);function Go(s){let e=s.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function cu(s,e){try{let t=To(s),{stdout:r}=await au(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??cu,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),n=Array.isArray(i)&&i.length===1?i[0]:i;return Oi(n)},this.verifyPackage=e.verifyPackage??Uo,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&&!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"),n=JSON.parse(await Ve(i,"utf8")),o=p=>p.nonce===e&&p.pid===n.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(n))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let c=await 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:n.pid,phase:"requested"};try{await Fo(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||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 jo(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 Ti(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 j(this.transactionPath,e),jt(e.phase)){let t=G(this.agentDir,"pi-web","update-history");await Mt(t,{recursive:!0}),await j(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 Ti(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}.${Hi()}.tmp`;try{await Mt(G(this.agentDir,"pi-web"),{recursive:!0}),await qo(t,JSON.stringify({channel:e}),{mode:384}),await Lo(t,this.preferencePath)}finally{this.savingPreference=!1,await zo(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),r=Bo(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 n=await this.transaction();if(n&&!jt(n.phase)?i.recovery={version:n.version,phase:n.phase,canCancel:n.phase!=="restart-requested"}:n?.phase==="failed"&&n.message&&(i.lastFailure={version:n.version,message:n.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...i,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...i,canRestart:!1,reason:i.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?i.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":i.canRestart||(i.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&i.canRestart&&(i.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let o=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),c=Array.isArray(o)&&o.length===1?o[0]:o,a=t==="alpha"?c:{latest:c};if(!a||!Dn(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(!nr(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(Bo(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 su(G(await nu(r),`${t.latest}-`)),n=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:n,ownerNonce:this.launcherNonce};this.ownTransaction=o.id,await this.record(o);try{let c=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...c,"--prefix",i,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let a=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&&Go(l)!==Go(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=>iu(w))),this.desktopManaged&&(await ri(this.agentDir,{version:t.latest,launcher:u,desktopProtocolVersion:je}),await this.verifyPackage(this.packageRoot,a)),await this.prefetchPlugins?.(t.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await Mo(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 zo(i,{recursive:!0,force:!0});let a=(c instanceof Error?c.message:String(c)).slice(0,500);throw await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${a}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),c}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:t=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let i,n=!1,o=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 Lo(o,G(l,`stale-${Hi()}.json`))}}catch{}try{await qo(o,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),n=!0}catch(a){try{let l=JSON.parse(await Ve(o,"utf8"));n=l.nonce===this.launcherNonce&&l.candidate===r.id}catch{}if(!n)throw a}this.restartPending=!0}catch(c){if(n){this.restartPending=!0;return}let a=await this.transaction();throw a?.id===r.id&&a.phase==="restart-requested"&&await this.record({...a,phase:"prepared"}),i&&await i(),c}}};import{createHash as Ca,randomUUID as ph}from"node:crypto";import{randomUUID as Ff}from"node:crypto";import{join as Ki}from"node:path";import{randomUUID as Xo}from"node:crypto";import{randomUUID as lu}from"node:crypto";function Jo(s){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof s[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let r=`__pi_web_contract_${lu().replaceAll("-","")}`,i;try{if(i=s.getActiveTools(),!Array.isArray(i))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let n={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{s.registerTool(n),s.setActiveTools([...i,r]),(s.getAllTools().find(c=>c.name===r)?.exposure!=="hidden"||s.getActiveTools().includes(r))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};s.registerTool({...n,parameters:o}),s.getAllTools().find(c=>c.name===r)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{s.setActiveTools(i)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var du;function Ko(){return du??=pu().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function pu(){let{createAgentSession:s,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:i,rm:n}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:c}=await import("node:path"),a=await i(c(o(),"pi-sdk-contract-")),l,p=[],u=0,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",{}),se=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!we.isError||!ye.isError)&&p.push("nested-tool-exposure"),(se.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 s({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:P}),await l.bindExtensions({mode:"print"});let E=l.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(E);let A=0;l.agent.streamFunction=async M=>{let R=A++===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 n(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??=Ko().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,i)=>{t=setTimeout(()=>i(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let r=this.install(e,t);r.ready=!0;try{this.publish(r)}catch(i){throw this.release(r),i}return()=>this.release(r)}install(e,t){let r={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let i=n=>{if(typeof n!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(n)};try{i(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(n=>this.waiters.add(n));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),i(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),i(e.on("tool_call",n=>{let o=r.owned.get(n.toolName);if(!o)return;let c=this.descriptors.get(o)?.find(a=>a.name===n.toolName);if(!c||!this.allowed(r,o,c,!!n.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),i(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),i(e.on("session_shutdown",()=>this.release(r)))}catch{for(let n of r.handlers)try{n()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let t=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(r=>{r.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(r){throw this.release(t),r}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,r,i=!1){let n=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&n.enabled&&(!n.allowlist||n.allowlist.includes(r.name))&&(!n.planMode||r.readonly===!0)&&(!i||n.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(i=>i.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(t);this.validateChange(e,r),this.descriptors.set(e,r);for(let i of this.bindings)i.ready&&this.publish(i)}validateChange(e,t){for(let i of this.bindings)if(i.compatible!==!1)for(let[n,o]of i.owned)this.assertOwner(i,o,n);let r=new Set;for(let i of t){if(!i.name||!i.action||!i.parameters||i.parameters.type!=="object"||r.has(i.name))throw new Error("Invalid hosted tool descriptor");r.add(i.name);for(let[n,o]of this.descriptors)if(n!==e&&o.some(c=>c.name===i.name))throw new Error(`Hosted tool ownership conflict: ${i.name}`);for(let n of this.bindings)n.compatible!==!1&&this.assertOwner(n,e,i.name)}}assertOwner(e,t,r){let i=e.owned.get(r);if(i&&i!==t)throw new Error(`Hosted tool ownership conflict: ${r}`);let n=e.pi.getAllTools().find(o=>o.name===r);if(n&&(!i||n.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=Jo(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,i]of e.owned)this.assertOwner(e,i,r);for(let[r,i]of this.descriptors)for(let n of i)this.assertOwner(e,r,n.name);let t=new Set;for(let[r,i]of this.descriptors)for(let n of i){if(e.owned.set(n.name,r),!this.allowed(e,r,n))continue;t.add(n.name);let o=this.service.policy(r,e.scope),c=o.exposure??"direct",a=!o.allowNested&&c==="direct"?"model-only":c,l={name:n.name,label:n.label,description:n.description,parameters:structuredClone(n.parameters),exposure:a,execute:async(p,u,w)=>{if(!this.allowed(e,r,n))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:Xo(),scope:{...e.scope},kind:"tool",action:n.action,input:u},w)}};e.pi.registerTool(l),e.definitions.set(n.name,l)}for(let r of e.owned.keys())if(!t.has(r)){let i={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute: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,n){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(c=>c.scope.sessionId===t.sessionId&&c.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:Xo(),scope:t,kind:"action",action:r,input:i},n)}};async function uu(){throw new Error("Hosted tool unavailable")}import{randomBytes as ff,randomUUID as hf,timingSafeEqual as gf}from"node:crypto";import{join as be}from"node:path";var fu=30,Yo=/^[a-z][a-z0-9-]{0,63}$/,hu=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Wt=s=>{throw new h("invalid_package",s)},Mi=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?Wt(`Invalid ${e} declaration`):s;function ut(s){let e=s&&typeof s=="object"?s:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),r=t.has("secrets")?Mi(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&Yo.test(a)?a:Wt("Invalid secret name")}):[],i=e.network,n=t.has("network")?Mi(i?.hosts,"network").map(c=>typeof c=="string"&&hu.test(c)?c:Wt("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"||!Yo.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<fu||a.intervalSec>86400?Wt("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&Wt("Duplicate schedule id"),{secrets:r,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as gu}from"node:dns/promises";import{isIP as mu}from"node:net";var wu=new Set(["GET","POST","PATCH","PUT","DELETE"]),yu=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),vu=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Sr=(s,e)=>{throw new h("network_denied",s,{status:403,reason:e})};function bu(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if(mu(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 Qo(s,e,t,r,i){let n=r;if(!n||typeof n!="object"||typeof n.url!="string")throw new h("invalid_input","Invalid network request");let o;try{o=new URL(n.url)}catch{throw new h("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&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=(n.method??"GET").toUpperCase();if(!wu.has(c))throw new h("invalid_input","Unsupported method");if(n.body!==void 0&&(typeof n.body!="string"||n.body.length>1024*1024))throw new h("invalid_input","Invalid body");let a={};for(let[E,A]of Object.entries(n.headers??{})){if(typeof A!="string"||yu.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(A))throw new h("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=A}let l=null;if(n.secret!==void 0){if(t.includes(n.secret)||Sr("Secret is not declared by the plugin","secret"),l=await i.secrets.get(s,n.secret),!l)throw new h("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(i.resolve??(async E=>(await gu(E,{all:!0})).map(A=>A.address)))(o.hostname);(!p.length||p.some(bu))&&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:n.body,redirect:"manual",signal:AbortSignal.timeout(u)}),f=[],y=0;if(m.body)for await(let E of m.body){if(y+=E.byteLength,y>w)throw new h("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let k=Buffer.concat(f).toString("utf8"),P={};return m.headers.forEach((E,A)=>{vu.has(A.toLowerCase())&&(P[A.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:m.status,headers:P,body:k}}var Er=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new h("invalid_input",`Invalid ${t}`);return s};async function Zo(s,e,t,r,i,n){let o=i&&typeof i=="object"&&!Array.isArray(i)?i:{};if(r==="sessions.create"){if(o.mode!=="plan")throw new h("invalid_input","Plugin sessions must start in plan mode");if(s.activeCount(e)>=n)throw new h("quota_exceeded","Too many active plugin sessions",{status:429});return s.create({pluginId:e,cwd:t,title:Er(o.title,200,"title"),prompt:Er(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=Er(o.sessionId,200,"sessionId");if(s.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 s.send(c,Er(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await s.release(c),{ok:!0};case"sessions.abort":return await s.abort(c),{ok:!0};case"sessions.events":return s.events(c,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new h("method_denied","Unknown sessions method")}}var ku=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 ku.has(e)}async call(e,t,r,i,n){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 Qo(e,o.networkHosts,o.secrets,n,this.options)}if(!o.sessions||!this.options.sessions)throw new h("capability_denied","Sessions capability is unavailable",{status:403});return Zo(this.options.sessions,e,r.scope.cwd,i,n,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,n)=>{let o=setInterval(i,n);return o.unref(),o});this.timers.set(e,t.map(i=>r(()=>{this.tick(e,i)},i.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])t(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let r=`${e}\0${t.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,t),!0}catch(i){return this.deps.onError?.(e,t,i),!1}finally{this.running.delete(r)}}};import{createHash as Bi,timingSafeEqual as Bu}from"node:crypto";import{lstat as da,mkdtemp as Ui,readdir as Lu,readFile as zu,realpath as qu,rename as Gu,rm as Ue,writeFile as Ju}from"node:fs/promises";import{tmpdir as Ku}from"node:os";import{join as L}from"node:path";import{gunzipSync as Au}from"node:zlib";import{mkdir as Tu,writeFile as Ru}from"node:fs/promises";import{dirname as Cu,join as Nu}from"node:path";import{constants as ji}from"node:fs";import{lstat as ra,open as Pu,readdir as ea,realpath as ia}from"node:fs/promises";import{createHash as Iu}from"node:crypto";import{join as sa,relative as Su,resolve as Eu,sep as xu}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},_u={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"]},B=s=>Iu("sha256").update(s).digest("hex");function V(s){throw new h("invalid_package",s)}async function Ye(s,e,t){let r=e.split("/");(!r.length||r.some(c=>!c||c==="."||c===".."||!/^[\w.-]+$/.test(c)))&&V("Invalid resource path");let i=s;for(let c=0;c<r.length;c++){i=sa(i,r[c]);let a=await ra(i);(a.isSymbolicLink()||(c<r.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&V("Links and non-regular package files are forbidden")}let n=await ia(i);(n!==Eu(s,e)||Su(s,n).startsWith(`..${xu}`))&&V("Resource escapes package root");let o=await Pu(i,ji.O_RDONLY|ji.O_NONBLOCK|(ji.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 ta(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return V("Invalid package JSON")}}async function Qe(s,e){let t=await ia(s);(await ra(s)).isSymbolicLink()&&V("Package root cannot be a symlink");let r=ta(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"),We(r.piWebapp)||V("Unsupported hosted manifest"),r.type!=="module"&&V("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))&&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,n=ta(await Ye(t,i.resourcesManifest.slice(2),J.other));(!n||n.version!==1||!Array.isArray(n.files)||!n.files.length||n.files.length>J.files)&&V("Invalid resource manifest");let o=new Map,c=0;for(let u of n.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);_u[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 ea(sa(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 na(s,e,t){if(t!==s.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Je(`./${r}`))return null;let i=s.resources.get(r);if(!i||r===s.manifest.backend.entry.slice(2))return null;let n=await Ye(s.root,r,i.bytes);if(n.length!==i.bytes||B(n)!==i.sha256)throw new h("resource_changed","Installed resource integrity mismatch");return{bytes:n,mime:i.mime}}var Ar=64*1024*1024,Du=J.total+J.files*2048,F=s=>{throw new h("invalid_archive",s)};function ft(s){let e=s.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?s:s.subarray(0,e))}catch{return F("Archive has invalid UTF-8 paths")}}function oa(s){let e=ft(s).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 Ou(s){let e=s.endsWith("/")?s.slice(0,-1):s;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 Hu(s){let e={},t=0;for(;t<s.length;){let r=s.indexOf(32,t);if(r<0)return F("Invalid PAX header");let i=s.subarray(t,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(i))return F("Invalid PAX record length");let n=Number(i),o=t+n;if(o>s.length||o<=r+2||s[o-1]!==10)return F("Truncated PAX record");let c=ft(s.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 Mu(s){if(!s.length||s.length>Ar)return F("Compressed archive exceeds budget");let e;try{e=Au(s,{maxOutputLength:Du})}catch{return F("Invalid or oversized gzip archive")}let t=[],r=new Set,i=0,n=0,o=0,c=0,a=null,l=!1;for(;i+512<=e.length;){let u=e.subarray(i,i+512);if(i+=512,u.every(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(oa(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=oa(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=Hu(E);continue}if(a=null,f!==0&&f!==48&&f!==53)return F("Links and special archive members are forbidden");let A=f===53;if(A&&P!==0||ft(u.subarray(157,257)))return F("Invalid archive link or directory");if(k=Ou(k),!k&&!A)return F("Invalid package root member");if(r.has(k))return F("Duplicate archive member");if(r.add(k),++n>J.files||(o+=P)>J.total)return F("Unpacked archive exceeds budget");t.push({path:k,data:E,directory:A})}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 Wi(s,e){let t=Mu(s);for(let r of t){if(!r.path)continue;let i=Nu(e,r.path);await Tu(r.directory?i:Cu(i),{recursive:!0,mode:448}),r.directory||await Ru(i,r.data,{flag:"wx",mode:384})}}import{lstat as ju,mkdir as Wu,readdir as $u,realpath as Fu,writeFile as Vu}from"node:fs/promises";import{dirname as Uu,join as $i}from"node:path";async function aa(s,e){let t=await Fu(s),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 n=[],o=0,c=0;async function a(w,m){if(m>16)throw new h("invalid_package","Package directory nesting limit exceeded");for(let f of await $u($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 Wu(Uu(P),{recursive:!0,mode:448}),await Vu(P,k,{flag:"wx",mode:384}),n.push([y,B(k)])}}let l;try{l=await ju($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 n.sort((w,m)=>w[0].localeCompare(m[0])),{contentHash:B(JSON.stringify({package:u,files:n})),packageJson:i}}function ve(s){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(s);return!e||e[0]!==s||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Se(s,e){let t=ve(s),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 ca(s){let e=ve(s);if(e)return e;if(!nr(s))return null;let[t,r]=s.split("-alpha."),i=ve(t),n=Number(r);return i&&Number.isSafeInteger(n)?{...i,alpha:n}:null}function Fi(s){return!!ca(s)}function ht(s,e){if(!Fi(s)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(i=>!i.trim()))return!1;let r=[];for(let i of t){let n=i.trim().split(/\s+/),o=!0;for(let c of n){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&ca(a[2]);if(!a||!l)return!1;let p=a[2],u=fe(s,p);switch(a[1]??"="){case"=":o&&=u===0;break;case">=":o&&=u>=0;break;case"<=":o&&=u<=0;break;case">":o&&=u>0;break;case"<":o&&=u<0;break;case"~":o&&=u>=0&&fe(s,`${l.major}.${l.minor+1}.0-0`)<0;break;case"^":{let w=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&fe(s,`${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(s,e=Ne){let t=e.find(r=>r.id===s);if(!t)throw new h("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Vi(s,e,t){let r=s.piWebapp;return s.name===e.id&&!!ve(s.version)&&!s.deprecated&&We(r)&&ht(t,r.hostRange)&&e.requiredCapabilities.every(i=>r.capabilities.includes(i))}function la(s,e,t,r,i){if(!s||typeof s!="object"||!("versions"in s)||!s.versions||typeof s.versions!="object"||Array.isArray(s.versions))throw new h("registry_invalid","Invalid registry version catalog");let n=Object.entries(s.versions);if(n.length>1e4)throw new h("registry_invalid","Registry version catalog exceeds budget");let c=n.flatMap(([a,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===a&&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 Xu(s,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new h("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(t[1],"base64"),i=Bi("sha512").update(s).digest();if(r.length!==i.length||!Bu(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??po}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(n=>!["schema","pluginId","next"].includes(n)))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(n=>n.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 Lu(r)){if(!/^stage-[A-Za-z0-9]+$/.test(i)||(await da(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(n=>!["schema","pluginId","records"].includes(n))||!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 n of r.records)this.validateRecord(r.pluginId,n);let i=r.records.filter(n=>e.versions[r.pluginId]?.some(o=>o.directory===n.directory));if(i.length&&i.length!==r.records.length)throw new 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 n of r.records)await Ue(this.path(n),{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]??[],n=new Set(await t()),o=i.at(-1);o&&n.add(o.version);let c=i.filter(a=>!n.has(a.version));return await this.removeLocked(e,r,c),c.map(a=>a.version)})}async removeLocked(e,t,r){r.length&&(await Z(L(this.root,"versions")),await Z(L(this.root,"versions",B(e))),await j(L(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),t.versions[e]=(t.versions[e]??[]).filter(i=>!r.some(n=>n.directory===i.directory)),t.revision++,await j(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 n=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:n,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw r?.aborted?r.reason:new 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(n.reason).catch(()=>{})};n.addEventListener("abort",p,{once:!0});try{if(n.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new h("download_too_large","Registry response exceeds budget");for(;;){let u=await c.read();if(u.done)break;if(l+=u.value.length,l>t)throw new h("download_too_large","Registry response exceeds budget");a.push(Buffer.from(u.value))}return n.throwIfAborted(),Buffer.concat(a)}catch(u){throw r?.aborted?r.reason:u instanceof h?u:new h("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{n.removeEventListener("abort",p),await c.cancel().catch(()=>{}),c.releaseLock()}}async check(e,t,r,i){let n=ge(e,this.catalog);if(r&&!ve(r))throw new h("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${n.registry}/${encodeURIComponent(e)}`,n),c,a=await this.download(o,8*1024*1024,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 la(c,n,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 n=await this.download(this.trustedUrl(t.dist.tarball,i),Ar,r);return this.installArchive(e,n,t.dist.integrity,t.version,r)}async installArchive(e,t,r,i,n){let o=ge(e,this.catalog);if(!ve(i))throw new h("invalid_version","Choose an exact stable version");if(t.length>Ar)throw new h("download_too_large","Package archive exceeds budget");return Xu(t,r),te(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await Ui(L(this.root,"staging","stage-"));try{await Wi(t,a),n?.throwIfAborted();let l=await Qe(a,e);if(l.version!==i||!We(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,n)}finally{await Ue(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,r,i,n,o){let c=t.versions[e]?.find(u=>u.version===i.version);if(c&&c.digest!==i.digest)throw new h("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:i.version,digest:i.digest,integrity:n,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 j(L(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await da(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 Gu(r,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await j(L(this.root,"installed.json"),t)),await Ue(L(this.root,"install-journal.json")),{...i,root:await qu(l)}}async installDevArchive(e,t,r){ge(e,this.catalog);let i=await zu(t),n="sha512-"+Bi("sha512").update(i).digest("base64"),o=await Ui(L(Ku(),"pi-dev-archive-"));try{await Wi(i,o);let c=(await Qe(o,e)).version;return await this.installArchive(e,i,n,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 n=await this.recoverLocked();r?.throwIfAborted();let o=await Ui(L(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await aa(t,o);r?.throwIfAborted();let l=L(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],w=n.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 Ju(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 A=i.requiredCapabilities.filter(R=>!E.manifest.capabilities.includes(R));if(A.length)throw new h("incompatible_plugin",`Package lacks required capabilities: ${A.join(", ")}`);let D="sha512-"+Bi("sha512").update(c).digest("base64"),M=await this.commitStaged(e,n,o,E,D,r);return p[e]={contentHash:c,version:P},await j(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(),n=i.versions[e]?.find(c=>c.version===t);if(!n)throw new h("not_installed","Plugin version is not installed");let o=await Qe(this.path(n),e);if(o.digest!==n.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(),n=(r.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,r,n)})}};import{lstat as Tr,mkdir as Yu,open as pa,realpath as ua,readdir as Li,link as Qu,rename as Zu,unlink as Ze,copyFile as ef,rm as tf}from"node:fs/promises";import{dirname as rf,isAbsolute as fa,join as O,relative as ha,resolve as sf,sep as zi,win32 as nf}from"node:path";import{randomUUID as qi}from"node:crypto";var $t=192*1024*1024,Ft=512*1024,ma=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function of(s){if(!s||typeof s!="object"||Array.isArray(s))throw new h("invalid_input","Expected object input");return s}function ga(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new h("invalid_input","Invalid state key");return s}function Vt(s){if(s&&(!ma(s.stateRef)||typeof s.version!="string"||!Number.isSafeInteger(s.generation)||s.generation<1||!Number.isSafeInteger(s.schema)||s.schema<1||typeof s.enabled!="boolean"||typeof s.operationId!="string"))throw new h("invalid_storage","Invalid active plugin record");return s}var 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 n=t.before;if(r==="committed"&&n&&n.stateRef!==e.stateRef&&await j(O(this.root,"previous.json"),n),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 n=Vt({...t,generation:e+1,operationId:qi()});await Z(O(this.root,"states")),await Z(O(this.root,"states",n.stateRef)),await j(O(this.root,"transition.json"),{version:1,before:r,next:n}),await this.checkpoint?.("prepared");try{await j(O(this.root,"active.json"),n)}catch(o){if((await this.active())?.operationId!==n.operationId)throw o}await this.checkpoint?.("committed");try{r&&r.stateRef!==n.stateRef&&await j(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"),n})}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 j(O(this.root,"fork.json"),{version:1,stateRef:r}),await Z(i);let n=O(this.root,"states",t.stateRef);for(let o of await Li(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await X(O(n,o),$t))throw new h("invalid_storage","Missing state file");await ef(O(n,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),n=O(this.root,"states");await Z(n);let o=await Li(n),c=new Set(i.map(l=>l.stateRef));for(let l of o){if(!ma(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(n,l),u=await Tr(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 Tr(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 tf(O(n,l),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let r=await this.active();if(!r||r.generation!==e||t&&!r.enabled)throw new 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 n=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return O(this.root,"states",e.stateRef,`${B(n+":state:"+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=of(r);return te(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(n,e,ga(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(n,e,ga(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==n.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:n.schema,value:i.value,requestId:e.requestId,inputHash:l};return await j(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,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(n,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")||fa(t)||nf.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let i=await ua(e),n=sf(i,t),o=ha(i,n);if(!o||o===".."||o.startsWith(`..${zi}`)||fa(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 Tr(c)}catch(w){if(!Me(w))throw w;if(p<a.length-1){if(!r||ha(i,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await Yu(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Tr(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 ua(rf(n));if(l!==i&&!l.startsWith(i+zi))throw new h("invalid_path","Workspace directory changed");return{target:n,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:n}=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 pa(`${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 j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=O(n,`.plugin-${qi()}.tmp`);let f=await pa(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!==n)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 Qu(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 Zu(u,i),u=void 0;return await j(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 pf}from"node:crypto";import{fork as af}from"node:child_process";import{randomUUID as cf}from"node:crypto";import{join as lf}from"node:path";import{EventEmitter as df}from"node:events";var wa=192*1024*1024,Ut=class s{child;pending=new Map;events=new df;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,r,i){this.package=e,this.generation=t,this.broker=i;let n={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(n[o]=process.env[o]);this.child=af(r,[],{env:n,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new 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,n=1e4){let o=new s(e,t,r,i);try{await o.request("initialize",{entry:lf(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},n);let c=await o.request("describe",void 0,n);if(!c||!Array.isArray(c.tools)||c.tools.length>128)throw new h("invalid_tools","Invalid hosted tool catalog");let a=new Set;for(let l of c.tools){if(!l||typeof l.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(l.name)||a.has(l.name)||typeof l.label!="string"||typeof l.description!="string"||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!l.parameters||typeof l.parameters!="object"||Array.isArray(l.parameters)||l.parameters.type!=="object")throw new h("invalid_tools","Invalid or duplicate tool descriptor");a.add(l.name)}return o.tools=structuredClone(c.tools),await o.request("health",void 0,n),o}catch(c){throw await o.dispose(),c}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>wa){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let i=this.pending.get(r.id);if(!i)return;if(clearTimeout(i.timer),this.pending.delete(r.id),!i.expired){let n=r.error;r.ok===!0?i.resolve(r.value):i.reject(new h(n?.code??"plugin_failed",n?.message??"Plugin request failed",n))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let i=this.pending.get(r.invocationId);try{if(!i?.invocation||i.expired)throw new h("invalid_lease","Plugin invocation lease is no longer writable");let n=await this.broker(i.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:n})}catch(n){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:K(n)})}}}request(e,t,r=3e4,i){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new h("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new h("worker_busy","Too many plugin requests"));let n=i?.requestId??cf();if(this.pending.has(n))return Promise.reject(new h("duplicate_request","An identical request is still running"));let o={type:"request",id:n,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>wa?Promise.reject(new h("message_too_large","Plugin request exceeds limit")):new Promise((c,a)=>{let l=setTimeout(()=>{let p=this.pending.get(n);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(n),a(new h("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(n,{resolve:c,reject:a,timer:l,invocation:i,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(n),a(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new 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 uf={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=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 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,n=this.worker;n||(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",n&&!await n.waitForIdle(t))throw new h("drain_pending","Plugin calls are still running; switch deferred without killing them");if(a=!0,await this.hooks.freeze(),n&&!await n.waitForIdle(t))throw new h("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new h("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let l=r?await this.broker.forkState(i):pf(),p=await this.broker.activate(i,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});c=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await n?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw c||(this.phaseValue=n?.healthy?"active":n?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,t=!1){return this.serialize(async()=>{let r=this.worker,i=this.phaseValue,n=await this.broker.active(),o=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(n))throw await this.releaseOwnership?.(),this.phaseValue="failed",new 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 n=!1;try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin still has in-flight work; not killed");if(n=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=i,n&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new 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 ya}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 n=this.closing?null:e.scheduledScope?.(r)??null;n&&await this.supervisor(r).invoke({requestId:hf(),scope:n,kind:"action",action:i.action,input:{schedule:i.id}})},onError:(r,i,n)=>e.onScheduleError?.(r,i.id,n),...e.scheduleTimers});for(let r of this.installer.catalog){let i=new et(be(e.root,"data"),r.id,e.legacy?.(r.id)),n=e.hooks(r.id);this.supervisors.set(r.id,new Rr(i,e.workerEntry,{validateCandidate:o=>n.validateCandidate?.(o),canSwitch:()=>n.canSwitch(),freeze:()=>n.freeze(),resume:()=>n.resume(),committed:async o=>{if(o.enabled){let c=await this.installer.load(r.id,o.version);this.packages.set(r.id,c),this.assetTokens.set(r.id,ff(24).toString("base64url"));try{this.scheduler.start(r.id,ut(c.manifest).schedules)}catch(a){this.scheduler.stop(r.id),this.errors.set(r.id,K(a))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await n.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return t?i=>this.installer.installDevDirectory(e,t,i):r?i=>this.installer.installDevArchive(e,r,i):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){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 j(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 n=await this.installer.check(e,t,r,i),o=!t||Se(n.version,t)>0;return o?this.available.set(e,n):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:n.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),n}catch(n){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:K(n).code,message:K(n).message}),n}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new 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 j(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 ya(this.options.workerEntry)).equals(await ya(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 j(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 n=await this.compatiblePackage(t.id,i.version);await this.lifecycle(t.id,()=>r.replace(n)),this.packages.set(t.id,n),e||await this.collectSettled(t.id)}catch(n){let o=K(n),c=["runtime_owned","storage_busy"].includes(o.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(t.id,{...o,message:`Plugin unavailable: startup failed (${o.code}): ${o.message}; data retained. ${c}`})}}}async compatiblePackage(e,t){try{return await this.installer.load(e,t)}catch(r){if(K(r).code!=="incompatible_plugin")throw r;let i=((await this.installer.inventory()).versions[e]??[]).map(n=>n.version).filter(n=>n!==t).sort((n,o)=>Se(o,n));for(let n of i)try{return await this.installer.load(e,n)}catch{}throw r}}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async n=>{let o=this.supervisor(n.id),c=await o.broker.active(),a=this.packages.get(n.id),l=(e.versions[n.id]??[]).map(p=>p.version).sort((p,u)=>Se(u,p));return{id:n.id,name:n.name,description:n.description,official:!0,installed:!!l.length,installedVersions:l,version:l[0]??null,activeVersion:c?.version??null,enabled:c?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[n.id]?.updatePolicy??"notify",pinnedVersion:t[n.id]?.pinnedVersion,updateDiagnostic:r[n.id],availableVersion:this.available.get(n.id)?.version??(r[n.id]?.status==="available"?r[n.id].version??null:null),...this.errors.has(n.id)?{error:this.errors.get(n.id)}:{},...a&&o.phase==="active"?{digest:a.digest,document:a.manifest.frontend.document.slice(2),controller:a.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(n.id)}/${this.assetTokens.get(n.id)}/${a.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,r,i){return this.serialize(e,async()=>{let n=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],c=o.map(l=>l.version).sort((l,p)=>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,()=>n.replace(p));return u.pending||this.packages.set(e,p),u}case"retry":{let l=n.pendingVersion,p=await this.lifecycle(e,()=>n.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!c)throw new h("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let f=await l(i),y=await n.broker.active();if(await this.recordDevSync(e,f.version),!y?.enabled)return{installed:!0,enabled:!1,version:f.version};if(y.version===f.version&&!n.pendingVersion)return{unchanged:!0,version:f.version};let k=await this.lifecycle(e,()=>n.replace(f));return k.pending||this.packages.set(e,f),k}let p=await this.check(e,c,r,i),u=await n.broker.active();if(p.version===c&&(!u?.enabled||u.version===c)&&!n.pendingVersion)return{unchanged:!0,version:c};let 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,()=>n.replace(w));return m.pending||this.packages.set(e,w),m}case"uninstall":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new h("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=K(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async r=>this.installer.collect(e,async()=>{let i=(await this.policies())[e];return[...r.map(n=>n.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...i?.pinnedVersion?[i.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,r){let i=this.supervisor(e);return t!==i.generation?Promise.reject(new 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 n=this.assetLeases.get(e);n||(n=new Map,this.assetLeases.set(e,n)),n.set(i.version,(n.get(i.version)??0)+1);try{return await na(i,r,t)}finally{let o=n.get(i.version)-1;o?n.set(i.version,o):n.delete(i.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let r;try{r=decodeURIComponent(t[1])}catch{return null}let i=this.assetTokens.get(r),n=Buffer.from(t[2]);return!i||n.length!==Buffer.byteLength(i)||!gf(n,Buffer.from(i))?null:this.asset(r,t[3],t[4])}async reconcileHostUpgrade(){if(Eo(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 n=e.versions[i.id];if(n?.length)try{let o=await this.supervisor(i.id).broker.active(),c=o?.enabled?o.version:n.map(l=>l.version).sort((l,p)=>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 n of this.installer.catalog){let o=(i.versions[n.id]??[]).map(l=>l.version).sort((l,p)=>Se(p,l)),c=await this.supervisor(n.id).broker.active();if(!o.length||this.isDevPlugin(n.id))continue;let a=!1;for(let l of new Set([...c?.enabled?[c.version]:[],...o]))try{await r.load(n.id,l),a=!0;break}catch{}if(!a)try{let l=await r.check(n.id,o[0],void 0,t),p=await r.install(n.id,l,t);await this.recordCheck(n.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(l){t?.throwIfAborted();let p=K(l);await this.recordCheck(n.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let t=new gt({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),i=[];for(let n of this.installer.catalog){let o=r.versions[n.id],c=await this.supervisor(n.id).broker.active();if(!c?.enabled)continue;if(!o?.length){i.push({pluginId:n.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let a=[c.version,...o.map(u=>u.version).sort((u,w)=>Se(w,u))],l=!1,p="";for(let u of new Set(a))try{await t.load(n.id,u),l=!0;break}catch(w){p||=K(w).message}l||i.push({pluginId:n.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return i}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let t=[],r=async()=>{let i=await Promise.allSettled(t.map(o=>o()));this.closing=!1;let n=i.find(o=>o.status==="rejected");if(n?.status==="rejected")throw n.reason};try{for(let i of this.supervisors.values())t.push(await i.suspendForRestart(void 0,e));return r}catch(i){throw await r(),i}}};import{randomUUID as mf}from"node:crypto";var N=s=>Object.assign(new Error(s),{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,n=12e4){this.pluginId=e,this.generation=t,this.pollMs=r,this.freezeMs=i,this.staleMs=n}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&r.scope.ownerId===t.ownerId&&r.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||t.ownerId!==r.scope.ownerId||t.workspaceId!==r.scope.workspaceId||t.sessionId!==r.identity.sessionId)throw N("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw N("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,t,r=++this.sequence){return e.commands.push({id:r,type:t,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw N("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw N("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw N("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw N("Invalid registration capability");let o=e.viewToken??mf();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw N("View initialization was cancelled; register a new document identity");let c=this.views.get(o);if(c){if(!this.sameScope(c,e,t)||c.kind!==e.kind)throw N("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw N("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw N("Invalid view capability");let r=this.views.get(e.viewToken),i=this.recoveries.get(e.viewToken),n=this.retired.get(e.viewToken);if(n&&!this.sameScope(n,e,t))throw N("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw N("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let o=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:o}}}if(r&&this.sameScope(r,e,t)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,t)||i&&!this.sameScope(i,e,t))throw N("Unknown or stale view capability");if(i)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(i,"retained")};if(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw N("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&i&&this.sameScope(i,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!i){if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");if(this.switching)throw N("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,t))throw N("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw N("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw N("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw N("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(N("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw N("Invalid acknowledgement");let o=r.commands.find(c=>c.id===e.commandId);if(!o)throw N("Unknown command acknowledgement");r.commands=r.commands.filter(c=>c.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(N(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw N("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw N("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw N("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw N("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw N("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw N("Invalid poll cursor");if(r.waiter)throw N("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw N("Invalid poll mode");return!e.immediate&&!r.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),r.waiter=void 0,o()}r.waiter=a}),{viewToken:r.token,commands:r.commands.filter(o=>o.id>e.after)}}default:throw N("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw N("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(r=>r.activeActions||r.kind!=="controller"&&!r.frozen&&(r.busy||!this.immediate&&["editor","workspace"].includes(r.kind)));throw N(`Close editors before updating; old version retained. Pending views: ${t.map(r=>`${r.kind}:${r.identity.mountId}${r.activeActions?` (action in flight x${r.activeActions})`:r.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,r)=>{let i=n=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,n?r(n):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(n=>n.token)),resolve:()=>i(),reject:n=>i(n),timer:setTimeout(()=>{let n=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));i(N(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${n.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let n of this.authoringViews())this.enqueue(n,"freeze",e);this.authoringViews().length||i()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw N("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(N("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(N("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var wf="@chengzhiyi/pi-excalidraw",yf={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"}}},vf="@chengzhiyi/pi-github",bf={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"}}},va=new Map([[wf,yf],[vf,bf]]);function Gi(s,e){let t=s.get(e);if(!t)throw new h("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as kf}from"node:crypto";var Pf="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"}),If="Ov23limJmKiuu8cOP83E";function Ji(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||If,scope:"repo",createUrl:Pf}}var Sf="https://github.com/login/device/code",Ef="https://github.com/login/oauth/access_token",xf=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>=xf)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let i=await this.post(Sf,{client_id:r.clientId,scope:r.scope}),{device_code:n,user_code:o,verification_uri:c}=i,a=Number(i.expires_in),l=Math.max(Number(i.interval)||5,1);if(typeof n!="string"||typeof o!="string"||typeof c!="string"||!c.startsWith("https://github.com/")||!Number.isFinite(a))throw new 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=kf();return this.flows.set(p,{pluginId:e,name:t,clientId:r.clientId,deviceCode:n,expiresAt:this.now()+a*1e3,interval:l,nextPoll:this.now()+l*1e3}),{deviceId:p,userCode:o,verificationUri:c,interval:l,expiresIn:a}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let r=await this.post(Ef,{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 ka,readFileSync as Pa,statSync as _f}from"node:fs";import{lstat as Af,readdir as Tf,writeFile as Rf,mkdir as Cf,rename as Nf}from"node:fs/promises";import{delimiter as Df,dirname as Of,isAbsolute as Hf,join as tt,resolve as Lt}from"node:path";var ba="@chengzhiyi/pi-github",Hr={[ba]:{id:ba,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"]}},Ia=()=>Object.keys(Hr).join(", ");function Mf(s=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,r=[],i="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(s??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=n.lastIndexOf("="),c=n.slice(0,o),a=n.slice(o+1),l=Hr[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?ka(Lt(a))?null:`archive not found: ${Lt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Ia()})`;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 Sa=s=>tt(s,"pi-web","hosted-dev.json"),Ea=s=>tt(s,"pi-web","hosted-dev-status.json");function jf(s,e,t=process.cwd()){let r=[],i=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(Df).map(c=>c.trim()).filter(Boolean);for(let c of n)r.push({path:Lt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&ka(e)){o=!0;try{let c=JSON.parse(Pa(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"||!Hf(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 Wf(s){let e=(i,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${i}`}}),t;try{t=_f(s.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(Pa(tt(s.path,"package.json"),"utf8"))}catch(i){return e(i.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof r.name!="string"?e("package.json has no name"):Hr[r.name]?We(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: ${Ia()})`)}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=Mf(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=jf(this.env,this.configPath,this.cwd),r=[],i=new Map,n=new Map;for(let o of t.specs){let c=Wf(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),n.set(a,o.source)}for(let o of[...this.roots.keys()])i.has(o)||this.roots.delete(o);for(let[o,c]of i)this.roots.set(o,c);this.rootSource.clear();for(let[o,c]of n)this.rootSource.set(o,c);return this.fileNotices=t.notices,this.rootNotices=r,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},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 n=await $f(r);if(n===null){this.set(t,i,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),i.seen=void 0;continue}if(n!==i.seen){i.seen=n;continue}n===i.applied||this.stopped||await this.apply(t,i,n)}await this.publish()}set(e,t,r,i={}){let n=t.state!==r||t.message!==i.message||t.version!==i.version;t.state=r,t.message=i.message,t.code=i.code,t.version=i.version??t.version,n&&(t.at=new Date().toISOString(),this.log(`${e}: ${r}${i.version?` ${i.version}`:""}${i.message?` \u2014 ${i.message}`:""}`))}async apply(e,t,r){this.set(e,t,"switching");try{let n=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=r,n?.installed?n.pendingVersion?this.set(e,t,"pending",{version:n.version,message:`Waiting for editors to close before switching to ${n.pendingVersion}`}):this.set(e,t,"synced",{version:n.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(i){let n=K(i);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(n.code)||(t.applied=r),n.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:n.code,message:`${n.message} (${n.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let i=Object.fromEntries([...this.roots].map(([c,a])=>[c,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),n=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(c=>c.id),plugins:i,notices:e.notices});if(n===this.lastStatus)return;this.lastStatus=n;let o=`${r}.${process.pid}.tmp`;try{await Cf(Of(r),{recursive:!0}),await Rf(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await Nf(o,r)}catch{}}};async function $f(s){let e=[],t=async(r,i)=>{let n=await Af(r);e.push(`${i}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(tt(s,"package.json"),"package.json");let r=async(i,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await Tf(i,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await r(tt(i,c.name),`${n}/${c.name}`,o+1):await t(tt(i,c.name),`${n}/${c.name}`)};if(await r(tt(s,"dist"),"dist",0),!e.some(i=>i.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function Vf(s){try{return[...ut(s).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??va,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(n=>n.pluginId===t)&&i?.enabled!==!1}},invoke:async(t,r,i)=>{i?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let n=this.manager.tools.find(c=>c.pluginId===t);if(!n)throw new h("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,n.generation,r);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new 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(n=>n.pluginId===t)?.descriptors:[];if(!i)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,i),r.enabled){let n=await this.manager.installer.load(t,r.version);this.documents.set(t,{document:n.manifest.frontend.document.replace(/^\.\//,""),controller:n.manifest.frontend.controller.replace(/^\.\//,""),secrets:Vf(n.manifest)})}else this.documents.delete(t);this.adapter.change(t,i),await this.coordinator(t).committed(r),e.changed?.(),this.recovery.delete(t)}catch(i){throw this.recovery.set(t,i),await this.coordinator(t).committed(r).catch(()=>{}),i}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,r,i)=>{let n=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!n)throw new 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 n.delete(t,r):await n.set(t,r,i),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let r=this.options.capabilities?.secrets;if(!r)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let n=this.documents.get(t.pluginId)?.secrets.includes(t.name)?Ji(t.pluginId,t.name):void 0;if(!n)throw new h("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,n)}let 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 n=await t();if(n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new 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 n}finally{if(!r)for(let n of this.views.values())n.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=i.catch(()=>{}),i.catch(n=>{throw r&&this.adapter.thaw(),n})}async admit(e){let t,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(i=>{t=setTimeout(()=>i(!1),e),t.unref?.()})])}finally{clearTimeout(t)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??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 j(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 n=i.enabled?this.documents.get(i.id)?.secrets??[]:[];t&&n.length&&r.set(i.id,await Promise.all(n.map(async o=>{let c=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(n=>n.id===i.id)?.icon,hasRetainedData:i.activeVersion!==null,phase:this.recovery.has(i.id)?"reconnect-required":i.phase,updatePolicy:i.updatePolicy,pinnedVersion:i.pinnedVersion,updateDiagnostic:i.updateDiagnostic,...i.enabled&&i.activeVersion?{version:i.activeVersion}:i.version?{version:i.version}:{},...i.availableVersion?{availableVersion:i.availableVersion}:{},...i.pendingVersion?{pendingVersion:i.pendingVersion}:{},...i.generation!==null?{generation:i.generation}:{},...this.recovery.has(i.id)||i.error?{error:this.recovery.get(i.id)instanceof Error?this.recovery.get(i.id).message:i.error?.message??"Recovery required",errorCode:this.recovery.has(i.id)?"reconnect_required":i.error?.code}:{},...i.enabled&&i.assetBase&&this.documents.has(i.id)&&this.trusted.has(i.id)?{documentUrl:i.assetBase+this.documents.get(i.id).document,controllerUrl:i.assetBase+this.documents.get(i.id).controller,contribution:structuredClone(this.trusted.get(i.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new 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 n={requestId:Ff(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,n);throw new h("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new h("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...n,kind:"action"})}finally{i()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let n of this.views.values())n.allowImmediateReopen(!0);let t=await this.manager.suspendForRestart(e),r=!1,i=async()=>{if(!r)try{await t(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(t){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),t}finally{for(let t of this.views.values())t.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as Uf,readdir as Bf,unlink as Lf}from"node:fs/promises";import{join as mt}from"node:path";import{randomUUID as zf}from"node:crypto";var Xi="hosted-migration.json";function xa(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:r,sessionId:i}=t.scope,n=mt(s,B(JSON.stringify([r,i])));await Z(s),await Z(n);let o=mt(n,"scope.lock"),c;try{c=await Uf(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:zf()}));let a=await ee(mt(n,Xi));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Bf(n),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(n,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(n,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(w=>w.id===u)))throw new h("invalid_storage","Invalid legacy focused drawing");return a||await j(mt(n,Xi),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Lf(o)}}}import{join as eh}from"node:path";import{randomUUID as qf}from"node:crypto";var Gf=6e4,jr=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<Gf?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:qf(),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 Jf,readFile as Kf,rename as Xf,writeFile as Yf}from"node:fs/promises";import{randomUUID as Qf,createHash as Zf}from"node:crypto";import{join as _a}from"node:path";var Wr=class{dir;queue=Promise.resolve();constructor(e){this.dir=_a(e,"secrets")}file=e=>_a(this.dir,`${Zf("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Kf(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 Jf(this.dir,{recursive:!0,mode:448});let i=`${this.file(e)}.${Qf()}.tmp`;await Yf(i,JSON.stringify(r),{mode:384}),await Xf(i,this.file(e))})}};function Aa(s,e){let t=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:i,title:n,prompt:o}){let c=await s.createDetached(i,r,n);try{await s.sendDetached(c,o,!1)}catch(a){throw await s.releaseDetached(c),a}return{sessionId:c}},ownerOf:r=>s.detachedOwner(r),activeCount:r=>s.detachedCount(r),async send(r,i,n){let o=s.detachedOwner(r);if(n==="execute"&&(!o||!await e(o,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await s.sendDetached(r,i,n==="execute")},abort:r=>s.abortDetached(r),release:r=>s.releaseDetached(r),async events(r,i){let n=s.detachedEvents(r,i);return{events:n.events.map(t),next:n.next}}}}var th="scheduler";function Ta(s){let e=new jr({describe:s.sessionTitle,changed:s.changed}),t=()=>{let i=s.sessions();if(!i)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return i},r={createDetached:(...i)=>t().createDetached(...i),detachedOwner:i=>s.sessions()?.detachedOwner(i)??null,detachedCount:i=>s.sessions()?.detachedCount(i)??0,sendDetached:(...i)=>t().sendDetached(...i),abortDetached:i=>t().abortDetached(i),releaseDetached:async i=>{e.forget(i),await t().releaseDetached(i)},detachedEvents:(...i)=>t().detachedEvents(...i)};return{approvals:e,capabilities:{secrets:new Wr(eh(s.root,"capability-secrets")),sessions:Aa(r,(i,n)=>e.authorize(i,n))},scheduledScope:()=>{let i=s.activeWorkspace();if(!i)return null;try{return s.trustedScope(i,th)}catch{return null}}}}async function rh(){for(let s of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=ir(s),t=new Ee({env:s,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:xt,buildId:Ie,browser:ir({}).browser}}async function Ra(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let s=new Ee({monitor:!1});try{if(await s.ready,!s.enabled)throw new Error("Sentry verification transport is disabled");let e=s.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await s.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:xt,buildId:Ie}}finally{await s.close()}}var zt=vt(sh(ah(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),uh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[uh]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new 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 fh=null;function hh(){return fh??=ch.create({refreshOnCreate:!1})}var Fr=new Map;async function yt(){let s=await hh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let r of Fr.keys())t.has(r)||(s.unregisterProvider(r),Fr.delete(r));for(let r of t){let i=e?.getRegisteredNativeProvider(r),n=e?.getRegisteredProviderConfig(r),o=i??n;!o||Fr.get(r)===o||(i?s.registerNativeProvider(i):n&&s.registerProvider(r,n),Fr.set(r,o))}return await s.refresh({allowNetwork:!1}),s}function ie(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():De()}function De(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...$n(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 rs(s,e,t,r,i){let n=de(s);Oe({...De(),idle:n.isIdle()},e,i);let o=n.isIdle();o&&dt(()=>d.hosted?.adapter.assertAdmission(),r,(c,a)=>d.bridge?.reportError?.(c,a)),o&&(d.operation=r);try{let c=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===s)await d.replacementContext.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:i});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:i})}d.current?.sessionManager.getSessionId()===s&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:De()})}catch(c){throw o&&(d.operation=void 0),c}}function Zi(){let s=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!s||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==s||d.tuiAgentError)return!1;let r=De();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!r.paused&&!r.interactions.length};d.tuiPrompts.schedule(t,(r,i,n)=>rs(s,r,i,n))}function ne(s){if(ie().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function Ha(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=ie(),i=d.current?De():null,n=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 ts.listAll(),a=d.workspaceSessions?.retainedSessions()??[];i&&o&&a.push({sessionId:i.sessionId,cwd:o,path:null,name:i.name,modified:i.messages.at(-1)?.timestamp??new Date().toISOString(),idle:i.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&i.idle&&d.tuiPrompts.length===0&&!i.messages.some(p=>p.role==="user")});let l=(await Promise.all(s.map(async p=>{let 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===n&&!w.some(m=>m.id===t.sessionId)&&w.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),w}))).flat();return{items:s,activeId:e,sessions:l}}var Na=0;async function re(){if(!d.bridge)return;let s=++Na;try{let e=await Ha();s===Na&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function es(s,e=!1){let t=d.workspaces?.get(s);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=s,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:ie()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await d.workspaceSessions.reuseBlank(t.path))&&await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=s,d.bridge?.publish({type:"snapshot",session:ie()})}await re()}async function Da(s,e,t){let r=d.workspaces?.get(s);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(s){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function ae(s){d.current=s,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:ie()})}function Ma(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let s=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!s)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return lh.create(s,void 0,{projectTrusted:e})}async function ja(){let s=Ma(),e=i=>({packages:(i.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:i.extensions??[],skills:i.skills??[]}),t=new Oa({cwd:ie().cwd,agentDir:me(),settingsManager:s}),r=yo(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:r}}async function gh(s){ne(s.sessionId);let e=d.selected==="tui"?de(s.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=Ma();if(s.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=s.value.trim(),i=s.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(s.kind==="packages"){let n=new Oa({cwd:ie().cwd,agentDir:me(),settingsManager:t});s.action==="add"?await n.installAndPersist(r,{local:s.scope==="project"}):await n.removeAndPersist(r,{local:s.scope==="project"})}else if(s.kind==="extensions"){let n=i.extensions??[],o=s.action==="add"?[...new Set([...n,r])]:n.filter(c=>c!==r);s.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let n=i.skills??[],o=s.action==="add"?[...new Set([...n,r])]:n.filter(c=>c!==r);s.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&ae(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await ja()}function Vr(s,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:Ca("sha256").update(p).digest("hex")}},r=wt(me(),"pi-web","hosted"),i=new Dr({configPath:Sa(me())});d.hosted??=new Mr({root:r,...i.enabled?{dev:i,devStatusPath:Ea(me())}:{},...i.catalog.length?{catalog:[...Ne,...i.catalog],devArchives:i.archives,devRoots:i.roots}:{},...Ta({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(nh(vt(zt,"../../package.json"),"utf8")).version,packageRoot:vt(zt,"../.."),workerEntry:vt(zt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${Ca("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:()=>xa(wt(me(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Zi),d.pi=s,d.tools?.clear(),d.tools=new lt({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(a,l)=>d.bridge?.reportError?.(a,l),breadcrumb:(a,l)=>d.bridge?.breadcrumb?.(a,l),anonymize:a=>d.telemetry?.session(a)??"unavailable"});let n=a=>({...d.operation,session:d.telemetry?.session(a.sessionManager.getSessionId()),piVersion:Qi,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new at(s.events,a=>!!d.bridge&&a.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(a.pluginId),()=>{d.current&&d.selected==="tui"&&ae(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=s.events.on(dr,()=>{d.selected==="tui"&&d.current&&ae(d.current)})};o(),s.on("session_start",async(a,l)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,o(),d.current=l,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(s,t(l.cwd,l.sessionManager.getSessionId())),d.hosted&&!await d.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new 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")}))}),s.on("agent_start",(a,l)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",n(l)),ae(l),re()}),s.on("agent_end",(a,l)=>ae(l)),s.on("agent_settled",(a,l)=>{d.bridge?.breadcrumb?.("agent_end",n(l)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Zi(),ae(l),re()}),s.on("tool_execution_start",(a,l)=>{d.tools?.start(a,n(l))}),s.on("tool_execution_end",(a,l)=>{d.tools?.end(a,n(l))}),s.on("model_select",(a,l)=>ae(l)),s.on("thinking_level_select",(a,l)=>ae(l)),s.on("message_end",(a,l)=>{if(a.message.role==="assistant"&&a.message.stopReason==="error"){d.tuiAgentError=!0;let p=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion: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,n(l)),a.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&a.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),ae(l),re()}),s.on("session_info_changed",(a,l)=>ae(l)),s.on("message_update",(a,l)=>{if(d.current=l,a.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(a.message.timestamp).toISOString(),blocks: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}))}),s.on("session_shutdown",async a=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,a.reason==="new"||a.reason==="resume"||a.reason==="fork"||a.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let l=d.bridge,p=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let u=d.workspaceSessions;d.workspaceSessions=null,await u?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,l?await l.close():await p?.close()});let c=async a=>{d.telemetry??=new Ee;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=s,d.tuiCatalog=await Ke.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new lr(Bn(me())),await d.workspaces.load());try{await d.workspaces.discover((await ts.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(ne(f),!$r()?.has(y))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,A=d.tuiGeneration,D=d.workspaceSessions?.session,M={requestId:ph(),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(ne(f),E!==d.selected||(E==="tui"?A!==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(ne(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){ne(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 A=E.message.content[k];return A?.type!=="image"?null:{data:Buffer.from(A.data,"base64"),mimeType:A.mimeType}},async workspaces(){return Ha()},async addWorkspace(f,y){let k=await d.workspaces.add(f,y);try{await es(k.id,!0)}catch(P){throw await re(),P}},async selectWorkspace(f){await es(f)},async newSessionInWorkspace(f){await es(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(A=>A.id===y&&A.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 Da(f,y,k),d.current?.sessionManager.getSessionId()===y&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(y,E)||ts.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 Da(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,A=E?.path??(k||null);A&&await wo(A,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 En(wt(me(),"models.json"),f,y)},async updateProviderModel(f,y,k){if(ne(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 xn(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 A=k.action==="save"?k.model.id:k.action==="base_url"&&P?.startsWith(`${y}/`)?P.slice(y.length+1):null;if(A&&P===`${y}/${A}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(y,A)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let D=de(f),M=D.modelRegistry.find(y,A);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(ne(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,vn(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(ne(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 bn(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(ne(f),d.selected==="sdk"){let k=d.workspaceSessions?.session;if(!k||!k.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await k.compact(),d.bridge?.publish({type:"snapshot",session: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(ne(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(A=>A.provider===y&&A.id===k))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(E))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");ae(P)},async setThinkingLevel(f,y){if(ne(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||!dh(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:ja,updateConfig:gh,async send(f,y,k=[],P,E){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.send(y,k,P,E);return}let A=de(f);if(Oe(De(),y,E),E==="followUp"&&(!A.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(y,k,P),Zi();return}if(A.isIdle()&&d.tuiPrompts.sending)throw new oe("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await rs(f,y,k,P,E)},async updateQueuedPrompt(f,y,k,P){if(ne(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,A,D)=>rs(f,E,A,D,"steer"))},async abort(f){if(ne(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(Tt),y.abort()}},async resume(f,y){if(ne(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(ne(f),d.selected==="sdk"){let P=d.workspaces?.get(d.activeWorkspaceId??"");if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(P.path)||await d.workspaceSessions.open(P.path,"new"),await 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 Wn(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(ih).filter(Boolean))try{u.push(oh(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}};s.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(a,l)=>c(l)}),s.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(a,l)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(a))throw new Error("Launcher stop receipt ID required");try{await d.hosted?.shutdown(),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!0})}`,"info")}catch(p){console.error("pi-webapp: plugin shutdown refused the stop request:",p),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!1})}`,"warning")}}}),s.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(a,l)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await l.waitForIdle(),await d.lifecycle.run(async()=>{let p=d.workspaceSessions?.session;p&&(await p.waitForIdle(),await d.workspaceSessions.reload()),await l.reload()}))}})}var YP=Vr;export{YP as default,rh as verifySentryDisabledRelease,Ra as verifySentryNodeRelease};
49
49
 
50
- //# debugId=458ba3da-fce1-440b-bce1-403e684ef316
50
+ //# debugId=0fbf3f22-b19a-42a0-ab5a-c11e8b3ab525