pi-webapp 0.1.50-alpha.4 → 0.1.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/extension.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="21797faa-38d4-4a0e-a037-226896d3ebe4",s._sentryDebugIdIdentifier="sentry-dbid-21797faa-38d4-4a0e-a037-226896d3ebe4")}catch{}})();import{delimiter as rh,dirname as sh,join as Pt,resolve as St}from"node:path";import{readFileSync as nh,realpathSync as Br,watch as oh}from"node:fs";import{fileURLToPath as ah}from"node:url";import{DefaultPackageManager as sa,getAgentDir as we,ModelRuntime as ch,SessionManager as qr,SettingsManager as lh,VERSION as Ur}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as dh}from"@earendil-works/pi-ai";import{randomBytes as Pn,randomUUID as rr,timingSafeEqual as al}from"node:crypto";import{readFile as cl,readdir as ll}from"node:fs/promises";import{createServer as dl}from"node:http";import{join as sr}from"node:path";import{getAgentDir as pl}from"@earendil-works/pi-coding-agent";import{isAbsolute as Wa,relative as $a}from"node:path";var ot={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Jr={id:ot.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as da}from"node:child_process";import{realpath as pa}from"node:fs/promises";import{isAbsolute as Kr,relative as ua,sep as ha,win32 as fa}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function L(s,e,t=2*1024*1024,i={}){let r=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=da("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,env:{...r,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:i.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new R("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,i.write?"outcome_unknown":"git_failed"));return}n(p);return}if(i.write){let m=l.killed||l.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(u)?"index_locked":/already exists/i.test(u)?"branch_exists":/already checked out|used by worktree/i.test(u)?"branch_in_use":/would be overwritten|local changes/i.test(u)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(u)?"identity_missing":"git_failed";o(new R("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",m==="outcome_unknown"?503:409,m));return}let y=l.code;y==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):y==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new R("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new R("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new R(l.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});a.stdin?.on("error",l=>{c=l}),i.input!==void 0&&a.stdin?.end(i.input)})}async function De(s){let e=await pa(s),t;try{t=(await L(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(r){if(r instanceof R&&r.status===404)return{kind:"not-repository"};if(r instanceof R&&r.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw r}let i=ua(t,e).split(ha).join("/");if(i===".."||i.startsWith("../")||Kr(i))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function qe(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||Kr(s)||fa.isAbsolute(s)||s.split("/").some(e=>!e||e==="."||e===".."))throw new R("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as xa}from"node:crypto";import{lstat as Gi,realpath as ds}from"node:fs/promises";import{dirname as ls,isAbsolute as _a,relative as Aa,resolve as xt}from"node:path";import{lstat as Ia}from"node:fs/promises";import{resolve as Sa}from"node:path";import{constants as at}from"node:fs";import{open as Zr,opendir as ga,realpath as Xr,stat as Li}from"node:fs/promises";import{isAbsolute as es,relative as ma,resolve as wa,sep as ya,win32 as va}from"node:path";var ba=1e3,ka=512*1024,ts=8*1024*1024,Yr=1e4,Pa=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),J=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function Qr(s,e){let t=ma(s,e);return t!==".."&&!t.startsWith(`..${ya}`)&&!es(t)}async function Kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||es(e)||va.isAbsolute(e))throw new J("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Xr(s),i=wa(t,e);if(!Qr(t,i))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let r=await Xr(i);if(!Qr(t,r))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return r}async function zi(s){try{return await s()}catch(e){if(e instanceof J)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new J("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new J("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function is(s,e){return zi(async()=>{let t=await Kt(s,e),i=[],r=!1;for await(let n of await ga(t)){if(i.length===ba){r=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await Li(await Kt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}i.push({name:n.name,path:o,kind:c})}return i.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Pa.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:i,truncated:r}})}function rs(s){if(s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(s.subarray(0,6).toString("ascii")))return"image/gif";if(s.subarray(0,4).toString("ascii")==="RIFF"&&s.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Et(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n={path:e,size:r.size},o=Buffer.alloc(16);await i.read(o,0,o.length,0);let c=rs(o),a=c?ts:ka;if(r.size>a)return{...n,kind:"too-large",limit:a,unit:"bytes"};let l=Buffer.alloc(Math.min(r.size+1,a+1)),p=0;for(;p<l.length;){let{bytesRead:m}=await i.read(l,p,l.length-p,p);if(!m)break;p+=m}if(p>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let u=l.subarray(0,p);if(c)return{...n,kind:"image",mimeType:c,data:u.toString("base64")};if(u.some(m=>m===0||m<32&&![9,10,12,13,27].includes(m)))return{...n,kind:"unsupported"};let y=1;for(let m=0;m<u.length-1;m++)if(u[m]===10&&++y>Yr)return{...n,kind:"too-large",limit:Yr,unit:"lines"};try{return{...n,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(u)}}catch{return{...n,kind:"unsupported"}}}finally{await i.close()}})}async function ss(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(r.size>ts)throw new J("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(r.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await i.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=rs(c);if(!a)throw new J("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:c}}finally{await i.close()}})}var Ea=1e3,ns=512*1024,os=1e4;function as(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function ct(s){let e=await De(s);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,r=await L(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=r.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);n.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);n.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(n.ahead=Number(P[1]),n.behind=Number(P[2]));continue}let l=a[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,u=0;for(let P=0;P<p;P++)u=a.indexOf(" ",u)+1;let y=as(i,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!y)continue;if(n.entries.length===Ea){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),w={path:y,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},k=m===void 0?void 0:as(i,m);k&&(w.originalPath=k),n.entries.push(w)}return n}async function cs(s,e,t){if(qe(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await ct(s);if(i.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r={path:e,area:t},n=i.entries.find(c=>c.path===e);if(!n)return{...r,kind:"empty"};if(n.conflict)return{...r,kind:"conflict"};if(n.submodule)return{...r,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...r,kind:"empty"};if(!(await Ia(Sa(s,e))).isFile())return{...r,kind:"unsupported"};let c=await Et(s,e);if(c.kind==="too-large")return{...r,kind:"too-large"};if(c.kind!=="text")return{...r,kind:"binary"};if(!c.text)return{...r,kind:"empty"};let a=c.text.split(`
1
+ (function(){try{var s=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new s.Error().stack;e&&(s._sentryDebugIds=s._sentryDebugIds||{},s._sentryDebugIds[e]="d3b85ce5-d862-45c5-8684-5abd7591b2f9",s._sentryDebugIdIdentifier="sentry-dbid-d3b85ce5-d862-45c5-8684-5abd7591b2f9")}catch{}})();import{delimiter as rh,dirname as sh,join as Pt,resolve as St}from"node:path";import{readFileSync as nh,realpathSync as Br,watch as oh}from"node:fs";import{fileURLToPath as ah}from"node:url";import{DefaultPackageManager as sa,getAgentDir as we,ModelRuntime as ch,SessionManager as qr,SettingsManager as lh,VERSION as Ur}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as dh}from"@earendil-works/pi-ai";import{randomBytes as Pn,randomUUID as rr,timingSafeEqual as al}from"node:crypto";import{readFile as cl,readdir as ll}from"node:fs/promises";import{createServer as dl}from"node:http";import{join as sr}from"node:path";import{getAgentDir as pl}from"@earendil-works/pi-coding-agent";import{isAbsolute as Wa,relative as $a}from"node:path";var ot={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var Jr={id:ot.git,kind:"builtin",version:"1.0.0",name:{zh:"Git",en:"Git"},description:{zh:"\u5BA1\u9605\u5DE5\u4F5C\u533A\u6539\u52A8\u4E0E\u63D0\u4EA4\u5386\u53F2\uFF0C\u6682\u5B58\u6587\u4EF6\u3001\u63D0\u4EA4\u5E76\u7BA1\u7406\u672C\u5730\u5206\u652F\u3002",en:"Review workspace changes and history, stage files, commit and manage local branches."}};import{execFile as da}from"node:child_process";import{realpath as pa}from"node:fs/promises";import{isAbsolute as Kr,relative as ua,sep as ha,win32 as fa}from"node:path";var R=class extends Error{status;reason;constructor(e,t=400,i="git_failed"){super(e),this.name="WorkspaceGitError",this.status=t,this.reason=i}};function L(s,e,t=2*1024*1024,i={}){let r=Object.fromEntries(Object.entries(process.env).filter(([n])=>!n.startsWith("GIT_")));return new Promise((n,o)=>{let c,a=da("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:s,env:{...r,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:i.write?3e4:1e4,maxBuffer:t,windowsHide:!0},(l,p,u)=>{if(!l){if(c){o(new R("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,i.write?"outcome_unknown":"git_failed"));return}n(p);return}if(i.write){let m=l.killed||l.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(u)?"index_locked":/already exists/i.test(u)?"branch_exists":/already checked out|used by worktree/i.test(u)?"branch_in_use":/would be overwritten|local changes/i.test(u)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(u)?"identity_missing":"git_failed";o(new R("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",m==="outcome_unknown"?503:409,m));return}let y=l.code;y==="ENOENT"?o(new R("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):y==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?o(new R("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(u)?o(new R("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):o(new R(l.killed?"Git \u8BFB\u53D6\u8D85\u65F6\uFF0C\u8BF7\u91CD\u8BD5":"Git \u8BFB\u53D6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u548C\u76EE\u5F55\u6743\u9650",503))});a.stdin?.on("error",l=>{c=l}),i.input!==void 0&&a.stdin?.end(i.input)})}async function De(s){let e=await pa(s),t;try{t=(await L(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(r){if(r instanceof R&&r.status===404)return{kind:"not-repository"};if(r instanceof R&&r.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw r}let i=ua(t,e).split(ha).join("/");if(i===".."||i.startsWith("../")||Kr(i))throw new R("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:t,scope:i?`${i}/`:""}}function qe(s){if(typeof s!="string"||!s||s.length>4096||s.includes("\0")||s.includes("\\")||Kr(s)||fa.isAbsolute(s)||s.split("/").some(e=>!e||e==="."||e===".."))throw new R("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as xa}from"node:crypto";import{lstat as Gi,realpath as ds}from"node:fs/promises";import{dirname as ls,isAbsolute as _a,relative as Aa,resolve as xt}from"node:path";import{lstat as Ia}from"node:fs/promises";import{resolve as Sa}from"node:path";import{constants as at}from"node:fs";import{open as Zr,opendir as ga,realpath as Xr,stat as Li}from"node:fs/promises";import{isAbsolute as es,relative as ma,resolve as wa,sep as ya,win32 as va}from"node:path";var ba=1e3,ka=512*1024,ts=8*1024*1024,Yr=1e4,Pa=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),J=class extends Error{status;constructor(e,t=400){super(e),this.name="WorkspaceFileError",this.status=t}};function Qr(s,e){let t=ma(s,e);return t!==".."&&!t.startsWith(`..${ya}`)&&!es(t)}async function Kt(s,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||es(e)||va.isAbsolute(e))throw new J("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let t=await Xr(s),i=wa(t,e);if(!Qr(t,i))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let r=await Xr(i);if(!Qr(t,r))throw new J("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return r}async function zi(s){try{return await s()}catch(e){if(e instanceof J)throw e;let t=e.code;throw t==="ENOENT"||t==="ENOTDIR"?new J("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):t==="EACCES"||t==="EPERM"?new J("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function is(s,e){return zi(async()=>{let t=await Kt(s,e),i=[],r=!1;for await(let n of await ga(t)){if(i.length===ba){r=!0;break}let o=e?`${e}/${n.name}`:n.name,c=n.isDirectory()?"directory":n.isFile()?"file":"other";if(n.isSymbolicLink())try{let a=await Li(await Kt(s,o));c=a.isDirectory()?"directory":a.isFile()?"file":"other"}catch{}i.push({name:n.name,path:o,kind:c})}return i.sort((n,o)=>+(o.kind==="directory")-+(n.kind==="directory")||Pa.compare(n.name,o.name)||n.name.localeCompare(o.name)),{path:e,entries:i,truncated:r}})}function rs(s){if(s.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(s.subarray(0,6).toString("ascii")))return"image/gif";if(s.subarray(0,4).toString("ascii")==="RIFF"&&s.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Et(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n={path:e,size:r.size},o=Buffer.alloc(16);await i.read(o,0,o.length,0);let c=rs(o),a=c?ts:ka;if(r.size>a)return{...n,kind:"too-large",limit:a,unit:"bytes"};let l=Buffer.alloc(Math.min(r.size+1,a+1)),p=0;for(;p<l.length;){let{bytesRead:m}=await i.read(l,p,l.length-p,p);if(!m)break;p+=m}if(p>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let u=l.subarray(0,p);if(c)return{...n,kind:"image",mimeType:c,data:u.toString("base64")};if(u.some(m=>m===0||m<32&&![9,10,12,13,27].includes(m)))return{...n,kind:"unsupported"};let y=1;for(let m=0;m<u.length-1;m++)if(u[m]===10&&++y>Yr)return{...n,kind:"too-large",limit:Yr,unit:"lines"};try{return{...n,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(u)}}catch{return{...n,kind:"unsupported"}}}finally{await i.close()}})}async function ss(s,e){return zi(async()=>{let t=await Kt(s,e);if(!(await Li(t)).isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let i=await Zr(t,at.O_RDONLY|at.O_NONBLOCK|(at.O_NOFOLLOW??0));try{let r=await i.stat();if(!r.isFile())throw new J("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(r.size>ts)throw new J("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let n=Buffer.alloc(r.size+1),o=0;for(;o<n.length;){let{bytesRead:l}=await i.read(n,o,n.length-o,o);if(!l)break;o+=l}if(o>r.size)throw new J("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let c=n.subarray(0,o),a=rs(c);if(!a)throw new J("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:a,bytes:c}}finally{await i.close()}})}var Ea=1e3,ns=512*1024,os=1e4;function as(s,e){return e.startsWith(s)&&e.slice(s.length)||void 0}async function ct(s){let e=await De(s);if(e.kind!=="repository")return e;let{root:t,scope:i}=e,r=await L(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),n={kind:"repository",root:t,scope:i,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},o=r.split("\0");for(let c=0;c<o.length;c++){let a=o[c];if(a.startsWith("# branch.oid ")){let P=a.slice(13);n.head=P==="(initial)"?null:P;continue}if(a.startsWith("# branch.head ")){let P=a.slice(14);n.branch=P==="(detached)"?null:P;continue}if(a.startsWith("# branch.upstream ")){n.upstream=a.slice(18);continue}if(a.startsWith("# branch.ab ")){let P=a.match(/\+(\d+) -(\d+)/);P&&(n.ahead=Number(P[1]),n.behind=Number(P[2]));continue}let l=a[0];if(!["1","2","u","?"].includes(l??""))continue;let p=l==="?"?1:l==="1"?8:l==="2"?9:10,u=0;for(let P=0;P<p;P++)u=a.indexOf(" ",u)+1;let y=as(i,a.slice(u)),m=l==="2"?o[++c]:void 0;if(!y)continue;if(n.entries.length===Ea){n.truncated=!0;continue}let f=a.slice(0,u).split(" "),w={path:y,index:l==="?"?"?":f[1][0],worktree:l==="?"?"?":f[1][1],conflict:l==="u",untracked:l==="?",submodule:l!=="?"&&f[2]!=="N..."},k=m===void 0?void 0:as(i,m);k&&(w.originalPath=k),n.entries.push(w)}return n}async function cs(s,e,t){if(qe(e),!["staged","unstaged","untracked"].includes(t))throw new R("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let i=await ct(s);if(i.kind!=="repository")throw new R("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let r={path:e,area:t},n=i.entries.find(c=>c.path===e);if(!n)return{...r,kind:"empty"};if(n.conflict)return{...r,kind:"conflict"};if(n.submodule)return{...r,kind:"submodule"};if(t==="untracked"){if(!n.untracked)return{...r,kind:"empty"};if(!(await Ia(Sa(s,e))).isFile())return{...r,kind:"unsupported"};let c=await Et(s,e);if(c.kind==="too-large")return{...r,kind:"too-large"};if(c.kind!=="text")return{...r,kind:"binary"};if(!c.text)return{...r,kind:"empty"};let a=c.text.split(`
2
2
  `),l=a.at(-1)==="";l&&a.pop();let p=`--- /dev/null
3
3
  +++ b/${e.replace(/[\r\n]/g," ")}
4
4
  @@ -0,0 +1,${a.length} @@
@@ -25,7 +25,7 @@ ${l.stack.split(`
25
25
  `).slice(1).join(`
26
26
  `)}`);let u=this.reportError(p,{...n,stage:"provider_login"});a.view={id:c,providerId:e,method:t,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:u}}}),{...a.view}}get(e){let t=this.flows.get(e)?.view;return t?{...t}:void 0}getActive(){let e=[...this.flows.values()].find(({view:t})=>t.status==="running"||t.status==="waiting")?.view;return e?{...e}:void 0}respond(e,t){let i=this.flows.get(e);if(!i?.answer||i.view.status!=="waiting"||i.view.prompt?.type==="select"&&!i.view.prompt.options.some(n=>n.id===t))return!1;let r=i.answer;return i.answer=void 0,i.reject=void 0,i.view={...i.view,status:"running",prompt:void 0},r(t),!0}cancel(e){let t=this.flows.get(e);return!t||t.view.status==="done"||t.view.status==="error"?!1:(t.view={...t.view,status:"cancelled",prompt:void 0},t.controller.abort(),t.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),t.answer=void 0,t.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as Cc}from"node:crypto";import{readFile as Dc,rename as Nc,rm as Hc,stat as Oc,writeFile as Mc,mkdir as jc}from"node:fs/promises";import{dirname as Wc}from"node:path";var $c=["openai-completions","openai-responses","anthropic-messages"];function er(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(e.id)||typeof e.name!="string"||!e.name.trim()||e.name.length>100||typeof e.modelId!="string"||!e.modelId.trim()||e.modelId.length>200||!$c.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let t=new URL(e.baseUrl);return(t.protocol==="https:"||t.protocol==="http:")&&!!t.hostname&&!t.username&&!t.password&&!t.hash}catch{return!1}}async function sn(s,e){if(!er(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let t;try{t=await Dc(s,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}let i;if(t===void 0)i={providers:{}};else{try{i=JSON.parse(t)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(i.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let r={...i,providers:{...i.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await jc(Wc(s),{recursive:!0});let n=t===void 0?384:(await Oc(s)).mode&511,o=`${s}.pi-web-${Cc(6).toString("hex")}.tmp`;try{await Mc(o,`${JSON.stringify(r,null,2)}
27
27
  `,{mode:n,flag:"wx"}),await Nc(o,s)}finally{await Hc(o,{force:!0})}}import{randomBytes as Vc}from"node:crypto";import{mkdir as Fc,readFile as Bc,rename as Uc,rm as Lc,stat as zc,writeFile as qc}from"node:fs/promises";import{dirname as Gc}from"node:path";function nn(s){if(!s||s.length>2048)return!1;try{let e=new URL(s);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function on(s){if(!s||typeof s!="object")return!1;let e=s;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&an(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&nn(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function an(s){if(!s||typeof s!="object")return!1;let e=s;if(typeof e.id!="string"||!e.id.trim()||e.id.length>200||e.name!==void 0&&(typeof e.name!="string"||!e.name.trim()||e.name.length>200))return!1;for(let t of[e.contextWindow,e.maxTokens])if(t!==void 0&&(!Number.isSafeInteger(t)||t<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(t=>t==="text"||t==="image")&&new Set(e.input).size===e.input.length}async function cn(s){let e;try{e=await Bc(s,"utf8")}catch(i){if(i.code!=="ENOENT")throw i}if(e===void 0)return{config:{providers:{}}};let t;try{t=JSON.parse(e)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u4FEE\u6539")}if(!t||typeof t!="object"||!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:t,existing:e}}async function Jc(s,e,t){await Fc(Gc(s),{recursive:!0});let i=t===void 0?384:(await zc(s)).mode&511,r=`${s}.pi-web-${Vc(6).toString("hex")}.tmp`;try{await qc(r,`${JSON.stringify(e,null,2)}
28
- `,{mode:i,flag:"wx"}),await Uc(r,s)}finally{await Lc(r,{force:!0})}}async function ln(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await cn(s),r=i.providers[e],n=new Set(r?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:r?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!r?.modelOverrides?.[o.id]}))}}async function dn(s,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r,existing:n}=await cn(s),o={...r.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!nn(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!an(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let l={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},p=t.originalId,u=p===void 0?-1:c.findIndex(y=>y.id===p);if(p===void 0&&(c.some(y=>y.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(c.some(m=>m.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let y={...c[u],...l};for(let m of["name","contextWindow","maxTokens","input"])l[m]===void 0&&delete y[m];c[u]=y}else if(p!==void 0&&i.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:y,...m}=l;a[p]={...a[p],...m};for(let f of["name","contextWindow","maxTokens","input"])l[f]===void 0&&delete a[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(l)}}else{let l=c.findIndex(p=>p.id===t.id);if(l>=0)c.splice(l,1);else if(Object.hasOwn(a,t.id))delete a[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(a).length?o.modelOverrides=a:delete o.modelOverrides,Object.keys(o).length?r.providers[e]=o:delete r.providers[e],await Jc(s,r,n)}function pn(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as un,createHash as Kc}from"node:crypto";import{fileURLToPath as Xc}from"node:url";var Tt="pi-webapp@0.1.50-alpha.4+6f276aca4a67bf831236",Se="6f276aca4a67bf831236";var Yc="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ni(s=process.env,e=console.warn){let t=i=>{let r={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Tt,buildId:Se},n=s[`PI_WEB_SENTRY_${i}_DSN`]??s.PI_WEB_SENTRY_DSN??Yc;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return r;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...r,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),r}};return{browser:t("BROWSER"),node:t("NODE")}}var xe=class{config;ready;reporter;client;salt=un(16);breadcrumbs=new At;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=ni(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Xc(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),r=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:r)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Se,integrations:[],transport:e.transport??(i=>As(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:_s,sendClientReports:!1,dataCollection:{...Ss,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Yt(this.client,"node",Se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=un(16).toString("hex");return this.early.push({error:lt(e),context:Ie(t),eventId:i}),i}catch{return}}setState(e){this.state=Ie({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return Kc("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as ul}from"@earendil-works/pi-coding-agent";function We(s,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(s.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!s.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Qc}from"node:crypto";function Rt(s){let e=[],t=s;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let r;try{r=JSON.parse(i[2])}catch{break}e.unshift({name:r,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(r)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Ct=s=>Buffer.byteLength(s.text)+s.images.reduce((e,t)=>e+t.data.length,0),ae=class extends Error{status=409},$e=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...Rt(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((r,n)=>r+Ct(n),Ct({text:e,images:t}))>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Qc(),revision:1,text:e,images:t.map(r=>({...r})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new ae("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(r=>r.id===e);if(!i||i.revision!==t)throw new ae("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new ae("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,r){let n=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(i.kind==="edit"){let o=Rt(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[i.text.trim(),c].filter(Boolean).join(`
28
+ `,{mode:i,flag:"wx"}),await Uc(r,s)}finally{await Lc(r,{force:!0})}}async function ln(s,e,t){if(!t.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:i}=await cn(s),r=i.providers[e],n=new Set(r?.models?.map(o=>o.id)??[]);return{providerId:e,baseUrl:r?.baseUrl,models:t.getModels(e).map(o=>({id:o.id,name:o.name,contextWindow:o.contextWindow,maxTokens:o.maxTokens,input:[...o.input],source:n.has(o.id)?"custom":"builtin",overridden:!!r?.modelOverrides?.[o.id]}))}}async function dn(s,e,t,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r,existing:n}=await cn(s),o={...r.providers[e]??{}},c=[...o.models??[]],a={...o.modelOverrides??{}};if(t.action==="base_url"){if(t.baseUrl!==null&&!nn(t.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");t.baseUrl===null?delete o.baseUrl:o.baseUrl=t.baseUrl}else if(t.action==="save"){if(!an(t.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let l={id:t.model.id.trim(),...t.model.name===void 0?{}:{name:t.model.name},...t.model.contextWindow===void 0?{}:{contextWindow:t.model.contextWindow},...t.model.maxTokens===void 0?{}:{maxTokens:t.model.maxTokens},...t.model.input===void 0?{}:{input:t.model.input}},p=t.originalId,u=p===void 0?-1:c.findIndex(y=>y.id===p);if(p===void 0&&(c.some(y=>y.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(u>=0){if(l.id!==p&&(c.some(m=>m.id===l.id)||i.getModel(e,l.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let y={...c[u],...l};for(let m of["name","contextWindow","maxTokens","input"])l[m]===void 0&&delete y[m];c[u]=y}else if(p!==void 0&&i.getModel(e,p)){if(l.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:y,...m}=l;a[p]={...a[p],...m};for(let f of["name","contextWindow","maxTokens","input"])l[f]===void 0&&delete a[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");c.push(l)}}else{let l=c.findIndex(p=>p.id===t.id);if(l>=0)c.splice(l,1);else if(Object.hasOwn(a,t.id))delete a[t.id];else throw new Error("\u53EA\u80FD\u79FB\u9664\u81EA\u5B9A\u4E49\u6A21\u578B\u6216\u6062\u590D\u5DF2\u4FEE\u6539\u7684\u5185\u7F6E\u6A21\u578B")}c.length?o.models=c:delete o.models,Object.keys(a).length?o.modelOverrides=a:delete o.modelOverrides,Object.keys(o).length?r.providers[e]=o:delete r.providers[e],await Jc(s,r,n)}function pn(s){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(s.trim())}import{randomBytes as un,createHash as Kc}from"node:crypto";import{fileURLToPath as Xc}from"node:url";var Tt="pi-webapp@0.1.50+69a663067b0de8af7f9c",Se="69a663067b0de8af7f9c";var Yc="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function ni(s=process.env,e=console.warn){let t=i=>{let r={enabled:!1,environment:s.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Tt,buildId:Se},n=s[`PI_WEB_SENTRY_${i}_DSN`]??s.PI_WEB_SENTRY_DSN??Yc;if(s.PI_WEB_SENTRY_ENABLED!=="true"||!n)return r;try{let o=new URL(n);if(o.protocol!=="https:"||!/^[\w-]+$/.test(o.username)||o.password||o.search||o.hash||!/\/(?:[\w-]+\/)*\d+$/.test(o.pathname))throw new Error;return{...r,enabled:!0,dsn:n}}catch{return e(`pi-webapp: invalid ${i.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),r}};return{browser:t("BROWSER"),node:t("NODE")}}var xe=class{config;ready;reporter;client;salt=un(16);breadcrumbs=new At;seen=new WeakSet;early=[];state={nodeVersion:process.version,platform:process.platform};fatal;closed=!1;failed=!1;get enabled(){return this.config.node.enabled&&!this.closed&&!this.failed}constructor(e={}){if(this.config=ni(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let t=Xc(import.meta.url).replace(/\\/g,"/"),i=t.lastIndexOf("/src/"),r=i>=0?t.slice(0,i+5):t.slice(0,t.lastIndexOf("/")+1);this.fatal=n=>{n.stack?.replace(/\\/g,"/").includes(t.endsWith("extension.js")?t:r)&&this.capture(n,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=import("@sentry/node").then(t=>{if(!this.closed){this.client=new t.NodeClient({...this.config.node,dist:Se,integrations:[],transport:e.transport??(i=>As(t.createTransport,i)),stackParser:t.defaultStackParser,beforeSend:_s,sendClientReports:!1,dataCollection:{...Ss,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Yt(this.client,"node",Se,t,this.breadcrumbs),this.reporter.setState(this.state);for(let i of this.early)this.reporter.capture(i.error,i.context,i.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,t={}){try{if(!this.enabled||Ge(e))return;if(typeof e=="object"&&e!==null){if(this.seen.has(e))return;this.seen.add(e)}if(this.reporter)return this.reporter.capture(e,t);if(this.early.length>=20)return;let i=un(16).toString("hex");return this.early.push({error:lt(e),context:Ie(t),eventId:i}),i}catch{return}}setState(e){this.state=Ie({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,t={}){this.enabled&&this.breadcrumbs.add(e,t)}session(e){return Kc("sha256").update(this.salt).update(e).digest("hex").slice(0,16)}async flush(e=3e3){await this.ready;try{return this.enabled&&!!await this.client?.flush(e)}catch{return!1}}async close(){let e=performance.now(),t;try{await Promise.race([this.ready,new Promise(i=>{t=setTimeout(i,500)})])}finally{clearTimeout(t),this.closed=!0,this.fatal&&process.off("uncaughtExceptionMonitor",this.fatal)}try{await this.client?.close(Math.max(1,500-(performance.now()-e)))}catch{}}};import{VERSION as ul}from"@earendil-works/pi-coding-agent";function We(s,e,t){if(t!==void 0&&t!=="steer"&&t!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(s.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!s.idle&&!t)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(t&&e.trimStart().startsWith("/"))throw new Error("\u8FFD\u52A0\u63D0\u793A\u8BCD\u4E0D\u652F\u6301\u659C\u6760\u6307\u4EE4\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u540E\u6267\u884C")}import{randomUUID as Qc}from"node:crypto";function Rt(s){let e=[],t=s;for(;;){let i=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(t);if(!i||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(i[3]))break;let r;try{r=JSON.parse(i[2])}catch{break}e.unshift({name:r,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(r)}),t=t.slice(0,i.index)}return{text:t,attachments:e}}var Ct=s=>Buffer.byteLength(s.text)+s.images.reduce((e,t)=>e+t.data.length,0),ae=class extends Error{status=409},$e=class{entries=[];pumping=!1;changed;constructor(e=()=>{}){this.changed=e}get length(){return this.entries.length}get sending(){return this.entries.some(e=>e.status==="sending")}view(){return this.entries.map(e=>({id:e.id,revision:e.revision,...Rt(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,t=[],i){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((r,n)=>r+Ct(n),Ct({text:e,images:t}))>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:Qc(),revision:1,text:e,images:t.map(r=>({...r})),correlation:i,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new ae("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,t){let i=this.entries.find(r=>r.id===e);if(!i||i.revision!==t)throw new ae("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(i.status!=="queued")throw new ae("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return i}async update(e,t,i,r){let n=this.find(e,t);if(i.kind==="remove"){this.entries=this.entries.filter(o=>o!==n),this.changed();return}if(i.kind==="edit"){let o=Rt(n.text),c=n.text.slice(o.text.length).replace(/^\n\n/u,""),a=[i.text.trim(),c].filter(Boolean).join(`
29
29
 
30
30
  `);if(this.validateText(a),this.entries.reduce((l,p)=>l+Ct(p),0)-Ct(n)+Ct({text:a,images:n.images})>64*1024*1024)throw new ae("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");n.text=a,n.revision++,delete n.error,this.changed();return}await this.deliver(n,r)}async deliver(e,t){e.status="sending",e.revision++,delete e.error,this.changed();try{await t(e.text,e.images,e.correlation),this.entries=this.entries.filter(i=>i!==e)}catch(i){throw e.status="queued",e.revision++,e.error=i instanceof Error?i.message:"\u53D1\u9001\u5931\u8D25",i}finally{this.changed()}}schedule(e,t){let i=this.entries[0];this.pumping||!i||i.status!=="queued"||i.error||!e()||(this.pumping=!0,i.status="sending",i.revision++,this.changed(),setImmediate(()=>{(async()=>{try{if(!e()){i.status="queued",i.revision++,this.changed();return}await this.deliver(i,t)}catch{}finally{this.pumping=!1,e()&&this.schedule(e,t)}})()}))}};var h=class extends Error{code;status;reason;constructor(e,t,i={}){super(t),this.name="HostedPluginError",this.code=e,this.status=i.status,this.reason=i.reason}};function G(s){let e=s&&typeof s=="object"?s:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:s instanceof Error?s.message:"Plugin operation failed",...Number.isInteger(e.status)&&Number(e.status)>=400&&Number(e.status)<=599?{status:Number(e.status)}:{},...typeof e.reason=="string"&&/^[\w.-]{1,80}$/.test(e.reason)?{reason:e.reason}:{}}}var Ve=s=>s.code==="ENOENT";var hn=["/api/hosted-plugins/manage","/api/hosted-plugins/action","/api/hosted-plugins/views","/api/hosted-plugins/approvals","/api/hosted-plugins/secrets"];async function tr(s,e,t,i){if(!s)throw new h("hosted_unavailable","Hosted plugin integration is not available in this runtime",{status:503});if(e==="/api/hosted-plugins")return s.inventory();if(!t||typeof t!="object"||Array.isArray(t))throw new h("invalid_input","Expected plugin request object",{status:400});let r=t;if(e==="/api/hosted-plugins/views"){if(i?.draining&&!["poll","pollMany","change","ack","close","reconcile","cancel-initialization"].includes(String(r.operation)))throw new h("host_restarting","Only existing view status/flush acknowledgements are admitted during restart",{status:409});if(r.operation!=="pollMany")return s.views(r);if(!Array.isArray(r.views)||!r.views.length||r.views.length>64||r.views.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.operation!=="poll"))throw new h("invalid_input","Expected 1\u201364 view polls",{status:400});return{replies:await Promise.all(r.views.map(async n=>{try{return{reply:await s.views({...n,operation:"poll",immediate:!0})}}catch(o){return{failure:oi(o)}}}))}}if(e==="/api/hosted-plugins/approvals"){if(i?.draining)throw new h("host_restarting","Host is updating; approvals are fenced",{status:409});if(typeof r.id!="string"||!/^[a-f0-9-]{36}$/.test(r.id)||r.decision!=="allow"&&r.decision!=="deny")throw new h("invalid_input","Invalid approval decision",{status:400});if(!s.decide)throw new h("hosted_unavailable","Approvals are not available in this runtime",{status:503});return s.decide(r.id,r.decision==="allow")}if(e==="/api/hosted-plugins/secrets"){if(i?.draining)throw new h("host_restarting","Host is updating; secret changes are fenced",{status:409});if(r.auth!==void 0){if(!s.secretAuth)throw new h("hosted_unavailable","Browser sign-in is not available in this runtime",{status:503});if(r.auth==="start"&&typeof r.pluginId=="string"&&r.pluginId.length<=214&&typeof r.name=="string"&&/^[a-z][a-z0-9-]{0,63}$/.test(r.name))return s.secretAuth({phase:"start",pluginId:r.pluginId,name:r.name});if((r.auth==="poll"||r.auth==="cancel")&&typeof r.deviceId=="string"&&/^[a-f0-9-]{36}$/.test(r.deviceId))return s.secretAuth({phase:r.auth,deviceId:r.deviceId});throw new h("invalid_input","Invalid sign-in request",{status:400})}if(typeof r.pluginId!="string"||r.pluginId.length>214||typeof r.name!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(r.name)||!(r.value===null||typeof r.value=="string"&&r.value.length>=1&&r.value.length<=4096&&!/[\u0000-\u001f\u007f]/.test(r.value)))throw new h("invalid_input","Invalid secret request",{status:400});if(!s.secret)throw new h("hosted_unavailable","Secrets are not available in this runtime",{status:503});return s.secret(r.pluginId,r.name,r.value)}if(typeof r.pluginId!="string"||r.pluginId.length>214)throw new h("invalid_input","Invalid plugin identity",{status:400});if(e==="/api/hosted-plugins/manage"){if(i?.draining)throw new h("host_restarting","Host is updating; plugin management is fenced",{status:409});if(typeof r.operation!="string"||!["install","enable","disable","update","uninstall","check","retry","policy","cancel-download"].includes(r.operation)||r.version!==void 0&&(typeof r.version!="string"||!/^\d+\.\d+\.\d+$/.test(r.version)))throw new h("invalid_input","Invalid plugin management request",{status:400});if(r.downloadId!==void 0&&(typeof r.downloadId!="string"||!/^[a-f0-9-]{36}$/.test(r.downloadId))||r.operation==="cancel-download"&&!r.downloadId)throw new h("invalid_input","Exact download identity required",{status:400});if(r.reopenEditors!==void 0&&typeof r.reopenEditors!="boolean")throw new h("invalid_input","Invalid editor reopen consent",{status:400});if(r.updatePolicy!==void 0&&!["notify","automatic","pinned"].includes(r.updatePolicy)||r.operation==="policy"&&(typeof r.updatePolicy!="string"||r.updatePolicy==="pinned"&&!r.version))throw new h("invalid_input","Invalid update policy or missing exact pin",{status:400});return s.manage({pluginId:r.pluginId,operation:r.operation,...typeof r.downloadId=="string"?{downloadId:r.downloadId}:{},...typeof r.updatePolicy=="string"?{updatePolicy:r.updatePolicy}:{},...typeof r.version=="string"?{version:r.version}:{},...typeof r.reopenEditors=="boolean"?{reopenEditors:r.reopenEditors}:{}})}if(e==="/api/hosted-plugins/action"){if(typeof r.sessionId!="string"||!r.sessionId||r.sessionId.length>200||!Number.isSafeInteger(r.generation)||Number(r.generation)<1||typeof r.action!="string"||!/^[\w.-]{1,80}$/.test(r.action))throw new h("invalid_input","Invalid plugin action request",{status:400});if(r.viewToken!==void 0&&(typeof r.viewToken!="string"||r.viewToken.length>200)||r.mountId!==void 0&&(typeof r.mountId!="string"||r.mountId.length>200))throw new h("invalid_input","Invalid view flush capability",{status:400});return s.action({sessionId:r.sessionId,pluginId:r.pluginId,generation:Number(r.generation),action:r.action,input:r.input??{},...typeof r.viewToken=="string"?{viewToken:r.viewToken}:{},...typeof r.mountId=="string"?{mountId:r.mountId}:{}},i?.draining?{checkpointOnly:!0}:void 0)}throw new h("invalid_route","Unknown hosted plugin route",{status:404})}function oi(s){let e=G(s);return{status:e.status??(["invalid_input","unknown_plugin","invalid_operation","invalid_version"].includes(e.code)?400:["not_installed"].includes(e.code)?404:["stale_generation","approval_required","plugin_unavailable","drain_pending","editor_busy","version_pinned","runtime_owned","storage_busy","revision_conflict","file_conflict","legacy_busy"].includes(e.code)?409:500),body:{error:e.message,errorCode:e.code,...e.reason?{reason:e.reason}:{}}}}import{readFile as fn}from"node:fs/promises";import{join as gn}from"node:path";async function mn(s){try{let e=JSON.parse(await fn(gn(s,".vite/manifest.json"),"utf8"));if(!e||typeof e!="object")return{};let t=new Set,i=await fn(gn(s,".vite/static-assets.json"),"utf8").then(JSON.parse).catch(()=>[]);for(let n of[...Object.values(e),{assets:Array.isArray(i)?i:[]}])if(!(!n||typeof n!="object"))for(let o of[n.file,...Array.isArray(n.css)?n.css:[],...Array.isArray(n.assets)?n.assets:[]])typeof o=="string"&&/^assets\/(?:[\w-]+\/)*[\w.-]+\.(?:js|css|woff2?|ttf|png|jpe?g|svg|webp)$/.test(o)&&t.add(o);let r={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};return Object.fromEntries([...t].map(n=>[`/${n}`,{path:n,type:r[n.split(".").pop()]}]))}catch{return{}}}import{access as el,readFile as ir,realpath as li,rename as tl,rm as il,writeFile as rl}from"node:fs/promises";import{randomUUID as sl}from"node:crypto";import{dirname as ci,join as _e,resolve as nl,sep as yn}from"node:path";import{createRequire as ol}from"node:module";var Zc=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;function Fe(s){let e=typeof s=="string"&&Zc.exec(s);if(!e||e[0]!==s)throw new Error("\u7248\u672C\u53F7\u65E0\u6548");let t=e.slice(1,4).map(Number),i=e[4]?.split(".")??[];if(!t.every(Number.isSafeInteger)||i.some(r=>/^\d+$/.test(r)&&r.length>1&&r[0]==="0"))throw new Error("\u7248\u672C\u53F7\u65E0\u6548");return{core:t,prerelease:i}}function ue(s,e){let t=Fe(s),i=Fe(e);for(let r=0;r<3;r++)if(t.core[r]!==i.core[r])return t.core[r]>i.core[r]?1:-1;if(!t.prerelease.length||!i.prerelease.length)return+!t.prerelease.length-+!i.prerelease.length;for(let r=0;r<Math.max(t.prerelease.length,i.prerelease.length);r++){let n=t.prerelease[r],o=i.prerelease[r];if(n===void 0||o===void 0)return n===void 0?-1:1;if(n===o)continue;let c=/^\d+$/.test(n),a=/^\d+$/.test(o);return c!==a?c?-1:1:c&&n.length!==o.length?n.length>o.length?1:-1:n>o?1:-1}return 0}function wn(s){try{return Fe(s).prerelease.length===0}catch{return!1}}function ai(s){try{return Fe(s),/^\d+\.\d+\.\d+-alpha\.(0|[1-9]\d*)$/.test(s)}catch{return!1}}var Be=1,vn=s=>_e(s,"pi-web","desktop-update.json");async function dt(s,e){let t=ol(_e(s,"package.json"));for(let i of t.resolve.paths(e)??[]){let r=_e(i,e);try{if(JSON.parse(await ir(_e(r,"package.json"),"utf8")).name===e)return await li(r)}catch{}}throw new Error(`\u7F3A\u5C11\u8FD0\u884C\u4F9D\u8D56\uFF1A${e}`)}async function di(s,e){if(ue(e?.version,e?.version),e.desktopProtocolVersion!==Be||typeof e.launcher!="string")throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u534F\u8BAE\u4E0D\u517C\u5BB9");let t=await li(nl(ci(e.launcher),"..")),i=await li(_e(s,"pi-web","releases")),r=ci(ci(t));if(await li(e.launcher)!==_e(t,"bin","pi-webapp.mjs")||ci(r)!==i||!r.startsWith(i+yn)||!r.slice(i.length+1).startsWith(`${e.version}-`)||!/^[\w-]+$/.test(r.slice(i.length+1+e.version.length+1)))throw new Error("\u62D2\u7EDD\u7528\u6237\u66F4\u65B0\u76EE\u5F55\u4E4B\u5916\u7684\u684C\u9762\u4E1A\u52A1\u5305");let n=JSON.parse(await ir(_e(t,"package.json"),"utf8"));if(n.name!=="pi-webapp"||n.version!==e.version)throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7248\u672C\u4E0E\u8BB0\u5F55\u4E0D\u4E00\u81F4");if(n.piWebappDesktopProtocol!==Be)throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF0C\u5C1A\u672A\u5207\u6362\u8FD0\u884C\u7248\u672C");let o=await dt(t,"@earendil-works/pi-coding-agent");if(!o.startsWith(r+yn))throw new Error("\u684C\u9762\u4E1A\u52A1\u5305\u7F3A\u5C11\u72EC\u7ACB\u7684 Pi \u8FD0\u884C\u4F9D\u8D56");let c=_e(o,"dist","bundle","cli.js");return await Promise.all([e.launcher,c,_e(t,"dist","extension.js"),_e(t,"web","dist","index.html")].map(a=>el(a))),e.fallbackVersion!==void 0&&Fe(e.fallbackVersion),{version:e.version,launcher:e.launcher,piCli:c,desktopProtocolVersion:Be,...e.fallbackVersion?{fallbackVersion:e.fallbackVersion}:{}}}async function bn(s,e,t=e){try{let i=JSON.parse(await ir(vn(s),"utf8"));return ue(i.version,e)<0&&i.fallbackVersion!==t?null:await di(s,i)}catch{return null}}async function kn(s,e){let t=vn(s),i=`${t}.${sl()}.tmp`;try{await rl(i,JSON.stringify(e),{mode:384}),await tl(i,t)}finally{await il(i,{force:!0})}}var hl={"/":{path:"index.html",type:"text/html; charset=utf-8"},"/assets/app.js":{path:"assets/app.js",type:"text/javascript; charset=utf-8"},"/assets/style.css":{path:"assets/style.css",type:"text/css; charset=utf-8"}};function I(s,e,t){typeof t=="object"&&t!==null&&"error"in t&&(t={errorCode:e>=500?"server_error":"validation_error",...t,requestId:s.getHeader("X-Request-ID"),operationId:s.getHeader("X-Operation-ID")}),s.writeHead(e,{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}),s.end(JSON.stringify(t))}function fl(s,e){let t=s.headers.authorization;if(typeof t!="string"||!t.startsWith("Bearer "))return!1;let i=Buffer.from(t.slice(7),"utf8");return i.length===e.length&&al(i,e)}async function In(s,e=64*1024){let t=0,i=[];for await(let r of s){let n=Buffer.isBuffer(r)?r:Buffer.from(r);if(t+=n.length,t>e)throw new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927");i.push(n)}return JSON.parse(Buffer.concat(i).toString("utf8"))}async function gl(s){let e=0,t=[];for await(let i of s){let r=Buffer.isBuffer(i)?i:Buffer.from(i);if(e+=r.length,e>ri)throw new Error("\u6587\u4EF6\u8D85\u8FC7 20 MB");t.push(r)}return Buffer.concat(t)}async function ml(s,e=0){await new Promise((i,r)=>{s.once("error",r),s.listen(e,"127.0.0.1",()=>{s.off("error",r),i()})});let t=s.address();if(t===null||typeof t=="string")throw new Error("\u65E0\u6CD5\u786E\u5B9A\u76D1\u542C\u7AEF\u53E3");return t.port}async function Sn(s,e,t=new xe,i={}){t.setState({piVersion:ul});let r=process.env.PI_WEBAPP_RESTART_TOKEN,n=r&&/^[A-Za-z0-9_-]{32}$/.test(r)?r:Pn(24).toString("base64url"),o=Buffer.from(n),c=Xs(),a=new Set,l=new ei(i.pluginSettingsFile??sr(pl(),"pi-web","plugins.json"));try{await l.load()}catch(b){throw await t.close(),b}let p=new ti(Bs(),l),u=async()=>await s.plugins?.()??{plugins:[],errors:[]},y=()=>({type:"plugin_state",disabled:p.plugins.filter(b=>!l.enabled(b.metadata.id)).map(b=>b.metadata.id)}),m=()=>{for(let b of a)b.write(`${JSON.stringify(y())}
31
31
  `)},f=new Map,w=new si((b,v)=>t.capture(b,v)),k=b=>t.setState({nodeVersion:process.version,platform:process.platform,session:t.session(b.sessionId),idle:b.idle,model:b.model,thinkingLevel:b.thinkingLevel,messageCount:b.messages.length}),P="",E=!1,_=!1,H={...hl,...await mn(e)};for(let b of await ll(sr(e,"assets")).catch(()=>[])){let v=/^[\w.-]+\.(js|css|woff2?|ttf)$/.exec(b);if(!v)continue;let $={js:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf"};H[`/assets/${b}`]={path:`assets/${b}`,type:$[v[1]]}}let N=dl(async(b,v)=>{let $=Pn(18).toString("base64"),ye=pe=>typeof pe=="string"&&/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(pe),ve=ye(b.headers["x-request-id"])?b.headers["x-request-id"]:rr(),se={requestId:ve,operationId:ye(b.headers["x-operation-id"])?b.headers["x-operation-id"]:void 0};v.setHeader("X-Request-ID",ve),se.operationId&&v.setHeader("X-Operation-ID",se.operationId);let x="/",ca=performance.now(),de=(pe,g,S)=>{let C=!Ge(pe)&&Es(x)?Ne(pe,"Agent or provider operation failed"):pe,q=t.capture(C,{...se,route:x,method:b.method,status:g,stage:"http"});I(v,g,{error:S,errorId:q,errorReported:t.enabled,errorCode:Ge(pe)?"validation_error":"unexpected_error"})};v.once("finish",()=>{x.startsWith("/api/telemetry/")||t.breadcrumb("request",{...se,route:x,method:b.method,status:v.statusCode,durationMs:Math.round(performance.now()-ca)})});try{v.setHeader("X-Content-Type-Options","nosniff"),v.setHeader("Referrer-Policy","no-referrer"),v.setHeader("Content-Security-Policy",`default-src 'self'; script-src 'self'; style-src 'self' 'nonce-${$}'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'${t.config.browser.dsn?` ${new URL(t.config.browser.dsn).origin}`:""}; img-src 'self' data: blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`);try{x=new URL(b.url??"/",P).pathname}catch{I(v,400,{error:"\u8BF7\u6C42\u5730\u5740\u65E0\u6548"});return}let pe=H[x];if(b.method==="GET"&&pe){try{let g=await cl(sr(e,pe.path));v.writeHead(200,{"Content-Type":pe.type,"Cache-Control":"no-store"}),v.end(x==="/"?g.toString("utf8").replace("<head>",`<head><meta name="pi-style-nonce" content="${$}">`):g)}catch(g){de(g,500,"\u9875\u9762\u6587\u4EF6\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x.startsWith("/hosted-plugins/")){try{let g=await s.hosted?.asset(x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.setHeader("Content-Security-Policy","default-src 'none'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; font-src 'self' data:; connect-src 'self'; img-src 'self' data: blob:; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'self'"),v.writeHead(200,{"Content-Type":g.mime,"Cache-Control":"private, no-store"}),v.end(g.bytes)}catch{I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528"})}return}if(b.method==="GET"&&x.startsWith("/plugins/")){try{let g=await s.pluginAsset?.(b.url??x);if(!g){I(v,404,{error:"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u5B58\u5728"});return}v.writeHead(200,{"Content-Type":g.type,"Cache-Control":"no-store"}),v.end(g.bytes)}catch(g){de(g,404,"\u63D2\u4EF6\u8D44\u6E90\u4E0D\u53EF\u7528")}return}if(!x.startsWith("/api/")){I(v,404,{error:"\u672A\u627E\u5230"});return}if(!fl(b,o)){I(v,401,{error:"\u8BBF\u95EE\u4EE4\u724C\u65E0\u6548"});return}if(b.method==="GET"&&x==="/api/hosted-plugins"){try{I(v,200,await tr(s.hosted,x,void 0))}catch(g){let S=oi(g);I(v,S.status,S.body)}return}if(b.method==="POST"&&hn.includes(x)){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}if(!b.headers["content-type"]?.startsWith("application/json")){I(v,415,{error:"\u9700\u8981 JSON \u8BF7\u6C42"});return}let g;try{g=await In(b,2*1024*1024)}catch(S){I(v,S instanceof Error&&S.message==="\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"?413:400,{error:"\u63D2\u4EF6\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u6216\u8FC7\u5927"});return}try{I(v,200,await tr(s.hosted,x,g,{draining:E}))}catch(S){let A=oi(S);I(v,A.status,A.body)}return}if(b.method==="GET"&&x==="/api/telemetry/config"){I(v,200,t.config.browser);return}if(b.method==="GET"&&x==="/api/update/version"){try{I(v,200,{current:await s.selfUpdate?.runningVersion()??null,desktopProtocolVersion:Be,...s.selfUpdate?.launcherIdentity?{launcher:s.selfUpdate.launcherIdentity(),desktopHandoffProtocol:s.selfUpdate.launcherIdentity().handoffProtocol}:{}})}catch(g){de(g,503,g instanceof Error?g.message:"\u65E0\u6CD5\u8BFB\u53D6\u7248\u672C")}return}if(b.method==="GET"&&x==="/api/update"){try{I(v,200,await s.selfUpdate?.check()??{canRestart:!1,reason:"\u5F53\u524D\u6269\u5C55\u4E0D\u652F\u6301\u5728\u7EBF\u5347\u7EA7"})}catch(g){de(g,503,g instanceof Error?g.message:"\u68C0\u67E5\u66F4\u65B0\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/image"){let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId")??"",A=g.searchParams.get("messageId")??"",C=Number(g.searchParams.get("index"));if(!S||S!==s.snapshot().sessionId||!A||!Number.isInteger(C)||C<0||C>100){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u56FE\u7247\u5730\u5740\u65E0\u6548"});return}let q=s.image?.(S,A,C);if(!q||!["image/png","image/jpeg","image/webp","image/gif"].includes(q.mimeType)){I(v,404,{error:"\u56FE\u7247\u4E0D\u53EF\u7528"});return}v.writeHead(200,{"Content-Type":q.mimeType,"Cache-Control":"private, no-store"}),v.end(q.data);return}if(b.method==="POST"&&x==="/api/attachment"){if(b.headers.origin!==void 0&&b.headers.origin!==P){I(v,403,{error:"\u6765\u6E90\u4E0D\u5339\u914D"});return}let g=new URL(b.url??x,P),S=g.searchParams.get("sessionId"),A=g.searchParams.get("name");try{if(!S||!A||A.length>1024||S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362\u6216\u6587\u4EF6\u540D\u65E0\u6548"});return}if(Number(b.headers["content-length"]??0)>ri){I(v,413,{error:"\u6587\u4EF6\u8D85\u8FC7 20 MB"});return}let C=await en(S,A,b.headers["content-type"]??"application/octet-stream",await gl(b));if(S!==s.snapshot().sessionId){I(v,409,{error:"\u4F1A\u8BDD\u5DF2\u5207\u6362"});return}f.set(C.id,C),I(v,201,{id:C.id,name:C.name,bytes:C.bytes})}catch(C){de(C,400,C instanceof Error?C.message:"\u4E0A\u4F20\u5931\u8D25")}return}if(b.method==="GET"&&x==="/api/session"){try{let g=s.snapshot();k(g),I(v,200,g)}catch(g){de(g,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugin-management"){try{I(v,200,p.inventory(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/plugins"){try{I(v,200,p.catalog(await u()))}catch(g){de(g,503,"\u63D2\u4EF6\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/providers"){try{I(v,200,await s.providers?.()??[])}catch(g){de(g,503,"\u6A21\u578B\u63D0\u4F9B\u65B9\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/models"){let g=new URL(b.url??x,P).searchParams.get("providerId")??"";try{if(!g||!s.providerModels){I(v,400,{error:"\u63D0\u4F9B\u65B9\u65E0\u6548"});return}I(v,200,await s.providerModels(g))}catch(S){de(S,400,S instanceof Error?S.message:"\u6A21\u578B\u76EE\u5F55\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/provider/login/active"){I(v,200,{active:w.getActive()??null});return}if(b.method==="GET"&&x==="/api/provider/login"){let g=new URL(b.url??x,P).searchParams.get("id")??"",S=w.get(g);I(v,S?200:404,S??{error:"\u767B\u5F55\u6D41\u7A0B\u4E0D\u5B58\u5728"});return}if(b.method==="GET"&&(x==="/api/models"||x==="/api/config"||x==="/api/workspaces"||x==="/api/commands")){try{I(v,200,x==="/api/models"?await s.models():x==="/api/config"?await s.config():x==="/api/commands"?s.commands?.()??[]:await s.workspaces())}catch(g){de(g,503,"Pi \u914D\u7F6E\u4E0D\u53EF\u7528")}return}if(b.method==="GET"&&x==="/api/directory/capability"){I(v,200,{kind:c});return}if(b.method==="GET"&&x==="/api/events"){let g;try{g=s.snapshot(),k(g)}catch(S){de(S,503,"\u5F53\u524D\u4F1A\u8BDD\u4E0D\u53EF\u7528");return}v.writeHead(200,{"Content-Type":"application/x-ndjson; charset=utf-8","Cache-Control":"no-store",Connection:"keep-alive","X-Accel-Buffering":"no"}),a.add(v),v.write(`${JSON.stringify({type:"snapshot",session:g})}
@@ -46,4 +46,4 @@ ${s.stack.split(`
46
46
  `)}`:void 0,t<3&&s.cause instanceof Error&&(r.cause=Bn(s.cause,e,t+1)),lt(r)}import{randomUUID as zn}from"node:crypto";import{randomUUID as sd}from"node:crypto";import{EnvHttpProxyAgent as nd,getGlobalDispatcher as Um,setGlobalDispatcher as Lm}from"undici";var Un=s=>({httpProxy:s.http_proxy??s.HTTP_PROXY??s.all_proxy??s.ALL_PROXY??"",httpsProxy:s.https_proxy??s.HTTPS_PROXY??s.all_proxy??s.ALL_PROXY??"",noProxy:s.no_proxy??s.NO_PROXY??""});function od(s,e){let t=Un(s),i;try{i=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(i.protocol==="https:"&&t.httpsProxy||t.httpProxy))return!1;let r=t.noProxy.toLowerCase();if(r==="*")return!1;let n=Number(i.port)||(i.protocol==="https:"?443:80),o=i.hostname.toLowerCase();return!r.split(/[,\s]/).filter(Boolean).some(c=>{let a=c.match(/^(.+):(\d+)$/),l=(a?.[1]??c).replace(/^\*?\./,"");return(!a||Number(a[2])===n)&&(o===l||o.endsWith("."+l))})}function ad(s){let e=Un(s);for(let t of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(t).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new nd(e)}function hr({env:s=process.env,onFailure:e=()=>{},fetchRequest:t=globalThis.fetch,autoClose:i=!1}={}){let r,n=new Set,o=t===globalThis.fetch,c=(p,u)=>{try{e(p,u)}catch{}},a=p=>p?p.close().finally(()=>n.delete(p)):Promise.resolve();return{fetch:async(p,u)=>{let y={requestId:sd(),phase:"headers",proxied:o&&od(s,p)},m=i?void 0:r,f=!1,w=u?.signal??(p instanceof Request?p.signal:void 0),k=()=>P(),P=()=>{w?.removeEventListener("abort",k),!f&&i&&(f=!0,a(m).catch(()=>{}))},E;try{o?(m??=ad(s),n.add(m),i||(r=m),E=await t(p,{...u,dispatcher:m})):E=await t(p,u)}catch(T){throw c(T,y),P(),T}if(E.ok||c(void 0,{...y,status:E.status}),!E.body)return P(),E;let _=E.body.getReader();w?.addEventListener("abort",k,{once:!0}),w?.aborted&&P();let H=new ReadableStream({async pull(T){try{let Y=await _.read();Y.done?(T.close(),_.releaseLock(),P()):T.enqueue(Y.value)}catch(Y){c(Y,{...y,phase:"body"}),T.error(Y),_.releaseLock(),P()}},async cancel(T){try{await _.cancel(T)}finally{_.releaseLock(),P()}}}),N=new Response(H,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(N,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),N},close:async()=>{await Promise.all([...n].map(a))}}}var Ln=(s,e)=>hr({autoClose:!0}).fetch(s,e);var cd=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),ld=s=>typeof s=="string"&&/^(?:E[A-Z0-9_]{1,40}|UND_ERR_[A-Z0-9_]{1,50}|CERT_[A-Z0-9_]{1,40}|DEPTH_ZERO_SELF_SIGNED_CERT|UNABLE_TO_[A-Z0-9_]{1,40}|PROXY_[A-Z_]{1,40}|ABORT_ERR|agent_settlement_timeout|sdk_capability_missing|hosted_admission_blocked)$/.test(s)?s:void 0;function fr(s,e={}){let t=[],i=new Set,r=(a,l=0)=>{if(!a||l>4||i.has(a)||t.length>=8)return;i.add(a);let p=ld(a.code);if(t.push({name:cd.has(a.name)?a.name:"Error",...p?{code:p}:{}}),r(a.cause,l+1),a instanceof AggregateError)for(let u of a.errors.slice(0,4))r(u,l+1)};r(s);let n=t.flatMap(a=>a.code?[a.code]:[]),o=e.stage==="model_admission"||n.some(a=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(a))?"lifecycle":n.some(a=>/CERT|TLS|SSL/.test(a))?"tls":n.some(a=>/^PROXY_/.test(a))||e.proxied&&n.some(a=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(a))?"proxy":n.some(a=>/TIMEOUT|ETIMEDOUT/.test(a))||t.some(a=>/TimeoutError$/.test(a.name))?"timeout":t.some(a=>a.name==="AbortError"||a.code==="ABORT_ERR"||a.code==="UND_ERR_ABORTED")?"cancelled":n.some(a=>/ENOTFOUND|EAI_AGAIN/.test(a))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",c=a=>typeof a=="string"&&/^[\w-]{1,80}$/.test(a)?a:void 0;return{errorId:zn(),requestId:c(e.requestId)??zn(),...c(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:o,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:t}}function qn({env:s=process.env,onDiagnostic:e=()=>{},fetchRequest:t=globalThis.fetch}={}){return hr({env:s,fetchRequest:t,onFailure:(i,r)=>e(fr(i,{...r,stage:r.phase==="body"?"model_stream":"model_headers"}))})}function dd(s){let e={...process.env,...s};for(let t of["http_proxy","https_proxy","all_proxy","no_proxy"])s&&t.toUpperCase()in s&&!(t in s)&&delete e[t];return e}var pd=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function Gn(s,e,t=()=>{}){let i=s.agent.streamFunction;s.agent.streamFunction=async(r,n,o)=>{if(!pd.has(r.api))return i(r,n,o);let c=t(),a=qn({env:dd(o?.env),...o?.fetch?{fetchRequest:o.fetch}:{},onDiagnostic:l=>{let p={...l,...c?{operationId:c}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let l=await i(r,n,{...o,fetch:a.fetch});return l.result().finally(()=>a.close()).catch(()=>{}),l}catch(l){throw await a.close(),l}}}function gt(s,e,t){try{s()}catch(i){let r=fr(i,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...r})),t?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:r.errorId,requestId:r.requestId,stage:r.stage,code:"hosted_admission_blocked",networkKind:r.kind,networkStage:r.stage,causeCodes:r.causes.flatMap(n=>n.code?[n.code]:[]).join(",")})}catch{}throw i}}var wd=["read","grep","find","ls"],Jn=200,wi=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Qe;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,t,i=()=>!1,r=()=>{},n={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},o=()=>{},c=[],a){this.hosted=a,this.publish=e,this.fallbackModel=t,this.isProjectTrusted=i,this.reportError=r,this.onSessionsChanged=o,this.customTools=c,this.offHosted=a?.adapter.onThaw(()=>{for(let l of this.runtimes.values())this.scheduleQueued(l)}),this.telemetry={enabled:()=>{try{return n.enabled()}catch{return!1}},breadcrumb:(l,p)=>{try{n.enabled()&&n.breadcrumb(l,p)}catch{}},anonymize:l=>{try{return n.enabled()?n.anonymize(l):"unavailable"}catch{return"unavailable"}}}}get session(){return this.active?.session??null}get path(){return this.active?.cwd??null}get catalog(){return this.active?.catalog??null}open(e,t){return this.queue.run(async()=>{this.ensureAvailable();let i=await Ae(e),r=t==="continue"?this.selectedByWorkspace.get(i):typeof t=="object"&&"sessionId"in t?this.runtimes.get(t.sessionId):void 0;if(r){if(r.cwd!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(r);return}if(typeof t=="object"&&"sessionId"in t)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let n;if(t==="new")n=Mt.create(i);else if(t==="continue"){let c=(await ht(i))[0];n=c?Mt.open(c.path):Mt.create(i)}else n="sessionManager"in t?t.sessionManager:Mt.open(t.sessionFile);if(await md(n.getCwd())!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let o=this.runtimes.get(n.getSessionId());if(o){if(o.cwd!==i)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(o);return}await this.replace(i,n,t==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let t=this.selectedByWorkspace.get(await Ae(e));return!t||!this.blank(t)?!1:(this.activate(t),!0)})}reload(){return this.queue.run(async()=>{this.ensureAvailable();let e=this.active;if(!e)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");if(!e.session.isIdle||e.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await this.replace(e.cwd,e.session.sessionManager,"reload")})}ensureAvailable(){if(this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED")}hostedScope(e){let t=this.runtimes.get(e);return!this.disposed&&t&&!t.closing?{cwd:t.cwd,sessionId:e}:null}hasSession(e,t){return this.runtimes.get(t)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:t,cwd:i,prompts:r}=e,n=t.sessionManager.getBranch(),o=n.flatMap(c=>{let a=Nt(c);return a?[a]:[]});return{sessionId:t.sessionManager.getSessionId(),cwd:i,path:t.sessionManager.getSessionFile()??null,idle:t.isIdle&&!r.sending,name:pi(t.sessionManager.getSessionName(),o),modified:n.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(t=>Nt(t)?.role==="user")}rename(e,t){let i=this.runtimes.get(e);if(!i||i.closing)return!1;if(i.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return i.session.setSessionName(t),!0}discard(e){return this.queue.run(async()=>{let t=this.runtimes.get(e);if(!t||t.closing)return null;if(t.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!t.session.isIdle||t.prompts.sending||t.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=this.active===t,r=t.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(t.cwd)===t&&this.selectedByWorkspace.delete(t.cwd),i&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged(),{path:r,cwd:t.cwd,wasActive:i}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,t){!this.disposed&&this.active===e&&!e.closing&&this.publish(t)}diagnostic(e,t,i,r){let n=`plugin=${t} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${i}: ${r}`;console.error(n),this.publishFor(e,{type:"error",message:n})}async replace(e,t,i,r){let n=this.runtimes.get(t.getSessionId()),o=await Ye.discover(e,this.isProjectTrusted(e)),c=hd(),a=await $n(e,o.extensionRoots),l=new fd({cwd:e,agentDir:gd(),noExtensions:!0,additionalExtensionPaths:a.paths,eventBus:c,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,t.getSessionId()))]:[]}),p=null;try{await l.reload();let u=l.getExtensions().errors;if(u.length)throw new Error(u.map(b=>`${b.path}: ${b.error}`).join("; "));let y=t.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:m}=await ud({cwd:e,sessionManager:t,model:y,resourceLoader:l,customTools:this.customTools}),f=new ft({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(b,v)=>this.telemetry.breadcrumb(b,v),anonymize:b=>this.telemetry.anonymize(b)}),w={session:m,cwd:e,catalog:o,bus:c,generation:++this.generation,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:a.release,tools:f,streaming:null,prompts:null,detached:r?{owner:r,events:[],seq:0,lastText:"",restoreTools:null}:void 0};w.prompts=n?.prompts??new $e(()=>{let b=this.runtimes.get(t.getSessionId())??w;this.publishFor(b,{type:"snapshot",session:this.snapshotOf(b)}),!this.disposed&&!b.closing&&this.onSessionsChanged()}),p=w,Gn(m,b=>{w.networkDiagnostic=b},()=>w.operation?.operationId);let k=b=>this.publishFor(w,b),P=w.detached,E=(b,v)=>{P&&(P.events.push({seq:++P.seq,type:b,...v===void 0?{}:{text:v}}),P.events.length>Jn&&P.events.splice(0,P.events.length-Jn))};w.interactions=new ut(c,b=>!w.closing&&b.sessionId===m.sessionManager.getSessionId()&&o.has(b.pluginId),()=>k({type:"snapshot",session:this.snapshotOf(w)}));let _=0,H=c.on(hi,()=>k({type:"snapshot",session:this.snapshotOf(w)})),N=m.subscribe(b=>{if(P&&!w.closing&&(b.type==="message_end"&&b.message.role==="assistant"&&(b.message.stopReason==="error"?E("error",b.message.errorMessage??"Agent response failed"):P.lastText=b.message.content.flatMap(v=>v.type==="text"?[v.text]:[]).join(`
47
47
  `)),b.type==="agent_settled"&&E("turn_end",P.lastText)),!this.disposed&&!w.closing){let v={...w.operation,session:this.telemetry.anonymize(m.sessionManager.getSessionId()),piVersion:mi,model:m.model?`${m.model.provider}/${m.model.id}`:null,thinkingLevel:m.thinkingLevel};if(b.type==="agent_start"&&this.telemetry.breadcrumb("agent_start",v),b.type==="tool_execution_start"&&f.start(b,v),b.type==="tool_execution_end"&&f.end(b,v),b.type==="message_end"&&b.message.role==="assistant"&&b.message.stopReason==="error"){w.agentErrorReported=!0;let $=w.networkDiagnostic,ye=this.reportError(new Error("Agent response failed"),{...w.operation,stage:"agent",code:"agent_failed",piVersion:mi,...$?{networkKind:$.kind,networkStage:$.stage,causeCodes:$.causes.flatMap(ve=>ve.code?[ve.code]:[]).join(","),requestId:$.requestId}:{}})??$?.errorId;k({type:"error",message:b.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:ye,...w.operation})}b.type==="message_end"&&b.message.role==="toolResult"&&f.message(b.message,v),b.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",v),f.clear(),w.operation=void 0)}b.type==="message_update"&&b.message.role==="assistant"&&(w.streaming={id:"stream",role:"assistant",timestamp:new Date(b.message.timestamp).toISOString(),blocks:Je(b.message.content)},Date.now()-_>=60&&(_=Date.now(),k({type:"stream",message:w.streaming}))),b.type==="agent_settled"&&this.scheduleQueued(w),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(b.type)&&((b.type==="message_end"&&b.message.role==="assistant"||b.type==="agent_settled")&&(w.streaming=null,k({type:"stream",message:null})),k({type:"snapshot",session:this.snapshotOf(w)}),!this.disposed&&!w.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(b.type)&&this.onSessionsChanged())});w.detach=()=>{H(),N()},w.releaseHosted=this.hosted?.adapter.attach(m);let T=[],Y=!0;if(await m.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:b=>{Y&&T.push(b.error),this.diagnostic(w,o.plugins.find(v=>b.extensionPath.startsWith(v.root+"/"))?.id??b.extensionPath,b.event??"runtime",b.error)}}),Y=!1,T.length)throw new Error(T.join("; "));if(this.ensureAvailable(),n&&(!n.session.isIdle||n.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(n&&await this.close(n,i),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");w.detached&&(w.detached.restoreTools=m.getActiveToolNames(),m.setActiveToolsByName(wd)),this.runtimes.set(m.sessionManager.getSessionId(),w),p=null,w.detached?this.onSessionsChanged():this.activate(w)}catch(u){throw this.hosted?.adapter.releasePending(t.getSessionId()),p?await this.close(p,"quit"):(c.clear(),await a.release()),u}}async close(e,t){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await Wn(e.session,t,i=>this.diagnostic(e,"host","shutdown",i),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:t,cwd:i,catalog:r}=e,n=t.sessionManager.getBranch().flatMap(o=>{let c=Nt(o);return c?[c]:[]});return{schemaVersion:1,sessionId:t.sessionManager.getSessionId(),cwd:i,name:pi(t.sessionManager.getSessionName(),n),model:t.model?`${t.model.provider}/${t.model.id}`:null,thinkingLevel:t.thinkingLevel,thinkingLevels:t.getAvailableThinkingLevels(),idle:t.isIdle&&!e.prompts.sending,paused:pt(t.sessionManager.getBranch()),promptQueue:{steering:[...t.getSteeringMessages()],followUp:[...t.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:t.getContextUsage()??null,messages:n,streaming:e.streaming,interactions:e.interactions.pending(t.sessionManager.getSessionId()),pluginEntries:or(t.sessionManager.getBranch(),r.ids())}}snapshot(){if(!this.active)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A\u4F1A\u8BDD");return this.snapshotOf(this.active)}async invokePluginAction(e){let t=this.active;if(this.disposed||!t||t.closing||e.sessionId!==t.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!t.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let i=t.session.extensionRunner,r=await fi(t.bus,e,15e3,t.waitController.signal);if(this.active!==t||t.closing||i!==t.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),r}resolveInteraction(e,t,i,r){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,t,i,r)}async send(e,t=[],i,r){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let n=this.active;if(We(this.snapshot(),e,r),r==="followUp"&&(!n.session.isIdle||n.prompts.length>0)){n.prompts.enqueue(e,t,i),this.scheduleQueued(n);return}if(n.session.isIdle&&n.prompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(n,e,t,i,r)}async prompt(e,t,i,r,n){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");gt(()=>this.hosted?.adapter.assertAdmission(),r,this.reportError),We({...this.snapshotOf(e),idle:e.session.isIdle},t,n);let o=e.session,c=o.isIdle;c&&(e.operation=r,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...r,piVersion:mi});let a=!1,l,p,u=new Promise((y,m)=>{l=y,p=m});o.prompt(t,{images:i,streamingBehavior:n,preflightResult:y=>{y&&(a=!0,l())}}).then(()=>{a||l()}).catch(y=>{if(!a)p(y);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let m=this.reportError(Ne(y,"Agent response failed"),{...r,stage:"agent",code:"agent_failed",piVersion:mi});this.publishFor(e,{type:"error",message:y instanceof Error?y.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:m,...r})}});try{await u}catch(y){throw c&&(e.operation=void 0),y}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!pt(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(t,i,r)=>this.prompt(e,t,i,r))}async updateQueuedPrompt(e,t,i){let r=this.active;if(this.disposed||!r||r.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(i.kind==="steer"&&r.session.isIdle)throw new ae("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await r.prompts.update(e,t,i,(n,o,c)=>this.prompt(r,n,o,c,"steer"))}async stop(){let e=this.active;!e||e.session.isIdle&&!e.prompts.sending||(e.tools.cancel(),this.telemetry.breadcrumb("cancel",{...e.operation}),e.session.sessionManager.appendCustomEntry(Dt),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let t=this.active;if(this.disposed||!t||t.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");gt(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let i=t.session;if(!i.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!pt(i.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!i.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(i.modelRuntime.hasConfiguredAuth(i.model.provider)||await i.modelRuntime.checkAuth(i.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==t||t.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!pt(i.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let n=gi(this.snapshotOf(t).messages);t.operation=e,t.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),i.sendCustomMessage(n,{triggerTurn:!0}).catch(o=>{if(!this.disposed&&!t.closing&&!t.agentErrorReported){let c=this.reportError(Ne(o,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(t,{type:"error",message:o instanceof Error?o.message:"\u7EE7\u7EED\u5931\u8D25",errorId:c,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(t=>({provider:t.provider,id:t.id,name:t.name}))}async setModel(e,t){let i=this.active;if(this.disposed||!i||i.closing||!i.session.isIdle||i.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=i.session.modelRuntime.getModel(e,t);if(!r)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await i.session.setModel(r),this.publishFor(i,{type:"snapshot",session:this.snapshotOf(i)})}createDetached(e,t,i){return this.queue.run(async()=>{this.ensureAvailable();let r=await Ae(e),n=Mt.create(r);return await this.replace(r,n,"new",t),this.runtimes.get(n.getSessionId()).session.setSessionName(i),n.getSessionId()})}detachedRuntime(e){let t=this.runtimes.get(e);return!this.disposed&&t?.detached&&!t.closing?t:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(t=>t.detached?.owner===e&&!t.closing).length}async sendDetached(e,t,i){let r=this.detachedRuntime(e);if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(i&&r.detached.restoreTools&&(r.session.setActiveToolsByName(r.detached.restoreTools),r.detached.restoreTools=null),!r.session.isIdle||r.prompts.length>0){r.prompts.enqueue(t,[],void 0),this.scheduleQueued(r);return}await this.prompt(r,t,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let t=this.detachedRuntime(e);t&&(this.runtimes.delete(e),this.active===t&&(this.active=null),await this.close(t,"quit"),this.onSessionsChanged())})}detachedEvents(e,t){let i=this.detachedRuntime(e)?.detached;if(!i)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:i.events.filter(r=>r.seq>t),next:i.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(t=>this.close(t,"quit")))})}};import{copyFile as yd,mkdir as vd,rename as bd,unlink as kd}from"node:fs/promises";import{basename as Pd,join as Kn}from"node:path";var Id=s=>Kn(s,"pi-web","trash");async function Xn(s,e){let t=Id(e);await vd(t,{recursive:!0});let i=Kn(t,`${Date.now()}_${Pd(s)}`);try{await bd(s,i)}catch(r){let n=r.code;if(n==="ENOENT")return null;if(n!=="EXDEV")throw r;await yd(s,i),await kd(s)}return i}import{basename as gr,dirname as Sd}from"node:path";function Yn(s,e){let t=i=>e[i].map(r=>({name:i==="skills"&&gr(r.path).toLowerCase()==="skill.md"?gr(Sd(r.path)):gr(r.path),path:r.path,source:r.metadata.source,scope:r.metadata.scope,enabled:r.enabled}));return{packages:s.map(i=>({name:i.source,path:i.installedPath??"",source:i.source,scope:i.scope,enabled:!!i.installedPath})),extensions:t("extensions"),skills:t("skills")}}import{execFile as Ed}from"node:child_process";var xd=(s,e)=>new Promise((t,i)=>{Ed(s,[...e],{windowsHide:!0},r=>{r?i(r):t()})});async function mr(s,e=process.platform,t=process.env,i=xd){if(t.PI_WEBAPP_AUTO_OPEN==="0"||t.PI_WEBAPP_RUNTIME==="desktop"||t.SSH_CONNECTION||t.SSH_TTY||t.SSH_CLIENT||e==="linux"&&!t.DISPLAY&&!t.WAYLAND_DISPLAY)return!1;let r=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return r===null?!1:(await i(r,[s]),!0)}import{execFile as rp}from"node:child_process";import{randomUUID as bi}from"node:crypto";import{existsSync as go}from"node:fs";import{access as xr,mkdir as ki,mkdtemp as sp,readFile as ge,realpath as np,rename as _r,rm as $t,writeFile as Pi}from"node:fs/promises";import{dirname as mo,join as M}from"node:path";import{createHash as vr,randomUUID as Hd}from"node:crypto";import{mkdir as Od,readFile as Md,readdir as jd,realpath as ro}from"node:fs/promises";import{join as Re}from"node:path";import{constants as wr}from"node:fs";import{DatabaseSync as _d}from"node:sqlite";import{lstat as eo,mkdir as Ad,open as jt,rename as Td,unlink as to}from"node:fs/promises";import{dirname as Rd,join as Qn,resolve as Cd}from"node:path";import{randomUUID as Dd}from"node:crypto";import{setTimeout as Nd}from"node:timers/promises";async function Z(s){await Ad(s,{recursive:!0,mode:448});let e=await eo(s);if(!e.isDirectory()||e.isSymbolicLink())throw new h("invalid_storage","Plugin storage must be a real directory")}async function X(s,e){let t;try{t=await jt(s,wr.O_RDONLY|wr.O_NONBLOCK|(wr.O_NOFOLLOW??0))}catch(i){if(Ve(i))return null;throw i}try{let i=await t.stat();if(!i.isFile()||i.nlink>1||i.size>e)throw new h("invalid_storage","Invalid storage record size or type");let r=Buffer.alloc(Math.min(i.size+1,e+1)),n=0;for(;n<r.length;){let o=await t.read(r,n,r.length-n,n);if(!o.bytesRead)break;n+=o.bytesRead}if(n>e||n!==i.size)throw new h("invalid_storage","Storage record changed during read");return r.subarray(0,n)}finally{await t.close()}}async function ee(s,e=2*1024*1024){let t=await X(s,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new h("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function ce(s){let e=await X(s,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new h("gc_recovery_required",`Invalid journal ${s}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new h("gc_recovery_required",`Invalid journal ${s}; original bytes preserved`);return t}async function j(s,e){let t=`${s}.${Dd()}.tmp`,i=await jt(t,"wx",384);try{try{await i.writeFile(JSON.stringify(e)),await i.sync()}finally{await i.close()}await Td(t,s);let r;try{r=await jt(Rd(s),"r"),await r.sync()}catch(n){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(n.code??""))throw n}finally{await r?.close()}}finally{await to(t).catch(()=>{})}}var io='{"version":2,"mechanism":"sqlite-exclusive"}',Zn=s=>s.toString("utf8")===io,yi=new Set;async function yr(s,e,t=0){await Z(s);let i=Qn(s,`${e}.lock`),r=Qn(s,`${e}.ownership.sqlite`),n=e==="runtime"?"runtime_owned":"storage_busy",o=()=>new h(n,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await jt(r,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await c?.close()}let a=await eo(r);if(!a.isFile()||a.isSymbolicLink()||a.nlink!==1||a.size>1024*1024)throw new h("invalid_storage","Ownership database must be a small, single-link regular file");let l=new _d(r,{allowExtension:!1}),p=Cd(r),u=Date.now()+t,y=!1;try{for(;;){if(!yi.has(p))try{l.exec("BEGIN EXCLUSIVE"),yi.add(p),y=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=u)throw new h(n,"Another host owns this plugin storage; wait for it to stop before retrying");await Nd(10)}let f=await X(i,4096);if(f===null){let w;try{w=await jt(i,"wx",384),await w.writeFile(io),await w.sync()}catch(k){if(k.code!=="EEXIST")throw k}finally{await w?.close()}f=await X(i,4096)}if(f===null||!Zn(f))throw o()}catch(f){throw l.close(),y&&yi.delete(p),f}let m=!1;return async()=>{if(m)return;let f=await X(i,4096);if(f===null||!Zn(f))throw new h("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await to(i),l.close(),yi.delete(p),m=!0}}async function W(s,e,t=2e3){let i=await yr(s,"transaction",t);try{return await e()}finally{await i()}}var Ee=s=>Re(s,"host-pair"),te=s=>vr("sha256").update(JSON.stringify(s)).digest("hex");async function Wd(s){let e=vr("sha256"),t=0,i=0;async function r(n){let o=(await jd(Re(s,n),{withFileTypes:!0})).sort((c,a)=>c.name<a.name?-1:c.name>a.name?1:0);for(let c of o){if(!n&&c.name==="node_modules")continue;let a=n?`${n}/${c.name}`:c.name;if(c.isSymbolicLink()||!c.isFile()&&!c.isDirectory())throw new h("host_pair_required","Candidate package contains non-regular resources");if(++t>1e4)throw new h("host_pair_required","Candidate package resource budget exceeded");if(c.isDirectory()){await r(a);continue}let l=await X(Re(s,a),64*1024*1024);if(!l||(i+=l.length)>256*1024*1024)throw new h("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([a,vr("sha256").update(l).digest("hex")]))}}return await r(""),e.digest("hex")}async function Ze(s,e){let t=await ro(e),i=Re(e,"dist","hosted-worker.js");if(await ro(i)!==Re(t,"dist","hosted-worker.js"))throw new h("host_pair_required","Candidate worker must remain inside the staged host");let r=await X(Re(e,"package.json"),512*1024);if(!r)throw new h("host_pair_required","Candidate package metadata missing");let n=JSON.parse(r.toString("utf8")),o=n.piWebappHostedRuntime;if(n.name!=="pi-webapp"||n.version!==s||o?.protocol!==2||o?.runtimeProtocol!==1||o?.pairJournal!==1||o?.ownershipProtocol!==2||!Array.isArray(o?.capabilities)||!["state","workspace","legacy","panels","messages"].every(a=>o.capabilities.includes(a)))throw new h("host_pair_required","Candidate host lacks explicit hosted protocol/capability/pair-journal/crash-safe ownership metadata; retain current host or install a capable host");let c=await X(i,32*1024*1024);if(!c)throw new h("host_pair_required","Candidate worker missing");return te([r.toString("base64"),c.toString("base64"),await Wd(e)])}async function Oe(s){let e=await ce(Re(Ee(s),"intent.json"));if(e&&(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||typeof e.packageRoot!="string"||!/^[a-f0-9]{64}$/.test(e.hostDigest)||!/^[a-f0-9]{64}$/.test(e.fingerprint)||!Array.isArray(e.selections)||e.selections.some(t=>!t||typeof t.id!="string"||typeof t.version!="string"||!/^[a-f0-9]{64}$/.test(t.digest)||!Object.hasOwn(t,"before"))||e.selection&&(typeof e.selection.path!="string"||!/^[a-f0-9]{64}$/.test(e.selection.digest))||!["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(e.phase)))throw new h("host_pair_required","Invalid host pair journal; preserve data and inspect intent.json with all owners stopped");if(e){let{lifecyclePhase:t,...i}=e;e={...i,phase:i.phase==="selected"&&t==="restart-requested"?"restart-requested":i.phase==="reconciled"&&t==="cancelled"?"cancelled":i.phase}}return e}async function Te(s,e){let{lifecyclePhase:t,...i}=e,r=i.phase==="cancelled"?{...i,phase:"reconciled",lifecyclePhase:"cancelled"}:i.phase==="restart-requested"?{...i,phase:"selected",lifecyclePhase:"restart-requested"}:i;await j(Re(Ee(s),"intent.json"),r)}var mt=s=>s&&!["prepared","reconciled","cancelled"].includes(s.phase);async function Wt(s){let e=await Oe(s);if(e&&mt(e))throw new h("host_pair_required",`Host pair selection pending (${e.version}, ${e.phase}): ${e.message??"restart selected host, or stop all owners and inspect host-pair/intent.json"}; data retained`)}function so(s,e,t,i=async()=>{}){let r=async o=>{let c=Re(Ee(s),"history");await Od(c,{recursive:!0,mode:448}),await j(Re(c,`${o.id}.json`),o)},n=async(o,c,a)=>{let l=await Ze(o,c),p=te(await t()),u=await e(o,a);if(a?.throwIfAborted(),te(await t())!==p)throw new h("host_pair_changed","Plugin policy/activation changed during preflight; recheck update");return await i(o,u),{schema:1,id:Hd(),phase:"prepared",version:o,packageRoot:c,hostDigest:l,fingerprint:p,selections:u}};return{status:()=>Oe(s),stage:(o,c,a)=>W(Ee(s),async()=>{await Wt(s);let l=await Oe(s);l&&await r(l.phase==="prepared"?{...l,phase:"cancelled",message:"Superseded before version selection; no code or data changed"}:l),await Te(s,await n(o,c,a))}),cancel:(o,c,a)=>W(Ee(s),async()=>{let l=await Oe(s);if(!l||l.phase==="cancelled"||l.phase==="reconciled")return;if(o&&l.version!==o||c&&l.packageRoot!==c)throw new h("host_pair_changed","Another update owns this transaction");if(mt(l)&&!a)throw new h("host_pair_required","Selected update requires its owned pointer recovery receipt before cancellation");await a?.();let p={...l,phase:"cancelled",message:"Update cancelled; current runtime and plugin data retained"};await Te(s,p),await r(p)}),select:(o,c,a)=>W(Ee(s),async()=>{await Wt(s);let l=await Oe(s),p=l?.phase==="prepared"&&l.version===o&&l.packageRoot===c&&l.fingerprint===te(await t())?l:await n(o,c),{hostDigest:u,selections:y}=p,m=p.fingerprint;if(await Te(s,p),await i(o,y),await Ze(o,c)!==u||te(await t())!==m)throw await Te(s,{...p,phase:"required-action",message:"Preflight changed; host pointer not written"}),new h("host_pair_changed","Preflight changed; host pointer not written");await Te(s,{...p,phase:"selecting"});let f=await a();await Te(s,{...p,phase:"selected",...f?{selection:f}:{}})}),restart:(o,c,a)=>W(Ee(s),async()=>{let l=await Oe(s);if(!l||l.phase!=="selected"||l.version!==o||l.packageRoot!==c||l.hostDigest!==await Ze(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed; restart refused, inspect pair journal");if(l.selection&&te((await Md(l.selection.path)).toString("base64"))!==l.selection.digest)throw new h("host_pair_changed","Host selection pointer changed; restart refused");if(await i(o,l.selections),l.hostDigest!==await Ze(o,c)||l.fingerprint!==te(await t()))throw new h("host_pair_changed","Selected pair changed during restart validation");await Te(s,{...l,phase:"restart-requested",message:"Restart authorized; awaiting launcher receipt and selected host health admission"}),await a()})}}import{promisify as op}from"node:util";import{realpathSync as ao,statSync as $d}from"node:fs";import{basename as Vd,delimiter as Fd,dirname as no,join as br,resolve as Bd}from"node:path";function oo(s){if(!s)return null;try{let e=ao(s);return Vd(e)==="npm-cli.js"&&$d(e).isFile()?e:null}catch{return null}}function Ud({execPath:s=process.execPath,env:e=process.env}={}){let t=oo(e.npm_execpath);if(t)return t;let i=new Set([no(s)]);try{i.add(no(ao(s)))}catch{}let r=Object.entries(e).find(([n])=>n.toLowerCase()==="path")?.[1]??"";for(let n of r.split(Fd).filter(Boolean))i.add(Bd(n));for(let n of i)for(let o of[br(n,"node_modules","npm","bin","npm-cli.js"),br(n,"..","lib","node_modules","npm","bin","npm-cli.js"),br(n,"npm")]){let c=oo(o);if(c)return c}throw new Error("\u627E\u4E0D\u5230 npm \u5165\u53E3 npm-cli.js\uFF1B\u8BF7\u5B89\u88C5\u5305\u542B npm \u7684 Node.js\uFF0C\u6216\u5C06 npm \u6240\u5728\u76EE\u5F55\u52A0\u5165 PATH \u540E\u91CD\u542F\u670D\u52A1\u3002")}function co(s){return{file:process.execPath,args:[Ud(),...s]}}import{readFile as Ld,rename as zd,writeFile as qd,unlink as Gd}from"node:fs/promises";import{join as Jd}from"node:path";import{randomUUID as Kd}from"node:crypto";var kr=1,lo=s=>Jd(s,"pi-web","launcher-handoff.json");function po(s){return s?.protocol===kr&&typeof s.nonce=="string"&&s.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(s.requestId)&&Number.isSafeInteger(s.pid)&&s.pid>0&&["requested","draining","stopped","refused","failed"].includes(s.phase)}async function Pr(s){try{let e=JSON.parse(await Ld(lo(s),"utf8"));if(!po(e))throw new Error("Invalid launcher handoff journal; original data retained");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Xd(s,e){let t=`${s}.${Kd()}.tmp`;try{await qd(t,JSON.stringify(e),{mode:384}),await zd(t,s)}finally{await Gd(t).catch(()=>{})}}async function uo(s,e){if(!po(e))throw new Error("Invalid launcher handoff receipt");await Xd(lo(s),e)}import{execFile as Yd}from"node:child_process";import{cp as Qd,readFile as Ir,realpath as Zd,rm as ep}from"node:fs/promises";import{join as wt,sep as tp}from"node:path";import{promisify as ip}from"node:util";var ho=ip(Yd),Sr=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Er(s){if(!s||typeof s!="object"||Array.isArray(s))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=s;return Sr.map(t=>{let i=e[t];if(typeof i!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(i))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${t}@${i}`})}async function vi(s){return Promise.all(Sr.map(async e=>{let t=await dt(s,e),i=JSON.parse(await Ir(wt(t,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(i.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${i.version}`}))}async function fo(s,e){let t=JSON.parse(await Ir(wt(e,"package.json"),"utf8"));if(t.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let i=t.peerDependencies===void 0?await vi(s):Er(t.peerDependencies);if(JSON.stringify(await vi(e))!==JSON.stringify(i))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let r=await dt(s,"node-pty"),n=await dt(e,"node-pty"),o=await Zd(wt(e,"../.."));if(r===n||!n.startsWith(o+tp))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let c=async u=>JSON.parse(await Ir(wt(u,"package.json"),"utf8")).version;if(await c(r)!==await c(n))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await ep(n,{recursive:!0,force:!0}),await Qd(r,n,{recursive:!0});let a={...process.env};delete a.NODE_OPTIONS,delete a.NODE_PATH,delete a.ELECTRON_RUN_AS_NODE,await ho(process.execPath,[wt(e,"desktop","check-pty.cjs")],{cwd:e,env:a,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let l=await dt(e,Sr[0]),{stdout:p}=await ho(process.execPath,[wt(l,"dist","bundle","cli.js"),"--version"],{cwd:e,env:a,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==i[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}var ap=op(rp);function wo(s){let e=s.piWebappDataVersion??1;if(!Number.isSafeInteger(e)||Number(e)<1)throw new Error("\u5E94\u7528\u6570\u636E\u683C\u5F0F\u7248\u672C\u65E0\u6548");return Number(e)}async function cp(s,e){try{let t=co(s),{stdout:i}=await ap(t.file,t.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return i}catch(t){let i=t;throw new Error(i.stderr?.trim()||i.message)}}var Ii=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;validateHostedPair;hostedPair;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??cp,this.desktopManaged=e.desktopManaged??process.env.PI_WEBAPP_RUNTIME==="desktop",this.desktopPackageUpdates=e.desktopPackageUpdates??process.env.PI_WEBAPP_DESKTOP_PACKAGE_UPDATES==="1",this.desktopReleaseChannels=e.desktopReleaseChannels??process.env.PI_WEBAPP_DESKTOP_RELEASE_CHANNELS==="1",this.targetPeerSpecs=e.peerSpecs?async()=>e.peerSpecs(this.packageRoot):async t=>{let i=(await this.runNpm(["view",`pi-webapp@${t}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!i)return vi(this.packageRoot);let r=JSON.parse(i),n=Array.isArray(r)&&r.length===1?r[0]:r;return Er(n)},this.verifyPackage=e.verifyPackage??fo,this.validateHostedPair=e.validateHostedPair,this.hostedPair=e.hostedPair,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?kr:0}}async requestLauncherHandoff(e,t){if(!this.desktopManaged||!this.launcherNonce||e!==this.launcherNonce||this.launcherIdentity().handoffProtocol!==1)throw new Error("\u65E7\u540E\u53F0\u542F\u52A8\u5668\u5C1A\u65E0\u5B89\u5168\u4EA4\u63A5\u534F\u8BAE\uFF0C\u8BF7\u5148\u5728\u7A33\u5B9A\u7248\u901A\u9053\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4ECE\u684C\u9762\u83DC\u5355\u91CD\u8BD5\uFF1B\u73B0\u6709\u4EFB\u52A1\u4FDD\u6301\u8FD0\u884C\u3002");if(!/^[a-f0-9-]{36}$/i.test(t))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let i=await this.transaction();if(i&&!["committed","cancelled","failed"].includes(i.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let r=M(this.agentDir,"pi-web","launcher.json"),n=JSON.parse(await ge(r,"utf8")),o=p=>p.nonce===e&&p.pid===n.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!o(n))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let c=await Pr(this.agentDir);if(c?.nonce===e&&["requested","draining"].includes(c.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let a,l=!1;try{if(!this.beforeRestart)throw new Error("\u540E\u53F0\u7F3A\u5C11\u56FE\u7A3F\u6392\u7A7A\u534F\u8BAE\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");if(a=await this.beforeRestart(),!o(JSON.parse(await ge(r,"utf8"))))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let p={protocol:1,nonce:e,requestId:t,pid:n.pid,phase:"requested"};try{await uo(this.agentDir,p),l=!0}catch(u){let y=await Pr(this.agentDir).catch(()=>null);if(l=y?.nonce===e&&y?.requestId===t&&["requested","draining","stopped"].includes(y.phase),!l)throw u}this.restartPending=!0}finally{!l&&a&&await a()}}async current(){let e=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return Fe(e.version),e.version}async runningVersion(){let e=await this.current(),t=await this.transaction();return t?.phase==="restart-requested"&&t.version===e&&(!this.hostedPair||(await this.hostedPair.status?.())?.phase==="reconciled")&&await this.record({...t,phase:"committed",message:"Selected host is running and hosted protocol health admission completed"}),e}get transactionPath(){return M(this.agentDir,"pi-web","update-transaction.json")}async transaction(){try{let e=await ce(this.transactionPath);if(!e)return null;if(e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||e.selectionPath!==M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json")||e.selectedDigest!==void 0&&!/^[a-f0-9]{64}$/.test(e.selectedDigest)||e.before!==void 0&&e.before!==null&&(typeof e.before!="string"||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e.before)))throw new Error("\u66F4\u65B0\u4E8B\u52A1\u8BB0\u5F55\u65E0\u6548\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u8BCA\u65AD");return e}catch(e){if(e.code==="ENOENT")return null;throw e}}async record(e){if(await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await j(this.transactionPath,e),["failed","cancelled","committed"].includes(e.phase)){let t=M(this.agentDir,"pi-web","update-history");await ki(t,{recursive:!0}),await j(M(t,`${e.id}-${e.phase}.json`),e)}}async admittedFallback(e,t){if(!e.ownerNonce||!this.launcherNonce||e.ownerNonce===this.launcherNonce||e.before===void 0)return!1;let i=t??await this.current();if(e.version===i)return!1;try{let r=await ce(M(this.agentDir,"pi-web","launcher.json"));if(r?.nonce!==this.launcherNonce||r.version!==i||r.piPid!==process.pid)return!1;let n;try{n=(await ge(e.selectionPath)).toString("base64")}catch(o){if(o.code!=="ENOENT")return!1;n=null}return n===e.before}catch{return!1}}async admittedLegacyRecovery(e){if(!this.launcherNonce)return!1;try{let t=await ce(M(this.agentDir,"pi-web","launcher.json"));if(t?.nonce!==this.launcherNonce||t.piPid!==process.pid||t.version!==(e??await this.current()))return!1;try{return await xr(M(this.agentDir,"pi-web","launcher.restart")),!1}catch(i){return i.code==="ENOENT"}}catch{return!1}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction();if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();if(r&&!["cancelled","reconciled","prepared"].includes(r.phase)){if(!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u9700\u8981\u5F53\u524D\u540E\u53F0\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E14\u4E0D\u80FD\u4E2D\u65AD\u542F\u52A8\u5668\u5DF2\u63A5\u53D7\u7684\u4EA4\u63A5");let n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");if(!r.selection||r.selection.path!==n)throw new Error("\u65E7\u5347\u7EA7\u4E8B\u52A1\u7F3A\u5C11\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u8BF7\u4FDD\u7559\u8BB0\u5F55\u5E76\u68C0\u67E5\u6062\u590D\u8BCA\u65AD");let o=await ge(n);if(te(o.toString("base64"))!==r.selection.digest)throw new Error("\u65E7\u5347\u7EA7\u9009\u62E9\u5DF2\u53D8\u5316\uFF0C\u6062\u590D\u672A\u8986\u76D6\u5176\u4ED6\u64CD\u4F5C");let c=JSON.parse(o.toString("utf8")),a=await this.current(),l=M(this.packageRoot,"bin","pi-webapp.mjs");await xr(l);let p=c.previous?.version===a&&c.previous.launcher===l?c.previous:this.desktopManaged?await di(this.agentDir,{version:a,launcher:l,desktopProtocolVersion:Be}):{version:a,launcher:l,baseVersion:c.baseVersion??a};e={schema:1,id:r.id,phase:"selected",version:r.version,channel:await this.channel(),packageRoot:r.packageRoot,selectionPath:n,before:Buffer.from(JSON.stringify(p)).toString("base64"),selectedDigest:r.selection.digest,ownerNonce:this.launcherNonce,legacyRecovery:!0},await this.record(e)}else r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot)}if(!e||["cancelled","failed","committed"].includes(e.phase)){let r=await this.hostedPair?.status?.();r?.phase==="prepared"&&await this.hostedPair?.cancel?.(r.version,r.packageRoot),this.preparedUpdate=void 0,this.restartPending=!1;return}if(e.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u540E\u53F0\u5F52\u5C5E\u6216\u4EA4\u63A5\u72B6\u6001\u5DF2\u53D8\u5316\uFF0C\u8BF7\u4ECE\u5F53\u524D\u8FD0\u884C\u5B9E\u4F8B\u6062\u590D");if(e.phase==="restart-requested"&&!await this.admittedFallback(e))throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u5F53\u524D\u5165\u53E3\u6CA1\u6709\u5DF2\u786E\u8BA4\u56DE\u9000\u7684\u5F52\u5C5E\u6536\u636E\uFF0C\u4E0D\u80FD\u53D6\u6D88\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B\u7684\u4EA4\u63A5");let t=e,i=async()=>{if(t.legacyRecovery&&!await this.admittedLegacyRecovery())throw new Error("\u65E7\u4E8B\u52A1\u6062\u590D\u7684\u5F52\u5C5E\u6216\u4EA4\u63A5\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(t.phase==="restart-requested"&&!await this.admittedFallback(t))throw new Error("\u91CD\u542F\u4EA4\u63A5\u7684\u5F52\u5C5E\u6216\u56DE\u9000\u6536\u636E\u5DF2\u53D8\u5316\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u5176\u4ED6\u8FD0\u884C\u5B9E\u4F8B");if(!t.selectedDigest)return;let r;try{r=await ge(t.selectionPath)}catch(n){if(n.code!=="ENOENT")throw n;r=null}if((r?.toString("base64")??null)!==t.before){if(!r||te(r.toString("base64"))!==t.selectedDigest)throw new Error("\u7248\u672C\u9009\u62E9\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u66F4\u6539\uFF0C\u53D6\u6D88\u672A\u8986\u76D6\u8BE5\u9009\u62E9\uFF1B\u5F53\u524D\u6570\u636E\u5DF2\u4FDD\u7559");if(t.before===null)await $t(t.selectionPath);else if(typeof t.before=="string"){let n=`${t.selectionPath}.${bi()}.tmp`;try{await Pi(n,Buffer.from(t.before,"base64"),{mode:384}),await _r(n,t.selectionPath)}finally{await $t(n,{force:!0})}}else throw new Error("\u7F3A\u5C11\u65E7\u7248\u672C\u9009\u62E9\u6536\u636E\uFF0C\u4E0D\u80FD\u81EA\u52A8\u6062\u590D\uFF1B\u8BF7\u4FDD\u7559\u4E8B\u52A1\u8BB0\u5F55")}};this.hostedPair?.cancel?await this.hostedPair.cancel(e.version,e.packageRoot,i):await W(M(this.agentDir,"pi-web","update-control"),i),await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0,this.restartPending=!1}get preferencePath(){return M(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ge(this.preferencePath,"utf8"));if(!e||typeof e!="object"||!["stable","alpha"].includes(e.channel))throw new Error("Invalid persisted update channel");return e.channel}catch(e){if(e.code==="ENOENT")return"stable";throw new Error("\u65E0\u6CD5\u8BFB\u53D6\u66F4\u65B0\u504F\u597D\uFF0C\u8BF7\u68C0\u67E5 update-preferences.json")}}async setChannel(e){if(e!=="stable"&&e!=="alpha")throw new Error("\u66F4\u65B0\u901A\u9053\u65E0\u6548");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");this.preparedUpdate&&e!==this.preparedUpdate.channel&&await this.cancel(),this.savingPreference=!0;let t=`${this.preferencePath}.${bi()}.tmp`;try{await ki(M(this.agentDir,"pi-web"),{recursive:!0}),await Pi(t,JSON.stringify({channel:e}),{mode:384}),await _r(t,this.preferencePath)}finally{this.savingPreference=!1,await $t(t,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),t=await this.channel(),i=go(M(this.packageRoot,".git")),r={current:e,channel:t,latest:null,available:!1,canRestart:!!this.launcherNonce&&!i};this.desktopManaged&&(r.launcher=this.launcherIdentity(),r.launcherHandoff={supported:r.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(r.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let n=await this.transaction(),o=await this.hostedPair?.status?.();if(n&&!["failed","cancelled","committed"].includes(n.phase)?r.recovery={version:n.version,phase:n.phase,canCancel:n.legacyRecovery?await this.admittedLegacyRecovery(e):n.phase!=="restart-requested"||await this.admittedFallback(n,e)}:o&&!["cancelled","reconciled"].includes(o.phase)&&(r.recovery={version:o.version,phase:o.phase,canCancel:o.phase==="prepared"||await this.admittedLegacyRecovery(e)}),this.desktopManaged&&!this.desktopPackageUpdates)return{...r,canRestart:!1,requiresDesktopUpgrade:!0,reason:"\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002"};if(this.desktopManaged&&t==="alpha"&&!this.desktopReleaseChannels)return{...r,canRestart:!1,reason:r.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};i?r.reason="\u5F53\u524D\u4ECE\u6E90\u7801\u76EE\u5F55\u8FD0\u884C\u3002\u7F51\u9875\u5347\u7EA7\u4EC5\u652F\u6301 npm \u5B89\u88C5\u7684\u7248\u672C\uFF0C\u4EE5\u514D\u8986\u76D6\u672C\u5730\u4EE3\u7801\u3002":r.canRestart||(r.reason="\u5F53\u524D\u9875\u9762\u7531 Pi \u7EC8\u7AEF\u6253\u5F00\uFF0C\u65E0\u6CD5\u4ECE\u7F51\u9875\u81EA\u52A8\u91CD\u542F Pi\uFF1B\u8BF7\u4F7F\u7528 pi-webapp \u542F\u52A8\u5668\u3002"),this.desktopManaged&&this.desktopPackageUpdates&&r.canRestart&&(r.reason="\u4E1A\u52A1\u5305\u66F4\u65B0\u5B89\u88C5\u5230\u7528\u6237\u76EE\u5F55\uFF0C\u4E0D\u4FEE\u6539 pi.app\u3002\u8BF7\u5148\u7ED3\u675F\u6240\u6709\u804A\u5929\u4EFB\u52A1\u5E76\u5173\u95ED\u7EC8\u7AEF\uFF0C\u518D\u5347\u7EA7\u5E76\u91CD\u542F\u540E\u53F0\u3002");try{let c=JSON.parse((await this.runNpm(["view","pi-webapp",t==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),a=Array.isArray(c)&&c.length===1?c[0]:c,l=t==="alpha"?a:{latest:a};if(!l||!wn(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let p=l.latest;if(t==="alpha"&&l.alpha!==void 0){if(!ai(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");ue(l.alpha,p)>0&&(p=l.alpha)}r.latest=p,r.downgrade=ue(p,e)<0,r.available=t==="stable"?ue(p,e)!==0:ue(p,e)>0,this.desktopManaged&&r.downgrade&&!this.desktopReleaseChannels&&ue(p,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(r.canRestart=!1,r.requiresDesktopUpgrade=!0,r.reason="\u5F53\u524D\u684C\u9762\u5916\u58F3\u5C1A\u4E0D\u652F\u6301\u5207\u56DE\u4F4E\u4E8E\u5185\u7F6E\u5305\u7684\u7248\u672C\uFF0C\u8BF7\u5148\u5B89\u88C5\u652F\u6301\u66F4\u65B0\u901A\u9053\u7684\u65B0\u7248\u684C\u9762\u5E94\u7528\u3002")}catch(c){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${c instanceof Error?c.message:String(c)}`)}return r}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let t=this.prepareUpdate(e);this.preparation=t;try{return await t}finally{this.preparation=void 0}}async prepareUpdate(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0\uFF0C\u8BF7\u5148\u5B89\u88C5\u65B0\u7248\u684C\u9762\u5E94\u7528");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");if(go(M(this.packageRoot,".git")))throw new Error("\u6E90\u7801\u76EE\u5F55\u4E0D\u80FD\u901A\u8FC7\u7F51\u9875\u5347\u7EA7");if(this.restartPending)throw new Error("\u5347\u7EA7\u5DF2\u5B8C\u6210\uFF0C\u6B63\u5728\u91CD\u542F");if(this.cancellation)throw new Error("\u5347\u7EA7\u53D6\u6D88\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparing||this.savingPreference)throw new Error("\u5347\u7EA7\u6216\u504F\u597D\u4FDD\u5B58\u6B63\u5728\u8FDB\u884C\u4E2D");if(this.preparedUpdate)if(e&&(e.version!==this.preparedUpdate.update.version||e.channel!==this.preparedUpdate.channel)){let t=await this.check();if(e.channel!==t.channel||e.version!==t.latest)throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");await this.cancel()}else return{...this.preparedUpdate.update};this.preparing=!0,this.downloadAbort=new AbortController;try{let t=await this.check();if(e&&(e.channel!==t.channel||e.version!==t.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!t.canRestart)throw new Error(t.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!t.available||!t.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(t.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let i=M(this.agentDir,"pi-web","releases");await ki(i,{recursive:!0});let r=await sp(M(await np(i),`${t.latest}-`)),n=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),o={schema:1,id:bi(),phase:"downloading",version:t.latest,channel:t.channel??"stable",selectionPath:n,ownerNonce:this.launcherNonce};await this.record(o);let c=!1;try{let a=this.desktopManaged?await this.targetPeerSpecs(t.latest):[];await this.runNpm(["install",`pi-webapp@${t.latest}`,...a,"--prefix",r,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=M(r,"node_modules","pi-webapp");o={...o,phase:"validating",packageRoot:l},await this.record(o);let p=JSON.parse(await ge(M(l,"package.json"),"utf8"));if(p.name!=="pi-webapp"||p.version!==t.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let u=JSON.parse(await ge(M(this.packageRoot,"package.json"),"utf8"));if(t.downgrade&&wo(p)!==wo(u))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let y=M(l,"bin","pi-webapp.mjs");await Promise.all([y,M(l,"dist","extension.js"),M(l,"web","dist","index.html")].map(w=>xr(w))),await this.validateHostedPair?.(t.latest,l);let m=this.desktopManaged?await di(this.agentDir,{version:t.latest,launcher:y,desktopProtocolVersion:Be}):null;this.desktopManaged&&await this.verifyPackage(this.packageRoot,l);let f=async()=>{let w;try{w=await ge(n)}catch(P){if(P.code!=="ENOENT")throw P;w=null}if(o={...o,phase:"selecting",before:w?.toString("base64")??null},await this.record(o),c=!0,this.desktopManaged){let P=m,E=await bn(this.agentDir,t.current),_=E?.version===t.current?E:null,H=process.env.PI_WEBAPP_DESKTOP_VERSION??E?.fallbackVersion??t.current,N={...P,...t.downgrade||E?.fallbackVersion?{fallbackVersion:H}:{},..._?{previous:_}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(N)).toString("base64"))},await this.record(o),await kn(this.agentDir,N)}else{let P=M(this.agentDir,"pi-web"),E=M(P,`update.${bi()}.tmp`);try{let _;try{_=JSON.parse(await ge(M(P,"update.json"),"utf8"))}catch{}let H=_?.baseVersion??t.current,N=_?.version===t.current?_:void 0;N&&delete N.previous;let T={version:t.latest,launcher:y,baseVersion:H,...t.downgrade||_?.allowDowngrade===!0?{allowDowngrade:!0}:{},...N?{previous:N}:{}};o={...o,selectedDigest:te(Buffer.from(JSON.stringify(T)).toString("base64"))},await this.record(o),await Pi(E,JSON.stringify(T),{mode:384}),await _r(E,M(P,"update.json"))}finally{await $t(E,{force:!0})}}let k=M(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json");return{path:k,digest:te((await ge(k)).toString("base64"))}};return this.hostedPair?.stage&&await this.hostedPair.stage(t.latest,l,this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted(),o={...o,phase:"prepared"},await this.record(o),this.preparedUpdate={update:{version:t.latest,launcher:y},channel:t.channel??"stable",select:async()=>{this.hostedPair?await this.hostedPair.select(t.latest,l,f):await W(M(this.agentDir,"pi-web","update-control"),f),o={...o,phase:"selected"},await this.record(o)}},{version:t.latest,launcher:y}}catch(a){throw c||await $t(r,{recursive:!0,force:!0}),await this.record({...o,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":"\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),a}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let t,i=!1;try{t=await this.beforeRestart?.(),await this.preparedUpdate?.select();let r=async()=>{let n=M(this.agentDir,"pi-web","launcher.restart"),o=await this.transaction();o&&await this.record({...o,phase:"restart-requested"});try{await Pi(n,JSON.stringify({nonce:this.launcherNonce,launcher:e.launcher}),{mode:384,flag:"wx"}),i=!0}catch(c){try{let a=JSON.parse(await ge(n,"utf8"));i=a.nonce===this.launcherNonce&&a.launcher===e.launcher}catch{}if(!i)throw c}};this.hostedPair?await this.hostedPair.restart(e.version,mo(mo(e.launcher)),r):await r(),this.restartPending=!0}catch(r){if(i){this.restartPending=!0;return}this.restartPending=!1;let n=await this.transaction();n?.phase==="restart-requested"&&await this.record({...n,phase:"selected",message:"Restart marker was not accepted; reverting owned selection"});let o=this.preparedUpdate;try{await this.cancel(),this.preparedUpdate=o}finally{t&&await t()}throw r}}};import{createHash as ta,randomUUID as ph}from"node:crypto";import{randomUUID as $u}from"node:crypto";import{access as Vu}from"node:fs/promises";import{join as ji}from"node:path";import{randomUUID as bo}from"node:crypto";import{randomUUID as lp}from"node:crypto";function yo(s){let t=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(o=>typeof s[o]!="function").map(o=>String(o));if(t.length)return{supported:!1,missing:t};let i=`__pi_web_contract_${lp().replaceAll("-","")}`,r;try{if(r=s.getActiveTools(),!Array.isArray(r))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let n={name:i,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{s.registerTool(n),s.setActiveTools([...r,i]),(s.getAllTools().find(c=>c.name===i)?.exposure!=="hidden"||s.getActiveTools().includes(i))&&t.push("hidden-tool-exposure");let o={type:"object",properties:{contract:{type:"boolean"}}};s.registerTool({...n,parameters:o}),s.getAllTools().find(c=>c.name===i)?.parameters!==o&&t.push("dynamic-tool-registry")}catch{t.push("tool-registry-contract")}finally{try{s.setActiveTools(r)}catch{t.push("active-tool-registry")}}return{supported:!t.length,missing:t}}var dp;function vo(){return dp??=pp().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function pp(){let{createAgentSession:s,DefaultResourceLoader:e,SessionManager:t}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:i}=await import("@earendil-works/pi-ai"),{mkdtemp:r,rm:n}=await import("node:fs/promises"),{tmpdir:o}=await import("node:os"),{join:c}=await import("node:path"),a=await r(c(o(),"pi-sdk-contract-")),l,p=[],u=0,y=0,m=!1,f=!1;try{let w=(N,T,Y)=>({name:N,label:N,description:"Inert host SDK contract check",exposure:T,parameters:{type:"object",properties:{}},execute:Y}),k=()=>({content:[],details:void 0}),P=new e({cwd:a,agentDir:a,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[N=>{N.on("tool_call",T=>{if(T.toolName==="__contract_direct"&&(m=!!T.parentToolCallId),T.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let T of["hidden","model-only"])N.registerTool(w(`__contract_${T.replace("-","_")}`,T,async()=>(y++,k())));N.registerTool(w("__contract_protected","direct",async()=>(y++,k()))),N.registerTool(w("__contract_direct","direct",async()=>(u++,k()))),N.registerTool(w("__contract_driver","direct",async(T,Y,b,v,$)=>{let ye=await $.executeTool("__contract_hidden",{}),ve=await $.executeTool("__contract_model_only",{}),se=await $.executeTool("__contract_direct",{}),x=await $.executeTool("__contract_protected",{});return(!ye.isError||!ve.isError)&&p.push("nested-tool-exposure"),(se.isError||u!==1)&&p.push("nested-tool-execution"),(!x.isError||y!==0)&&p.push("nested-tool-permission-guard"),m||p.push("nested-parent-identity"),f=!0,k()}))}]});await P.reload(),{session:l}=await s({cwd:a,agentDir:a,sessionManager:t.inMemory(a),resourceLoader:P}),await l.bindExtensions({mode:"print"});let E=l.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await l.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await l.setModel(E);let _=0;l.agent.streamFunction=async N=>{let T=_++===0,Y={role:"assistant",api:N.api,provider:N.provider,model:N.id,timestamp:Date.now(),content:T?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:T?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},b=i();return b.push({type:"start",partial:Y}),b.push({type:"done",reason:T?"toolUse":"stop",message:Y}),b.end(Y),b};let H;try{await Promise.race([l.prompt("Inert in-memory SDK permission contract check"),new Promise((N,T)=>{H=setTimeout(()=>T(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(H)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{l?.dispose(),await n(a,{recursive:!0,force:!0})}}var Si=class{bindings=new Set;descriptors=new Map;frozen=!1;waiters=new Set;admissionListeners=new Set;onThaw(e){return this.admissionListeners.add(e),()=>{this.admissionListeners.delete(e)}}service;sdkContract;verification;verifyCompatibility(){return this.verification??=vo().then(e=>{this.sdkContract=e;for(let t of this.bindings)if(t.ready&&!t.disposed)try{this.publish(t)}catch{t.compatible=!1,t.missing=["sdk-tool-publication"]}return e})}constructor(e){this.service=e}get compatibilityIssues(){return[...this.bindings].filter(e=>e.compatible===!1).map(e=>({sessionId:e.scope.sessionId,missing:e.missing??[]}))}get isFrozen(){return this.frozen}assertAdmission(){if(this.frozen)throw Object.assign(new Error("Hosted tools are switching; retry after thaw"),{code:"hosted_admission_blocked"})}notify(){for(let e of this.waiters)e();this.waiters.clear()}async until(e){for(;!e();)await new Promise(t=>this.waiters.add(t))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let t;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(i=>i.compatible===!1||!i.busy)),new Promise((i,r)=>{t=setTimeout(()=>r(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(i){throw this.thaw(),i}finally{clearTimeout(t)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async t=>{await this.verifyCompatibility(),this.install(t,e)}}mountTui(e,t){let i=this.install(e,t);i.ready=!0;try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}install(e,t){let i={pi:e,scope:{...t},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(i),typeof e.on!="function")return i.compatible=!1,i.missing=["on"],i;let r=n=>{if(typeof n!="function")throw new Error("SDK event subscription cannot be released");i.handlers.push(n)};try{r(e.on("before_agent_start",async()=>{for(;this.frozen&&i.compatible!==!1&&!i.busy&&!i.disposed;)await new Promise(n=>this.waiters.add(n));if(i.disposed)throw new Error("Hosted session disposed");i.busy=i.compatible!==!1})),r(e.on("agent_settled",()=>{i.busy=!1,this.notify()})),r(e.on("tool_call",n=>{let o=i.owned.get(n.toolName);if(!o)return;let c=this.descriptors.get(o)?.find(a=>a.name===n.toolName);if(!c||!this.allowed(i,o,c,!!n.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),r(e.on("session_start",()=>{i.ready=!0,this.publish(i)})),r(e.on("session_shutdown",()=>this.release(i)))}catch{for(let n of i.handlers)try{n()}catch{}i.handlers=[],i.compatible=!1,i.missing=["hosted-lifecycle-events"]}return i}attach(e){let t=[...this.bindings].find(i=>i.scope.sessionId===e.sessionManager.getSessionId()&&!i.session);if(!t)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");t.session=e,t.ready=!0,t.off=e.subscribe(i=>{i.type==="agent_settled"&&(t.busy=!1,this.notify())});try{this.publish(t)}catch(i){throw this.release(t),i}return()=>this.release(t)}releasePending(e){for(let t of this.bindings)!t.session&&!t.ready&&t.scope.sessionId===e&&this.release(t)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let t of e.handlers)t();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,t,i,r=!1){let n=this.service.policy(t,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&n.enabled&&(!n.allowlist||n.allowlist.includes(i.name))&&(!n.planMode||i.readonly===!0)&&(!r||n.allowNested===!0)}change(e,t){if(!this.frozen||[...this.bindings].some(r=>r.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let i=structuredClone(t);this.validateChange(e,i),this.descriptors.set(e,i);for(let r of this.bindings)r.ready&&this.publish(r)}validateChange(e,t){for(let r of this.bindings)if(r.compatible!==!1)for(let[n,o]of r.owned)this.assertOwner(r,o,n);let i=new Set;for(let r of t){if(!r.name||!r.action||!r.parameters||r.parameters.type!=="object"||i.has(r.name))throw new Error("Invalid hosted tool descriptor");i.add(r.name);for(let[n,o]of this.descriptors)if(n!==e&&o.some(c=>c.name===r.name))throw new Error(`Hosted tool ownership conflict: ${r.name}`);for(let n of this.bindings)n.compatible!==!1&&this.assertOwner(n,e,r.name)}}assertOwner(e,t,i){let r=e.owned.get(i);if(r&&r!==t)throw new Error(`Hosted tool ownership conflict: ${i}`);let n=e.pi.getAllTools().find(o=>o.name===i);if(n&&(!r||n.parameters!==e.definitions.get(i)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${i}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let i=yo(e.pi);e.compatible=i.supported,e.missing=i.missing}if(!e.compatible)return;for(let[i,r]of e.owned)this.assertOwner(e,r,i);for(let[i,r]of this.descriptors)for(let n of r)this.assertOwner(e,i,n.name);let t=new Set;for(let[i,r]of this.descriptors)for(let n of r){if(e.owned.set(n.name,i),!this.allowed(e,i,n))continue;t.add(n.name);let o=this.service.policy(i,e.scope),c=o.exposure??"direct",a=!o.allowNested&&c==="direct"?"model-only":c,l={name:n.name,label:n.label,description:n.description,parameters:structuredClone(n.parameters),exposure:a,execute:async(p,u,y)=>{if(!this.allowed(e,i,n))throw new Error("Hosted tool denied by host policy");return this.service.invoke(i,{requestId:bo(),scope:{...e.scope},kind:"tool",action:n.action,input:u},y)}};e.pi.registerTool(l),e.definitions.set(n.name,l)}for(let i of e.owned.keys())if(!t.has(i)){let r={name:i,label:i,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:up};e.pi.registerTool(r),e.definitions.set(i,r)}e.pi.setActiveTools(e.pi.getActiveTools().filter(i=>{let r=e.definitions.get(i);return!r||r.exposure==="direct"||r.exposure==="model-only"}))}async invokeAction(e,t,i,r,n){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(c=>c.scope.sessionId===t.sessionId&&c.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let o=this.service.policy(e,t);if(!o.enabled||o.planMode||o.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:bo(),scope:t,kind:"action",action:i,input:r},n)}};async function up(){throw new Error("Hosted tool unavailable")}import{randomBytes as uu,randomUUID as hu,timingSafeEqual as fu}from"node:crypto";import{join as Pe}from"node:path";var hp=30,ko=/^[a-z][a-z0-9-]{0,63}$/,fp=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,Vt=s=>{throw new h("invalid_package",s)},Ar=(s,e)=>s===void 0?[]:!Array.isArray(s)||s.length>32?Vt(`Invalid ${e} declaration`):s;function yt(s){let e=s&&typeof s=="object"?s:{},t=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(c=>typeof c=="string"):[]),i=t.has("secrets")?Ar(e.secrets,"secrets").map(c=>{let a=c?.name;return typeof a=="string"&&ko.test(a)?a:Vt("Invalid secret name")}):[],r=e.network,n=t.has("network")?Ar(r?.hosts,"network").map(c=>typeof c=="string"&&fp.test(c)?c:Vt("Network hosts must be exact lowercase DNS names")):[],o=t.has("scheduler")?Ar(e.schedules,"schedules").map(c=>{let a=c;return!a||typeof a.id!="string"||!ko.test(a.id)||typeof a.action!="string"||!/^[\w.-]{1,80}$/.test(a.action)||!Number.isSafeInteger(a.intervalSec)||a.intervalSec<hp||a.intervalSec>86400?Vt("Invalid schedule declaration"):{id:a.id,intervalSec:a.intervalSec,action:a.action}}):[];return new Set(o.map(c=>c.id)).size!==o.length&&Vt("Duplicate schedule id"),{secrets:i,networkHosts:n,schedules:o,sessions:t.has("sessions")}}import{lookup as gp}from"node:dns/promises";import{isIP as mp}from"node:net";var wp=new Set(["GET","POST","PATCH","PUT","DELETE"]),yp=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),vp=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),Ei=(s,e)=>{throw new h("network_denied",s,{status:403,reason:e})};function bp(s){let e=s.toLowerCase().replace(/^::ffff:/,"");if(mp(e)===4){let[t,i]=e.split(".").map(Number);return t===0||t===10||t===127||t===169&&i===254||t===172&&i>=16&&i<=31||t===192&&i===168||t===100&&i>=64&&i<=127||t>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function Po(s,e,t,i,r){let n=i;if(!n||typeof n!="object"||typeof n.url!="string")throw new h("invalid_input","Invalid network request");let o;try{o=new URL(n.url)}catch{throw new h("invalid_input","Invalid URL")}(o.protocol!=="https:"||o.username||o.password||o.port&&o.port!=="443")&&Ei("Only plain https on port 443 is allowed","scheme"),e.includes(o.hostname)||Ei("Host is not declared by the plugin","host");let c=(n.method??"GET").toUpperCase();if(!wp.has(c))throw new h("invalid_input","Unsupported method");if(n.body!==void 0&&(typeof n.body!="string"||n.body.length>1024*1024))throw new h("invalid_input","Invalid body");let a={};for(let[E,_]of Object.entries(n.headers??{})){if(typeof _!="string"||yp.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(_))throw new h("invalid_input",`Header not allowed: ${E.slice(0,64)}`);a[E]=_}let l=null;if(n.secret!==void 0){if(t.includes(n.secret)||Ei("Secret is not declared by the plugin","secret"),l=await r.secrets.get(s,n.secret),!l)throw new h("secret_missing","Secret has not been configured",{status:412});a.Authorization=`Bearer ${l}`}let p=await(r.resolve??(async E=>(await gp(E,{all:!0})).map(_=>_.address)))(o.hostname);(!p.length||p.some(bp))&&Ei("Host resolves to a non-public address","address");let u=r.timeoutMs??2e4,y=r.maxResponseBytes??2*1024*1024,m=await(r.fetch??fetch)(o,{method:c,headers:a,body:n.body,redirect:"manual",signal:AbortSignal.timeout(u)}),f=[],w=0;if(m.body)for await(let E of m.body){if(w+=E.byteLength,w>y)throw new h("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let k=Buffer.concat(f).toString("utf8"),P={};return m.headers.forEach((E,_)=>{vp.has(_.toLowerCase())&&(P[_.toLowerCase()]=E)}),l&&(k=k.split(l).join("[redacted]")),{status:m.status,headers:P,body:k}}var xi=(s,e,t)=>{if(typeof s!="string"||!s||s.length>e)throw new h("invalid_input",`Invalid ${t}`);return s};async function Io(s,e,t,i,r,n){let o=r&&typeof r=="object"&&!Array.isArray(r)?r:{};if(i==="sessions.create"){if(o.mode!=="plan")throw new h("invalid_input","Plugin sessions must start in plan mode");if(s.activeCount(e)>=n)throw new h("quota_exceeded","Too many active plugin sessions",{status:429});return s.create({pluginId:e,cwd:t,title:xi(o.title,200,"title"),prompt:xi(o.prompt,64*1024,"prompt"),mode:"plan"})}let c=xi(o.sessionId,200,"sessionId");if(s.ownerOf(c)!==e)throw new h("session_denied","Session was not created by this plugin",{status:403});switch(i){case"sessions.send":if(o.mode!==void 0&&o.mode!=="execute")throw new h("invalid_input","Invalid mode");return await s.send(c,xi(o.message,64*1024,"message"),o.mode),{ok:!0};case"sessions.release":return await s.release(c),{ok:!0};case"sessions.abort":return await s.abort(c),{ok:!0};case"sessions.events":return s.events(c,Number.isSafeInteger(o.after)&&o.after>=0?o.after:0);default:throw new h("method_denied","Unknown sessions method")}}var kp=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),_i=class{options;constructor(e){this.options=e}handles(e){return kp.has(e)}async call(e,t,i,r,n){let o=yt(t);if(r==="network.fetch"){if(!o.networkHosts.length)throw new h("capability_denied","Plugin did not declare network access",{status:403});return Po(e,o.networkHosts,o.secrets,n,this.options)}if(!o.sessions||!this.options.sessions)throw new h("capability_denied","Sessions capability is unavailable",{status:403});return Io(this.options.sessions,e,i.scope.cwd,r,n,this.options.maxActiveSessions??3)}};var Ai=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,t){this.stop(e);let i=this.deps.setInterval??((r,n)=>{let o=setInterval(r,n);return o.unref(),o});this.timers.set(e,t.map(r=>i(()=>{this.tick(e,r)},r.intervalSec*1e3)))}stop(e){let t=this.deps.clearInterval??(i=>clearInterval(i));for(let i of this.timers.get(e)??[])t(i);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,t){let i=`${e}\0${t.id}`;if(this.running.has(i))return!1;this.running.add(i);try{return await this.deps.invoke(e,t),!0}catch(r){return this.deps.onError?.(e,t,r),!1}finally{this.running.delete(i)}}};import{createHash as Or,timingSafeEqual as Up}from"node:crypto";import{lstat as Ho,mkdtemp as Hr,readdir as Lp,readFile as zp,realpath as qp,rename as Gp,rm as ze,writeFile as Jp}from"node:fs/promises";import{tmpdir as Kp}from"node:os";import{join as U}from"node:path";import{gunzipSync as Ap}from"node:zlib";import{mkdir as Tp,writeFile as Rp}from"node:fs/promises";import{dirname as Cp,join as Dp}from"node:path";import{constants as Tr}from"node:fs";import{lstat as xo,open as Pp,readdir as So,realpath as _o}from"node:fs/promises";import{createHash as Ip}from"node:crypto";import{join as Ao,relative as Sp,resolve as Ep,sep as xp}from"node:path";var K={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024},_p={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],css:["text/css"],html:["text/html"],json:["application/json"],woff2:["font/woff2"],woff:["font/woff"],png:["image/png"],svg:["image/svg+xml"],txt:["text/plain"]},B=s=>Ip("sha256").update(s).digest("hex");function F(s){throw new h("invalid_package",s)}async function et(s,e,t){let i=e.split("/");(!i.length||i.some(c=>!c||c==="."||c===".."||!/^[\w.-]+$/.test(c)))&&F("Invalid resource path");let r=s;for(let c=0;c<i.length;c++){r=Ao(r,i[c]);let a=await xo(r);(a.isSymbolicLink()||(c<i.length-1?!a.isDirectory():!a.isFile()||a.nlink!==1))&&F("Links and non-regular package files are forbidden")}let n=await _o(r);(n!==Ep(s,e)||Sp(s,n).startsWith(`..${xp}`))&&F("Resource escapes package root");let o=await Pp(r,Tr.O_RDONLY|Tr.O_NONBLOCK|(Tr.O_NOFOLLOW??0));try{let c=await o.stat();(!c.isFile()||c.nlink!==1||c.size>t)&&F("Oversized or non-regular package file");let a=Buffer.alloc(Math.min(c.size+1,t+1)),l=0;for(;l<a.length;){let p=await o.read(a,l,a.length-l,l);if(!p.bytesRead)break;l+=p.bytesRead}return(l>t||l!==c.size)&&F("Package resource changed during read"),a.subarray(0,l)}finally{await o.close()}}function Eo(s){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(s))}catch{return F("Invalid package JSON")}}async function tt(s,e){let t=await _o(s);(await xo(s)).isSymbolicLink()&&F("Package root cannot be a symlink");let i=Eo(await et(t,"package.json",K.other));(!i||typeof i.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(i.name)||i.name.length>214||e&&i.name!==e)&&F("Package identity mismatch"),(typeof i.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(i.version))&&F("Invalid package version"),Ue(i.piWebapp)||F("Unsupported hosted manifest"),i.type!=="module"&&F("Hosted package must declare ESM module type");for(let u of await So(t,{withFileTypes:!0}))u.name==="dist"&&u.isDirectory()||(!u.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(u.name))&&F("Undeclared package-root asset or code");i.scripts&&Object.keys(i.scripts).some(u=>/^(?:preinstall|install|postinstall|prepare)$/.test(u))&&F("Hosted packages cannot run install lifecycle scripts");for(let u of["dependencies","optionalDependencies"]){let y=i[u];y&&(typeof y!="object"||Object.keys(y).length>0)&&F("Hosted packages must contain all runtime dependencies")}let r=i.piWebapp,n=Eo(await et(t,r.resourcesManifest.slice(2),K.other));(!n||n.version!==1||!Array.isArray(n.files)||!n.files.length||n.files.length>K.files)&&F("Invalid resource manifest");let o=new Map,c=0;for(let u of n.files){(!u||typeof u!="object")&&F("Invalid resource entry");let y=u,m={...y,path:typeof y.path=="string"&&y.path.startsWith("./")?y.path.slice(2):y.path};(!Xe(`./${m.path}`)||typeof m.sha256!="string"||!/^[a-f0-9]{64}$/.test(m.sha256)||!Number.isSafeInteger(m.bytes)||m.bytes<0||o.has(m.path))&&F("Invalid or duplicate resource");let f=m.path.split(".").at(-1);_p[f]?.includes(m.mime)||F("Unsupported resource MIME");let w=f==="js"||f==="mjs"?K.js:f==="css"?K.css:f==="woff"||f==="woff2"?K.font:K.other;(m.bytes>w||(c+=m.bytes)>K.total)&&F("Resource budget exceeded");let k=await et(t,m.path,w);(k.length!==m.bytes||B(k)!==m.sha256)&&F("Resource integrity mismatch"),o.set(m.path,Object.freeze({...m}))}for(let u of[r.backend.entry,r.frontend.document,r.frontend.controller])o.has(u.slice(2))||F("Entrypoint is absent from resource manifest");let a=0;async function l(u,y=0){y>16&&F("Package directory nesting limit exceeded");for(let m of await So(Ao(t,u),{withFileTypes:!0})){++a>K.files*2&&F("Too many package entries");let f=`${u}/${m.name}`;(m.isSymbolicLink()||!m.isDirectory()&&!m.isFile())&&F("Invalid archive member"),m.isDirectory()?await l(f,y+1):f!==r.resourcesManifest.slice(2)&&!o.has(f)&&F("Undeclared distribution asset")}}await l("dist");let p=B(JSON.stringify({id:i.name,version:i.version,manifest:r,resources:[...o.values()].sort((u,y)=>u.path.localeCompare(y.path))}));return{id:i.name,version:i.version,root:t,manifest:r,resources:o,digest:p}}async function To(s,e,t){if(t!==s.digest||e.length>1536)return null;let i;try{i=decodeURIComponent(e)}catch{return null}if(!Xe(`./${i}`))return null;let r=s.resources.get(i);if(!r||i===s.manifest.backend.entry.slice(2))return null;let n=await et(s.root,i,r.bytes);if(n.length!==r.bytes||B(n)!==r.sha256)throw new h("resource_changed","Installed resource integrity mismatch");return{bytes:n,mime:r.mime}}var Ti=64*1024*1024,Np=K.total+K.files*2048,V=s=>{throw new h("invalid_archive",s)};function vt(s){let e=s.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?s:s.subarray(0,e))}catch{return V("Archive has invalid UTF-8 paths")}}function Ro(s){let e=vt(s).trim();if(!/^[0-7]+$/.test(e))return V("Unsupported archive number encoding");let t=parseInt(e,8);return Number.isSafeInteger(t)?t:V("Archive number exceeds limits")}function Hp(s){let e=s.endsWith("/")?s.slice(0,-1):s;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return V("Archive must have one package root");let t=e.slice(8);return t.split("/").some(i=>!i||i==="."||i===".."||!/^[A-Za-z0-9_@.-]+$/.test(i))?V("Archive path is not a safe relative package path"):t}function Op(s){let e={},t=0;for(;t<s.length;){let i=s.indexOf(32,t);if(i<0)return V("Invalid PAX header");let r=s.subarray(t,i).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(r))return V("Invalid PAX record length");let n=Number(r),o=t+n;if(o>s.length||o<=i+2||s[o-1]!==10)return V("Truncated PAX record");let c=vt(s.subarray(i+1,o-1)),a=c.indexOf("=");if(a<1)return V("Invalid PAX record");let l=c.slice(0,a),p=c.slice(a+1);if(Object.hasOwn(e,l)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(l))return V("Unsupported PAX feature");e[l]=p,t=o}return e}function Mp(s){if(!s.length||s.length>Ti)return V("Compressed archive exceeds budget");let e;try{e=Ap(s,{maxOutputLength:Np})}catch{return V("Invalid or oversized gzip archive")}let t=[],i=new Set,r=0,n=0,o=0,c=0,a=null,l=!1;for(;r+512<=e.length;){let u=e.subarray(r,r+512);if(r+=512,u.every(H=>H===0)){if(a||e.subarray(r).some(H=>H!==0))return V("Unexpected archive data after end marker");l=!0;break}if(++c>K.files*2)return V("Too many archive headers");let y=0;for(let H=0;H<512;H++)y+=H>=148&&H<156?32:u[H];if(Ro(u.subarray(148,156))!==y)return V("Invalid tar header checksum");let m=vt(u.subarray(257,263));if(m&&m!=="ustar"&&m!=="ustar ")return V("Unsupported tar format");let f=u[156],w=vt(u.subarray(345,500)),k=(w?w+"/":"")+vt(u.subarray(0,100)),P=Ro(u.subarray(124,136));if(a&&(a.path!==void 0&&(k=a.path),a.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(a.size))return V("Invalid PAX size");P=Number(a.size)}if(!Number.isSafeInteger(P)||P<0||P>K.total||r+P>e.length)return V("Truncated or oversized tar member");let E=e.subarray(r,r+P);if(r+=Math.ceil(P/512)*512,f===120){if(a||P>8192)return V("Oversized or chained PAX header");a=Op(E);continue}if(a=null,f!==0&&f!==48&&f!==53)return V("Links and special archive members are forbidden");let _=f===53;if(_&&P!==0||vt(u.subarray(157,257)))return V("Invalid archive link or directory");if(k=Hp(k),!k&&!_)return V("Invalid package root member");if(i.has(k))return V("Duplicate archive member");if(i.add(k),++n>K.files||(o+=P)>K.total)return V("Unpacked archive exceeds budget");t.push({path:k,data:E,directory:_})}if(!l||!i.has("package.json"))return V("Archive is incomplete or has no package.json");let p=new Set(t.filter(u=>!u.directory).map(u=>u.path));for(let u of t){let y=u.path.split("/");for(let m=1;m<y.length;m++)if(p.has(y.slice(0,m).join("/")))return V("Archive file/directory collision")}return t}async function Rr(s,e){let t=Mp(s);for(let i of t){if(!i.path)continue;let r=Dp(e,i.path);await Tp(i.directory?r:Cp(r),{recursive:!0,mode:448}),i.directory||await Rp(r,i.data,{flag:"wx",mode:384})}}import{lstat as jp,mkdir as Wp,readdir as $p,realpath as Vp,writeFile as Fp}from"node:fs/promises";import{dirname as Bp,join as Cr}from"node:path";async function Co(s,e){let t=await Vp(s),i=await et(t,"package.json",K.other),r;try{r=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new h("invalid_package","package.json is not valid JSON")}if(!r||typeof r!="object"||Array.isArray(r))throw new h("invalid_package","package.json must be an object");let n=[],o=0,c=0;async function a(y,m){if(m>16)throw new h("invalid_package","Package directory nesting limit exceeded");for(let f of await $p(Cr(t,y),{withFileTypes:!0})){let w=`${y}/${f.name}`;if(++o>K.files)throw new h("invalid_package","Too many package entries");if(f.isDirectory()){await a(w,m+1);continue}if(!f.isFile())throw new h("invalid_package",`Links and non-regular files are forbidden: ${w}`);let k=await et(t,w,K.js);if((c+=k.length)>K.total)throw new h("invalid_package","Resource budget exceeded");let P=Cr(e,w);await Wp(Bp(P),{recursive:!0,mode:448}),await Fp(P,k,{flag:"wx",mode:384}),n.push([w,B(k)])}}let l;try{l=await jp(Cr(t,"dist"))}catch(y){throw y.code==="ENOENT"?new h("dist_missing","dist/ does not exist yet; build the plugin first"):y}if(!l.isDirectory())throw new h("invalid_package","dist must be a real directory");await a("dist",0);let{version:p,...u}=r;return n.sort((y,m)=>y[0].localeCompare(m[0])),{contentHash:B(JSON.stringify({package:u,files:n})),packageJson:r}}function ke(s){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(s);return!e||e[0]!==s||e.slice(1).some(t=>!Number.isSafeInteger(Number(t)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function Ce(s,e){let t=ke(s),i=ke(e);if(!t||!i)throw new h("invalid_version","Only exact stable semantic versions are supported");return t.major-i.major||t.minor-i.minor||t.patch-i.patch}function Do(s){let e=ke(s);if(e)return e;if(!ai(s))return null;let[t,i]=s.split("-alpha."),r=ke(t),n=Number(i);return r&&Number.isSafeInteger(n)?{...r,alpha:n}:null}function Dr(s){return!!Do(s)}function bt(s,e){if(!Dr(s)||typeof e!="string"||e.length>256)return!1;let t=e.split("||");if(!t.length||t.some(r=>!r.trim()))return!1;let i=[];for(let r of t){let n=r.trim().split(/\s+/),o=!0;for(let c of n){let a=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(c),l=a&&Do(a[2]);if(!a||!l)return!1;let p=a[2],u=ue(s,p);switch(a[1]??"="){case"=":o&&=u===0;break;case">=":o&&=u>=0;break;case"<=":o&&=u<=0;break;case">":o&&=u>0;break;case"<":o&&=u<0;break;case"~":o&&=u>=0&&ue(s,`${l.major}.${l.minor+1}.0-0`)<0;break;case"^":{let y=l.major?`${l.major+1}.0.0`:l.minor?`0.${l.minor+1}.0`:`0.0.${l.patch+1}`;o&&=u>=0&&ue(s,`${y}-0`)<0;break}}}i.push(o)}return i.some(Boolean)}var Me=Object.freeze([Object.freeze({id:"@chengzhiyi/pi-excalidraw",name:"Excalidraw",icon:"drawing",description:{zh:"\u672C\u5730\u624B\u7ED8\u753B\u5E03\u3001AI \u7ED8\u56FE\u53CA\u5DE5\u4F5C\u533A\u56FE\u7A3F\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"Local sketch canvas, AI diagrams and workspace drawings. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","workspace","legacy","panels","messages"]})]);function me(s,e=Me){let t=e.find(i=>i.id===s);if(!t)throw new h("unknown_plugin","Plugin is not in the trusted official catalog");return t}function Nr(s,e,t){let i=s.piWebapp;return s.name===e.id&&!!ke(s.version)&&!s.deprecated&&Ue(i)&&bt(t,i.hostRange)&&e.requiredCapabilities.every(r=>i.capabilities.includes(r))}function No(s,e,t,i,r){if(!s||typeof s!="object"||!("versions"in s)||!s.versions||typeof s.versions!="object"||Array.isArray(s.versions))throw new h("registry_invalid","Invalid registry version catalog");let n=Object.entries(s.versions);if(n.length>1e4)throw new h("registry_invalid","Registry version catalog exceeds budget");let c=n.flatMap(([a,l])=>{if(!l||typeof l!="object")return[];let p=l;return p.version===a&&Nr(p,e,t)&&(!r||a===r)&&(!i||Ce(a,i)>=0)?[p]:[]}).sort((a,l)=>Ce(l.version,a.version))[0];if(!c)throw new h("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!c.dist||typeof c.dist.tarball!="string"||typeof c.dist.integrity!="string")throw new h("registry_invalid","Release is missing its immutable tarball integrity");return c}function Xp(s,e){let t=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!t)throw new h("invalid_integrity","A single SHA-512 tarball integrity is required");let i=Buffer.from(t[1],"base64"),r=Or("sha512").update(s).digest();if(i.length!==r.length||!Up(i,r))throw new h("integrity_mismatch","Downloaded package failed integrity verification")}var it=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Dr(e.hostVersion))throw new h("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Me,this.fetcher=e.fetch??Ln}async index(){let e=await ee(U(this.root,"installed.json"));if(!e){if(await X(U(this.root,"installed.json"),2*1024*1024))throw new h("invalid_storage","Null installation index; restore metadata before cleanup");return{schema:1,revision:0,versions:{}}}if(e.schema!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!e.versions||typeof e.versions!="object"||Array.isArray(e.versions))throw new h("invalid_storage","Invalid plugin installation index");for(let[t,i]of Object.entries(e.versions))if(this.catalog.some(r=>r.id===t)){if(!Array.isArray(i)||i.length>16||new Set(i.map(r=>r.version)).size!==i.length)throw new h("invalid_storage","Invalid installed version list");for(let r of i)this.validateRecord(t,r)}return e}validateRecord(e,t){if(!t||!ke(t.version)||!/^[a-f0-9]{64}$/.test(t.digest)||t.directory!==`${B(e)}/${t.version}-${t.digest}`||typeof t.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(t.integrity)||typeof t.installedAt!="string")throw new h("invalid_storage","Invalid installed plugin record")}path(e){return U(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),t=await ce(U(this.root,"install-journal.json"));if(t){if(t.schema!==1||Object.keys(t).some(n=>!["schema","pluginId","next"].includes(n)))throw new h("invalid_storage","Invalid install journal");me(t.pluginId,this.catalog),this.validateRecord(t.pluginId,t.next);let r=e.versions[t.pluginId]?.find(n=>n.version===t.next.version);if(r&&r.digest!==t.next.digest)throw new h("invalid_storage","Conflicting installation journal");await ze(U(this.root,"install-journal.json"))}await this.recoverCollection(e);let i=U(this.root,"staging");await Z(i);for(let r of await Lp(i)){if(!/^stage-[A-Za-z0-9]+$/.test(r)||(await Ho(U(i,r))).isSymbolicLink())throw new h("invalid_storage","Invalid abandoned staging directory");await ze(U(i,r),{recursive:!0})}return e}async recoverCollection(e){let t=U(this.root,"gc-journal.json"),i=await ce(t);if(!i)return;if(i.schema!==1||Object.keys(i).some(n=>!["schema","pluginId","records"].includes(n))||!Array.isArray(i.records)||!i.records.length)throw new h("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");me(i.pluginId,this.catalog);for(let n of i.records)this.validateRecord(i.pluginId,n);let r=i.records.filter(n=>e.versions[i.pluginId]?.some(o=>o.directory===n.directory));if(r.length&&r.length!==i.records.length)throw new h("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!r.length){await Z(U(this.root,"versions")),await Z(U(this.root,"versions",B(i.pluginId)));for(let n of i.records)await ze(this.path(n),{recursive:!0,force:!0})}await ze(t)}async collect(e,t){return me(e,this.catalog),W(this.root,async()=>{let i=await this.recoverLocked(),r=i.versions[e]??[],n=new Set(await t()),o=r.at(-1);o&&n.add(o.version);let c=r.filter(a=>!n.has(a.version));return await this.removeLocked(e,i,c),c.map(a=>a.version)})}async removeLocked(e,t,i){i.length&&(await Z(U(this.root,"versions")),await Z(U(this.root,"versions",B(e))),await j(U(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:i}),t.versions[e]=(t.versions[e]??[]).filter(r=>!i.some(n=>n.directory===r.directory)),t.revision++,await j(U(this.root,"installed.json"),t),await this.recoverCollection(t))}async inventory(){return W(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,t){let i;try{i=new URL(e)}catch{throw new h("registry_denied","Invalid registry URL")}let r=new URL(t.registry);if(i.protocol!=="https:"||i.origin!==r.origin||i.username||i.password||i.hash||i.search)throw new h("registry_denied","Only the official registry origin is permitted");return i}async download(e,t,i,r="tarball"){let n=AbortSignal.any([AbortSignal.timeout(6e4),...i?[i]:[]]),o;try{o=await this.fetcher(e,{redirect:"error",signal:n,headers:{Accept:"application/json, application/octet-stream"}})}catch(u){throw i?.aborted?i.reason:new h("registry_unreachable",u instanceof Error?u.message:"Registry network request failed")}if(!o.ok||!o.body)throw await o.body?.cancel().catch(()=>{}),new h(o.status===404?`${r}_not_found`:"download_failed",`Registry ${r} request failed (${o.status})`);if(o.url&&new URL(o.url).origin!==e.origin)throw new h("registry_denied","Registry redirect is forbidden");let c=o.body.getReader(),a=[],l=0,p=()=>{c.cancel(n.reason).catch(()=>{})};n.addEventListener("abort",p,{once:!0});try{if(n.throwIfAborted(),Number(o.headers.get("content-length"))>t)throw new h("download_too_large","Registry response exceeds budget");for(;;){let u=await c.read();if(u.done)break;if(l+=u.value.length,l>t)throw new h("download_too_large","Registry response exceeds budget");a.push(Buffer.from(u.value))}return n.throwIfAborted(),Buffer.concat(a)}catch(u){throw i?.aborted?i.reason:u instanceof h?u:new h("registry_unreachable",u instanceof Error?u.message:"Registry response interrupted")}finally{n.removeEventListener("abort",p),await c.cancel().catch(()=>{}),c.releaseLock()}}async check(e,t,i,r){let n=me(e,this.catalog);if(i&&!ke(i))throw new h("invalid_version","Choose an exact stable version");let o=this.trustedUrl(`${n.registry}/${encodeURIComponent(e)}`,n),c,a=await this.download(o,8*1024*1024,r,"metadata");try{c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{throw new h("registry_invalid","Invalid registry metadata JSON")}return No(c,n,this.hostVersion,t,i)}async install(e,t,i){let r=me(e,this.catalog);if(!Nr(t,r,this.hostVersion))throw new h("incompatible_plugin","Plugin release is incompatible with this host");let n=await this.download(this.trustedUrl(t.dist.tarball,r),Ti,i);return this.installArchive(e,n,t.dist.integrity,t.version,i)}async installArchive(e,t,i,r,n){let o=me(e,this.catalog);if(!ke(r))throw new h("invalid_version","Choose an exact stable version");if(t.length>Ti)throw new h("download_too_large","Package archive exceeds budget");return Xp(t,i),W(this.root,async()=>{let c=await this.recoverLocked();n?.throwIfAborted();let a=await Hr(U(this.root,"staging","stage-"));try{await Rr(t,a),n?.throwIfAborted();let l=await tt(a,e);if(l.version!==r||!Ue(l.manifest)||!bt(this.hostVersion,l.manifest.hostRange)||!o.requiredCapabilities.every(p=>l.manifest.capabilities.includes(p)))throw new h("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,c,a,l,i,n)}finally{await ze(a,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,t,i,r,n,o){let c=t.versions[e]?.find(u=>u.version===r.version);if(c&&c.digest!==r.digest)throw new h("version_replaced","An installed immutable version cannot be replaced with different content");let a={version:r.version,digest:r.digest,integrity:n,directory:`${B(e)}/${r.version}-${r.digest}`,installedAt:new Date().toISOString()};if(await Z(U(this.root,"versions",B(e))),!c&&(t.versions[e]?.length??0)>=16)throw new h("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await j(U(this.root,"install-journal.json"),{schema:1,pluginId:e,next:a});let l=this.path(a),p=!1;try{await Ho(l),p=!0}catch(u){if(!Ve(u))throw u}if(p){if((await tt(l,e)).digest!==r.digest)throw new h("resource_changed","Installed package content was modified")}else await Gp(i,l);return o?.throwIfAborted(),c||(t.versions[e]=[...t.versions[e]??[],a],t.revision++,await j(U(this.root,"installed.json"),t)),await ze(U(this.root,"install-journal.json")),{...r,root:await qp(l)}}async installDevArchive(e,t,i){me(e,this.catalog);let r=await zp(t),n="sha512-"+Or("sha512").update(r).digest("base64"),o=await Hr(U(Kp(),"pi-dev-archive-"));try{await Rr(r,o);let c=(await tt(o,e)).version;return await this.installArchive(e,r,n,c,i)}finally{await ze(o,{recursive:!0,force:!0})}}async installDevDirectory(e,t,i){let r=me(e,this.catalog);return W(this.root,async()=>{let n=await this.recoverLocked();i?.throwIfAborted();let o=await Hr(U(this.root,"staging","stage-"));try{let{contentHash:c,packageJson:a}=await Co(t,o);i?.throwIfAborted();let l=U(this.root,"dev-sources.json"),p=await ee(l)??{},u=p[e],y=n.versions[e]??[],m=u?.contentHash===c?y.find(T=>T.version===u.version):void 0;if(m){let T=await tt(this.path(m),e);if(T.digest!==m.digest)throw new h("resource_changed","Installed package integrity changed");return T}let f=typeof a.version=="string"?ke(a.version):null;if(!f)throw new h("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let w=Math.max(-1,...y.map(T=>ke(T.version)).filter(T=>T&&T.major===f.major&&T.minor===f.minor).map(T=>T.patch)),k=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),w+1),P=`${f.major}.${f.minor}.${k}`;await Jp(U(o,"package.json"),JSON.stringify({...a,version:P},null,2),{flag:"wx",mode:384});let E=await tt(o,e);if(!bt(this.hostVersion,E.manifest.hostRange))throw new h("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let _=r.requiredCapabilities.filter(T=>!E.manifest.capabilities.includes(T));if(_.length)throw new h("incompatible_plugin",`Package lacks required capabilities: ${_.join(", ")}`);let H="sha512-"+Or("sha512").update(c).digest("base64"),N=await this.commitStaged(e,n,o,E,H,i);return p[e]={contentHash:c,version:P},await j(l,p),N}finally{await ze(o,{recursive:!0,force:!0})}},1e4)}async load(e,t){let i=me(e,this.catalog);return W(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]?.find(c=>c.version===t);if(!n)throw new h("not_installed","Plugin version is not installed");let o=await tt(this.path(n),e);if(o.digest!==n.digest)throw new h("resource_changed","Installed package integrity changed");if(!bt(this.hostVersion,o.manifest.hostRange)||!i.requiredCapabilities.every(c=>o.manifest.capabilities.includes(c)))throw new h("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return o})}async removeVersions(e,t){me(e,this.catalog),await W(this.root,async()=>{let i=await this.recoverLocked(),n=(i.versions[e]??[]).filter(o=>t.includes(o.version));await this.removeLocked(e,i,n)})}};import{lstat as Ri,mkdir as Yp,open as Oo,realpath as Mo,readdir as Mr,link as Qp,rename as Zp,unlink as rt,copyFile as eu,rm as tu}from"node:fs/promises";import{dirname as iu,isAbsolute as jo,join as O,relative as Wo,resolve as ru,sep as jr,win32 as su}from"node:path";import{randomUUID as Wr}from"node:crypto";var Ft=192*1024*1024,Bt=512*1024,Vo=s=>typeof s=="string"&&/^[a-f0-9-]{36}$/.test(s);function nu(s){if(!s||typeof s!="object"||Array.isArray(s))throw new h("invalid_input","Expected object input");return s}function $o(s){if(typeof s!="string"||!/^[\w.-]{1,160}$/.test(s)||s==="."||s==="..")throw new h("invalid_input","Invalid state key");return s}function Ut(s){if(s&&(!Vo(s.stateRef)||typeof s.version!="string"||!Number.isSafeInteger(s.generation)||s.generation<1||!Number.isSafeInteger(s.schema)||s.schema<1||typeof s.enabled!="boolean"||typeof s.operationId!="string"))throw new h("invalid_storage","Invalid active plugin record");return s}var st=class{root;pluginId;legacy;checkpoint;constructor(e,t,i,r){this.root=O(e,B(t)),this.pluginId=t,this.legacy=i,this.checkpoint=r}active(){return ee(O(this.root,"active.json")).then(Ut)}async recover(){return W(this.root,async()=>{let e=await this.active(),t=await ce(O(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(o=>!["version","before","next"].includes(o))||Object.hasOwn(t,"version")&&t.version!==1)throw new h("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Ut(t.next),Ut(t.before);let i=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((o,c)=>o===null||c===null?o===c:["version","generation","stateRef","schema","enabled","operationId"].every(a=>o[a]===c[a]))(e,i==="committed"?t.next:t.before))throw new h("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let n=t.before;if(i==="committed"&&n&&n.stateRef!==e.stateRef&&await j(O(this.root,"previous.json"),n),i==="committed"){let o=await ce(O(this.root,"fork.json"));o?.version===1&&o.stateRef===e.stateRef&&Object.keys(o).every(c=>["version","stateRef"].includes(c))&&await rt(O(this.root,"fork.json"))}return await rt(O(this.root,"transition.json")),{active:e,recovered:i}})}async activate(e,t){return W(this.root,async()=>{let i=await this.active();if((i?.generation??0)!==e)throw new h("stale_generation","Plugin activation changed concurrently");let r=await ce(O(this.root,"fork.json"));if(r&&(r.version!==1||r.stateRef!==t.stateRef||Object.keys(r).some(o=>!["version","stateRef"].includes(o))))throw new h("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let n=Ut({...t,generation:e+1,operationId:Wr()});await Z(O(this.root,"states")),await Z(O(this.root,"states",n.stateRef)),await j(O(this.root,"transition.json"),{version:1,before:i,next:n}),await this.checkpoint?.("prepared");try{await j(O(this.root,"active.json"),n)}catch(o){if((await this.active())?.operationId!==n.operationId)throw o}await this.checkpoint?.("committed");try{i&&i.stateRef!==n.stateRef&&await j(O(this.root,"previous.json"),i),await rt(O(this.root,"transition.json")),await rt(O(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),n})}async forkState(e){return W(this.root,async()=>{let t=await this.assertGeneration(e,!1),i=Wr(),r=O(this.root,"states",i);if(await ce(O(this.root,"fork.json")))throw new h("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await j(O(this.root,"fork.json"),{version:1,stateRef:i}),await Z(r);let n=O(this.root,"states",t.stateRef);for(let o of await Mr(n)){if(!/^[a-f0-9]{64}\.json$/.test(o))throw new h("invalid_storage","Unexpected state file");if(!await X(O(n,o),Ft))throw new h("invalid_storage","Missing state file");await eu(O(n,o),O(r,o))}return await this.checkpoint?.("forked"),i})}async collect(e){return W(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await X(O(this.root,l),2*1024*1024))throw new h("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),i=Ut(await ce(O(this.root,"previous.json")));if(!t&&await X(O(this.root,"active.json"),2*1024*1024))throw new h("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let r=[t,i].filter(l=>!!l),n=O(this.root,"states");await Z(n);let o=await Mr(n),c=new Set(r.map(l=>l.stateRef));for(let l of o){if(!Vo(l))throw new h("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=O(n,l),u=await Ri(p);if(!u.isDirectory()||u.isSymbolicLink())throw new h("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let y of await Mr(p)){let m=await Ri(O(p,y));if(!/^[a-f0-9]{64}\.json$/.test(y)||!m.isFile()||m.isSymbolicLink()||m.nlink!==1)throw new h("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let f=await ee(O(p,y),Ft);if(!f)throw new h("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(f,"committed")){let w=f;if(Object.keys(w).some(k=>!["requestId","inputHash","nextHash","committed"].includes(k))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new h("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(f).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new h("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(f)}}}}for(let l of c)if(!o.includes(l))throw new h("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let a=await e(r);for(let l of o)c.has(l)||await tu(O(n,l),{recursive:!0,force:!0});return a})}async assertGeneration(e,t=!0){let i=await this.active();if(!i||i.generation!==e||t&&!i.enabled)throw new h("stale_generation","Plugin generation is no longer active");return i}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new h("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,i,r="session"){if(r!=="session"&&r!=="workspace")throw new h("invalid_input","Invalid state scope");let n=r==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return O(this.root,"states",e.stateRef,`${B(n+":state:"+i)}.json`)}async call(e,t,i){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new h("invalid_lease","Invalid invocation lease");this.scopeKey(e);let r=nu(i);return W(this.root,async()=>{let n=await this.assertGeneration(e.generation);switch(t){case"state.read":{let o=await ee(this.statePath(n,e,$o(r.key),r.scope),Ft);return o?(this.validateState(o),{revision:o.revision,schema:o.schema,value:o.value}):null}case"state.compareAndSwap":{let o=this.statePath(n,e,$o(r.key),r.scope);if(!Number.isSafeInteger(r.expectedRevision)||r.expectedRevision<0||r.schema!==n.schema||!Object.hasOwn(r,"value"))throw new h("invalid_input","Invalid state revision or schema");if(JSON.stringify(r.value)===void 0)throw new h("invalid_input","State value must be JSON serializable");let c=JSON.stringify(r);if(Buffer.byteLength(c)>Ft)throw new h("state_too_large","Plugin state exceeds limit");let a=await ee(o,Ft);a&&this.validateState(a);let l=B(c);if(a?.requestId===e.requestId&&a.inputHash===l)return{revision:a.revision,schema:a.schema,value:a.value};if((a?.revision??0)!==r.expectedRevision)throw new h("revision_conflict","Plugin state changed concurrently");let p={revision:r.expectedRevision+1,schema:n.schema,value:r.value,requestId:e.requestId,inputHash:l};return await j(o,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let{target:o}=await this.fileTarget(e.scope.cwd,r.path),c=r.maxBytes===void 0?Bt:r.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>Bt)throw new h("invalid_input","Invalid workspace read limit");let a=await X(o,c);return a?{text:new TextDecoder("utf-8",{fatal:!0}).decode(a),hash:B(a)}:null}case"workspace.commit":return this.commitFile(n,e,r);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new h("method_denied","Unknown host broker method")}})}validateState(e){if(!Number.isSafeInteger(e.revision)||e.revision<1||!Number.isSafeInteger(e.schema)||e.schema<1||!Object.hasOwn(e,"value")||typeof e.requestId!="string"||!/^[a-f0-9]{64}$/.test(e.inputHash))throw new h("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,i=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||jo(t)||su.isAbsolute(t))throw new h("invalid_path","Use a workspace-relative .excalidraw path");let r=await Mo(e),n=ru(r,t),o=Wo(r,n);if(!o||o===".."||o.startsWith(`..${jr}`)||jo(o))throw new h("invalid_path","Workspace path escapes root");let c=r,a=o.split(jr);for(let p=0;p<a.length;p++){c=O(c,a[p]);let u;try{u=await Ri(c)}catch(y){if(!Ve(y))throw y;if(p<a.length-1){if(!i||Wo(r,c)!=="diagrams")throw new h("invalid_path","Workspace directory does not exist");try{await Yp(c,{mode:448})}catch(m){if(m.code!=="EEXIST")throw m}u=await Ri(c)}}if(u&&(u.isSymbolicLink()||(p<a.length-1?!u.isDirectory():!u.isFile()||u.nlink!==1)))throw new h("invalid_path","Workspace path contains a link or non-regular file")}let l=await Mo(iu(n));if(l!==r&&!l.startsWith(r+jr))throw new h("invalid_path","Workspace directory changed");return{target:n,parent:l}}async commitFile(e,t,i){if(typeof i.text!="string"||Buffer.byteLength(i.text)>Bt||!(i.expectedHash===null||typeof i.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(i.expectedHash)))throw new h("invalid_input","Invalid file content or expected hash");let{target:r,parent:n}=await this.fileTarget(t.scope.cwd,i.path,!0),o=O(this.root,"states",e.stateRef,`${B(this.scopeKey(t)+":file:"+t.requestId+":"+String(i.path))}.json`),c=B(JSON.stringify(i)),a=B(i.text),l=await ee(o);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==a))throw new h("duplicate_request","Request ID was reused with different content");let p;try{p=await Oo(`${r}.lock`,"wx",384)}catch(y){throw y.code==="EEXIST"?new h("file_busy","Workspace file is locked; original file preserved"):y}let u;try{await p.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let y=await X(r,Bt),m=y?B(y):null;if(l&&m===a)return{hash:a};if(l?.committed||m!==i.expectedHash)throw new h("file_conflict","Workspace file already exists or changed externally");await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!1}),u=O(n,`.plugin-${Wr()}.tmp`);let f=await Oo(u,"wx",384);try{await f.writeFile(i.text),await f.sync()}finally{await f.close()}if((await this.fileTarget(t.scope.cwd,i.path)).parent!==n)throw new h("file_conflict","Workspace directory changed during save");let k=await X(r,Bt);if((k?B(k):null)!==i.expectedHash)throw new h("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),i.expectedHash===null){try{await Qp(u,r)}catch(P){throw P.code==="EEXIST"?new h("file_conflict","Workspace file was created concurrently"):P}await rt(u),u=void 0}else await Zp(u,r),u=void 0;return await j(o,{requestId:t.requestId,inputHash:c,nextHash:a,committed:!0}),{hash:a}}finally{u&&await rt(u).catch(()=>{}),await p.close(),await rt(`${r}.lock`)}}};import{randomUUID as du}from"node:crypto";import{fork as ou}from"node:child_process";import{randomUUID as au}from"node:crypto";import{join as cu}from"node:path";import{EventEmitter as lu}from"node:events";var Fo=192*1024*1024,Lt=class s{child;pending=new Map;events=new lu;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,t,i,r){this.package=e,this.generation=t,this.broker=r;let n={};for(let o of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[o]&&(n[o]=process.env[o]);this.child=ou(i,[],{env:n,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",o=>{this.receive(o)}),this.child.once("error",o=>this.fail(o)),this.child.once("exit",()=>this.fail(new h("worker_exited","Plugin process exited")))}get pid(){return this.child.pid}get inFlight(){return[...this.pending.values()].filter(e=>!!e.invocation).length}get healthy(){return!this.stopped&&!this.unhealthy&&!this.closing}static async start(e,t,i,r,n=1e4){let o=new s(e,t,i,r);try{await o.request("initialize",{entry:cu(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:t},n);let c=await o.request("describe",void 0,n);if(!c||!Array.isArray(c.tools)||c.tools.length>128)throw new h("invalid_tools","Invalid hosted tool catalog");let a=new Set;for(let l of c.tools){if(!l||typeof l.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(l.name)||a.has(l.name)||typeof l.label!="string"||typeof l.description!="string"||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!l.parameters||typeof l.parameters!="object"||Array.isArray(l.parameters)||l.parameters.type!=="object")throw new h("invalid_tools","Invalid or duplicate tool descriptor");a.add(l.name)}return o.tools=structuredClone(c.tools),await o.request("health",void 0,n),o}catch(c){throw await o.dispose(),c}}fail(e){this.stopped=!0;for(let t of this.pending.values())clearTimeout(t.timer),t.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let t;try{t=Buffer.byteLength(JSON.stringify(e))}catch{return}if(t>Fo){this.unhealthy=!0;return}let i=e;if(i.type==="response"&&typeof i.id=="string"){let r=this.pending.get(i.id);if(!r)return;if(clearTimeout(r.timer),this.pending.delete(i.id),!r.expired){let n=i.error;i.ok===!0?r.resolve(i.value):r.reject(new h(n?.code??"plugin_failed",n?.message??"Plugin request failed",n))}this.inFlight||this.events.emit("idle")}else if(i.type==="broker-request"&&typeof i.id=="string"&&typeof i.invocationId=="string"&&typeof i.method=="string"){let r=this.pending.get(i.invocationId);try{if(!r?.invocation||r.expired)throw new h("invalid_lease","Plugin invocation lease is no longer writable");let n=await this.broker(r.invocation,i.method,i.input);this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!0,value:n})}catch(n){this.child.connected&&this.child.send({type:"broker-response",id:i.id,ok:!1,error:G(n)})}}}request(e,t,i=3e4,r){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new h("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new h("worker_busy","Too many plugin requests"));let n=r?.requestId??au();if(this.pending.has(n))return Promise.reject(new h("duplicate_request","An identical request is still running"));let o={type:"request",id:n,method:e,input:t};return Buffer.byteLength(JSON.stringify(o))>Fo?Promise.reject(new h("message_too_large","Plugin request exceeds limit")):new Promise((c,a)=>{let l=setTimeout(()=>{let p=this.pending.get(n);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(n),a(new h("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},i);this.pending.set(n,{resolve:c,reject:a,timer:l,invocation:r,expired:!1}),this.child.send(o,p=>{p&&(clearTimeout(l),this.pending.delete(n),a(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,t=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,t,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(t=>{let i=()=>{clearTimeout(r),this.events.off("idle",i),t(!0)},r=setTimeout(()=>{this.events.off("idle",i),t(!1)},e);this.events.once("idle",i)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new h("worker_busy","Refusing to kill a plugin with in-flight operations");if(!this.closing){this.closing=!0;try{await this.request("dispose",void 0,2e3)}catch{}this.stopped||await new Promise(e=>{let t=()=>{clearTimeout(i),e()},i=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",t),this.child.kill("SIGTERM")})}}}};var pu={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},Ci=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,t,i=pu,r){this.broker=e,this.workerEntry=t,this.hooks=i,this.capabilities=r}get phase(){return this.phaseValue}get pid(){return this.worker?.pid}get tools(){return this.worker?.tools??[]}get pendingVersion(){return this.pendingPackage?.version??null}get generation(){return this.worker?.generation??null}serialize(e){let t=this.operations.then(e,e);return this.operations=t.catch(()=>{}),t}async ownRuntime(){if(this.releaseOwnership)return;let e=await yr(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,t,i)=>this.capabilities?.handles(t)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new h("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,t,i):this.broker.call(e,t,i);invoke(e,t){return this.phaseValue!=="active"||!this.worker?Promise.reject(new h("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},t)}flushAction(e,t){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new h("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},t)}replace(e,t=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new h("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let i;try{if(i=(await this.broker.recover()).active,i&&i.schema!==e.manifest.dataSchemaVersion)throw new h("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(l){throw this.worker||await this.releaseOwnership?.(),l}let r=i?.generation??0,n=this.worker;n||(this.phaseValue="starting");let o=null,c=!1,a=!1;try{if(o=await Lt.start(e,r+1,this.workerEntry,this.callBroker),this.phaseValue="draining",n&&!await n.waitForIdle(t))throw new h("drain_pending","Plugin calls are still running; switch deferred without killing them");if(a=!0,await this.hooks.freeze(),n&&!await n.waitForIdle(t))throw new h("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new h("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(o.tools)),this.phaseValue="switching";let l=i?await this.broker.forkState(r):du(),p=await this.broker.activate(r,{version:e.version,stateRef:l,schema:e.manifest.dataSchemaVersion,enabled:!0});c=!0,this.worker=o,o=null,this.phaseValue="active",this.pendingPackage=null;let u=!1;try{await this.hooks.committed(p)}catch{u=!0}return await n?.dispose(),{pending:!1,active:p,...u?{reconnectRequired:!0}:{}}}catch(l){throw c||(this.phaseValue=n?.healthy?"active":n?"failed":"disabled",a&&await this.hooks.resume().catch(()=>{})),l}finally{await o?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue,r=await this.broker.active(),n=async()=>{if(!(!t||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(r))throw await this.releaseOwnership?.(),this.phaseValue="failed",new h("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Lt.start(t.package,t.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(c){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),c}}};this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin work is still draining; current host retained");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint work is still draining; current host retained");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(c){try{await n(),this.phaseValue=i,await this.hooks.resume()}catch(a){throw this.phaseValue="failed",a}throw c}let o=!1;return()=>this.serialize(async()=>{o||(await n(),this.phaseValue=i,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let t=this.worker,i;try{i=(await this.broker.recover()).active}catch(o){throw t||await this.releaseOwnership?.(),o}if(!i){if(t)throw this.phaseValue="failed",new h("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!t&&!i.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let r=this.phaseValue;this.phaseValue="draining";let n=!1;try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Plugin still has in-flight work; not killed");if(n=!0,await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Checkpoint synchronization is still running");let o=await this.broker.activate(i.generation,{version:i.version,stateRef:i.stateRef,schema:i.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await t?.dispose(),await this.hooks.committed(o)}catch(o){throw this.worker===t&&(this.phaseValue=r,n&&await this.hooks.resume().catch(()=>{})),o}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let t=this.worker,i=this.phaseValue;this.phaseValue="draining";try{if(t&&!await t.waitForIdle(e))throw new h("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),t&&!await t.waitForIdle(e))throw new h("drain_pending","Host checkpoint synchronization is still running");await t?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(r){throw this.phaseValue=i,await this.hooks.resume().catch(()=>{}),r}})}};import{readFile as Bo}from"node:fs/promises";var Di=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;pairAdmittedValue=!1;get pairAdmitted(){return this.pairAdmittedValue}constructor(e){this.options=e,this.installer=new it({root:Pe(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let t=e.capabilities?new _i(e.capabilities):void 0;this.scheduler=new Ai({invoke:async(i,r)=>{let n=this.closing?null:e.scheduledScope?.(i)??null;n&&await this.supervisor(i).invoke({requestId:hu(),scope:n,kind:"action",action:r.action,input:{schedule:r.id}})},onError:(i,r,n)=>e.onScheduleError?.(i,r.id,n),...e.scheduleTimers});for(let i of this.installer.catalog){let r=new st(Pe(e.root,"data"),i.id,e.legacy?.(i.id)),n=e.hooks(i.id);this.supervisors.set(i.id,new Ci(r,e.workerEntry,{validateCandidate:o=>n.validateCandidate?.(o),canSwitch:()=>n.canSwitch(),freeze:()=>n.freeze(),resume:()=>n.resume(),committed:async o=>{if(o.enabled){let c=await this.installer.load(i.id,o.version);this.packages.set(i.id,c),this.assetTokens.set(i.id,uu(24).toString("base64url"));try{this.scheduler.start(i.id,yt(c.manifest).schedules)}catch(a){this.scheduler.stop(i.id),this.errors.set(i.id,G(a))}}else this.scheduler.stop(i.id),this.packages.delete(i.id),this.assetTokens.delete(i.id);await n.committed(o)}},t))}}devSource(e){let t=this.options.devRoots?.get(e),i=this.options.devArchives?.get(e);return t?r=>this.installer.installDevDirectory(e,t,r):i?r=>this.installer.installDevArchive(e,i,r):null}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){me(e,this.installer.catalog);let t=this.supervisors.get(e);if(!t)throw new h("unknown_plugin","Plugin runtime is not registered");return t}serialize(e,t){if(this.supervisor(e),this.closing)return Promise.reject(new h("manager_closed","Plugin manager is shutting down"));let i=()=>W(Ee(this.options.root),async()=>(await Wt(this.options.root),t())),r=(this.operations.get(e)??Promise.resolve()).then(i,i);return this.operations.set(e,r),r.then(()=>this.errors.delete(e),n=>{this.errors.set(e,G(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,t,i=!1){return this.options.lifecycle?this.options.lifecycle(e,t,i):t()}async policies(){let e=await ee(Pe(this.options.root,"policies","policies.json"));if(!e){if(await X(Pe(this.options.root,"policies","policies.json"),2*1024*1024))throw new h("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[t,i]of Object.entries(e))if(this.installer.catalog.some(r=>r.id===t)&&(!i||!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion)))throw new h("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(t=>[t,{updatePolicy:"notify"}]))}async diagnostics(){return await ee(Pe(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,t){await W(Pe(this.options.root,"policies"),async()=>{let i=await this.diagnostics();i[e]={...t,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await j(Pe(this.options.root,"policies","update-checks.json"),i)})}recordDevSync(e,t){return this.recordCheck(e,{status:"up-to-date",version:t,message:"Developer source installed"})}async check(e,t,i,r){try{let n=await this.installer.check(e,t,i,r),o=!t||Ce(n.version,t)>0;return o?this.available.set(e,n):this.available.delete(e),await this.recordCheck(e,{status:o?"available":"up-to-date",version:n.version,message:o?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),n}catch(n){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:G(n).code,message:G(n).message}),n}}async setPolicy(e,t){if(this.supervisor(e),!["notify","automatic","pinned"].includes(t.updatePolicy)||t.updatePolicy==="pinned"&&!t.pinnedVersion||t.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(t.pinnedVersion))throw new h("invalid_input","Invalid plugin update policy");await W(Ee(this.options.root),async()=>{await Wt(this.options.root),await W(Pe(this.options.root,"policies"),async()=>{let i=await this.policies();i[e]={updatePolicy:"notify"},await j(Pe(this.options.root,"policies","policies.json"),i)})})}async start(){await W(Ee(this.options.root),()=>this.startLocked())}async startLocked(){await W(Pe(this.options.root,"policies"),async()=>{let r=await this.policies();await j(Pe(this.options.root,"policies","policies.json"),r)});let e=await Oe(this.options.root),t=mt(e);if(t&&e)try{if(await this.validatePairPackages(e.version,e.selections),e.version!==this.options.hostVersion||e.hostDigest!==await Ze(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await Ze(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Bo(this.options.workerEntry)).equals(await Bo(Pe(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(r){let n=`Required action: restart the selected compatible host or inspect host-pair/intent.json with all owners stopped. ${G(r).message}; data retained`;for(let o of this.installer.catalog)this.errors.set(o.id,G(new h("host_pair_required",n)));await Te(this.options.root,{...e,phase:"required-action",message:n}),t=!1}await this.installer.inventory();let i=te(await this.pairSnapshot());for(let r of this.installer.catalog){let n=this.supervisor(r.id),o=await n.broker.active();if(o?.enabled)try{let c=t?e?.selections.find(p=>p.id===r.id):void 0,a=c&&te(o)===te(c.before)&&e?.fingerprint===i,l=await this.installer.load(r.id,a?c.version:o.version);if(a&&l.digest!==c.digest)throw new Error("Staged plugin digest changed");await this.lifecycle(r.id,()=>n.replace(l)),this.packages.set(r.id,l),mt(e)||await this.collectSettled(r.id)}catch(c){let a=G(c),l=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool; do not delete the pair journal.":"Choose a compatible host/plugin and inspect plugin diagnostics; do not delete the pair journal.";this.errors.set(r.id,{...a,message:`Required action: plugin startup failed (${a.code}): ${a.message}; data retained. ${l}`})}}t&&e&&(await Te(this.options.root,{...e,phase:this.errors.size?"required-action":"reconciled",message:this.errors.size?[...this.errors].map(([r,n])=>`${r}: ${n.message}`).join("; "):"Current compatible state admitted; no previous state restored"}),this.pairAdmittedValue=!this.errors.size)}async inventory(){let e=await this.installer.inventory(),t=await this.policies(),i=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async n=>{let o=this.supervisor(n.id),c=await o.broker.active(),a=this.packages.get(n.id),l=(e.versions[n.id]??[]).map(p=>p.version).sort((p,u)=>Ce(u,p));return{id:n.id,name:n.name,description:n.description,official:!0,installed:!!l.length,installedVersions:l,version:l[0]??null,activeVersion:c?.version??null,enabled:c?.enabled??!1,phase:o.phase,generation:o.generation,pendingVersion:o.pendingVersion,updatePolicy:t[n.id]?.updatePolicy??"notify",pinnedVersion:t[n.id]?.pinnedVersion,updateDiagnostic:i[n.id],availableVersion:this.available.get(n.id)?.version??(i[n.id]?.status==="available"?i[n.id].version??null:null),...this.errors.has(n.id)?{error:this.errors.get(n.id)}:{},...a&&o.phase==="active"?{digest:a.digest,document:a.manifest.frontend.document.slice(2),controller:a.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(n.id)}/${this.assetTokens.get(n.id)}/${a.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,t])=>t.phase==="active"&&t.generation!==null?[{pluginId:e,generation:t.generation,descriptors:t.tools}]:[])}async manage(e,t,i,r){return this.serialize(e,async()=>{let n=this.supervisor(e),o=(await this.installer.inventory()).versions[e]??[],c=o.map(l=>l.version).sort((l,p)=>Ce(p,l))[0],a=await(async()=>{switch(t){case"check":return this.isDevPlugin(e)?{version:c??null,dev:!0}:{version:(await this.check(e,c,void 0,r)).version};case"install":{let l=this.devSource(e);if(l){let y=await l(r);return await this.recordDevSync(e,y.version),{installed:!0,version:y.version}}let p=await this.check(e,c,i,r),u=await this.installer.install(e,p,r);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:u.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:u.version}}case"enable":{let l=i??c;if(!l)throw new h("not_installed","Install the plugin first");let p=await this.installer.load(e,l),u=await this.lifecycle(e,()=>n.replace(p));return u.pending||this.packages.set(e,p),u}case"retry":{let l=n.pendingVersion,p=await this.lifecycle(e,()=>n.retryPending());return l&&!p.pending&&this.packages.set(e,await this.installer.load(e,l)),p}case"disable":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!c)throw new h("not_installed","Only installed plugins can be updated");let l=this.devSource(e);if(l){let f=await l(r),w=await n.broker.active();if(await this.recordDevSync(e,f.version),!w?.enabled)return{installed:!0,enabled:!1,version:f.version};if(w.version===f.version&&!n.pendingVersion)return{unchanged:!0,version:f.version};let k=await this.lifecycle(e,()=>n.replace(f));return k.pending||this.packages.set(e,f),k}let p=await this.check(e,c,i,r),u=await n.broker.active();if(p.version===c&&(!u?.enabled||u.version===c)&&!n.pendingVersion)return{unchanged:!0,version:c};let y=p.version===c?await this.installer.load(e,c):await this.installer.install(e,p,r);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:y.version,message:"Selected compatible release installed; activation may wait for editors"}),!u?.enabled)return{installed:!0,enabled:!1,version:y.version};let m=await this.lifecycle(e,()=>n.replace(y));return m.pending||this.packages.set(e,y),m}case"uninstall":return await this.lifecycle(e,()=>n.disable()),this.packages.delete(e),await this.installer.removeVersions(e,o.map(l=>l.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new h("invalid_operation","Unknown plugin management operation")}})().catch(async l=>{if(["install","update"].includes(t)){this.available.delete(e);let p=G(l);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw l});return["install","enable","retry","update"].includes(t)&&await this.collectSettled(e),a})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let t=this.supervisor(e);return t.broker.collect(async i=>this.installer.collect(e,async()=>{let r=(await this.policies())[e];return[...i.map(n=>n.version),...t.pendingVersion?[t.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...r?.pinnedVersion?[r.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Reconnect the plugin view before editing",{status:409})):r.invoke(i)}flush(e,t,i){let r=this.supervisor(e);return t!==r.generation?Promise.reject(new h("stale_generation","Flush generation changed",{status:409})):r.flushAction(i)}async asset(e,t,i){let r=this.packages.get(e);if(!r)return null;let n=this.assetLeases.get(e);n||(n=new Map,this.assetLeases.set(e,n)),n.set(r.version,(n.get(r.version)??0)+1);try{return await To(r,i,t)}finally{let o=n.get(r.version)-1;o?n.set(r.version,o):n.delete(r.version)}}async assetRequest(e){let t=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!t)return null;let i;try{i=decodeURIComponent(t[1])}catch{return null}let r=this.assetTokens.get(i),n=Buffer.from(t[2]);return!r||n.length!==Buffer.byteLength(r)||!fu(n,Buffer.from(r))?null:this.asset(i,t[3],t[4])}async reconcileHostUpgrade(){if(mt(await Oe(this.options.root)))return!1;let e=await this.installer.inventory(),t=await this.policies(),i=!0;for(let r of this.installer.catalog){let n=e.versions[r.id];if(n?.length)try{let o=await this.supervisor(r.id).broker.active(),c=o?.enabled?o.version:n.map(l=>l.version).sort((l,p)=>Ce(p,l))[0];try{await this.installer.load(r.id,c);continue}catch(l){if(G(l).code!=="incompatible_plugin")throw l}let a=await this.manage(r.id,"update");a&&typeof a=="object"&&"pending"in a&&a.pending&&(i=!1)}catch(o){i=!1;let c=G(o);this.errors.set(r.id,c),await this.recordCheck(r.id,{status:"failed",code:c.code,message:c.message})}}return i}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}get hostPair(){return so(this.options.root,(e,t)=>this.prepareHostPair(e,t),()=>this.pairSnapshot(),(e,t)=>this.validatePairPackages(e,t))}async validatePairPackages(e,t){let i=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog});for(let r of t)if((await i.load(r.id,r.version)).digest!==r.digest)throw new h("host_pair_changed","Staged plugin digest changed; selection refused")}async prepareHostPair(e,t){let i=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),r=await this.installer.inventory(),n=await this.policies(),o=[];for(let c of this.installer.catalog){let a=r.versions[c.id];if(!a?.length)continue;let l=await this.supervisor(c.id).broker.active(),p=a.map(y=>y.version).sort((y,m)=>Ce(m,y))[0],u;try{u=await i.load(c.id,l?.enabled?l.version:p),o.push({id:c.id,version:u.version,digest:u.digest,before:l});continue}catch(y){if(G(y).code!=="incompatible_plugin")throw y}try{let y=await i.check(c.id,p,void 0,t);u=y.version===p?await i.load(c.id,p):await i.install(c.id,y,t),await this.recordCheck(c.id,{status:"up-to-date",version:u.version,message:"Compatible combination prepared for software update"}),this.errors.delete(c.id)}catch(y){let m=G(y);await this.recordCheck(c.id,{status:"failed",code:m.code,message:m.message}),this.errors.set(c.id,m);try{u=await i.load(c.id,p)}catch(f){throw new h("host_pair_required",`${m.message}; ${G(f).message}; current host/plugin and data retained`)}}o.push({id:c.id,version:u.version,digest:u.digest,before:l})}return o}async validateHostUpdate(e){let t=new it({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),i=await this.installer.inventory(),r=await this.policies(),n=!1;for(let o of this.installer.catalog){let c=i.versions[o.id];if(!c?.length)continue;n=!0;let a=await this.supervisor(o.id).broker.active(),l=c.map(u=>u.version).sort((u,y)=>Ce(y,u))[0],p=new Set([l,...a?[a.version]:[],...r[o.id]?.pinnedVersion?[r[o.id].pinnedVersion]:[],...this.supervisor(o.id).pendingVersion?[this.supervisor(o.id).pendingVersion]:[]]);for(let u of p)try{await t.load(o.id,u)}catch(y){throw new h("host_pair_required",`Host update blocked for ${o.id}@${u}: ${G(y).message}. Prepare a compatible pair; installed code/data retained`)}}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());try{await Promise.all([...this.supervisors].map(([e,t])=>this.lifecycle(e,()=>t.shutdown(),!0))),this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(e){throw this.closing=!1,e}}async suspendForRestart(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[],t=async()=>{let i=await Promise.allSettled(e.map(n=>n()));this.closing=!1;let r=i.find(n=>n.status==="rejected");if(r?.status==="rejected")throw r.reason};try{for(let i of this.supervisors.values())e.push(await i.suspendForRestart());return t}catch(i){throw await t(),i}}};import{randomUUID as gu}from"node:crypto";var D=s=>Object.assign(new Error(s),{status:409,code:"view_barrier"}),zt=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;constructor(e,t,i=2e4,r=15e3){this.pluginId=e,this.generation=t,this.pollMs=i,this.freezeMs=r}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(t=>t.scope.ownerId===e).map(t=>({...t.identity,viewToken:t.token,kind:t.kind,dirty:t.dirty,busy:t.busy}))}sameScope(e,t,i){return e.scope.ownerId===i.ownerId&&e.scope.workspaceId===i.workspaceId&&e.identity.sessionId===t.sessionId&&e.identity.mountId===t.mountId&&e.identity.generation===t.generation}recovery(e,t){return{state:t,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,t){let i=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&i&&this.barrier.pending.has(i.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&i.identity.generation===e.generation&&i.identity.mountId===e.mountId&&i.identity.sessionId===e.sessionId&&t.sessionId===e.sessionId&&i.scope.ownerId===t.ownerId&&i.scope.workspaceId===t.workspaceId)}admitAction(e,t){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let i=e.viewToken?this.views.get(e.viewToken):void 0;if(!i||i.identity.generation!==this.generation||e.generation!==i.identity.generation||e.mountId!==i.identity.mountId||e.sessionId!==i.identity.sessionId||t.ownerId!==i.scope.ownerId||t.workspaceId!==i.scope.workspaceId||t.sessionId!==i.identity.sessionId)throw D("Unknown or stale view action capability");if(this.switching&&i.kind==="controller")throw D("Controller admission paused during plugin switching");return i.initialized=!0,i.activeActions=(i.activeActions??0)+1,()=>{i.activeActions--}}enqueue(e,t,i=++this.sequence){return e.commands.push({id:i,type:t,generation:this.generation}),e.waiter?.(),i}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,t){if(!e||e.pluginId!==this.pluginId||e.sessionId!==t.sessionId||!t.ownerId||!t.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw D("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw D("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw D("Invalid mount kind");if(e.viewToken!==void 0&&(typeof e.viewToken!="string"||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(e.viewToken)))throw D("Invalid registration capability");let o=e.viewToken??gu();if(this.cancelledRegistrations.has(o)||this.recoveries.has(o))throw D("View initialization was cancelled; register a new document identity");let c=this.views.get(o);if(c){if(!this.sameScope(c,e,t)||c.kind!==e.kind)throw D("Duplicate view capability");return{viewToken:o,commands:[]}}if([...this.views.values()].some(a=>a.scope.ownerId===t.ownerId&&a.identity.mountId===e.mountId))throw D("Duplicate mount");return this.views.set(o,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...t},token:o,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[]}),{viewToken:o,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw D("Invalid view capability");let i=this.views.get(e.viewToken),r=this.recoveries.get(e.viewToken),n=this.retired.get(e.viewToken);if(n&&!this.sameScope(n,e,t))throw D("Unknown or stale view capability");if(e.operation==="reconcile"||e.operation==="recover"){if(i&&!this.sameScope(i,e,t)||r&&!this.sameScope(r,e,t))throw D("Unknown or stale view capability");if(r)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(r,"retained")};if(n)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!i)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||i.activeActions)return{viewToken:i.token,commands:[],recovery:this.recovery(i,"active")};if(i.kind==="controller")return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw D("Explicit recovery confirmation required");return i.waiter?.(),this.views.delete(i.token),this.cancelledRegistrations.add(i.token),this.recoveries.set(i.token,i),{viewToken:i.token,commands:[],recovery:this.recovery(i,"retained")}}return{viewToken:i.token,commands:[],recovery:this.recovery(i,"unconfirmed")}}if(e.operation==="discard"&&r&&this.sameScope(r,e,t)){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!i&&!r){if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching)throw D("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!i||!this.sameScope(i,e,t))throw D("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(i.initialized||i.activeActions||this.switching)throw D("View already initialized; preserve its recovery record");this.retire(i);break;case"change":if(e.generation!==this.generation)throw D("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw D("Invalid view status");i.initialized=!0,i.dirty=e.dirty,i.busy=e.busy,(i.dirty||i.busy)&&i.frozen&&(i.frozen=!1,this.barrier?.reject(D("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw D("Invalid acknowledgement");let o=i.commands.find(c=>c.id===e.commandId);if(!o)throw D("Unknown command acknowledgement");i.commands=i.commands.filter(c=>c.id>e.commandId),o.type==="freeze"&&this.barrier?.id===o.id&&(e.ok?(i.frozen=!0,i.dirty=!1,i.busy=!1,this.barrier.pending.delete(i.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(D(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw D("Explicit per-view discard confirmation required");if(this.switching||i.activeActions)throw D("View has an active barrier or action; discard refused");this.retire(i);break;case"close":if(i.activeActions)throw D("View action still in flight");if(i.kind!=="controller"&&(i.dirty||i.busy)&&!i.frozen)throw D("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(i.token))throw D("View must acknowledge freeze before closing");this.retire(i);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw D("Invalid poll cursor");if(i.waiter)throw D("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw D("Invalid poll mode");return!e.immediate&&!i.commands.some(o=>o.id>e.after)&&await new Promise(o=>{let c=setTimeout(a,Math.min(25e3,Math.max(50,this.pollMs)));function a(){clearTimeout(c),i.waiter=void 0,o()}i.waiter=a}),{viewToken:i.token,commands:i.commands.filter(o=>o.id>e.after)}}default:throw D("Unknown view operation")}return{viewToken:i.token,commands:[]}}freeze=async()=>{if(this.switching)throw D("A view barrier is already active");if(!this.canSwitch()){let t=[...this.views.values()].filter(i=>i.activeActions||i.kind!=="controller"&&!i.frozen&&(i.busy||!this.immediate&&["editor","workspace"].includes(i.kind)));throw D(`Close editors before updating; old version retained. Pending views: ${t.map(i=>`${i.kind}:${i.identity.mountId}${i.activeActions?` (action in flight x${i.activeActions})`:i.busy?" (busy)":""}`).join(", ")}`)}this.switching=!0;let e=++this.sequence;try{await new Promise((t,i)=>{let r=n=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,n?i(n):t())};this.barrier={id:e,pending:new Set(this.authoringViews().map(n=>n.token)),resolve:()=>r(),reject:n=>r(n),timer:setTimeout(()=>{let n=this.authoringViews().filter(o=>this.barrier?.pending.has(o.token));r(D(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${n.map(o=>`${o.kind}:${o.identity.mountId} (session ${o.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let n of this.authoringViews())this.enqueue(n,"freeze",e);this.authoringViews().length||r()})}catch(t){throw await this.resume(),t}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(t=>!t.frozen))throw D("Cannot commit before all views freeze");this.generation=e.generation;for(let t of this.views.values())this.enqueue(t,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(D("Switch cancelled"));for(let e of this.views.values())this.enqueue(e,"resume"),e.frozen=!1;this.switching=!1,this.immediate=!1};dispose(){this.barrier?.reject(D("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var mu="@chengzhiyi/pi-excalidraw",wu={tools:{excalidraw_read_me:"reference",excalidraw_create_view:"view",diagram_reference:"reference",diagram_create:"create",diagram_read:"read",diagram_patch:"patch"},readonlyActions:["read","reference"],actions:["list","new","open","import","get","focus","sync","initialize","accept","reject","save"],checkpointActions:["sync","get","list"],contribution:{entry:{label:"Excalidraw",description:{zh:"\u624B\u7ED8\u56FE\u7A3F",en:"Editable drawings"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["excalidraw_create_view","diagram_create","diagram_patch"],toolViews:["excalidraw_create_view","diagram_create","diagram_patch"],panelAlias:{prefix:"diagram:",kind:"editor",title:"Excalidraw"}}},yu="@chengzhiyi/pi-github",vu={tools:{},readonlyActions:[],actions:["get","configure","pickup","sync","cancel","approve","reject","answer","remove"],checkpointActions:["get"],contribution:{entry:{label:"GitHub",description:{zh:"GitHub \u4EFB\u52A1",en:"GitHub tasks"},kind:"workspace"},panels:["workspace"],artifactTools:[],toolViews:[],panelAlias:{prefix:"github:",kind:"workspace",title:"GitHub"}}},Uo=new Map([[mu,wu],[yu,vu]]);function $r(s,e){let t=s.get(e);if(!t)throw new h("unreviewed_plugin","No trusted tool policy for this package");return t}import{randomUUID as bu}from"node:crypto";var ku="https://github.com/settings/personal-access-tokens/new?"+new URLSearchParams({name:"pi-webapp",description:"pi-webapp GitHub plugin",issues:"write",pull_requests:"write",contents:"write"}),Pu="Ov23limJmKiuu8cOP83E";function Vr(s,e,t=process.env){if(s==="@chengzhiyi/pi-github"&&e==="github-token")return{clientId:t.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||Pu,scope:"repo",createUrl:ku}}var Iu="https://github.com/login/device/code",Su="https://github.com/login/oauth/access_token",Eu=8,Ni=class{flows=new Map;fetcher;now;constructor(e=(i,r)=>fetch(i,{...r,signal:r.signal??AbortSignal.timeout(15e3)}),t=Date.now){this.fetcher=e,this.now=t}async post(e,t){let i;try{i=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(t).toString()})}catch{throw new h("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let r=await i.json().catch(()=>null);if(!r||typeof r!="object"||!i.ok&&!("error"in r))throw new h("oauth_failed",`GitHub sign-in failed (${i.status})`,{status:502});return r}async start(e,t,i){if(!i.clientId)throw new h("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[u,y]of this.flows)y.expiresAt<=this.now()&&this.flows.delete(u);if(this.flows.size>=Eu)throw new h("oauth_busy","Too many sign-ins in progress",{status:429});let r=await this.post(Iu,{client_id:i.clientId,scope:i.scope}),{device_code:n,user_code:o,verification_uri:c}=r,a=Number(r.expires_in),l=Math.max(Number(r.interval)||5,1);if(typeof n!="string"||typeof o!="string"||typeof c!="string"||!c.startsWith("https://github.com/")||!Number.isFinite(a))throw new h("oauth_failed",typeof r.error_description=="string"?r.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=bu();return this.flows.set(p,{pluginId:e,name:t,clientId:i.clientId,deviceCode:n,expiresAt:this.now()+a*1e3,interval:l,nextPoll:this.now()+l*1e3}),{deviceId:p,userCode:o,verificationUri:c,interval:l,expiresIn:a}}async poll(e){let t=this.flows.get(e);if(!t||t.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<t.nextPoll)return{status:"pending"};t.nextPoll=this.now()+t.interval*1e3;let i=await this.post(Su,{client_id:t.clientId,device_code:t.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof i.access_token=="string"&&i.access_token)return this.flows.delete(e),{status:"granted",token:i.access_token,pluginId:t.pluginId,name:t.name};switch(i.error){case"authorization_pending":return{status:"pending"};case"slow_down":return t.interval+=5,t.nextPoll=this.now()+t.interval*1e3,{status:"pending"};case"access_denied":return this.flows.delete(e),{status:"denied"};default:return this.flows.delete(e),{status:"expired"}}}cancel(e){this.flows.delete(e)}};import{existsSync as zo,readFileSync as qo,statSync as xu}from"node:fs";import{lstat as _u,readdir as Au,writeFile as Tu,mkdir as Ru,rename as Cu}from"node:fs/promises";import{delimiter as Du,dirname as Nu,isAbsolute as Hu,join as nt,resolve as qt}from"node:path";var Lo="@chengzhiyi/pi-github",Mi={[Lo]:{id:Lo,name:"GitHub",icon:"github",description:{zh:"\u628A GitHub issue \u4EA4\u7ED9 agent\uFF1A\u5148\u51FA\u65B9\u6848\uFF0C\u7ECF\u4F60\u6279\u51C6\u540E\u5B9E\u73B0\u5E76\u63D0\u4EA4\u8349\u7A3F PR\u3002",en:"Hand GitHub issues to an agent: it plans, you approve, then it implements and opens a draft PR."},registry:"https://registry.npmjs.org",recommendedVersion:"0.1.0",requiredCapabilities:["state","panels","scheduler","network","secrets","sessions"]}},Go=()=>Object.keys(Mi).join(", ");function Ou(s=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=[],t=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(s??"").split(/[;\n]/).map(o=>o.trim()).filter(Boolean)){let o=n.lastIndexOf("="),c=n.slice(0,o),a=n.slice(o+1),l=Mi[c],p=o<1?`entry "${n}" is not <id>=<path.tgz>`:l?a.endsWith(".tgz")?zo(qt(a))?null:`archive not found: ${qt(a)}`:`"${a}" is not a .tgz archive`:`unknown plugin id "${c}" (known: ${Go()})`;if(p){i.push({level:"error",source:r,...l?{pluginId:c}:{},message:p});continue}e.push(l),t.set(c,qt(a))}return{catalog:e,archives:t,notices:i}}var Jo=s=>nt(s,"pi-web","hosted-dev.json"),Ko=s=>nt(s,"pi-web","hosted-dev-status.json");function Mu(s,e,t=process.cwd()){let i=[],r=[],n=(s.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(Du).map(c=>c.trim()).filter(Boolean);for(let c of n)i.push({path:qt(t,c),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let o=n.length>0;if(e&&zo(e)){o=!0;try{let c=JSON.parse(qo(e,"utf8")),a=c&&typeof c=="object"?c.roots:void 0;if(!Array.isArray(a))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let l of a)typeof l!="string"||!Hu(l)?r.push({level:"error",source:e,message:`root ${JSON.stringify(l)} must be an absolute path string`}):i.push({path:qt(l),source:e})}catch(c){r.push({level:"error",source:e,message:`cannot read dev configuration: ${c instanceof Error?c.message:String(c)}`})}}return{specs:i,notices:r,configured:o}}function ju(s){let e=(r,n)=>({notice:{level:"error",source:s.source,...n?{pluginId:n}:{},message:`${s.path}: ${r}`}}),t;try{t=xu(s.path)}catch{return e("directory does not exist")}if(!t.isDirectory())return e("not a directory (expected the package directory containing package.json)");let i;try{i=JSON.parse(qo(nt(s.path,"package.json"),"utf8"))}catch(r){return e(r.code==="ENOENT"?"package.json not found (point at the package directory, not its parent)":"package.json is not valid JSON")}return typeof i.name!="string"?e("package.json has no name"):Mi[i.name]?Ue(i.piWebapp)?{pluginId:i.name}:e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',i.name):e(`unknown plugin id "${i.name}" (known: ${Go()})`)}var Hi=class{catalog;archives;roots=new Map;rootSource=new Map;fileNotices;archiveNotices;rootNotices=[];env;configPath;cwd;enabled=!1;constructor(e={}){this.env=e.env??process.env,this.configPath=e.configPath,this.cwd=e.cwd??process.cwd();let t=Ou(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.catalog=[...t.catalog],this.archives=t.archives,this.archiveNotices=t.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let i=this.refresh(!0);this.enabled||=i.configured}refresh(e=!1){let t=Mu(this.env,this.configPath,this.cwd),i=[],r=new Map,n=new Map;for(let o of t.specs){let c=ju(o);if(c.notice){i.push(c.notice);continue}let a=c.pluginId;if(r.has(a)){i.push({level:"error",pluginId:a,source:o.source,message:`${o.path}: plugin ${a} is already provided by ${r.get(a)}`});continue}if(this.archives.has(a)&&i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${a}; the dev directory wins`}),!this.catalog.some(l=>l.id===a)){if(!e){i.push({level:"warning",pluginId:a,source:o.source,message:`${o.path}: ${a} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}this.catalog.push(Mi[a])}r.set(a,o.path),n.set(a,o.source)}for(let o of[...this.roots.keys()])r.has(o)||this.roots.delete(o);for(let[o,c]of r)this.roots.set(o,c);this.rootSource.clear();for(let[o,c]of n)this.rootSource.set(o,c);return this.fileNotices=t.notices,this.rootNotices=i,{configured:t.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Oi=class{options;roots=new Map;timer;current=Promise.resolve();running=!1;stopped=!1;lastStatus="";lastNotices="";constructor(e){this.options=e}start(){if(this.running)return;this.running=!0,this.stopped=!1;for(let t of this.options.sources.notices())this.log(`${t.level}: ${t.message}`);let e=()=>{this.current=this.tick().catch(t=>{this.running&&this.log(`poll failed: ${G(t).message}`)}).finally(()=>{this.running&&(this.timer=setTimeout(e,this.options.pollMs??700),this.timer.unref?.())})};e()}stop(){this.running=!1,this.stopped=!0,clearTimeout(this.timer)}invalidate(e){let t=this.roots.get(e);t&&(t.applied=void 0)}idle(){return this.current}info(){return{notices:this.options.sources.notices().map(e=>({level:e.level,...e.pluginId?{pluginId:e.pluginId}:{},message:e.message})),sources:[...this.roots].map(([e,t])=>({pluginId:e,root:t.root,state:t.state,...t.version?{version:t.version}:{},...t.message?{message:t.message}:{}}))}}log(e){(this.options.log??(t=>console.error(`pi-webapp [hosted-dev] ${t}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let t of[...this.roots.keys()])e.has(t)||this.roots.delete(t);for(let[t,i]of e){let r=this.roots.get(t);(!r||r.root!==i)&&(r={root:i,state:"waiting-build",at:new Date().toISOString()},this.roots.set(t,r));let n=await Wu(i);if(n===null){this.set(t,r,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),r.seen=void 0;continue}if(n!==r.seen){r.seen=n;continue}n===r.applied||this.stopped||await this.apply(t,r,n)}await this.publish()}set(e,t,i,r={}){let n=t.state!==i||t.message!==r.message||t.version!==r.version;t.state=i,t.message=r.message,t.code=r.code,t.version=r.version??t.version,n&&(t.at=new Date().toISOString(),this.log(`${e}: ${i}${r.version?` ${r.version}`:""}${r.message?` \u2014 ${r.message}`:""}`))}async apply(e,t,i){this.set(e,t,"switching");try{let n=(await this.options.switcher.update(e)).plugins.find(o=>o.pluginId===e);t.applied=i,n?.installed?n.pendingVersion?this.set(e,t,"pending",{version:n.version,message:`Waiting for editors to close before switching to ${n.pendingVersion}`}):this.set(e,t,"synced",{version:n.version}):this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(r){let n=G(r);["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(n.code)||(t.applied=i),n.code==="not_installed"?this.set(e,t,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,t,"error",{code:n.code,message:`${n.message} (${n.code}). Fix and save again.`})}t.at=new Date().toISOString()}async publish(){let e=this.info(),t=JSON.stringify(e);t!==this.lastNotices&&(this.lastNotices=t,this.options.changed?.());let i=this.options.statusPath;if(!i)return;let r=Object.fromEntries([...this.roots].map(([c,a])=>[c,{root:a.root,state:a.state,version:a.version,message:a.message,code:a.code,at:a.at}])),n=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(c=>c.id),plugins:r,notices:e.notices});if(n===this.lastStatus)return;this.lastStatus=n;let o=`${i}.${process.pid}.tmp`;try{await Ru(Nu(i),{recursive:!0}),await Tu(o,JSON.stringify({...JSON.parse(n),updatedAt:new Date().toISOString()})),await Cu(o,i)}catch{}}};async function Wu(s){let e=[],t=async(i,r)=>{let n=await _u(i);e.push(`${r}:${n.size}:${n.mtimeMs}:${n.ino}`)};try{await t(nt(s,"package.json"),"package.json");let i=async(r,n,o)=>{if(!(o>16||e.length>8192))for(let c of(await Au(r,{withFileTypes:!0})).sort((a,l)=>a.name.localeCompare(l.name)))c.isDirectory()?await i(nt(r,c.name),`${n}/${c.name}`,o+1):await t(nt(r,c.name),`${n}/${c.name}`)};if(await i(nt(s,"dist"),"dist",0),!e.some(r=>r.startsWith("dist/resources.json:")))return null}catch(i){if(i.code==="ENOENT")return null;throw i}return e.join("|")}function Fu(s){try{return[...yt(s).secrets]}catch{return[]}}var Wi=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ni;restartPreparation;restartResume;closing=!1;started=!1;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Uo,e.dev?.enabled&&(this.devWatcher=new Oi({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async t=>{let i=await this.inventory();return i.plugins.find(r=>r.pluginId===t)?.installed?this.manage({pluginId:t,operation:"update",reopenEditors:!0}):i}}})),this.adapter=new Si({policy:(t,i)=>{let r=e.policy?.(t,i);return{...r,enabled:!this.recovery.has(t)&&this.manager.tools.some(n=>n.pluginId===t)&&r?.enabled!==!1}},invoke:async(t,i,r)=>{r?.throwIfAborted(),this.scope(i.scope.sessionId,i.scope);let n=this.manager.tools.find(c=>c.pluginId===t);if(!n)throw new h("plugin_unavailable","Hosted tool unavailable");let o=await this.manager.invoke(t,n.generation,i);return{content:[{type:"text",text:JSON.stringify(o)??"null"}],details:o}}}),this.manager=new Di({...e,lifecycle:(t,i,r)=>this.lifecycle(t,i,r),hooks:t=>({canSwitch:()=>this.coordinator(t).canSwitch(),validateCandidate:i=>{if(i.length!==Object.keys($r(this.trusted,t).tools).length)throw new h("unreviewed_tool","Official tool set changed; review required");this.verifyTools(t,i),this.adapter.validateChange(t,i)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(t).freeze()},committed:async i=>{try{let r=i.enabled?this.manager.tools.find(n=>n.pluginId===t)?.descriptors:[];if(!r)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(t,r),i.enabled){let n=await this.manager.installer.load(t,i.version);this.documents.set(t,{document:n.manifest.frontend.document.replace(/^\.\//,""),controller:n.manifest.frontend.controller.replace(/^\.\//,""),secrets:Fu(n.manifest)})}else this.documents.delete(t);this.adapter.change(t,r),await this.coordinator(t).committed(i),e.changed?.(),this.recovery.delete(t)}catch(r){throw this.recovery.set(t,r),await this.coordinator(t).committed(i).catch(()=>{}),r}},resume:()=>this.coordinator(t).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:t=>this.manage(t),secret:async(t,i,r)=>{let n=this.options.capabilities?.secrets,o=this.documents.get(t)?.secrets;if(!n)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(!o?.includes(i))throw new h("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return r===null?await n.delete(t,i):await n.set(t,i,r),this.options.changed?.(),this.inventory()},secretAuth:async t=>{let i=this.options.capabilities?.secrets;if(!i)throw new h("hosted_unavailable","Secrets are not available",{status:503});if(t.phase==="cancel")return this.deviceFlows.cancel(t.deviceId),{status:"cancelled"};if(t.phase==="start"){let n=this.documents.get(t.pluginId)?.secrets.includes(t.name)?Vr(t.pluginId,t.name):void 0;if(!n)throw new h("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(t.pluginId,t.name,n)}let r=await this.deviceFlows.poll(t.deviceId);return r.status!=="granted"?{status:r.status}:(await i.set(r.pluginId,r.name,r.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(t,i)=>{if(!this.options.approvals)throw new h("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(t,i),this.inventory()},action:(t,i)=>this.action(t,i?.checkpointOnly),views:async t=>{if(t.operation==="list-pending"){if(typeof t.pluginId!="string")throw new h("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(t.pluginId).pendingViews(this.options.ownerId)}}let i=t,r=this.scope(i.sessionId);return i.operation==="register"&&this.generation(i.pluginId,i.generation),this.coordinator(i.pluginId).handle(i,this.viewScope(r))},asset:t=>this.manager.assetRequest(t)}}verifyTools(e,t){let i=$r(this.trusted,e);for(let r of t)if(!Object.hasOwn(i.tools,r.name)||i.tools[r.name]!==r.action||r.readonly!==i.readonlyActions.includes(r.action))throw new h("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let t=this.views.get(e);if(!t)throw new h("unknown_plugin","Hosted coordinator unavailable");return t}scope(e,t){let i=typeof e=="string"?this.options.resolveSession(e):null;if(!i||i.sessionId!==e||!i.cwd||!i.workspaceId||t&&(i.cwd!==t.cwd||i.workspaceId!==t.workspaceId))throw new h("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...i}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,t){let i=this.manager.tools.find(r=>r.pluginId===e);if(!i||i.generation!==t)throw new h("stale_generation","Reconnect and re-handshake hosted views",{status:409});return i}enqueue(e,t=!1){let i=this.queue.then(async()=>{if(this.closing&&!t)throw new h("manager_closed","Host is shutting down");return e()});return this.queue=i.catch(()=>{}),i}lifecycle(e,t,i=!1){let r=this.switches.then(async()=>{if(this.closing&&!i)throw new h("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let n=await t();if(n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let o=await new st(ji(this.options.root,"data"),e).active();o&&await this.coordinator(e).committed(o).catch(()=>{})}if(this.recovery.has(e)&&!i)throw new h("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return n}finally{if(!i)for(let n of this.views.values())n.allowImmediateReopen(!1);i||this.adapter.thaw()}});return this.switches=r.catch(()=>{}),r.catch(n=>{throw i&&this.adapter.thaw(),n})}async start(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Me)try{let t=await new st(ji(this.options.root,"data"),e.id).active();this.views.set(e.id,new zt(e.id,t?.generation??0))}catch(t){this.recovery.set(e.id,t),this.views.set(e.id,new zt(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=ji(this.options.root,"host-version.json");(await ee(e))?.version!==this.options.hostVersion&&(this.manager.pairAdmitted?!(await this.manager.inventory()).plugins.some(i=>i.updateDiagnostic?.status==="failed"):await this.manager.reconcileHostUpgrade())&&(await Z(this.options.root),await j(e,{version:this.options.hostVersion}))}).catch(e=>{for(let t of this.options.catalog??Me)this.recovery.set(t.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}async validateHostUpdate(e,t){await this.enqueue(async()=>{if(await this.manager.validateHostUpdate(e))try{await Vu(ji(t,"dist","hosted-worker.js"))}catch{throw new h("host_pair_required","Selected host has no hosted worker; keep current host/plugin pair")}})}async inventory(){let e=await this.manager.inventory(),t=this.options.capabilities?.secrets,i=new Map;for(let r of e.plugins){let n=r.enabled?this.documents.get(r.id)?.secrets??[]:[];t&&n.length&&i.set(r.id,await Promise.all(n.map(async o=>{let c=Vr(r.id,o);return{name:o,configured:await t.has(r.id,o),...c?{signIn:c.clientId?"browser":"token-page",...c.createUrl?{createUrl:c.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(r=>({pluginId:r.id,name:r.name,official:r.official,installed:r.installed,enabled:r.enabled,description:r.description,...i.has(r.id)?{secrets:i.get(r.id)}:{},icon:(this.options.catalog??Me).find(n=>n.id===r.id)?.icon,hasRetainedData:r.activeVersion!==null,phase:this.recovery.has(r.id)?"reconnect-required":r.phase,updatePolicy:r.updatePolicy,pinnedVersion:r.pinnedVersion,updateDiagnostic:r.updateDiagnostic,...r.enabled&&r.activeVersion?{version:r.activeVersion}:r.version?{version:r.version}:{},...r.availableVersion?{availableVersion:r.availableVersion}:{},...r.pendingVersion?{pendingVersion:r.pendingVersion}:{},...r.generation!==null?{generation:r.generation}:{},...this.recovery.has(r.id)||r.error?{error:this.recovery.get(r.id)instanceof Error?this.recovery.get(r.id).message:r.error?.message??"Recovery required",errorCode:this.recovery.has(r.id)?"reconnect_required":r.error?.code}:{},...r.enabled&&r.assetBase&&this.documents.has(r.id)&&this.trusted.has(r.id)?{documentUrl:r.assetBase+this.documents.get(r.id).document,controllerUrl:r.assetBase+this.documents.get(r.id).controller,contribution:structuredClone(this.trusted.get(r.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let i=this.downloads.get(e.pluginId);if(!i||i.id!==e.downloadId)throw new h("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return i.abort.abort(new h("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let t=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(t){if(this.downloads.has(e.pluginId))throw new h("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,t)}try{return await this.enqueue(async()=>{let i=this.coordinator(e.pluginId);i.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new h("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let r=await this.manager.manage(e.pluginId,e.operation,e.version,t?.abort.signal);if(this.recovery.has(e.pluginId)||r&&typeof r=="object"&&"reconnectRequired"in r&&r.reconnectRequired)throw new h("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{i.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{t&&this.downloads.get(e.pluginId)===t&&this.downloads.delete(e.pluginId)}}async action(e,t=!1){let i=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new h("action_denied","Action is not reviewed by this host",{status:403});let r=this.coordinator(e.pluginId).admitAction(e,this.viewScope(i));try{let n={requestId:$u(),scope:i,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||t){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(i)))return await this.manager.flush(e.pluginId,e.generation,n);throw new h("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new h("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...n,kind:"action"})}finally{r()}}prepareRestart(){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let r of this.views.values())r.allowImmediateReopen(!0);let e=await this.manager.suspendForRestart(),t=!1,i=async()=>{if(!t)try{await e(),t=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=i,i}catch(e){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}finally{for(let e of this.views.values())e.allowImmediateReopen(!1)}}),this.restartPreparation)}shutdown(){if(this.stopping)return this.stopping;if(this.devWatcher?.stop(),this.restartResume){for(let e of this.views.values())e.dispose();return this.stopping=Promise.resolve(),this.stopping}return this.closing=!0,this.stopping=this.enqueue(async()=>{for(let e of this.views.values())e.allowImmediateReopen(!0);await this.manager.shutdown();for(let e of this.views.values())e.dispose()},!0).then(()=>this.devWatcher?.idle()).catch(e=>{for(let t of this.views.values())t.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as Bu,readdir as Uu,unlink as Lu}from"node:fs/promises";import{join as kt}from"node:path";import{randomUUID as zu}from"node:crypto";var Fr="hosted-migration.json";function Xo(s,e="@chengzhiyi/pi-excalidraw"){return async t=>{let{cwd:i,sessionId:r}=t.scope,n=kt(s,B(JSON.stringify([i,r])));await Z(s),await Z(n);let o=kt(n,"scope.lock"),c;try{c=await Bu(o,"wx",384)}catch(a){throw a.code==="EEXIST"?new h("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):a}try{await c.writeFile(JSON.stringify({pid:process.pid,operationId:zu()}));let a=await ee(kt(n,Fr));if(a&&(a.version!==1||a.pluginId!==e))throw new h("invalid_storage","Legacy scope belongs to another migration");let l=await Uu(n),p=[];for(let y of l){if(y==="scope.lock"||y==="focus.json"||y===Fr||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(y))continue;if(!/^[\w-]{1,80}\.json$/.test(y))throw new h("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new h("invalid_storage","Too many legacy checkpoints");let m=await ee(kt(n,y),3*512*1024);if(!m||m.version!==1||m.cwd!==i||m.sessionId!==r||!m.draft||y!==`${m.draft.id}.json`)throw new h("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(m.draft)}let u=await ee(kt(n,"focus.json"),1024);if(u!==null&&(typeof u!="string"||!p.some(y=>y.id===u)))throw new h("invalid_storage","Invalid legacy focused drawing");return a||await j(kt(n,Fr),{version:1,pluginId:e,operationId:t.requestId}),{drafts:p,focused:u}}finally{await c.close(),await Lu(o)}}}import{join as eh}from"node:path";import{randomUUID as qu}from"node:crypto";var Gu=6e4,$i=class{entries=new Map;options;constructor(e={}){this.options=e}now(){return this.options.now?.()??Date.now()}pending(){return[...this.entries.values()].filter(e=>e.status==="pending").map(({id:e,pluginId:t,sessionId:i,title:r})=>({id:e,pluginId:t,sessionId:i,title:r}))}async authorize(e,t){let i=this.entries.get(t);if(i&&i.pluginId!==e)throw new h("execute_denied","Session belongs to another plugin",{status:403});if(i?.status==="allowed")return!0;throw i?.status==="pending"?new h("approval_required","Waiting for the user to approve execution",{status:409}):i?.status==="denied"&&this.now()-i.decidedAt<Gu?new h("execute_denied","The user denied execution",{status:403}):(this.entries.set(t,{id:qu(),pluginId:e,sessionId:t,title:this.options.describe?.(t)??t,status:"pending"}),this.options.changed?.(),new h("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,t){let i=[...this.entries.values()].find(r=>r.id===e&&r.status==="pending");if(!i)throw new h("unknown_approval","No such pending approval",{status:404});i.status=t?"allowed":"denied",i.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as Ju,readFile as Ku,rename as Xu,writeFile as Yu}from"node:fs/promises";import{randomUUID as Qu,createHash as Zu}from"node:crypto";import{join as Yo}from"node:path";var Vi=class{dir;queue=Promise.resolve();constructor(e){this.dir=Yo(e,"secrets")}file=e=>Yo(this.dir,`${Zu("sha256").update(e).digest("hex")}.json`);async read(e){try{let t=JSON.parse(await Ku(this.file(e),"utf8"));if(t&&typeof t=="object"&&!Array.isArray(t))return t}catch(t){if(!Ve(t))throw new h("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let t=this.queue.then(e,e);return this.queue=t.catch(()=>{}),t}async get(e,t){return(await this.read(e))[t]??null}has(e,t){return this.get(e,t).then(i=>i!==null)}set(e,t,i){return this.mutate(e,r=>{r[t]=i})}delete(e,t){return this.mutate(e,i=>{delete i[t]})}mutate(e,t){return this.serialize(async()=>{let i=await this.read(e);t(i),await Ju(this.dir,{recursive:!0,mode:448});let r=`${this.file(e)}.${Qu()}.tmp`;await Yu(r,JSON.stringify(i),{mode:384}),await Xu(r,this.file(e))})}};function Qo(s,e){let t=i=>({seq:i.seq,type:i.type,...i.text===void 0?{}:{text:i.text}});return{async create({pluginId:i,cwd:r,title:n,prompt:o}){let c=await s.createDetached(r,i,n);try{await s.sendDetached(c,o,!1)}catch(a){throw await s.releaseDetached(c),a}return{sessionId:c}},ownerOf:i=>s.detachedOwner(i),activeCount:i=>s.detachedCount(i),async send(i,r,n){let o=s.detachedOwner(i);if(n==="execute"&&(!o||!await e(o,i)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await s.sendDetached(i,r,n==="execute")},abort:i=>s.abortDetached(i),release:i=>s.releaseDetached(i),async events(i,r){let n=s.detachedEvents(i,r);return{events:n.events.map(t),next:n.next}}}}var th="scheduler";function Zo(s){let e=new $i({describe:s.sessionTitle,changed:s.changed}),t=()=>{let r=s.sessions();if(!r)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return r},i={createDetached:(...r)=>t().createDetached(...r),detachedOwner:r=>s.sessions()?.detachedOwner(r)??null,detachedCount:r=>s.sessions()?.detachedCount(r)??0,sendDetached:(...r)=>t().sendDetached(...r),abortDetached:r=>t().abortDetached(r),releaseDetached:async r=>{e.forget(r),await t().releaseDetached(r)},detachedEvents:(...r)=>t().detachedEvents(...r)};return{approvals:e,capabilities:{secrets:new Vi(eh(s.root,"capability-secrets")),sessions:Qo(i,(r,n)=>e.authorize(r,n))},scheduledScope:()=>{let r=s.activeWorkspace();if(!r)return null;try{return s.trustedScope(r,th)}catch{return null}}}}async function ih(){for(let s of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=ni(s),t=new xe({env:s,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await t.ready,e.node.enabled||e.browser.enabled||t.enabled||t.reporter||t.capture(new Error("Disabled release probe"))||await t.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await t.close()}}return{release:Tt,buildId:Se,browser:ni({}).browser}}async function ea(){if(process.env.PI_WEB_SENTRY_VERIFY_RELEASE!=="true"||process.env.PI_WEB_SENTRY_ENVIRONMENT!=="sentry-verification")throw new Error("Sentry release verification is not enabled");let s=new xe({monitor:!1});try{if(await s.ready,!s.enabled)throw new Error("Sentry verification transport is disabled");let e=s.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await s.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Tt,buildId:Se}}finally{await s.close()}}var Gt=St(sh(ah(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),uh=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),d=globalThis[uh]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Qe,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};d.lifecycle??=new Qe;d.tuiGeneration??=0;d.stopChanged??=null;d.tuiWaitController??=new AbortController;d.tuiStreaming??=null;d.tuiPrompts??=new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()});d.tuiPromptSessionId??=null;d.tuiAgentError??=!1;function Fi(){return d.selected==="sdk"?d.workspaceSessions?.catalog??null:d.tuiCatalog}var hh=null;function fh(){return hh??=ch.create({refreshOnCreate:!1})}var Bi=new Map;async function It(){let s=await fh(),e=d.selected==="tui"?d.current?.modelRegistry:void 0,t=new Set(e?.getRegisteredProviderIds()??[]);for(let i of Bi.keys())t.has(i)||(s.unregisterProvider(i),Bi.delete(i));for(let i of t){let r=e?.getRegisteredNativeProvider(i),n=e?.getRegisteredProviderConfig(i),o=r??n;!o||Bi.get(i)===o||(r?s.registerNativeProvider(r):n&&s.registerProvider(i,n),Bi.set(i,o))}return await s.refresh({allowNetwork:!1}),s}function re(){return d.selected==="sdk"?d.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():je()}function je(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...En(d.current,d.current.sessionManager.getSessionName(),d.tuiCatalog?.ids()??[]),idle:d.current.isIdle()&&!d.tuiPrompts.sending,streaming:d.tuiStreaming,queuedPrompts:d.tuiPrompts.view(),hasPendingPrompts:d.current.hasPendingMessages?.()??!1,interactions:d.interactions?.pending(d.current.sessionManager.getSessionId())??[]}}async function Gr(s,e,t,i,r){let n=he(s);We({...je(),idle:n.isIdle()},e,r);let o=n.isIdle();o&&gt(()=>d.hosted?.adapter.assertAdmission(),i,(c,a)=>d.bridge?.reportError?.(c,a)),o&&(d.operation=i);try{let c=t.length?[{type:"text",text:e},...t]:e;if(d.replacementContext!==null&&d.replacementSessionId===s)await d.replacementContext.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:r});else{if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.sendUserMessage(c,{expandPromptTemplates:!0,deliverAs:r})}d.current?.sessionManager.getSessionId()===s&&d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:je()})}catch(c){throw o&&(d.operation=void 0),c}}function Lr(){let s=d.current?.sessionManager.getSessionId(),e=d.tuiGeneration,t=()=>{if(!s||!d.current||d.tuiGeneration!==e||d.current.sessionManager.getSessionId()!==s||d.tuiAgentError)return!1;let i=je();return!d.hosted?.adapter.isFrozen&&d.current.isIdle()&&!i.paused&&!i.interactions.length};d.tuiPrompts.schedule(t,(i,r,n)=>Gr(s,i,r,n))}function ne(s){if(re().sessionId!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function na(){let s=(d.workspaces?.list()??[]).map(p=>({...p})),e=d.activeWorkspaceId,t=re(),r=d.current?je():null,n=await Ke(t.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)),o=r?await Ke(r.cwd).catch(p=>(d.bridge?.reportError?.(p,{stage:"workspace_path"}),null)):null,c=await qr.listAll(),a=d.workspaceSessions?.retainedSessions()??[];r&&o&&a.push({sessionId:r.sessionId,cwd:o,path:null,name:r.name,modified:r.messages.at(-1)?.timestamp??new Date().toISOString(),idle:r.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&r.idle&&d.tuiPrompts.length===0&&!r.messages.some(p=>p.role==="user")});let l=(await Promise.all(s.map(async p=>{let y=(await ht(p.path,c).catch(m=>(m instanceof Ht?p.available=!1:d.bridge?.reportError?.(m,{stage:"workspace_sessions"}),[]))).map(m=>({id:m.id,workspaceId:p.id,path:m.path,name:m.name||m.firstMessage?.slice(0,50)||"",modified:m.modified.toISOString(),idle:!0}));for(let m of a.filter(f=>f.cwd===p.path)){if(m.blank&&m.sessionId!==t.sessionId)continue;let f=y.findIndex(k=>k.id===m.sessionId),w={id:m.sessionId,workspaceId:p.id,path:m.path??y[f]?.path??null,name:m.name,modified:m.modified,idle:m.idle};f<0?y.unshift(w):y[f]=w}return p.path===n&&!y.some(m=>m.id===t.sessionId)&&y.unshift({id:t.sessionId,workspaceId:p.id,path:null,name:t.name,modified:new Date().toISOString(),idle:t.idle}),y}))).flat();return{items:s,activeId:e,sessions:l}}var ia=0;async function ie(){if(!d.bridge)return;let s=++ia;try{let e=await na();s===ia&&d.bridge?.publish({type:"workspaces",value:e})}catch(e){d.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function zr(s,e=!1){let t=d.workspaces?.get(s);if(!t)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(t.path),!e&&d.current&&t.path===await Ke(d.current.cwd)&&!d.workspaceSessions?.hasWorkspace(t.path))d.selected="tui",d.activeWorkspaceId=s,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:re()});else{if(!d.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await d.workspaceSessions.reuseBlank(t.path))&&await d.workspaceSessions.open(t.path,e?"new":"continue"),d.selected="sdk",d.activeWorkspaceId=s,d.bridge?.publish({type:"snapshot",session:re()})}await ie()}async function ra(s,e,t){let i=d.workspaces?.get(s);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let r=await Ae(i.path);if(d.workspaceSessions?.hasSession(r,e)||d.current?.sessionManager.getSessionId()===e&&await Ke(d.current.cwd)===r)return i;if(!(await ht(r)).some(o=>o.id===e&&o.path===t))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return i}function he(s){let e=d.current;if(e===null||e.sessionManager.getSessionId()!==s)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function le(s){d.current=s,d.selected==="tui"&&d.bridge?.publish({type:"snapshot",session:re()})}function oa(){if(d.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let s=d.selected==="sdk"?d.workspaceSessions?.path:d.current.cwd;if(!s)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=d.selected==="tui"?d.current.isProjectTrusted():d.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return lh.create(s,void 0,{projectTrusted:e})}async function aa(){let s=oa(),e=r=>({packages:(r.packages??[]).map(n=>typeof n=="string"?n:n.source),extensions:r.extensions??[],skills:r.skills??[]}),t=new sa({cwd:re().cwd,agentDir:we(),settingsManager:s}),i=Yn(t.listConfiguredPackages(),await t.resolve(async()=>"skip"));return{projectTrusted:s.isProjectTrusted(),global:e(s.getGlobalSettings()),project:e(s.getProjectSettings()),installed:i}}async function gh(s){ne(s.sessionId);let e=d.selected==="tui"?he(s.sessionId):null;if(e?!e.isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let t=oa();if(s.scope==="project"&&!t.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let i=s.value.trim(),r=s.scope==="project"?t.getProjectSettings():t.getGlobalSettings();if(s.kind==="packages"){let n=new sa({cwd:re().cwd,agentDir:we(),settingsManager:t});s.action==="add"?await n.installAndPersist(i,{local:s.scope==="project"}):await n.removeAndPersist(i,{local:s.scope==="project"})}else if(s.kind==="extensions"){let n=r.extensions??[],o=s.action==="add"?[...new Set([...n,i])]:n.filter(c=>c!==i);s.scope==="project"?t.setProjectExtensionPaths(o):t.setExtensionPaths(o)}else{let n=r.skills??[],o=s.action==="add"?[...new Set([...n,i])]:n.filter(c=>c!==i);s.scope==="project"?t.setProjectSkillPaths(o):t.setSkillPaths(o)}return await t.flush(),d.selected==="tui"?(d.commandContext&&await d.commandContext.reload(),d.current&&le(d.current)):(await d.workspaceSessions?.reload(),d.bridge?.publish({type:"plugins_changed"})),await aa()}function Ui(s,e=mr){if(d.hostedMode===!1||d.hostedMode===void 0&&d.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");d.hostedMode=!0;let t=(a,l)=>{let p=Br(a);return{cwd:p,sessionId:l,workspaceId:ta("sha256").update(p).digest("hex")}},i=Pt(we(),"pi-web","hosted"),r=new Hi({configPath:Jo(we())});d.hosted??=new Wi({root:i,...r.enabled?{dev:r,devStatusPath:Ko(we())}:{},...r.catalog.length?{catalog:[...Me,...r.catalog],devArchives:r.archives,devRoots:r.roots}:{},...Zo({root:i,sessions:()=>d.workspaceSessions,activeWorkspace:()=>d.workspaceSessions?.path??null,trustedScope:t,sessionTitle:a=>d.workspaceSessions?.retainedSessions().find(l=>l.sessionId===a)?.name,changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(nh(St(Gt,"../../package.json"),"utf8")).version,packageRoot:St(Gt,"../.."),workerEntry:St(Gt,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${ta("sha256").update(we()).digest("hex")}`,resolveSession:a=>{let l=d.current;if(l?.sessionManager.getSessionId()===a)return t(l.cwd,a);let p=d.workspaceSessions?.hostedScope(a);return p?t(p.cwd,a):null},legacy:()=>Xo(Pt(we(),"pi-web","diagrams")),changed:()=>d.bridge?.publish({type:"hosted_plugins_changed"})}),d.offHostedThaw?.(),d.offHostedThaw=d.hosted?.adapter.onThaw(Lr),d.pi=s,d.tools?.clear(),d.tools=new ft({enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,capture:(a,l)=>d.bridge?.reportError?.(a,l),breadcrumb:(a,l)=>d.bridge?.breadcrumb?.(a,l),anonymize:a=>d.telemetry?.session(a)??"unavailable"});let n=a=>({...d.operation,session:d.telemetry?.session(a.sessionManager.getSessionId()),piVersion:Ur,model:a.model?`${a.model.provider}/${a.model.id}`:null,thinkingLevel:a.thinkingLevel});d.interactions?.dispose(),d.interactions=new ut(s.events,a=>!!d.bridge&&a.sessionId===d.current?.sessionManager.getSessionId()&&!!d.tuiCatalog?.has(a.pluginId),()=>{d.current&&d.selected==="tui"&&le(d.current)});let o=()=>{d.stopChanged?.(),d.stopChanged=s.events.on(hi,()=>{d.selected==="tui"&&d.current&&le(d.current)})};o(),s.on("session_start",async(a,l)=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiWaitController=new AbortController,d.tuiGeneration++,o(),d.current=l,d.releaseHostedTui?.(),d.releaseHostedTui=d.hosted?.adapter.mountTui(s,t(l.cwd,l.sessionManager.getSessionId())),await d.hosted?.start(),d.tuiPromptSessionId!==l.sessionManager.getSessionId()&&(d.tuiPrompts=new $e(()=>{d.selected==="tui"&&d.current&&d.bridge?.publish({type:"snapshot",session:je()}),ie()}),d.tuiPromptSessionId=l.sessionManager.getSessionId()),d.tuiAgentError=!1,d.bridge){let p=await Ye.discover(l.cwd,l.isProjectTrusted?.()??!1);if(d.current!==l)return;d.tuiCatalog=p}d.replacementSessionId!==l.sessionManager.getSessionId()&&(d.replacementContext=null,d.replacementSessionId=null),le(l),d.bridge&&d.selected==="tui"&&d.bridge.publish({type:"plugins_changed"}),d.selected==="tui"&&d.workspaces&&d.workspaces.add(l.cwd).then(async p=>{d.selected!=="tui"||d.current?.sessionManager.getSessionId()!==l.sessionManager.getSessionId()||(d.activeWorkspaceId=p.id,await ie())}).catch(p=>{d.bridge?.publish({type:"error",message:p instanceof Error?p.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:d.bridge.reportError?.(p,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&l.mode==="tui"&&!d.autoOpened&&(d.autoOpened=!0,c(l).catch(p=>{l.ui.notify(p instanceof Error?p.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),s.on("agent_start",(a,l)=>{d.tuiAgentError=!1,d.bridge?.breadcrumb?.("agent_start",n(l)),le(l),ie()}),s.on("agent_end",(a,l)=>le(l)),s.on("agent_settled",(a,l)=>{d.bridge?.breadcrumb?.("agent_end",n(l)),d.tools?.clear(),d.operation=void 0,d.tuiStreaming=null,Lr(),le(l),ie()}),s.on("tool_execution_start",(a,l)=>{d.tools?.start(a,n(l))}),s.on("tool_execution_end",(a,l)=>{d.tools?.end(a,n(l))}),s.on("model_select",(a,l)=>le(l)),s.on("thinking_level_select",(a,l)=>le(l)),s.on("message_end",(a,l)=>{if(a.message.role==="assistant"&&a.message.stopReason==="error"){d.tuiAgentError=!0;let p=d.bridge?.reportError?.(new Error("Agent response failed"),{...d.operation,stage:"agent",code:"agent_failed",piVersion:Ur});d.selected==="tui"&&d.bridge?.publish({type:"error",message:a.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:p,...d.operation})}a.message.role==="toolResult"&&d.tools?.message(a.message,n(l)),a.message.role==="assistant"&&(d.tuiStreaming=null),d.selected==="tui"&&a.message.role==="assistant"&&d.bridge?.publish({type:"stream",message:null}),le(l),ie()}),s.on("session_info_changed",(a,l)=>le(l)),s.on("message_update",(a,l)=>{if(d.current=l,a.message.role!=="assistant"||(d.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(a.message.timestamp).toISOString(),blocks:Je(a.message.content)},d.selected!=="tui"||d.bridge===null))return;let p=Date.now();p-d.lastStreamAt<60||(d.lastStreamAt=p,d.bridge.publish({type:"stream",message:d.tuiStreaming}))}),s.on("session_shutdown",async a=>{if(d.tuiStreaming=null,d.tools?.clear(),d.operation=void 0,d.tuiWaitController.abort(),d.tuiGeneration++,d.stopChanged?.(),d.stopChanged=null,d.interactions?.cancelAll(),d.releaseHostedTui?.(),d.releaseHostedTui=void 0,a.reason==="new"||a.reason==="resume"||a.reason==="fork"||a.reason==="reload"){d.current=null;return}await d.hosted?.shutdown(),d.hosted=void 0,d.offHostedThaw?.(),d.offHostedThaw=void 0,d.current=null;let l=d.bridge,p=d.telemetry;d.bridge=null,d.commandContext=null,d.replacementContext=null,d.replacementSessionId=null,d.pi=null;let u=d.workspaceSessions;d.workspaceSessions=null,await u?.dispose(),d.selected="tui",d.activeWorkspaceId=null,d.autoOpened=!1,d.tuiCatalog=null,d.stopPluginWatch?.(),d.stopPluginWatch=null,d.operation=void 0,d.telemetry=null,l?await l.close():await p?.close()});let c=async a=>{d.telemetry??=new xe;try{d.current=a,d.commandContext="newSession"in a?a:null,d.pi=s,d.tuiCatalog=await Ye.discover(a.cwd,a.isProjectTrusted?.()??!1),d.workspaces===null&&(d.workspaces=new ui(Tn(we())),await d.workspaces.load());try{await d.workspaces.discover((await qr.listAll()).map(u=>u.cwd))}catch(u){a.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${u instanceof Error?u.message:String(u)}`,"warning")}let l=await d.workspaces.add(a.cwd);if(d.selected==="tui"&&(d.activeWorkspaceId=l.id),d.bridge&&(d.bridge.protocolVersion!==7||d.bridge.buildId!==Se||typeof d.bridge.reportError!="function"||typeof d.bridge.runPluginTool!="function")){let u=d.bridge;if(d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)&&d.workspaceSessions.session&&!d.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");d.bridge=null,await u.close(),await d.telemetry.close(),d.telemetry=new xe}if(d.bridge===null){let u=d.workspaceSessions&&(d.workspaceSessions.telemetryVersion!==2||d.workspaceSessions.runtimeVersion!==4)?d.workspaceSessions:null,y=u?.session&&u.path?{path:u.path,sessionManager:u.session.sessionManager}:null;u&&(await u.dispose(),d.workspaceSessions=null),d.workspaceSessions??=new wi(f=>{d.selected==="sdk"&&d.bridge?.publish(f)},()=>d.current?.model,f=>{try{return!!d.current&&Br(d.current.cwd)===f&&(d.current.isProjectTrusted?.()??!1)}catch{return!1}},(f,w)=>d.bridge?.reportError?.(f,w),{enabled:()=>!!d.telemetry?.enabled&&!!d.bridge,breadcrumb:(f,w)=>d.bridge?.breadcrumb?.(f,w),anonymize:f=>d.telemetry?.session(f)??"unavailable"},()=>{ie()},[],{adapter:d.hosted.adapter,scope:t}),y&&await d.workspaceSessions.open(y.path,{sessionManager:y.sessionManager});let m={hosted:d.hosted?.handlers,selfUpdate:new Ii({agentDir:we(),packageRoot:St(Gt,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,hostedPair:d.hosted.manager.hostPair,beforeRestart:()=>d.hosted.prepareRestart()}),snapshot:re,busyGitWorkspaces:()=>{let f=(d.workspaceSessions?.retainedSessions()??[]).filter(w=>!w.idle).map(w=>w.cwd);if(d.current&&(!d.current.isIdle()||d.tuiPrompts.sending))try{f.push(Br(d.current.cwd))}catch{f.push(d.current.cwd)}return f},plugins:async()=>{let f=Fi();return await f?.refreshAssets(),f?.view()??{plugins:[],errors:[]}},pluginAsset:async f=>Fi()?.asset(f)??null,async invokePluginAction(f,w,k,P){if(ne(f),!Fi()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let E=d.selected,_=d.tuiGeneration,H=d.workspaceSessions?.session,N={requestId:ph(),sessionId:f,pluginId:w,action:k,input:P},T=d.selected==="sdk"?await d.workspaceSessions.invokePluginAction(N):await fi(d.pi.events,N,15e3,d.tuiWaitController.signal);if(ne(f),E!==d.selected||(E==="tui"?_!==d.tuiGeneration:H!==d.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return d.selected==="tui"&&d.current&&le(d.current),T},async resolvePluginInteraction(f,w,k,P){if(ne(f),!Fi()?.has(w))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");d.selected==="sdk"?d.workspaceSessions.resolveInteraction(f,w,k,P):d.interactions.resolve(f,w,k,P)},image(f,w,k){ne(f);let E=(d.selected==="sdk"?d.workspaceSessions?.session?.sessionManager.getBranch():d.current?.sessionManager.getBranch())?.find(H=>H.id===w);if(E?.type!=="message"||E.message.role!=="user"||!Array.isArray(E.message.content))return null;let _=E.message.content[k];return _?.type!=="image"?null:{data:Buffer.from(_.data,"base64"),mimeType:_.mimeType}},async workspaces(){return na()},async addWorkspace(f,w){let k=await d.workspaces.add(f,w);try{await zr(k.id,!0)}catch(P){throw await ie(),P}},async selectWorkspace(f){await zr(f)},async newSessionInWorkspace(f){await zr(f,!0)},async removeWorkspace(f){if(f===d.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await d.workspaces.remove(f),await ie()},async selectSession(f,w,k){let P=d.workspaces?.get(f);if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await Ae(P.path),w===d.current?.sessionManager.getSessionId()&&P.path===await Ke(d.current.cwd))d.selected="tui",d.activeWorkspaceId=f,d.bridge?.publish({type:"stream",message:null}),d.bridge?.publish({type:"snapshot",session:re()});else{if(d.selected==="sdk"&&d.workspaceSessions?.session?.sessionManager.getSessionId()===w&&d.workspaceSessions.path===P.path)return;if(d.workspaceSessions?.hasSession(P.path,w))await d.workspaceSessions.open(P.path,{sessionId:w});else{if(!(await ht(P.path)).some(_=>_.id===w&&_.path===k))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");await d.workspaceSessions.open(P.path,{sessionFile:k})}d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:re()})}await ie()},async renameSession(f,w,k,P){let E=P.replace(/\s+/g," ").trim();if(E.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await ra(f,w,k),d.current?.sessionManager.getSessionId()===w&&d.pi?d.pi.setSessionName(E):d.workspaceSessions?.rename(w,E)||qr.open(k).appendSessionInfo(E),d.selected==="tui"&&d.current?.sessionManager.getSessionId()===w&&d.bridge?.publish({type:"snapshot",session:re()}),await ie()},async deleteSession(f,w,k){let P=await ra(f,w,k);if(d.current?.sessionManager.getSessionId()===w)throw new Error("\u8BE5\u4F1A\u8BDD\u6B63\u5728 Pi \u7EC8\u7AEF\u4E2D\u4F7F\u7528\uFF0C\u8BF7\u5728\u7EC8\u7AEF\u91CC\u5207\u6362\u5230\u5176\u4ED6\u4F1A\u8BDD\u540E\u518D\u5220\u9664");let E=await d.workspaceSessions?.discard(w)??null,_=E?.path??(k||null);_&&await Xn(_,we()),E?.wasActive&&d.selected==="sdk"&&(await d.workspaceSessions.open(P.path,"new"),d.selected="sdk",d.activeWorkspaceId=f,d.bridge?.publish({type:"snapshot",session:re()})),await ie()},async models(){if(d.selected==="sdk")return d.workspaceSessions?.models()??[];let f=d.current;if(!f)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let w=f.scopedModels?.map(k=>`${k.model.provider}/${k.model.id}`)??[];return f.modelRegistry.getAvailable().filter(k=>w.length===0||w.includes(`${k.provider}/${k.id}`)).map(k=>({provider:k.provider,id:k.id,name:k.name}))},async providers(){let f=await It(),w=new Set((await f.listCredentials()).map(k=>k.providerId));return f.getProviders().map(k=>({id:k.id,name:k.name,configured:f.getProviderAuthStatus(k.id).configured,storedCredential:w.has(k.id),methods:[k.auth.apiKey?.login?"api_key":null,k.auth.oauth?"oauth":null].filter(P=>P!==null)}))},async providerModels(f){let w=await It();return ln(Pt(we(),"models.json"),f,w)},async updateProviderModel(f,w,k){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let P=re().model;if(k.action==="remove"&&P===`${w}/${k.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(k.action==="save"&&k.originalId&&k.originalId!==k.model.id&&P===`${w}/${k.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let E=await It();await dn(Pt(we(),"models.json"),w,k,E),await E.refresh({providers:[w],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[w],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[w],allowNetwork:!1});let _=k.action==="save"?k.model.id:k.action==="base_url"&&P?.startsWith(`${w}/`)?P.slice(w.length+1):null;if(_&&P===`${w}/${_}`)if(d.selected==="sdk")try{await d.workspaceSessions.setModel(w,_)}catch{throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570")}else{let H=he(f),N=H.modelRegistry.find(w,_);if(!N||!d.pi||!await d.pi.setModel(N))throw new Error("\u6A21\u578B\u5DF2\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u8BE5\u6A21\u578B\u4EE5\u5E94\u7528\u65B0\u53C2\u6570");le(H)}},async logoutProvider(f,w){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let k=await It();if(!(await k.listCredentials()).some(P=>P.providerId===w))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await k.logout(w),await d.current?.modelRegistry.refresh({providers:[w],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[w],allowNetwork:!1})},async loginProvider(f,w,k){let P=await It();await P.login(f,w,rn(f,w,k)),await P.refresh({providers:[f],allowNetwork:!1}),await d.current?.modelRegistry.refresh({providers:[f],allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({providers:[f],allowNetwork:!1})},async addCustomProvider(f,w){if(ne(f),d.selected==="tui"?!he(f).isIdle():!d.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let k=await It();if(k.getProvider(w.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await sn(Pt(we(),"models.json"),w),await k.refresh({allowNetwork:!1}),await d.current?.modelRegistry.refresh({allowNetwork:!1}),await d.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return d.selected==="tui"?(d.pi?.getCommands()??[]).filter(f=>f.name!=="web"&&f.name!=="web-dev-reload").map(f=>({name:f.name,description:f.description})):[]},async compact(f){if(ne(f),d.selected==="sdk"){let k=d.workspaceSessions?.session;if(!k||!k.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await k.compact(),d.bridge?.publish({type:"snapshot",session:re()});return}let w=he(f);if(!w.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");w.compact()},async setModel(f,w,k){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.setModel(w,k);return}let P=he(f);if(!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=P.modelRegistry.find(w,k);if(!E||!P.modelRegistry.getAvailable().some(_=>_.provider===w&&_.id===k))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!d.pi||!await d.pi.setModel(E))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");le(P)},async setThinkingLevel(f,w){if(ne(f),!["off","minimal","low","medium","high","xhigh"].includes(w))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(d.selected==="sdk"){let E=d.workspaceSessions?.session;if(!E||!E.isIdle||!E.getAvailableThinkingLevels().includes(w))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");E.setThinkingLevel(w),d.bridge?.publish({type:"snapshot",session:re()});return}let P=he(f);if(!P.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!P.model||!dh(P.model).includes(w))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.pi.setThinkingLevel(w),le(P)},config:aa,updateConfig:gh,async send(f,w,k=[],P,E){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.send(w,k,P,E);return}let _=he(f);if(We(je(),w,E),E==="followUp"&&(!_.isIdle()||d.tuiPrompts.length>0)){d.tuiPrompts.enqueue(w,k,P),Lr();return}if(_.isIdle()&&d.tuiPrompts.sending)throw new ae("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await Gr(f,w,k,P,E)},async updateQueuedPrompt(f,w,k,P){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.updateQueuedPrompt(w,k,P);return}if(P.kind==="steer"&&he(f).isIdle())throw new ae("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await d.tuiPrompts.update(w,k,P,(E,_,H)=>Gr(f,E,_,H,"steer"))},async abort(f){if(ne(f),d.selected==="sdk")await d.workspaceSessions.stop();else{let w=he(f);if(w.isIdle()&&!d.tuiPrompts.sending)return;if(!d.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");d.tools?.cancel(),d.bridge?.breadcrumb?.("cancel",{...d.operation}),d.pi.appendEntry(Dt),w.abort()}},async resume(f,w){if(ne(f),d.selected==="sdk"){await d.workspaceSessions.resume(w);return}let k=he(f);if(gt(()=>d.hosted?.adapter.assertAdmission(),w,(P,E)=>d.bridge?.reportError?.(P,E)),!k.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!k.model||!d.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!k.modelRegistry.hasConfiguredAuth(k.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");d.operation=w;try{d.pi.sendMessage(gi(re().messages),{triggerTurn:!0})}catch(P){throw d.operation=void 0,P}},async newSession(f){if(ne(f),d.selected==="sdk"){let P=d.workspaces?.get(d.activeWorkspaceId??"");if(!P)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await d.workspaceSessions.reuseBlank(P.path)||await d.workspaceSessions.open(P.path,"new"),await ie();return}let w=he(f);if(!w.isIdle()||d.tuiPrompts.length>0||d.commandContext===null){await d.workspaceSessions.open(w.cwd,"new"),d.selected="sdk",d.bridge?.publish({type:"snapshot",session:re()}),await ie();return}if((await d.commandContext.newSession({withSession:async P=>{d.commandContext=P,d.replacementContext=P,d.replacementSessionId=P.sessionManager.getSessionId(),d.current=P}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await ie()}};m.addWorkspace=d.lifecycle.wrap(m.addWorkspace),m.selectWorkspace=d.lifecycle.wrap(m.selectWorkspace),m.newSessionInWorkspace=d.lifecycle.wrap(m.newSessionInWorkspace),m.removeWorkspace=d.lifecycle.wrap(m.removeWorkspace),m.selectSession=d.lifecycle.wrap(m.selectSession),m.renameSession=d.lifecycle.wrap(m.renameSession),m.deleteSession=d.lifecycle.wrap(m.deleteSession),m.newSession=d.lifecycle.wrap(m.newSession),m.updateConfig=d.lifecycle.wrap(m.updateConfig),d.bridge=await Sn(m,Gt,d.telemetry)}if(d.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let u=[],y=null;for(let m of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(rh).filter(Boolean))try{u.push(oh(Pt(St(m),"dist"),(f,w)=>{let k=String(w??"");["client.js","client.css"].includes(k)&&(y&&clearTimeout(y),y=setTimeout(()=>d.bridge?.publish({type:"plugins_changed"}),180))}))}catch(f){d.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${m}: ${String(f)}`})}d.stopPluginWatch=()=>{for(let m of u)m.close();y&&clearTimeout(y)}}let p=await e(d.bridge.url).catch(()=>!1);a.ui.notify(`pi-webapp: ${d.bridge.url}`,p?"info":"warning"),a.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(l){throw d.telemetry?.capture(l,{stage:"open_web",piVersion:Ur}),d.bridge||(await d.telemetry?.close(),d.telemetry=null),l}};s.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(a,l)=>c(l)}),s.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(a,l)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(a))throw new Error("Launcher stop receipt ID required");try{await d.hosted?.shutdown(),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!0})}`,"info")}catch(p){console.error("pi-webapp: plugin shutdown refused the stop request:",p),l.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:a,ok:!1})}`,"warning")}}}),s.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(a,l)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await l.waitForIdle(),await d.lifecycle.run(async()=>{let p=d.workspaceSessions?.session;p&&(await p.waitForIdle(),await d.workspaceSessions.reload()),await l.reload()}))}})}var Ck=Ui;export{Ck as default,ih as verifySentryDisabledRelease,ea as verifySentryNodeRelease};
48
48
 
49
- //# debugId=21797faa-38d4-4a0e-a037-226896d3ebe4
49
+ //# debugId=d3b85ce5-d862-45c5-8684-5abd7591b2f9
@@ -1,8 +1,8 @@
1
- (function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="fba8c735-12ac-4b50-b08d-3b20fb0e2535",r._sentryDebugIdIdentifier="sentry-dbid-fba8c735-12ac-4b50-b08d-3b20fb0e2535")}catch{}})();import{resolve as je}from"node:path";import{lstat as ie,readdir as Pe,rename as oe}from"node:fs/promises";import{join as k}from"node:path";import{createHash as de}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var q=r=>r.code==="ENOENT";var Ue={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var y=r=>de("sha256").update(r).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ue}from"node:sqlite";import{lstat as V,mkdir as pe,open as N,rename as he,unlink as X}from"node:fs/promises";import{dirname as we,join as K,resolve as ge}from"node:path";import{randomUUID as me}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";async function x(r){await pe(r,{recursive:!0,mode:448});let e=await V(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function g(r,e){let t;try{t=await N(r,J.O_RDONLY|J.O_NONBLOCK|(J.O_NOFOLLOW??0))}catch(n){if(q(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(n.size+1,e+1)),s=0;for(;s<i.length;){let a=await t.read(i,s,i.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==n.size)throw new o("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function E(r,e=2*1024*1024){let t=await g(r,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new o("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(r){let e=await g(r,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new o("gc_recovery_required",`Invalid journal ${r}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new o("gc_recovery_required",`Invalid journal ${r}; original bytes preserved`);return t}async function b(r,e){let t=`${r}.${me()}.tmp`,n=await N(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await he(t,r);let i;try{i=await N(we(r),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await X(t).catch(()=>{})}}var Y='{"version":2,"mechanism":"sqlite-exclusive"}',M=r=>r.toString("utf8")===Y,C=new Set;async function ve(r,e,t=0){await x(r);let n=K(r,`${e}.lock`),i=K(r,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new o(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await N(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let f=await V(i);if(!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>1024*1024)throw new o("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ue(i,{allowExtension:!1}),u=ge(i),p=Date.now()+t,m=!1;try{for(;;){if(!C.has(u))try{l.exec("BEGIN EXCLUSIVE"),C.add(u),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=p)throw new o(s,"Another host owns this plugin storage; wait for it to stop before retrying");await ye(10)}let h=await g(n,4096);if(h===null){let w;try{w=await N(n,"wx",384),await w.writeFile(Y),await w.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await w?.close()}h=await g(n,4096)}if(h===null||!M(h))throw a()}catch(h){throw l.close(),m&&C.delete(u),h}let v=!1;return async()=>{if(v)return;let h=await g(n,4096);if(h===null||!M(h))throw new o("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await X(n),l.close(),C.delete(u),v=!0}}async function R(r,e,t=2e3){let n=await ve(r,"transaction",t);try{return await e()}finally{await n()}}import{lstat as F,mkdir as be,open as Q,realpath as Z,readdir as W,link as ke,rename as Ie,unlink as S,copyFile as _e,rm as Se}from"node:fs/promises";import{dirname as xe,isAbsolute as ee,join as d,relative as te,resolve as Ee,sep as U,win32 as Re}from"node:path";import{randomUUID as G}from"node:crypto";var A=192*1024*1024,H=512*1024,re=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Oe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function ne(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function T(r){if(r&&(!re(r.stateRef)||typeof r.version!="string"||!Number.isSafeInteger(r.generation)||r.generation<1||!Number.isSafeInteger(r.schema)||r.schema<1||typeof r.enabled!="boolean"||typeof r.operationId!="string"))throw new o("invalid_storage","Invalid active plugin record");return r}var D=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,i){this.root=d(e,y(t)),this.pluginId=t,this.legacy=n,this.checkpoint=i}active(){return E(d(this.root,"active.json")).then(T)}async recover(){return R(this.root,async()=>{let e=await this.active(),t=await I(d(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(t,"version")&&t.version!==1)throw new o("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");T(t.next),T(t.before);let n=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(f=>a[f]===c[f]))(e,n==="committed"?t.next:t.before))throw new o("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(n==="committed"&&s&&s.stateRef!==e.stateRef&&await b(d(this.root,"previous.json"),s),n==="committed"){let a=await I(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await S(d(this.root,"fork.json"))}return await S(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return R(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let i=await I(d(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(a=>!["version","stateRef"].includes(a))))throw new o("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=T({...t,generation:e+1,operationId:G()});await x(d(this.root,"states")),await x(d(this.root,"states",s.stateRef)),await b(d(this.root,"transition.json"),{version:1,before:n,next:s}),await this.checkpoint?.("prepared");try{await b(d(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==s.stateRef&&await b(d(this.root,"previous.json"),n),await S(d(this.root,"transition.json")),await S(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return R(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=G(),i=d(this.root,"states",n);if(await I(d(this.root,"fork.json")))throw new o("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await b(d(this.root,"fork.json"),{version:1,stateRef:n}),await x(i);let s=d(this.root,"states",t.stateRef);for(let a of await W(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await g(d(s,a),A))throw new o("invalid_storage","Missing state file");await _e(d(s,a),d(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return R(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await g(d(this.root,l),2*1024*1024))throw new o("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),n=T(await I(d(this.root,"previous.json")));if(!t&&await g(d(this.root,"active.json"),2*1024*1024))throw new o("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,n].filter(l=>!!l),s=d(this.root,"states");await x(s);let a=await W(s),c=new Set(i.map(l=>l.stateRef));for(let l of a){if(!re(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(s,l),p=await F(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await W(u)){let v=await F(d(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!v.isFile()||v.isSymbolicLink()||v.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await E(d(u,m),A);if(!h)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new o("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let l of c)if(!a.includes(l))throw new o("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let f=await e(i);for(let l of a)c.has(l)||await Se(d(s,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}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 o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n,i="session"){if(i!=="session"&&i!=="workspace")throw new o("invalid_input","Invalid state scope");let s=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return d(this.root,"states",e.stateRef,`${y(s+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=Oe(n);return R(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await E(this.statePath(s,e,ne(i.key),i.scope),A);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,ne(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>A)throw new o("state_too_large","Plugin state exceeds limit");let f=await E(a,A);f&&this.validateState(f);let l=y(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==i.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?H:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>H)throw new o("invalid_input","Invalid workspace read limit");let f=await g(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:y(f)}:null}case"workspace.commit":return this.commitFile(s,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new o("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 o("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,n=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||ee(t)||Re.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let i=await Z(e),s=Ee(i,t),a=te(i,s);if(!a||a===".."||a.startsWith(`..${U}`)||ee(a))throw new o("invalid_path","Workspace path escapes root");let c=i,f=a.split(U);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await F(c)}catch(m){if(!q(m))throw m;if(u<f.length-1){if(!n||te(i,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await be(c,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}p=await F(c)}}if(p&&(p.isSymbolicLink()||(u<f.length-1?!p.isDirectory():!p.isFile()||p.nlink!==1)))throw new o("invalid_path","Workspace path contains a link or non-regular file")}let l=await Z(xe(s));if(l!==i&&!l.startsWith(i+U))throw new o("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>H||!(n.expectedHash===null||typeof n.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(n.expectedHash)))throw new o("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${y(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=y(JSON.stringify(n)),f=y(n.text),l=await E(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==f))throw new o("duplicate_request","Request ID was reused with different content");let u;try{u=await Q(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):m}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let m=await g(i,H),v=m?y(m):null;if(l&&v===f)return{hash:f};if(l?.committed||v!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(s,`.plugin-${G()}.tmp`);let h=await Q(p,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==s)throw new o("file_conflict","Workspace directory changed during save");let _=await g(i,H);if((_?y(_):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ke(p,i)}catch(B){throw B.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):B}await S(p),p=void 0}else await Ie(p,i),p=void 0;return await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await S(p).catch(()=>{}),await u.close(),await S(`${i}.lock`)}}};var z="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function $(r){let e=[];async function t(n,i=""){let s=await ie(n);if(!s.isDirectory()||s.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Pe(n)).sort()){let c=k(n,a),f=i+a,l=await ie(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,f+"/");else{if(e.length>=1e4)throw new o("invalid_storage","Recovery inspection budget exceeded");let u=await g(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:y(u)})}}}return await t(r),{fingerprint:y(JSON.stringify(e)),files:e,warning:"Offline only: externally stop/fence ALL hosts and plugin workers, back up storage and workspace files. Never infer stopped ownership from PID alone."}}async function se(r,e,t,n){let i=new D(r,e),s=await $(i.root);if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(s.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return i.recover()}async function ae(r,e,t,n){let i=new D(r,e),s=i.root;if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await $(s);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await g(k(s,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(k(s,"fork.json")),f=await i.active(),l=await I(k(s,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(p=>!["version","stateRef"].includes(p))||!f||l&&typeof l.stateRef!="string"||[f?.stateRef,l?.stateRef].includes(c.stateRef))throw new o("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${t}-fork.json`;if(a.files.some(p=>p.path===u))throw new o("recovery_changed","Recovery evidence already exists");return await oe(k(s,"fork.json"),k(s,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function ce(r,e,t){if(t!==z||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await $(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let s of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(k(r,s.path),2097152);a&&!M(a)&&i.push(s)}for(let s of i){let a=`recovered-${e}-${s.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let s of i)await oe(k(r,s.path),k(r,`recovered-${e}-${s.path}.json`));return await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:i.map(s=>s.path),fingerprint:e}}var[O,le,P,j,L,...Ne]=process.argv.slice(2),Ae=le&&!Ne.length&&(O==="inspect"&&!P&&!j&&!L||O==="recover-locks"&&P&&j&&!L||["recover-fork","reconcile-transition"].includes(O??"")&&P&&j&&L);if(!Ae)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
1
+ (function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new r.Error().stack;e&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[e]="de73f4dd-c79a-4a98-a712-c4a7df53b206",r._sentryDebugIdIdentifier="sentry-dbid-de73f4dd-c79a-4a98-a712-c4a7df53b206")}catch{}})();import{resolve as je}from"node:path";import{lstat as ie,readdir as Pe,rename as oe}from"node:fs/promises";import{join as k}from"node:path";import{createHash as de}from"node:crypto";var o=class extends Error{code;status;reason;constructor(e,t,n={}){super(t),this.name="HostedPluginError",this.code=e,this.status=n.status,this.reason=n.reason}};var q=r=>r.code==="ENOENT";var Ue={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,other:2*1024*1024};var y=r=>de("sha256").update(r).digest("hex");import{constants as J}from"node:fs";import{DatabaseSync as ue}from"node:sqlite";import{lstat as V,mkdir as pe,open as N,rename as he,unlink as X}from"node:fs/promises";import{dirname as we,join as K,resolve as ge}from"node:path";import{randomUUID as me}from"node:crypto";import{setTimeout as ye}from"node:timers/promises";async function x(r){await pe(r,{recursive:!0,mode:448});let e=await V(r);if(!e.isDirectory()||e.isSymbolicLink())throw new o("invalid_storage","Plugin storage must be a real directory")}async function g(r,e){let t;try{t=await N(r,J.O_RDONLY|J.O_NONBLOCK|(J.O_NOFOLLOW??0))}catch(n){if(q(n))return null;throw n}try{let n=await t.stat();if(!n.isFile()||n.nlink>1||n.size>e)throw new o("invalid_storage","Invalid storage record size or type");let i=Buffer.alloc(Math.min(n.size+1,e+1)),s=0;for(;s<i.length;){let a=await t.read(i,s,i.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==n.size)throw new o("invalid_storage","Storage record changed during read");return i.subarray(0,s)}finally{await t.close()}}async function E(r,e=2*1024*1024){let t=await g(r,e);if(!t)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{throw new o("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function I(r){let e=await g(r,2097152);if(e===null)return null;let t;try{t=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new o("gc_recovery_required",`Invalid journal ${r}; stop all owners and inspect original bytes`)}if(!t||typeof t!="object"||Array.isArray(t))throw new o("gc_recovery_required",`Invalid journal ${r}; original bytes preserved`);return t}async function b(r,e){let t=`${r}.${me()}.tmp`,n=await N(t,"wx",384);try{try{await n.writeFile(JSON.stringify(e)),await n.sync()}finally{await n.close()}await he(t,r);let i;try{i=await N(we(r),"r"),await i.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await i?.close()}}finally{await X(t).catch(()=>{})}}var Y='{"version":2,"mechanism":"sqlite-exclusive"}',M=r=>r.toString("utf8")===Y,C=new Set;async function ve(r,e,t=0){await x(r);let n=K(r,`${e}.lock`),i=K(r,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new o(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),c;try{c=await N(i,"wx",384)}catch(h){if(h.code!=="EEXIST")throw h}finally{await c?.close()}let f=await V(i);if(!f.isFile()||f.isSymbolicLink()||f.nlink!==1||f.size>1024*1024)throw new o("invalid_storage","Ownership database must be a small, single-link regular file");let l=new ue(i,{allowExtension:!1}),u=ge(i),p=Date.now()+t,m=!1;try{for(;;){if(!C.has(u))try{l.exec("BEGIN EXCLUSIVE"),C.add(u),m=!0;break}catch(w){if(w.errcode!==5)throw w}if(Date.now()>=p)throw new o(s,"Another host owns this plugin storage; wait for it to stop before retrying");await ye(10)}let h=await g(n,4096);if(h===null){let w;try{w=await N(n,"wx",384),await w.writeFile(Y),await w.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await w?.close()}h=await g(n,4096)}if(h===null||!M(h))throw a()}catch(h){throw l.close(),m&&C.delete(u),h}let v=!1;return async()=>{if(v)return;let h=await g(n,4096);if(h===null||!M(h))throw new o("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await X(n),l.close(),C.delete(u),v=!0}}async function R(r,e,t=2e3){let n=await ve(r,"transaction",t);try{return await e()}finally{await n()}}import{lstat as F,mkdir as be,open as Q,realpath as Z,readdir as W,link as ke,rename as Ie,unlink as S,copyFile as _e,rm as Se}from"node:fs/promises";import{dirname as xe,isAbsolute as ee,join as d,relative as te,resolve as Ee,sep as U,win32 as Re}from"node:path";import{randomUUID as G}from"node:crypto";var A=192*1024*1024,H=512*1024,re=r=>typeof r=="string"&&/^[a-f0-9-]{36}$/.test(r);function Oe(r){if(!r||typeof r!="object"||Array.isArray(r))throw new o("invalid_input","Expected object input");return r}function ne(r){if(typeof r!="string"||!/^[\w.-]{1,160}$/.test(r)||r==="."||r==="..")throw new o("invalid_input","Invalid state key");return r}function T(r){if(r&&(!re(r.stateRef)||typeof r.version!="string"||!Number.isSafeInteger(r.generation)||r.generation<1||!Number.isSafeInteger(r.schema)||r.schema<1||typeof r.enabled!="boolean"||typeof r.operationId!="string"))throw new o("invalid_storage","Invalid active plugin record");return r}var D=class{root;pluginId;legacy;checkpoint;constructor(e,t,n,i){this.root=d(e,y(t)),this.pluginId=t,this.legacy=n,this.checkpoint=i}active(){return E(d(this.root,"active.json")).then(T)}async recover(){return R(this.root,async()=>{let e=await this.active(),t=await I(d(this.root,"transition.json"));if(!t)return{active:e,recovered:"none"};if(!t.next||!Object.hasOwn(t,"before")||Object.keys(t).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(t,"version")&&t.version!==1)throw new o("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");T(t.next),T(t.before);let n=e?.operationId===t.next.operationId?"committed":"not_committed";if(!((a,c)=>a===null||c===null?a===c:["version","generation","stateRef","schema","enabled","operationId"].every(f=>a[f]===c[f]))(e,n==="committed"?t.next:t.before))throw new o("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=t.before;if(n==="committed"&&s&&s.stateRef!==e.stateRef&&await b(d(this.root,"previous.json"),s),n==="committed"){let a=await I(d(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(c=>["version","stateRef"].includes(c))&&await S(d(this.root,"fork.json"))}return await S(d(this.root,"transition.json")),{active:e,recovered:n}})}async activate(e,t){return R(this.root,async()=>{let n=await this.active();if((n?.generation??0)!==e)throw new o("stale_generation","Plugin activation changed concurrently");let i=await I(d(this.root,"fork.json"));if(i&&(i.version!==1||i.stateRef!==t.stateRef||Object.keys(i).some(a=>!["version","stateRef"].includes(a))))throw new o("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=T({...t,generation:e+1,operationId:G()});await x(d(this.root,"states")),await x(d(this.root,"states",s.stateRef)),await b(d(this.root,"transition.json"),{version:1,before:n,next:s}),await this.checkpoint?.("prepared");try{await b(d(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{n&&n.stateRef!==s.stateRef&&await b(d(this.root,"previous.json"),n),await S(d(this.root,"transition.json")),await S(d(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return R(this.root,async()=>{let t=await this.assertGeneration(e,!1),n=G(),i=d(this.root,"states",n);if(await I(d(this.root,"fork.json")))throw new o("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await b(d(this.root,"fork.json"),{version:1,stateRef:n}),await x(i);let s=d(this.root,"states",t.stateRef);for(let a of await W(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new o("invalid_storage","Unexpected state file");if(!await g(d(s,a),A))throw new o("invalid_storage","Missing state file");await _e(d(s,a),d(i,a))}return await this.checkpoint?.("forked"),n})}async collect(e){return R(this.root,async()=>{for(let l of["transition.json","fork.json"])if(await g(d(this.root,l),2*1024*1024))throw new o("gc_recovery_required",`GC refused: unresolved ${l}; stop all owners and inspect recovery references`);let t=await this.active(),n=T(await I(d(this.root,"previous.json")));if(!t&&await g(d(this.root,"active.json"),2*1024*1024))throw new o("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let i=[t,n].filter(l=>!!l),s=d(this.root,"states");await x(s);let a=await W(s),c=new Set(i.map(l=>l.stateRef));for(let l of a){if(!re(l))throw new o("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let u=d(s,l),p=await F(u);if(!p.isDirectory()||p.isSymbolicLink())throw new o("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await W(u)){let v=await F(d(u,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!v.isFile()||v.isSymbolicLink()||v.nlink!==1)throw new o("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!c.has(l)){let h=await E(d(u,m),A);if(!h)throw new o("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(h,"committed")){let w=h;if(Object.keys(w).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||w.committed!==!0||!/^[a-f0-9]{64}$/.test(w.inputHash)||!/^[a-f0-9]{64}$/.test(w.nextHash)||typeof w.requestId!="string")throw new o("gc_recovery_required",`GC refused: unresolved file intent in states/${l}; reconcile the workspace save before cleanup`)}else{if(Object.keys(h).some(w=>!["revision","schema","value","requestId","inputHash"].includes(w)))throw new o("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(h)}}}}for(let l of c)if(!a.includes(l))throw new o("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let f=await e(i);for(let l of a)c.has(l)||await Se(d(s,l),{recursive:!0,force:!0});return f})}async assertGeneration(e,t=!0){let n=await this.active();if(!n||n.generation!==e||t&&!n.enabled)throw new o("stale_generation","Plugin generation is no longer active");return n}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 o("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,t,n,i="session"){if(i!=="session"&&i!=="workspace")throw new o("invalid_input","Invalid state scope");let s=i==="workspace"?(this.scopeKey(t),JSON.stringify([t.scope.workspaceId,t.scope.cwd])):this.scopeKey(t);return d(this.root,"states",e.stateRef,`${y(s+":state:"+n)}.json`)}async call(e,t,n){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new o("invalid_lease","Invalid invocation lease");this.scopeKey(e);let i=Oe(n);return R(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(t){case"state.read":{let a=await E(this.statePath(s,e,ne(i.key),i.scope),A);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,ne(i.key),i.scope);if(!Number.isSafeInteger(i.expectedRevision)||i.expectedRevision<0||i.schema!==s.schema||!Object.hasOwn(i,"value"))throw new o("invalid_input","Invalid state revision or schema");if(JSON.stringify(i.value)===void 0)throw new o("invalid_input","State value must be JSON serializable");let c=JSON.stringify(i);if(Buffer.byteLength(c)>A)throw new o("state_too_large","Plugin state exceeds limit");let f=await E(a,A);f&&this.validateState(f);let l=y(c);if(f?.requestId===e.requestId&&f.inputHash===l)return{revision:f.revision,schema:f.schema,value:f.value};if((f?.revision??0)!==i.expectedRevision)throw new o("revision_conflict","Plugin state changed concurrently");let u={revision:i.expectedRevision+1,schema:s.schema,value:i.value,requestId:e.requestId,inputHash:l};return await b(a,u),{revision:u.revision,schema:u.schema,value:u.value}}case"workspace.read":{let{target:a}=await this.fileTarget(e.scope.cwd,i.path),c=i.maxBytes===void 0?H:i.maxBytes;if(!Number.isSafeInteger(c)||c<=0||c>H)throw new o("invalid_input","Invalid workspace read limit");let f=await g(a,c);return f?{text:new TextDecoder("utf-8",{fatal:!0}).decode(f),hash:y(f)}:null}case"workspace.commit":return this.commitFile(s,e,i);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new o("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 o("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,t,n=!1){if(typeof t!="string"||t.length>4096||!t.endsWith(".excalidraw")||t.includes("\\")||t.includes("\0")||ee(t)||Re.isAbsolute(t))throw new o("invalid_path","Use a workspace-relative .excalidraw path");let i=await Z(e),s=Ee(i,t),a=te(i,s);if(!a||a===".."||a.startsWith(`..${U}`)||ee(a))throw new o("invalid_path","Workspace path escapes root");let c=i,f=a.split(U);for(let u=0;u<f.length;u++){c=d(c,f[u]);let p;try{p=await F(c)}catch(m){if(!q(m))throw m;if(u<f.length-1){if(!n||te(i,c)!=="diagrams")throw new o("invalid_path","Workspace directory does not exist");try{await be(c,{mode:448})}catch(v){if(v.code!=="EEXIST")throw v}p=await F(c)}}if(p&&(p.isSymbolicLink()||(u<f.length-1?!p.isDirectory():!p.isFile()||p.nlink!==1)))throw new o("invalid_path","Workspace path contains a link or non-regular file")}let l=await Z(xe(s));if(l!==i&&!l.startsWith(i+U))throw new o("invalid_path","Workspace directory changed");return{target:s,parent:l}}async commitFile(e,t,n){if(typeof n.text!="string"||Buffer.byteLength(n.text)>H||!(n.expectedHash===null||typeof n.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(n.expectedHash)))throw new o("invalid_input","Invalid file content or expected hash");let{target:i,parent:s}=await this.fileTarget(t.scope.cwd,n.path,!0),a=d(this.root,"states",e.stateRef,`${y(this.scopeKey(t)+":file:"+t.requestId+":"+String(n.path))}.json`),c=y(JSON.stringify(n)),f=y(n.text),l=await E(a);if(l&&(l.requestId!==t.requestId||l.inputHash!==c||l.nextHash!==f))throw new o("duplicate_request","Request ID was reused with different content");let u;try{u=await Q(`${i}.lock`,"wx",384)}catch(m){throw m.code==="EEXIST"?new o("file_busy","Workspace file is locked; original file preserved"):m}let p;try{await u.writeFile(JSON.stringify({pid:process.pid,requestId:t.requestId}));let m=await g(i,H),v=m?y(m):null;if(l&&v===f)return{hash:f};if(l?.committed||v!==n.expectedHash)throw new o("file_conflict","Workspace file already exists or changed externally");await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!1}),p=d(s,`.plugin-${G()}.tmp`);let h=await Q(p,"wx",384);try{await h.writeFile(n.text),await h.sync()}finally{await h.close()}if((await this.fileTarget(t.scope.cwd,n.path)).parent!==s)throw new o("file_conflict","Workspace directory changed during save");let _=await g(i,H);if((_?y(_):null)!==n.expectedHash)throw new o("file_conflict","Workspace file changed during save");if(await this.assertGeneration(t.generation),n.expectedHash===null){try{await ke(p,i)}catch(B){throw B.code==="EEXIST"?new o("file_conflict","Workspace file was created concurrently"):B}await S(p),p=void 0}else await Ie(p,i),p=void 0;return await b(a,{requestId:t.requestId,inputHash:c,nextHash:f,committed:!0}),{hash:f}}finally{p&&await S(p).catch(()=>{}),await u.close(),await S(`${i}.lock`)}}};var z="ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED";async function $(r){let e=[];async function t(n,i=""){let s=await ie(n);if(!s.isDirectory()||s.isSymbolicLink())throw new o("invalid_storage","Recovery refuses linked/non-directory storage");for(let a of(await Pe(n)).sort()){let c=k(n,a),f=i+a,l=await ie(c);if(l.isSymbolicLink())throw new o("invalid_storage","Recovery refuses links");if(l.isDirectory())await t(c,f+"/");else{if(e.length>=1e4)throw new o("invalid_storage","Recovery inspection budget exceeded");let u=await g(c,192*1024*1024);if(!u)throw new o("invalid_storage","Recovery input disappeared");e.push({path:f,bytes:u.length,sha256:y(u)})}}}return await t(r),{fingerprint:y(JSON.stringify(e)),files:e,warning:"Offline only: externally stop/fence ALL hosts and plugin workers, back up storage and workspace files. Never infer stopped ownership from PID alone."}}async function se(r,e,t,n){let i=new D(r,e),s=await $(i.root);if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");if(s.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");return i.recover()}async function ae(r,e,t,n){let i=new D(r,e),s=i.root;if(n!==z)throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let a=await $(s);if(a.fingerprint!==t)throw new o("recovery_changed","Storage changed since inspection");if(await g(k(s,"transition.json"),2*1024*1024))throw new o("gc_recovery_required","Reconcile transition.json using broker.recover before resolving a fork");let c=await I(k(s,"fork.json")),f=await i.active(),l=await I(k(s,"previous.json"));if(!c||c.version!==1||!/^[a-f0-9-]{36}$/.test(c.stateRef)||Object.keys(c).some(p=>!["version","stateRef"].includes(p))||!f||l&&typeof l.stateRef!="string"||[f?.stateRef,l?.stateRef].includes(c.stateRef))throw new o("gc_recovery_required","Fork is unknown or referenced by active/previous; original bytes preserved");let u=`recovered-${t}-fork.json`;if(a.files.some(p=>p.path===u))throw new o("recovery_changed","Recovery evidence already exists");return await oe(k(s,"fork.json"),k(s,u)),{recovered:"fork.json",stateRef:c.stateRef,fingerprint:t}}async function ce(r,e,t){if(t!==z||!/^[a-f0-9]{64}$/.test(e))throw new o("confirmation_required","Explicit stopped-owner and verified-backup confirmation required");let n=await $(r);if(n.fingerprint!==e)throw new o("recovery_changed","Storage changed since inspection; nothing recovered, inspect again");let i=[];for(let s of n.files.filter(a=>["runtime.lock","transaction.lock"].includes(a.path))){let a=await g(k(r,s.path),2097152);a&&!M(a)&&i.push(s)}for(let s of i){let a=`recovered-${e}-${s.path}.json`;if(n.files.some(c=>c.path===a))throw new o("recovery_changed","Recovery evidence already exists")}for(let s of i)await oe(k(r,s.path),k(r,`recovered-${e}-${s.path}.json`));return await b(k(r,`recovery-${e}.json`),{version:1,fingerprint:e,locks:i,confirmation:t,recoveredAt:new Date().toISOString()}),{recovered:i.map(s=>s.path),fingerprint:e}}var[O,le,P,j,L,...Ne]=process.argv.slice(2),Ae=le&&!Ne.length&&(O==="inspect"&&!P&&!j&&!L||O==="recover-locks"&&P&&j&&!L||["recover-fork","reconcile-transition"].includes(O??"")&&P&&j&&L);if(!Ae)console.error(`Offline only. Usage: node --experimental-strip-types scripts/hosted-stopped-recovery.ts
2
2
  inspect BROKER_ROOT
3
3
  recover-locks BROKER_ROOT FINGERPRINT CONFIRMATION
4
4
  reconcile-transition DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
5
5
  recover-fork DATA_ROOT PLUGIN_ID FINGERPRINT CONFIRMATION
6
6
  CONFIRMATION = ALL_HOSTS_AND_PLUGIN_WORKERS_STOPPED_AND_BACKUP_VERIFIED`),process.exitCode=2;else try{let r=je(le),e=O==="inspect"?await $(r):O==="recover-locks"?await ce(r,P,j):O==="recover-fork"?await ae(r,P,j,L):await se(r,P,j,L);console.log(JSON.stringify(e,null,2))}catch(r){console.error(r instanceof Error?r.message:"Recovery failed"),process.exitCode=1}var mt=void 0;export{mt as default};
7
7
 
8
- //# debugId=fba8c735-12ac-4b50-b08d-3b20fb0e2535
8
+ //# debugId=de73f4dd-c79a-4a98-a712-c4a7df53b206
@@ -1,3 +1,3 @@
1
- (function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="6a95746b-fbd8-4edc-878b-2ecb1e9b1494",t._sentryDebugIdIdentifier="sentry-dbid-6a95746b-fbd8-4edc-878b-2ecb1e9b1494")}catch{}})();import{AsyncLocalStorage as w}from"node:async_hooks";import{pathToFileURL as y}from"node:url";function c(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.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 l=new w,s=new Map,v=0,n,a=t=>{process.connected&&process.send?.(t)};process.on("message",t=>{if(!t||typeof t!="object")return;let e=t;if(e.type==="broker-response"&&typeof e.id=="string"){let r=s.get(e.id);if(!r)return;if(s.delete(e.id),e.ok)r.resolve(e.value);else{let o=e.error;r.reject(Object.assign(new Error(o?.message??"Host broker rejected request"),{code:o?.code,status:o?.status,reason:o?.reason}))}return}if(e.type!=="request"||typeof e.id!="string"||typeof e.method!="string")return;let i=e.id;(async()=>{switch(e.method){case"initialize":{if(n)throw new Error("Already initialized");let r=e.input,o=await import(y(r.entry).href);if(typeof o.createRuntime!="function")throw new Error("Missing createRuntime export");return n=await o.createRuntime({pluginId:r.pluginId,version:r.version,generation:r.generation,broker:{call(f,g){let u=l.getStore();if(!u)return Promise.reject(new Error("Broker calls require an active invocation"));if(s.size>=64)return Promise.reject(new Error("Too many broker requests"));let d=`b${++v}`;return new Promise((m,b)=>{s.set(d,{resolve:m,reject:b}),a({type:"broker-request",id:d,invocationId:u.requestId,method:f,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return l.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
1
+ (function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="644975af-de87-4558-95ce-3c338771a7bb",t._sentryDebugIdIdentifier="sentry-dbid-644975af-de87-4558-95ce-3c338771a7bb")}catch{}})();import{AsyncLocalStorage as y}from"node:async_hooks";import{pathToFileURL as b}from"node:url";function c(t){let e=t&&typeof t=="object"?t:{};return{code:typeof e.code=="string"&&/^[\w.-]{1,80}$/.test(e.code)?e.code:"plugin_failed",message:t instanceof Error?t.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 l=new y,s=new Map,v=0,n,a=t=>{process.connected&&process.send?.(t)};process.on("message",t=>{if(!t||typeof t!="object")return;let e=t;if(e.type==="broker-response"&&typeof e.id=="string"){let r=s.get(e.id);if(!r)return;if(s.delete(e.id),e.ok)r.resolve(e.value);else{let o=e.error;r.reject(Object.assign(new Error(o?.message??"Host broker rejected request"),{code:o?.code,status:o?.status,reason:o?.reason}))}return}if(e.type!=="request"||typeof e.id!="string"||typeof e.method!="string")return;let i=e.id;(async()=>{switch(e.method){case"initialize":{if(n)throw new Error("Already initialized");let r=e.input,o=await import(b(r.entry).href);if(typeof o.createRuntime!="function")throw new Error("Missing createRuntime export");return n=await o.createRuntime({pluginId:r.pluginId,version:r.version,generation:r.generation,broker:{call(f,g){let u=l.getStore();if(!u)return Promise.reject(new Error("Broker calls require an active invocation"));if(s.size>=64)return Promise.reject(new Error("Too many broker requests"));let d=`b${++v}`;return new Promise((m,w)=>{s.set(d,{resolve:m,reject:w}),a({type:"broker-request",id:d,invocationId:u.requestId,method:f,input:g})})}}}),{initialized:!0}}case"describe":if(!n)throw new Error("Not initialized");return n.describe();case"health":if(!n)throw new Error("Not initialized");return n.health();case"invoke":{if(!n)throw new Error("Not initialized");let r=e.input;return l.run(r,()=>n.invoke(r))}case"dispose":return await n?.dispose?.(),{disposed:!0};default:throw new Error("Unknown runtime operation")}})().then(r=>a({type:"response",id:i,ok:!0,value:r}),r=>a({type:"response",id:i,ok:!1,error:c(r)}))});process.on("disconnect",()=>{for(let t of s.values())t.reject(new Error("Host disconnected"));s.clear(),process.exitCode=1,Promise.resolve(n?.dispose?.()).finally(()=>process.exit(1))});var H=void 0;export{H as default};
2
2
 
3
- //# debugId=6a95746b-fbd8-4edc-878b-2ecb1e9b1494
3
+ //# debugId=644975af-de87-4558-95ce-3c338771a7bb
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-webapp",
3
- "version": "0.1.50-alpha.4",
3
+ "version": "0.1.50",
4
4
  "type": "module",
5
5
  "piWebappDesktopProtocol": 1,
6
6
  "piWebappDataVersion": 1,
@@ -30,7 +30,7 @@
30
30
  "pi-webapp": "./bin/pi-webapp.mjs"
31
31
  },
32
32
  "pi": {
33
- "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.50-alpha.4/assets/cover-webapp.png",
33
+ "image": "https://cdn.jsdelivr.net/npm/pi-webapp@0.1.50/assets/cover-webapp.png",
34
34
  "extensions": [
35
35
  "./dist/extension.js"
36
36
  ]
@@ -1,11 +1,11 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/app-BJZp9fzs.js","assets/app.css"])))=>i.map(i=>d[i]);
2
- var O=Object.defineProperty;var x=(e,t,i)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var d=(e,t,i)=>x(e,typeof t!="symbol"?t+"":t,i);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3c1c4a8-a0ce-4e1f-b8b0-4930319de85d",e._sentryDebugIdIdentifier="sentry-dbid-e3c1c4a8-a0ce-4e1f-b8b0-4930319de85d")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function i(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=i(s);fetch(s.href,n)}})();const B="modulepreload",D=function(e){return"/"+e},I={},A=function(t,i,r){let s=Promise.resolve();if(i&&i.length>0){let a=function(o){return Promise.all(o.map(l=>Promise.resolve(l).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),m=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));s=a(i.map(o=>{if(o=D(o),o in I)return;I[o]=!0;const l=o.endsWith(".css"),g=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${g}`))return;const f=document.createElement("link");if(f.rel=l?"stylesheet":B,l||(f.as="script"),f.crossOrigin="",f.href=o,m&&f.setAttribute("nonce",m),document.head.appendChild(f),l)return new Promise((T,N)=>{f.addEventListener("load",T),f.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${o}`)))})}))}function n(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&n(c.reason);return t().catch(n)})},j=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),q=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),ee={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},R=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),U=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function te(e){return e==="/api/message"||e==="/api/prompt-queue"||e.startsWith("/api/provider/")||e.startsWith("/api/workspace/files/")||e.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(e)}function p(e){return e.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function h(e){const t={};for(const i of R){const r=e[i];i==="toolName"?typeof r=="string"&&(j.has(r)||r==="custom")&&(t[i]=r):i==="failureKind"?q.has(r)&&(t[i]=r):i==="level"?(r==="warning"||r==="error")&&(t[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(t[i]=r):i==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(t[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(t[i]=r):i==="route"&&typeof r=="string"?t[i]=U.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?t[i]=r.split("/").map(p).join("/"):typeof r=="string"?t[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:p(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(t[i]=r)}return t}function v(e){var r;const t=e.replace(/\\/g,"/").split(/[?#]/)[0];return t.startsWith("node:")?t.slice(0,150):`app:///${(((r=t.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/))==null?void 0:r[1])??t.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function S(e,t=0){const i=e instanceof Error?e:new Error(typeof e=="string"?e:"Non-Error rejection"),r=new Error(p(i.message));if(r.name=p(i.name).slice(0,100),i.stack){const s=i.stack.split(`
2
+ var O=Object.defineProperty;var x=(e,t,i)=>t in e?O(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;var d=(e,t,i)=>x(e,typeof t!="symbol"?t+"":t,i);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="188bed0a-2507-4a63-b7f8-37aad0162e6e",e._sentryDebugIdIdentifier="sentry-dbid-188bed0a-2507-4a63-b7f8-37aad0162e6e")}catch{}})();(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const n of s)if(n.type==="childList")for(const a of n.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function i(s){const n={};return s.integrity&&(n.integrity=s.integrity),s.referrerPolicy&&(n.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?n.credentials="include":s.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(s){if(s.ep)return;s.ep=!0;const n=i(s);fetch(s.href,n)}})();const B="modulepreload",D=function(e){return"/"+e},I={},A=function(t,i,r){let s=Promise.resolve();if(i&&i.length>0){let a=function(o){return Promise.all(o.map(l=>Promise.resolve(l).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),m=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));s=a(i.map(o=>{if(o=D(o),o in I)return;I[o]=!0;const l=o.endsWith(".css"),g=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${o}"]${g}`))return;const f=document.createElement("link");if(f.rel=l?"stylesheet":B,l||(f.as="script"),f.crossOrigin="",f.href=o,m&&f.setAttribute("nonce",m),document.head.appendChild(f),l)return new Promise((T,N)=>{f.addEventListener("load",T),f.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${o}`)))})}))}function n(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return s.then(a=>{for(const c of a||[])c.status==="rejected"&&n(c.reason);return t().catch(n)})},j=new Set(["bash","powershell","read","write","edit","grep","find","ls"]),q=new Set(["cancelled","blocked","validation","not_found","permission","timeout","process_exit","unknown"]),ee={userInfo:!1,cookies:!1,httpHeaders:!1,httpBodies:[],urlQueryParams:!1,genAI:{inputs:!1,outputs:!1},graphQL:{document:!1,variables:!1},databaseQueryData:!1,queues:!1,stackFrameVariables:!1,frameContextLines:0},R=new Set(["stage","route","method","status","durationMs","connection","idle","model","thinkingLevel","messageCount","attachmentCount","session","requestId","operationId","errorId","repeats","dropped","componentStack","eventType","sequence","nodeVersion","piVersion","platform","browser","buildId","code","toolName","toolId","toolCallId","failureKind","errorCode","exitCode","timeoutMs","diagnosticSource","originalStackAvailable","errorSummary","summaryOmitted","summaryOmittedReason","level","networkKind","networkStage","causeCodes"]),U=new Set(["/api/workspace/git/control","/api/workspace/git/write","/api/workspace/git/status","/api/workspace/git/diff","/api/workspace/git/history","/api/workspace/git/commit-detail","/api/workspace/git/commit-diff","/api/workspace/files/list","/api/workspace/files/preview","/api/workspace/files/raw","/api/plugins","/api/plugin-action","/api/plugin-interaction","/api/resume","/api/update","/api/update/version","/api/update/channel","/api/provider/models","/api/provider/logout","/api/provider/login/active","/api/telemetry/config","/api/image","/api/attachment","/api/attachment/remove","/api/session","/api/providers","/api/models","/api/config","/api/workspaces","/api/commands","/api/events","/api/message","/api/prompt-queue","/api/abort","/api/compact","/api/new-session","/api/model","/api/thinking-level","/api/provider/login","/api/provider/login/respond","/api/provider/login/cancel","/api/provider/custom","/api/workspace/add","/api/workspace/select","/api/workspace/new-session","/api/workspace/remove","/api/session/select","/api/directory/capability","/api/directory/list","/api/directory/create","/api/directory/pick"]);function te(e){return e==="/api/message"||e==="/api/prompt-queue"||e.startsWith("/api/provider/")||e.startsWith("/api/workspace/files/")||e.startsWith("/api/workspace/git/")||["/api/plugin-action","/api/plugin-interaction","/api/resume","/api/compact"].includes(e)}function p(e){return e.slice(0,8192).replace(/-----BEGIN [^-\n]+-----[\s\S]*?(?:-----END [^-\n]+-----|$)/g,"[redacted]").replace(/(["'`])[\s\S]*?\1/g,"[quoted]").replace(/(?:Bearer\s+\S+|(?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*\S+)/gi,"[redacted]").replace(/\b(?:sk-|sntrys_|eyJ)[A-Za-z0-9_.-]+/g,"[redacted]").replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g,"[email]").replace(/https?:\/\/[^\s)]+/gi,"[url]").replace(/(?:file:\/\/)?(?:\/[\w.~-]+){2,}(?::\d+(?::\d+)?)?/g,"[path]").replace(/[A-Za-z]:\\[^\s)]+/g,"[path]").replace(/(?:^|\s)(?:\.\.?[\\/]|~[\\/])[^\s)]+/g," [path]").replace(/\b(?:[\w.-]+[\\/])+[\w.-]+/g,"[path]").replace(/\{[^\n]*\}/g,"[object]").replace(/\b[A-Za-z0-9_-]{24,}\b/g,"[redacted]").slice(0,1024)}function h(e){const t={};for(const i of R){const r=e[i];i==="toolName"?typeof r=="string"&&(j.has(r)||r==="custom")&&(t[i]=r):i==="failureKind"?q.has(r)&&(t[i]=r):i==="level"?(r==="warning"||r==="error")&&(t[i]=r):i==="diagnosticSource"?(r==="tool_execution_end"||r==="message_end")&&(t[i]=r):i==="errorCode"?typeof r=="string"&&/^(?:E[A-Z0-9]{1,20}|nonzero_exit|timeout|cancelled|blocked|invalid_arguments|tool_not_found|unknown)$/.test(r)&&(t[i]=r):i==="toolId"?typeof r=="string"&&/^[a-f0-9]{16}$/.test(r)&&(t[i]=r):i==="route"&&typeof r=="string"?t[i]=U.has(r.split("?")[0])?r.split("?")[0]:"[route]":i==="model"&&typeof r=="string"&&/^[\w.-]+\/[\w.-]+$/.test(r)?t[i]=r.split("/").map(p).join("/"):typeof r=="string"?t[i]=["requestId","operationId","errorId","session","buildId","toolId","toolCallId"].includes(i)&&/^[\w-]{1,80}$/.test(r)?r:p(r).slice(0,i==="errorSummary"?512:1024):(typeof r=="boolean"||typeof r=="number"&&Number.isFinite(r)||r===null)&&(t[i]=r)}return t}function v(e){var r;const t=e.replace(/\\/g,"/").split(/[?#]/)[0];return t.startsWith("node:")?t.slice(0,150):`app:///${(((r=t.match(/(?:^|\/)((?:web\/src|extension|shared|dist|assets)\/[^\s:)]+)$/))==null?void 0:r[1])??t.split("/").pop()??"unknown").replace(/[^\w./-]/g,"_").slice(-200)}`}function S(e,t=0){const i=e instanceof Error?e:new Error(typeof e=="string"?e:"Non-Error rejection"),r=new Error(p(i.message));if(r.name=p(i.name).slice(0,100),i.stack){const s=i.stack.split(`
3
3
  `).slice(1,31).map(n=>{const a=n.match(/((?:file:\/\/|https?:\/\/|\/|[A-Za-z]:\\)[^\s()]+):(\d+):(\d+)(\)?)$/);return a?`${p(n.slice(0,a.index))}${a[1]}:${a[2]}:${a[3]}${a[4]}`:p(n)});r.stack=`${r.name}: ${r.message}
4
4
  ${s.join(`
5
5
  `)}`}else r.stack=void 0;return t<3&&i.cause!==void 0&&(r.cause=S(i.cause,t+1)),r}function re(e,t){const i=new Error(t);return e instanceof Error&&(i.name=e.name,e.stack&&(i.stack=`${i.name}: ${t}
6
6
  ${e.stack.split(`
7
7
  `).slice(1).join(`
8
8
  `)}`)),i}function F(e){return{...e.filename?{filename:v(e.filename)}:{},...e.abs_path?{abs_path:v(e.abs_path)}:{},...e.function?{function:p(e.function)}:{},lineno:e.lineno,colno:e.colno,in_app:e.in_app}}function K(e){var r,s,n,a,c,m;const t=h(((r=e.contexts)==null?void 0:r.diagnostic)??{}),i=C(t);return{event_id:e.event_id,timestamp:e.timestamp,platform:e.platform,level:e.level,release:e.release,dist:e.dist,environment:p(e.environment??"production"),...e.message?{message:p(e.message)}:{},exception:e.exception?{values:(s=e.exception.values)==null?void 0:s.slice(0,4).map(o=>{var l;return{type:p(o.type??"Error"),value:p(o.value??""),...o.stacktrace?{stacktrace:{frames:(l=o.stacktrace.frames)==null?void 0:l.slice(-30).map(F)}}:{},...o.mechanism?{mechanism:{type:o.mechanism.type,handled:o.mechanism.handled}}:{}}})}:void 0,tags:{side:(n=e.tags)==null?void 0:n.side,buildId:(a=e.tags)==null?void 0:a.buildId,...t.toolName?{toolName:t.toolName}:{},...t.failureKind?{failureKind:t.failureKind}:{},...t.errorCode?{errorCode:t.errorCode}:{}},...i?{fingerprint:i}:{},contexts:{diagnostic:t},breadcrumbs:(c=e.breadcrumbs)==null?void 0:c.slice(-100).map(o=>({timestamp:o.timestamp,category:p(o.category??"app"),data:h(o.data??{})})),debug_meta:e.debug_meta?{images:(m=e.debug_meta.images)==null?void 0:m.slice(0,10).map(o=>({type:o.type,debug_id:o.debug_id,...o.code_file?{code_file:v(o.code_file)}:{}}))}:void 0}}function C(e){if(!(e.stage!=="tool"||e.originalStackAvailable!==!1||!e.toolName||!e.failureKind))return["pi-webapp-tool-result",String(e.toolName),String(e.toolId??"builtin"),String(e.failureKind),String(e.errorCode??"unknown")]}function ie(e,t){return t.attachments=[],K(e)}class Z{constructor(){d(this,"items",[]);d(this,"bytes",0);d(this,"encoder",new TextEncoder)}add(t,i={}){const r={timestamp:Date.now()/1e3,category:p(t),data:h(i)},s=this.encoder.encode(JSON.stringify(r)).byteLength+1;for(this.items.push({item:r,size:s}),this.bytes+=s;this.items.length>100||this.bytes>64*1024-2;)this.bytes-=this.items.shift().size}snapshot(){return this.items.map(({item:t})=>t)}}class V{constructor(){d(this,"windowAt",-1);d(this,"total",0);d(this,"seen",new Map)}take(t,i=Date.now()){(this.windowAt<0||i-this.windowAt>=6e4)&&(this.windowAt=i,this.total=0);const r=this.seen.get(t);if(r&&i-r.at<6e4){r.repeats++;return}if(!(this.total>=20))return this.total++,this.seen.size>=64&&!r&&this.seen.delete(this.seen.keys().next().value),this.seen.set(t,{at:i,repeats:0}),{repeats:(r==null?void 0:r.repeats)??0}}}const W=new Set(["目录路径必须是绝对路径","父目录路径必须是绝对路径","文件夹名称无效","工作区目录不可用,请恢复目录或从列表移除后重新添加","会话已切换","Pi 正在运行,请等待当前回复结束","请等待当前回复结束","请等待当前回复结束再切换工作区","请等待当前回复结束再切换会话","请先切换到其他工作区","新会话已取消","已有登录正在进行","模型不可用","模型提供方未配置认证","当前模型不支持此推理强度","其他提供方的登录正在进行,请先完成或取消当前登录","当前会话没有暂停的任务","请先完成当前交互或审批","请先选择模型","请先连接当前模型","插件未启用","会话运行实例已切换","提供方已存在","文件超过 20 MB","请求内容过大","会话不属于该工作区","推理强度无效","会话名称过长","会话不存在","插件会话不能重命名或删除","该会话正在 Pi 终端中使用,请在终端里切换到其他会话后再删除"]);function L(e){return e instanceof Error&&(e.name==="AbortError"||W.has(e.message))}class se{constructor(t,i,r,s,n=new Z){d(this,"budget",new V);d(this,"breadcrumbs");d(this,"scopeClass");d(this,"seen",new WeakSet);d(this,"state",{});d(this,"client");d(this,"side");d(this,"buildId");this.client=t,this.side=i,this.buildId=r,this.scopeClass=s.Scope,this.breadcrumbs=n,t.addIntegration(s.linkedErrorsIntegration({limit:4}))}setState(t){this.state=h(t)}capture(t,i={},r){var s;try{if(L(t))return;if(typeof t=="object"&&t!==null){if(this.seen.has(t))return;this.seen.add(t)}const n=S(t),a=h({...this.state,...i}),c=C(a),m=c?JSON.stringify(c):`${n.name}:${n.message}:${((s=n.stack)==null?void 0:s.split(`
9
- `)[1])??""}:${i.stage??""}`,o=this.budget.take(m);if(!o)return;const l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),a.level==="warning"&&l.setLevel("warning"),c&&l.setFingerprint(c),l.setContext("diagnostic",{...a,repeats:o.repeats});for(const g of this.breadcrumbs.snapshot())l.addBreadcrumb(g,100);return l.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(t){this.seen.add(t)}}function ne(e,t){return e({...t,bufferSize:20},async({body:i})=>{const r=await fetch(t.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}let w;function M(){if(w!==void 0)return w;const e=location.hash.slice(1);try{w=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{w=e||null}return e&&history.replaceState(null,"",location.pathname),w}const H="pi-webapp@0.1.50-alpha.4+6f276aca4a67bf831236",J="6f276aca4a67bf831236";function Q(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}let u,P=!0,$=!1,z=!1,_=[];const E=new WeakSet,y=new Map;let b={};function k(e,t={}){try{if(L(e))return;if(typeof e=="object"&&e!==null){if(E.has(e))return;E.add(e)}if(u)return u.capture(e,t);P&&_.length<20&&_.push({error:S(e),context:h(t)})}catch{}}function oe(e){E.add(e)}function ae(e,t={}){u==null||u.breadcrumbs.add(e,t)}function ce(e){e.sessionId&&(y.has(e.sessionId)||(y.size>=32&&y.delete(y.keys().next().value),y.set(e.sessionId,Q())),e={...e,session:y.get(e.sessionId)}),b=h({...b,...e}),u==null||u.setState(b)}function G(){$||($=!0,z=new URL(location.href).searchParams.get("sentry_release_probe")==="1",window.addEventListener("error",e=>{e instanceof ErrorEvent?k(e.error??new Error(e.message),{stage:"global"}):(e.target instanceof HTMLScriptElement||e.target instanceof HTMLLinkElement)&&k(new Error("Application resource failed to load"),{stage:"resource"})},!0),window.addEventListener("unhandledrejection",e=>k(e.reason,{stage:"unhandled_rejection"})),X())}async function X(){var e;try{const t=M();if(!t)return;const i=await fetch("/api/telemetry/config",{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e3)});if(!i.ok)return;const r=await i.json();if(!r.enabled||!r.dsn)return;const{createBrowserReporter:s}=await A(async()=>{const{createBrowserReporter:a}=await import("./telemetry-client-CBQBug9X.js");return{createBrowserReporter:a}},[]);u=s({...r,buildId:J,release:H});const n=((e=navigator.userAgent.match(/(?:Firefox|Edg|Chrome|Version)\/[\d.]+/))==null?void 0:e[0])??"unknown";u.setState({...b,browser:n,platform:navigator.platform}),b={...b,browser:n,platform:navigator.platform};for(const a of _)u.capture(a.error,a.context);r.environment==="sentry-verification"&&z&&u.capture(new Error("Sentry browser release verification"),{stage:"release_verification",code:"sentry_release_probe"})}catch{}finally{_=[],P=!1}}G();A(()=>import("./app-BJZp9fzs.js").then(e=>e.p),__vite__mapDeps([0,1])).catch(e=>k(e,{stage:"startup"}));export{se as E,A as _,Q as a,ae as b,te as c,M as d,ie as e,ne as f,oe as i,re as o,ee as p,k as r,ce as s};
9
+ `)[1])??""}:${i.stage??""}`,o=this.budget.take(m);if(!o)return;const l=new this.scopeClass;l.setClient(this.client),l.setTags({side:this.side,buildId:this.buildId}),a.level==="warning"&&l.setLevel("warning"),c&&l.setFingerprint(c),l.setContext("diagnostic",{...a,repeats:o.repeats});for(const g of this.breadcrumbs.snapshot())l.addBreadcrumb(g,100);return l.captureException(n,r?{event_id:r}:void 0)}catch{return}}ignore(t){this.seen.add(t)}}function ne(e,t){return e({...t,bufferSize:20},async({body:i})=>{const r=await fetch(t.url,{method:"POST",body:i,signal:AbortSignal.timeout(3e3),credentials:"omit",referrerPolicy:"no-referrer",redirect:"error",headers:{"Content-Type":"application/x-sentry-envelope"}});return{statusCode:r.status,headers:{"x-sentry-rate-limits":r.headers.get("x-sentry-rate-limits"),"retry-after":r.headers.get("retry-after")}}})}let w;function M(){if(w!==void 0)return w;const e=location.hash.slice(1);try{w=e||sessionStorage.getItem("pi-web-token"),e&&sessionStorage.setItem("pi-web-token",e)}catch{w=e||null}return e&&history.replaceState(null,"",location.pathname),w}const H="pi-webapp@0.1.50+69a663067b0de8af7f9c",J="69a663067b0de8af7f9c";function Q(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,i=>i.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}let u,P=!0,$=!1,z=!1,_=[];const E=new WeakSet,y=new Map;let b={};function k(e,t={}){try{if(L(e))return;if(typeof e=="object"&&e!==null){if(E.has(e))return;E.add(e)}if(u)return u.capture(e,t);P&&_.length<20&&_.push({error:S(e),context:h(t)})}catch{}}function oe(e){E.add(e)}function ae(e,t={}){u==null||u.breadcrumbs.add(e,t)}function ce(e){e.sessionId&&(y.has(e.sessionId)||(y.size>=32&&y.delete(y.keys().next().value),y.set(e.sessionId,Q())),e={...e,session:y.get(e.sessionId)}),b=h({...b,...e}),u==null||u.setState(b)}function G(){$||($=!0,z=new URL(location.href).searchParams.get("sentry_release_probe")==="1",window.addEventListener("error",e=>{e instanceof ErrorEvent?k(e.error??new Error(e.message),{stage:"global"}):(e.target instanceof HTMLScriptElement||e.target instanceof HTMLLinkElement)&&k(new Error("Application resource failed to load"),{stage:"resource"})},!0),window.addEventListener("unhandledrejection",e=>k(e.reason,{stage:"unhandled_rejection"})),X())}async function X(){var e;try{const t=M();if(!t)return;const i=await fetch("/api/telemetry/config",{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e3)});if(!i.ok)return;const r=await i.json();if(!r.enabled||!r.dsn)return;const{createBrowserReporter:s}=await A(async()=>{const{createBrowserReporter:a}=await import("./telemetry-client-CBQBug9X.js");return{createBrowserReporter:a}},[]);u=s({...r,buildId:J,release:H});const n=((e=navigator.userAgent.match(/(?:Firefox|Edg|Chrome|Version)\/[\d.]+/))==null?void 0:e[0])??"unknown";u.setState({...b,browser:n,platform:navigator.platform}),b={...b,browser:n,platform:navigator.platform};for(const a of _)u.capture(a.error,a.context);r.environment==="sentry-verification"&&z&&u.capture(new Error("Sentry browser release verification"),{stage:"release_verification",code:"sentry_release_probe"})}catch{}finally{_=[],P=!1}}G();A(()=>import("./app-BJZp9fzs.js").then(e=>e.p),__vite__mapDeps([0,1])).catch(e=>k(e,{stage:"startup"}));export{se as E,A as _,Q as a,ae as b,te as c,M as d,ie as e,ne as f,oe as i,re as o,ee as p,k as r,ce as s};
10
10
 
11
- //# debugId=e3c1c4a8-a0ce-4e1f-b8b0-4930319de85d
11
+ //# debugId=188bed0a-2507-4a63-b7f8-37aad0162e6e