pi-webapp 0.1.58-alpha.1 → 0.1.58-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/launcher-diagnostics.mjs +179 -0
- package/bin/launcher-logs.mjs +145 -0
- package/bin/pi-webapp.mjs +183 -39
- package/dist/extension.js +4 -4
- package/dist/hosted-recovery.js +2 -2
- package/dist/hosted-worker.js +2 -2
- package/package.json +2 -2
- package/web/dist/assets/app.js +3 -3
package/dist/extension.js
CHANGED
|
@@ -186,7 +186,7 @@ Reason: ${_}`))})}_process(t,e){this._numProcessing++,this._promiseBuffer.add(t)
|
|
|
186
186
|
__apm$patchIter('throw');
|
|
187
187
|
__apm$patchIter('return');
|
|
188
188
|
}
|
|
189
|
-
`}})),y5=Rc()});var Nc,Bb=w(()=>{Nc={}});var Pc,N5,Fb=w(()=>{ue();Lb();kc();Ec();Tc();zs();xc();Oc();qb();jb();Bb();Pc=ce(((t,e)=>{Ac(),pn(),dn(),un();let i=Ks.v??{},{parse:r}=Ys.v??{},{generate:n}=Ub.v??{},s=Rc(),a,o;var l=new WeakMap,c=new WeakMap,p=new WeakMap,d=new WeakMap,m=new WeakMap,g=new WeakMap,f=new WeakSet,h=class{constructor(C,N,G,P,I,x={}){Db(this,f),Je(this,l,null),Je(this,c,null),Je(this,p,null),Je(this,d,[]),Je(this,m,null),Je(this,g,{}),gt(l,this,C),gt(c,this,N),gt(p,this,G),gt(d,this,P),gt(m,this,I),gt(g,this,x)}free(){}get moduleName(){return ge(l,this)}get filePath(){return ge(p,this)}transform(C,N,G,P){let I=P?.sourceFile||`${ge(l,this)}/${ge(p,this)}`;if(Buffer.isBuffer(C)&&(C=C.toString()),!C)return{code:C};let x,L={},k=0,b={...s,...ge(g,this),defaults:{...s}};for(let j of ge(d,this)){let{astQuery:F,functionQuery:W={}}=j;if(!x){let Y={loc:!0,ranges:!0,raw:!0,module:N==="esm"};try{x=r(C,Y)}catch{x=r(C,{...Y,module:!Y.module})}N==="esm"&&(L=mt(f,this,E).call(this,x))}let $=mt(f,this,A).call(this,W,L),O=F||mt(f,this,D).call(this,$),he={...j,dcModule:ge(m,this),moduleType:N,moduleVersion:ge(c,this),functionQuery:$,transforms:b};he.operator=mt(f,this,S).call(this,he),i.traverse(x,i.parse(O),(...Y)=>{k++,mt(f,this,_).call(this,he,...Y)})}if(k===0&&ge(d,this).length>0){let j=ge(d,this).map(({astQuery:F,functionQuery:W={}})=>{if(F)return F;let $=mt(f,this,A).call(this,W,L),he=(Ce=>Ce.methodName||Ce.privateMethodName||Ce.functionName||Ce.expressionName||"constructor")(W),Y=W.className||W.functionName||W.expressionName,ae=$.className||$.functionName||$.expressionName;return Y&&Y!==ae?`${Y} (local name: ${ae})`:he});throw new Error(`Failed to find injection points for: ${JSON.stringify(j)}`)}if(x){a??(a=(Nc.v??{}).SourceMapConsumer),o??(o=(Nc.v??{}).SourceMapGenerator);let j=new o({file:I});j.setSourceContent(I,C);let F=n(x,{sourceMap:j});return G&&j.applySourceMap(new a(G),I),{code:F,map:j.toString()}}return{code:C}}};function _(C,...N){let G=typeof C.transform=="function"?C.transform:C.transforms[C.operator],{index:P=0}=C.functionQuery,[I]=N,x=I.init?.type||I.type;x!=="ClassDeclaration"&&x!=="ClassExpression"&&(I.type==="VariableDeclarator"||(C.functionIndex=++C.functionIndex||0,P!==null&&P!==C.functionIndex))||G(C,...N)}function S({transform:C,functionQuery:{kind:N}}){if(typeof C=="string")return C;switch(N){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}}function E(C){let N={};for(let G of C.body)if(G.type==="ExportNamedDeclaration"&&!G.source){for(let P of G.specifiers)if(P.exported&&P.local){let I=P.exported.name??P.exported.value,x=P.local.name??P.local.value;I&&x&&(N[I]=x)}}return N}function A(C,N){if(!C.isExportAlias)return C;let{functionName:G,expressionName:P,className:I}=C;return G&&N[G]?{...C,functionName:N[G]}:P&&N[P]?{...C,expressionName:N[P]}:I&&N[I]?{...C,className:N[I]}:C}function D(C){let{functionName:N,expressionName:G,className:P,objectName:I,propertyName:x}=C,L=C.privateMethodName?"PrivateIdentifier":"Identifier",k=[],b=C.methodName||C.privateMethodName;if(P?(b??(b="constructor"),k.push(`[id.name="${P}"]`,`[id.name="${P}"] > ClassExpression`,`[id.name="${P}"] > ClassBody > [key.name="${b}"][key.type=${L}] > [async]`,`[id.name="${P}"] > ClassExpression > ClassBody > [key.name="${b}"][key.type=${L}] > [async]`)):b&&k.push(`ClassBody > [key.name="${b}"][key.type=${L}] > [async]`,`Property[key.name="${b}"][key.type=${L}] > [async]`),N?k.push(`FunctionDeclaration[id.name="${N}"][async]`):G&&k.push(`FunctionExpression[id.name="${G}"][async]`,`ArrowFunctionExpression[id.name="${G}"][async]`,`VariableDeclarator[id.name="${G}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${G}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${G}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${G}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${G}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${G}"] > ArrowFunctionExpression[async]`),I||x){if(!I||!x)throw new Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${I}, propertyName=${x})`);let j=I==="this"?"left.object.type=ThisExpression":`left.object.name="${I}"`;k.push(`AssignmentExpression[${j}][left.property.name="${x}"] > [async]`)}return k.join(", ")}e.exports={Transformer:h}})),N5=Pc()});var Cc,B5,Hb=w(()=>{ue();kc();Ec();Tc();Mb();Fb();Cc=ce(((t,e)=>{pn(),dn(),un();let i=Ic(),{Transformer:r}=Pc();var n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=class{constructor(c,p){Je(this,n,[]),Je(this,s,null),Je(this,a,{}),Je(this,o,{}),gt(n,this,c),gt(s,this,p||"diagnostics_channel")}free(){gt(a,this,{})}addTransform(c,p){ge(o,this)[c]=p}getTransformer(c,p,d){d=d.replace(/\\/g,"/");let m=`${c}/${d}@${p}`;if(ge(a,this)[m])return ge(a,this)[m];let g=ge(n,this).filter(({module:f})=>f.name===c&&(typeof f.filePath=="string"?f.filePath===d:f.filePath.test(d))&&i(p,f.versionRange));if(g.length!==0)return ge(a,this)[m]=new r(c,p,d,g,ge(s,this),ge(o,this)),ge(a,this)[m]}};e.exports={InstrumentationMatcher:l}})),B5=Cc()});var Mc,$5,Gb=w(()=>{ue();Hb();Mc=ce(((t,e)=>{let{InstrumentationMatcher:i}=Cc();function r(n,s){return new i(n,s)}e.exports={create:r}})),$5=Mc()});var mn,Y5,Dc=w(()=>{ue();Gb();mn=ce(((t,e)=>{e.exports=Mc()})),Y5=mn()});import lI from"node:path";var gn,Z5,Lc=w(()=>{ue();gn=ce(((t,e)=>{var i=lI.sep;e.exports=function(r){var n=r.split(i),s=n.lastIndexOf("node_modules");if(s!==-1&&n[s+1]){for(var a=n[s+1][0]==="@",o=a?n[s+1]+"/"+n[s+2]:n[s+1],l=a?3:2,c="",p=s+l-1,d=0;d<=p;d++)d===p?c+=n[d]:c+=n[d]+i;for(var m="",g=n.length-1,f=s+l;f<=g;f++)f===g?m+=n[f]:m+=n[f]+i;return{name:o,basedir:c,path:m}}}})),Z5=gn()});import cI from"node:fs";import pI from"node:path";var fn,nG,Uc=w(()=>{ue();fn=ce(((t,e)=>{let{readFileSync:i}=cI,{join:r}=pI,n=new Map;function s(a){if(n.has(a))return n.get(a);try{let o=r(a,"package.json"),l=i(o),{version:c}=JSON.parse(l);return n.set(a,c),c}catch{return process.version.slice(1)}}e.exports=s})),nG=fn()});var Ii,oG,Qs=w(()=>{ue();Ii=ce(((t,e)=>{let i;function r(s){i=s}function n(s){i&&i(s)}e.exports={setDiagnosticsHook:r,emitDiagnostics:n}})),oG=Ii()});import{format as dI}from"node:util";function uI(t){return(...e)=>{U.isEnabled()&&U.log(`[${t}]`,dI(...e))}}var Wb,qc,$b=w(()=>{ue();vt();Wb=Nb({default:()=>uI});qc=Ue((()=>{}));qc()});var hn,fG,jc=w(()=>{ue();$b();hn=ce(((t,e)=>{e.exports=(qc(),Cb(Wb)).default})),fG=hn()});import mI from"node:module";import gI from"node:url";import fI from"node:os";import hI from"node:path";import yI from"node:fs";var Bc,xG,Vb=w(()=>{ue();Dc();Lc();Uc();Qs();jc();Bc=ce(((t,e)=>{let{create:i}=mn(),r=mI,n=gn(),{pathToFileURL:s}=gI,a=fn(),{emitDiagnostics:o}=Ii(),l=hn()("@apm-js-collab/tracing-hooks:module-patch");var c=class{constructor({instrumentations:d=[]}={}){this.packages=new Set(d.map(m=>m.module.name)),this.instrumentator=i(d),this.compile=r.prototype._compile}patch(){let d=this;r.prototype._compile=function(...g){let[f,h]=g,_=n(h);if(_&&d.packages.has(_.name)){l("found resolved module, checking if there is a transformer %s",h);let S=a(_.basedir,_.name),E=d.instrumentator.getTransformer(_.name,S,_.path);if(E){l("transforming file %s",h);try{g[0]=E.transform(f,"cjs")?.code,o({url:s(h).href,moduleName:E.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&p(g[0],h)}catch(A){l("Error transforming module %s: %o",h,A),o({url:s(h).href,moduleName:E.moduleName,error:A})}finally{E.free()}}}return d.compile.apply(this,g)}}unpatch(){r.prototype._compile=this.compile}};function p(d,m){let g=fI,f=hI,h=yI,_=process.env.TRACING_DUMP_DIR??g.tmpdir(),S=f.dirname(m),E=f.basename(m),A=f.join(_,S.slice(f.parse(S).root.length)),D=f.join(A,E);l("Dumping patched code to: %s",D),h.mkdirSync(A,{recursive:!0}),h.writeFileSync(D,d)}e.exports=c})),xG=Bc()});import{readFileSync as zb}from"node:fs";import{dirname as Kb,join as bI}from"node:path";import{fileURLToPath as Yb}from"node:url";import{MessageChannel as _I}from"node:worker_threads";function Xb(){let{port1:t,port2:e}=new _I;return t.on("message",Wc.emitDiagnostics),t.unref(),e}function Zb(t={}){let e=t?.instrumentations||[];Jb=(0,wI.create)(e),Qb=new Set(e.map(i=>i.module.name)),yn=new Map,Gc=t?.diagnosticsPort?EI(t.diagnosticsPort):Wc.emitDiagnostics}function EI(t){return e=>{try{let i=e.error===void 0||e.error instanceof Error?e.error:new Error(String(e.error));t.postMessage({...e,error:i})}catch(i){Hc("failed to post diagnostics for %s: %o",e.url,i)}}}function TI(t){if(!t.url.startsWith("file:"))return t;let e=(0,SI.default)(Yb(t.url));if(e&&Qb.has(e.name)){let i=e.basedir,r=(0,kI.default)(i),n=Jb.getTransformer(e.name,r,e.path);n&&yn.set(t.url,n)}return t}function e_(t,e,i){return TI(i(t,e))}function $c(t,e,i){let r=i(t,e);if(yn.has(t)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??t);r.source??(r.source=zb(n))}return II(t,r)}function II(t,e){let i=e.source;if(i){let r=yn.get(t);if(xI(t,e.format))return Hc("skipping json module %s",t),r.free(),yn.delete(t),e;try{let n=typeof i=="string"?i:Buffer.from(i).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":RI(t,n);e.source=r.transform(n,s)?.code,e.shortCircuit=!0,Gc({url:t,moduleName:r.moduleName})}catch(n){Hc("Error transforming module %s: %o",t,n),Gc({url:t,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function xI(t,e){return e==="json"||AI.test(t)}function RI(t,e){return NI(t)??(OI.test(e)?"esm":"cjs")}function NI(t){let e;try{e=Yb(t)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let i=t_(Kb(e));return i==="module"?"esm":i==="commonjs"?"cjs":void 0}function t_(t){if(Fc.has(t))return Fc.get(t);let e;try{e=JSON.parse(zb(bI(t,"package.json"),"utf8")).type}catch{let i=Kb(t);i!==t&&(e=t_(i))}return Fc.set(t,e),e}var vI,wI,SI,kI,Wc,Hc,yn,Qb,Jb,Gc,AI,OI,Fc,i_=w(()=>{ue();jc();Dc();Lc();Uc();Qs();vI=ar(hn(),1),wI=mn(),SI=ar(gn(),1),kI=ar(fn(),1),Wc=Ii(),Hc=(0,vI.default)("@apm-js-collab/tracing-hooks:esm-hook"),yn=null,Qb=null,Jb=null,Gc=Wc.emitDiagnostics;AI=/\.json([?#]|$)/;OI=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;Fc=new Map});import{createHash as r_}from"node:crypto";import{existsSync as o_,readFileSync as PI}from"node:fs";import*as CI from"node:module";import{dirname as Js,join as l_}from"node:path";import{fileURLToPath as Kc,pathToFileURL as Vc}from"node:url";function LI(t){if(t)return!0;let{major:e=0,minor:i=0}=fo(process.versions.node??"0.0.0");return e>25||e===25&&i>=1||e===24&&i>=13}function c_(t){if(zc.has(t))return zc.get(t);let e,i=l_(t,"package.json");if(o_(i))try{e=JSON.parse(PI(i,"utf8")).type}catch{e=void 0}else Js(t)!==t&&(e=c_(Js(t)));return zc.set(t,e),e}function UI(t){if(t.endsWith(".json"))return"json";if(t.endsWith(".mjs")||t.startsWith("file:")&&t.endsWith(".js")&&c_(Js(Kc(t)))==="module")return"module"}function qI(t){return(e,i,r)=>t(e,i,(n,s)=>{let a=r(n,s);if(a&&a.format==null){let o=UI(n);o&&(a.format=o)}return a})}function p_(t){st(()=>{console.warn(`[Sentry] ${t}`)})}function d_(t){p_(`${t} See ${DI}`)}function jI(t,e){let i=e instanceof Error?e.message:String(e),r=/^[\w$]+ is not a function$/.test(i),n=i==="transform is not a function",s=(Q.__SENTRY_ORCHESTRION__?.runtime?.length??0)===0;if(!(r&&!n&&s)){if(a_.has(t))return;a_.add(t),p_(`Could not instrument \`${t}\` (${i}). Other instrumented dependencies are unaffected, so this is not a bundling problem. If \`${t}\` should be traced, please report it.`);return}s_||(s_=!0,d_(`\`@sentry/server-runtime-injection\` was bundled into your application, so \`${t}\` and any other instrumented dependency load uninstrumented (${i}). Keep \`@sentry/server-runtime-injection\` external in your server bundle, or use the Sentry bundler plugin for build-time instrumentation.`))}function BI(){(0,MI.setDiagnosticsHook)(({url:t,moduleName:e,error:i})=>{if(i)i instanceof TypeError&&jI(e,i),U.warn(`[instrumentation] failed to inject diagnostics-channel into ${e}:`,i);else{var r;Q.__SENTRY_ORCHESTRION__=Q.__SENTRY_ORCHESTRION__||{},Q.__SENTRY_ORCHESTRION__.runtime=Q.__SENTRY_ORCHESTRION__.runtime||[],Q.__SENTRY_ORCHESTRION__.runtime.push(e),((r=Q.__SENTRY_ORCHESTRION__).runtimeFiles??(r.runtimeFiles={}))[e]=t,bt()?.emit("orchestrion.module-injected",e)}})}function u_(){let t=Q.__SENTRY_ORCHESTRION__??(Q.__SENTRY_ORCHESTRION__={});if(t.runtime||t.runtimeUnavailable)return;let e=globalThis,i=LI(!!e.Deno),r=CI;BI();try{if(typeof r.registerHooks=="function"&&i){Zb({instrumentations:ln});let n=new Map,s=e.Deno?qI($c):$c;r.registerHooks({resolve:e_,load:(c,p,d)=>{let m=s(c,p,d),g=m?.format??p.format;if((g==null||g==="commonjs")&&m?.shortCircuit===!0&&m?.source!=null&&c.startsWith("file:")){let f=r_("sha256").update(m.source).digest("hex");n.set(Vc(Kc(c)).href,f)}return m}});let a=r.Module.prototype,o=a._compile;new n_.default({instrumentations:ln}).patch();let l=a._compile;a._compile=function(c,p,...d){let m=Vc(p).href,g=n.get(m);return n.delete(m),(g!==void 0&&g===r_("sha256").update(c).digest("hex")?o:l).call(this,c,p,...d)},U.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof r.register=="function"&&!e.Bun&&!e.Deno){let n=Xb(),s;s=import.meta.url;let a;a=l_(Js(Kc(import.meta.url)),"hook.js");let o=o_(a);o||U.warn(`No orchestrion loader hook at ${a}; falling back to the package specifier.`);let l=o?Vc(a).href:"@sentry/server-runtime-injection/hook";r.register(l,{parentURL:s,data:{instrumentations:ln,diagnosticsPort:n},transferList:[n]}),new n_.default({instrumentations:ln}).patch(),U.log("Registered diagnostics-channel injection via Module.register()")}else{t.runtimeUnavailable=!0,U.warn("No available Node API to register diagnostics-channel injection hooks; skipping.");return}}catch(n){t.runtimeUnavailable=!0;let s=n instanceof Error?n.message:String(n);d_(n?.code==="ERR_MODULE_NOT_FOUND"?`Channel-based integrations will not record spans: your deployment is missing a file from \`@sentry/server-runtime-injection\` (${s}). Your build's file tracing left it out. Deploy the whole \`@sentry/server-runtime-injection\` package directory with your server.`:`Failed to register diagnostics-channel injection hooks (${s}), so channel-based integrations will not record spans.`),U.warn("Diagnostics-channel injection registration error:",n);return}t.runtime=t.runtime||[]}var n_,MI,DI,zc,s_,a_,m_=w(()=>{ue();Vb();i_();Qs();vt();_b();n_=ar(Bc()),MI=Ii(),DI="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";zc=new Map;s_=!1,a_=new Set});import*as g_ from"node:os";import{isMainThread as FI,threadId as HI}from"worker_threads";var GI,Yc,f_=w(()=>{Gu();_t();vt();dl();Fs();vb();Rb();m_();GI=6e4,Yc=class extends cl{constructor(t){let e=t.includeServerName===!1?void 0:t.serverName||global.process.env.SENTRY_NAME||g_.hostname(),i={...t,platform:"node",runtime:t.runtime||{name:"node",version:global.process.version},serverName:e};tl(i,"node"),U.log(`Initializing Sentry: process: ${process.pid}, thread: ${FI?"main":`worker-${HI}`}.`),super(i),this._onExitFlushListener=()=>{this.emit("flush")},e&&this.on("beforeCaptureLog",r=>{r.attributes={...r.attributes,[ps]:e}}),process.on("beforeExit",this._onExitFlushListener),Go(this),Ob(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&t.enableRuntimeChannelInjection!==!1&&u_()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=xb():this.asyncLocalStorageLookup={asyncLocalStorage:kl()},super.init()}get tracer(){if(this._tracer)return this._tracer;let t="@sentry/node",e=At,i=Kt.getTracer(t,e);return this._tracer=i,i}async flush(t){return await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(t)}async close(t){this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off("beforeExit",this._clientReportOnExitFlushListener),this._onExitFlushListener&&process.off("beforeExit",this._onExitFlushListener);let e=await super.close(t);return this.traceProvider&&await this.traceProvider.shutdown(),e}startClientReportTracking(){let t=this.getOptions();t.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{Hu&&U.log("Flushing client reports based on interval."),this._flushOutcomes()},t.clientReportFlushInterval??GI).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){Jo(),super._setupIntegrations()}}});var h_=w(()=>{Eb();f_()});var y_={};Jw(y_,{NodeClient:()=>Yc,Scope:()=>We,createTransport:()=>Ko,defaultStackParser:()=>mc,linkedErrorsIntegration:()=>ol});var b_=w(()=>{"use strict";h_();vt()});(function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="05ae3b56-f6e9-4909-a5d5-02aee1aeb655",t._sentryDebugIdIdentifier="sentry-dbid-05ae3b56-f6e9-4909-a5d5-02aee1aeb655")}catch{}})();import{delimiter as PN,dirname as CN,join as wr,resolve as kr}from"node:path";import{readFileSync as MN,realpathSync as ed,watch as DN}from"node:fs";import{fileURLToPath as LN}from"node:url";import{DefaultPackageManager as Vw,getAgentDir as Pe,ModelRuntime as UN,SessionManager as Ln,SettingsManager as qN,VERSION as td}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as jN}from"@earendil-works/pi-ai";import{randomBytes as N_,randomUUID as Xc,timingSafeEqual as tA}from"node:crypto";import{readFile as iA,readdir as rA}from"node:fs/promises";import{createServer as nA}from"node:http";import{join as Zc}from"node:path";import{getAgentDir as sA}from"@earendil-works/pi-coding-agent";import{isAbsolute as A0,relative as x0}from"node:path";var Be={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var ld={id:Be.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 Xw}from"node:child_process";import{realpath as Zw}from"node:fs/promises";import{isAbsolute as cd,relative as e0,sep as t0,win32 as i0}from"node:path";var H=class extends Error{status;reason;constructor(e,i=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=i,this.reason=r}};function ee(t,e,i=2*1024*1024,r={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,a)=>{let o,l=Xw("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:t,env:{...n,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:i,windowsHide:!0},(c,p,d)=>{if(!c){if(o){a(new H("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let g=c.killed||c.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(d)?"index_locked":/already exists/i.test(d)?"branch_exists":/already checked out|used by worktree/i.test(d)?"branch_in_use":/would be overwritten|local changes/i.test(d)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(d)?"identity_missing":"git_failed";a(new H("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",g==="outcome_unknown"?503:409,g));return}let m=c.code;m==="ENOENT"?a(new H("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):m==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?a(new H("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(d)?a(new H("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):a(new H(c.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))});l.stdin?.on("error",c=>{o=c}),r.input!==void 0&&l.stdin?.end(r.input)})}async function Fe(t){let e=await Zw(t),i;try{i=(await ee(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof H&&n.status===404)return{kind:"not-repository"};if(n instanceof H&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let r=e0(i,e).split(t0).join("/");if(r===".."||r.startsWith("../")||cd(r))throw new H("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:i,scope:r?`${r}/`:""}}function pi(t){if(typeof t!="string"||!t||t.length>4096||t.includes("\0")||t.includes("\\")||cd(t)||i0.isAbsolute(t)||t.split("/").some(e=>!e||e==="."||e===".."))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as f0}from"node:crypto";import{lstat as Wa,realpath as kd}from"node:fs/promises";import{dirname as Sd,isAbsolute as h0,relative as y0,resolve as Ar}from"node:path";import{lstat as u0}from"node:fs/promises";import{resolve as m0}from"node:path";import{createHash as r0}from"node:crypto";import{constants as Et}from"node:fs";import{open as Fa,opendir as n0,realpath as pd,stat as Un}from"node:fs/promises";import{isAbsolute as ud,relative as s0,resolve as a0,sep as o0,win32 as l0}from"node:path";var c0=1e3,p0={bytes:512*1024,lines:1e4},Ha={bytes:5*1024*1024,lines:2e5},md=8*1024*1024,d0=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Ba=t=>r0("sha256").update(t).digest("hex"),X=class extends Error{status;reason;constructor(e,i=400,r){super(e),this.name="WorkspaceFileError",this.status=i,this.reason=r}};function dd(t,e){let i=s0(t,e);return i!==".."&&!i.startsWith(`..${o0}`)&&!ud(i)}async function Tr(t,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ud(e)||l0.isAbsolute(e))throw new X("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let i=await pd(t),r=a0(i,e);if(!dd(i,r))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await pd(r);if(!dd(i,n))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function qn(t){try{return await t()}catch(e){if(e instanceof X)throw e;let i=e.code;throw i==="ENOENT"||i==="ENOTDIR"?new X("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):i==="EACCES"||i==="EPERM"?new X("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function gd(t,e){return qn(async()=>{let i=await Tr(t,e),r=[],n=!1;for await(let s of await n0(i)){if(s.name===".git")continue;if(r.length===c0){n=!0;break}let a=e?`${e}/${s.name}`:s.name,o=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let l=await Un(await Tr(t,a));o=l.isDirectory()?"directory":l.isFile()?"file":"other"}catch{}r.push({name:s.name,path:a,kind:o})}return r.sort((s,a)=>+(a.kind==="directory")-+(s.kind==="directory")||d0.compare(s.name,a.name)||s.name.localeCompare(a.name)),{path:e,entries:r,truncated:n}})}function fd(t){if(t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(t.subarray(0,6).toString("ascii")))return"image/gif";if(t.subarray(0,4).toString("ascii")==="RIFF"&&t.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Ir(t,e,i=p0){return qn(async()=>{let r=await Tr(t,e);if(!(await Un(r)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Fa(r,Et.O_RDONLY|Et.O_NONBLOCK|(Et.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let a={path:e,size:s.size},o=Buffer.alloc(16);await n.read(o,0,o.length,0);let l=fd(o),c=l?md:i.bytes;if(s.size>c)return{...a,kind:"too-large",limit:c,unit:"bytes"};let p=Buffer.alloc(Math.min(s.size+1,c+1)),d=0;for(;d<p.length;){let{bytesRead:f}=await n.read(p,d,p.length-d,d);if(!f)break;d+=f}if(d>s.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let m=p.subarray(0,d);if(l)return{...a,kind:"image",mimeType:l,data:m.toString("base64")};if(m.some(f=>f===0||f<32&&![9,10,12,13,27].includes(f)))return{...a,kind:"unsupported"};let g=1;for(let f=0;f<m.length-1;f++)if(m[f]===10&&++g>i.lines)return{...a,kind:"too-large",limit:i.lines,unit:"lines"};try{return{...a,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(m),version:Ba(m)}}catch{return{...a,kind:"unsupported"}}}finally{await n.close()}})}async function hd(t,e){return qn(async()=>{let i=await Tr(t,e);if(!(await Un(i)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Fa(i,Et.O_RDONLY|Et.O_NONBLOCK|(Et.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>md)throw new X("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(n.size+1),a=0;for(;a<s.length;){let{bytesRead:c}=await r.read(s,a,s.length-a,a);if(!c)break;a+=c}if(a>n.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let o=s.subarray(0,a),l=fd(o);if(!l)throw new X("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:l,bytes:o}}finally{await r.close()}})}async function yd(t,e,i,r){if(typeof i!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new X("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(i,"utf8"),{bytes:s,lines:a}=Ha;if(n.length>s)throw new X(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let o=1;for(let l of n)if(l===10&&++o>a+1)throw new X(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${a} \u884C`,413);return qn(async()=>{let l=await Tr(t,e);if(!(await Un(l)).isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Fa(l,Et.O_RDWR|Et.O_NONBLOCK|(Et.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");let d=Buffer.alloc(p.size+1),m=0;for(;m<d.length;){let{bytesRead:f}=await c.read(d,m,d.length-m,m);if(!f)break;m+=f}if(m>p.size||Ba(d.subarray(0,m))!==r)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");await c.truncate(0);let g=0;for(;g<n.length;)g+=(await c.write(n,g,n.length-g,g)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Ba(n)}}finally{await c.close()}})}var g0=1e3,bd=512*1024,_d=1e4;function vd(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}async function Bi(t){let e=await Fe(t);if(e.kind!=="repository")return e;let{root:i,scope:r}=e,n=await ee(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:i,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},a=n.split("\0");for(let o=0;o<a.length;o++){let l=a[o];if(l.startsWith("# branch.oid ")){let S=l.slice(13);s.head=S==="(initial)"?null:S;continue}if(l.startsWith("# branch.head ")){let S=l.slice(14);s.branch=S==="(detached)"?null:S;continue}if(l.startsWith("# branch.upstream ")){s.upstream=l.slice(18);continue}if(l.startsWith("# branch.ab ")){let S=l.match(/\+(\d+) -(\d+)/);S&&(s.ahead=Number(S[1]),s.behind=Number(S[2]));continue}let c=l[0];if(!["1","2","u","?"].includes(c??""))continue;let p=c==="?"?1:c==="1"?8:c==="2"?9:10,d=0;for(let S=0;S<p;S++)d=l.indexOf(" ",d)+1;let m=vd(r,l.slice(d)),g=c==="2"?a[++o]:void 0;if(!m)continue;if(s.entries.length===g0){s.truncated=!0;continue}let f=l.slice(0,d).split(" "),h={path:m,index:c==="?"?"?":f[1][0],worktree:c==="?"?"?":f[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&f[2]!=="N..."},_=g===void 0?void 0:vd(r,g);_&&(h.originalPath=_),s.entries.push(h)}return s}async function wd(t,e,i){if(pi(e),!["staged","unstaged","untracked"].includes(i))throw new H("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await Bi(t);if(r.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:i},s=r.entries.find(o=>o.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(i==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await u0(m0(t,e))).isFile())return{...n,kind:"unsupported"};let o=await Ir(t,e);if(o.kind==="too-large")return{...n,kind:"too-large"};if(o.kind!=="text")return{...n,kind:"binary"};if(!o.text)return{...n,kind:"empty"};let l=o.text.split(`
|
|
189
|
+
`}})),y5=Rc()});var Nc,Bb=w(()=>{Nc={}});var Pc,N5,Fb=w(()=>{ue();Lb();kc();Ec();Tc();zs();xc();Oc();qb();jb();Bb();Pc=ce(((t,e)=>{Ac(),pn(),dn(),un();let i=Ks.v??{},{parse:r}=Ys.v??{},{generate:n}=Ub.v??{},s=Rc(),a,o;var l=new WeakMap,c=new WeakMap,p=new WeakMap,d=new WeakMap,m=new WeakMap,g=new WeakMap,f=new WeakSet,h=class{constructor(C,N,G,P,I,x={}){Db(this,f),Je(this,l,null),Je(this,c,null),Je(this,p,null),Je(this,d,[]),Je(this,m,null),Je(this,g,{}),gt(l,this,C),gt(c,this,N),gt(p,this,G),gt(d,this,P),gt(m,this,I),gt(g,this,x)}free(){}get moduleName(){return ge(l,this)}get filePath(){return ge(p,this)}transform(C,N,G,P){let I=P?.sourceFile||`${ge(l,this)}/${ge(p,this)}`;if(Buffer.isBuffer(C)&&(C=C.toString()),!C)return{code:C};let x,L={},k=0,b={...s,...ge(g,this),defaults:{...s}};for(let j of ge(d,this)){let{astQuery:F,functionQuery:W={}}=j;if(!x){let Y={loc:!0,ranges:!0,raw:!0,module:N==="esm"};try{x=r(C,Y)}catch{x=r(C,{...Y,module:!Y.module})}N==="esm"&&(L=mt(f,this,E).call(this,x))}let $=mt(f,this,A).call(this,W,L),O=F||mt(f,this,D).call(this,$),he={...j,dcModule:ge(m,this),moduleType:N,moduleVersion:ge(c,this),functionQuery:$,transforms:b};he.operator=mt(f,this,S).call(this,he),i.traverse(x,i.parse(O),(...Y)=>{k++,mt(f,this,_).call(this,he,...Y)})}if(k===0&&ge(d,this).length>0){let j=ge(d,this).map(({astQuery:F,functionQuery:W={}})=>{if(F)return F;let $=mt(f,this,A).call(this,W,L),he=(Ce=>Ce.methodName||Ce.privateMethodName||Ce.functionName||Ce.expressionName||"constructor")(W),Y=W.className||W.functionName||W.expressionName,ae=$.className||$.functionName||$.expressionName;return Y&&Y!==ae?`${Y} (local name: ${ae})`:he});throw new Error(`Failed to find injection points for: ${JSON.stringify(j)}`)}if(x){a??(a=(Nc.v??{}).SourceMapConsumer),o??(o=(Nc.v??{}).SourceMapGenerator);let j=new o({file:I});j.setSourceContent(I,C);let F=n(x,{sourceMap:j});return G&&j.applySourceMap(new a(G),I),{code:F,map:j.toString()}}return{code:C}}};function _(C,...N){let G=typeof C.transform=="function"?C.transform:C.transforms[C.operator],{index:P=0}=C.functionQuery,[I]=N,x=I.init?.type||I.type;x!=="ClassDeclaration"&&x!=="ClassExpression"&&(I.type==="VariableDeclarator"||(C.functionIndex=++C.functionIndex||0,P!==null&&P!==C.functionIndex))||G(C,...N)}function S({transform:C,functionQuery:{kind:N}}){if(typeof C=="string")return C;switch(N){case"Async":return"tracePromise";case"Auto":return"traceAuto";case"Callback":return"traceCallback";case"Sync":return"traceSync";default:return"traceSync"}}function E(C){let N={};for(let G of C.body)if(G.type==="ExportNamedDeclaration"&&!G.source){for(let P of G.specifiers)if(P.exported&&P.local){let I=P.exported.name??P.exported.value,x=P.local.name??P.local.value;I&&x&&(N[I]=x)}}return N}function A(C,N){if(!C.isExportAlias)return C;let{functionName:G,expressionName:P,className:I}=C;return G&&N[G]?{...C,functionName:N[G]}:P&&N[P]?{...C,expressionName:N[P]}:I&&N[I]?{...C,className:N[I]}:C}function D(C){let{functionName:N,expressionName:G,className:P,objectName:I,propertyName:x}=C,L=C.privateMethodName?"PrivateIdentifier":"Identifier",k=[],b=C.methodName||C.privateMethodName;if(P?(b??(b="constructor"),k.push(`[id.name="${P}"]`,`[id.name="${P}"] > ClassExpression`,`[id.name="${P}"] > ClassBody > [key.name="${b}"][key.type=${L}] > [async]`,`[id.name="${P}"] > ClassExpression > ClassBody > [key.name="${b}"][key.type=${L}] > [async]`)):b&&k.push(`ClassBody > [key.name="${b}"][key.type=${L}] > [async]`,`Property[key.name="${b}"][key.type=${L}] > [async]`),N?k.push(`FunctionDeclaration[id.name="${N}"][async]`):G&&k.push(`FunctionExpression[id.name="${G}"][async]`,`ArrowFunctionExpression[id.name="${G}"][async]`,`VariableDeclarator[id.name="${G}"] > FunctionExpression[async]`,`VariableDeclarator[id.name="${G}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.property.name="${G}"] > FunctionExpression[async]`,`AssignmentExpression[left.property.name="${G}"] > ArrowFunctionExpression[async]`,`AssignmentExpression[left.name="${G}"] > FunctionExpression[async]`,`AssignmentExpression[left.name="${G}"] > ArrowFunctionExpression[async]`),I||x){if(!I||!x)throw new Error(`functionQuery: 'objectName' and 'propertyName' must be used together (got objectName=${I}, propertyName=${x})`);let j=I==="this"?"left.object.type=ThisExpression":`left.object.name="${I}"`;k.push(`AssignmentExpression[${j}][left.property.name="${x}"] > [async]`)}return k.join(", ")}e.exports={Transformer:h}})),N5=Pc()});var Cc,B5,Hb=w(()=>{ue();kc();Ec();Tc();Mb();Fb();Cc=ce(((t,e)=>{pn(),dn(),un();let i=Ic(),{Transformer:r}=Pc();var n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=class{constructor(c,p){Je(this,n,[]),Je(this,s,null),Je(this,a,{}),Je(this,o,{}),gt(n,this,c),gt(s,this,p||"diagnostics_channel")}free(){gt(a,this,{})}addTransform(c,p){ge(o,this)[c]=p}getTransformer(c,p,d){d=d.replace(/\\/g,"/");let m=`${c}/${d}@${p}`;if(ge(a,this)[m])return ge(a,this)[m];let g=ge(n,this).filter(({module:f})=>f.name===c&&(typeof f.filePath=="string"?f.filePath===d:f.filePath.test(d))&&i(p,f.versionRange));if(g.length!==0)return ge(a,this)[m]=new r(c,p,d,g,ge(s,this),ge(o,this)),ge(a,this)[m]}};e.exports={InstrumentationMatcher:l}})),B5=Cc()});var Mc,$5,Gb=w(()=>{ue();Hb();Mc=ce(((t,e)=>{let{InstrumentationMatcher:i}=Cc();function r(n,s){return new i(n,s)}e.exports={create:r}})),$5=Mc()});var mn,Y5,Dc=w(()=>{ue();Gb();mn=ce(((t,e)=>{e.exports=Mc()})),Y5=mn()});import lI from"node:path";var gn,Z5,Lc=w(()=>{ue();gn=ce(((t,e)=>{var i=lI.sep;e.exports=function(r){var n=r.split(i),s=n.lastIndexOf("node_modules");if(s!==-1&&n[s+1]){for(var a=n[s+1][0]==="@",o=a?n[s+1]+"/"+n[s+2]:n[s+1],l=a?3:2,c="",p=s+l-1,d=0;d<=p;d++)d===p?c+=n[d]:c+=n[d]+i;for(var m="",g=n.length-1,f=s+l;f<=g;f++)f===g?m+=n[f]:m+=n[f]+i;return{name:o,basedir:c,path:m}}}})),Z5=gn()});import cI from"node:fs";import pI from"node:path";var fn,nG,Uc=w(()=>{ue();fn=ce(((t,e)=>{let{readFileSync:i}=cI,{join:r}=pI,n=new Map;function s(a){if(n.has(a))return n.get(a);try{let o=r(a,"package.json"),l=i(o),{version:c}=JSON.parse(l);return n.set(a,c),c}catch{return process.version.slice(1)}}e.exports=s})),nG=fn()});var Ii,oG,Qs=w(()=>{ue();Ii=ce(((t,e)=>{let i;function r(s){i=s}function n(s){i&&i(s)}e.exports={setDiagnosticsHook:r,emitDiagnostics:n}})),oG=Ii()});import{format as dI}from"node:util";function uI(t){return(...e)=>{U.isEnabled()&&U.log(`[${t}]`,dI(...e))}}var Wb,qc,$b=w(()=>{ue();vt();Wb=Nb({default:()=>uI});qc=Ue((()=>{}));qc()});var hn,fG,jc=w(()=>{ue();$b();hn=ce(((t,e)=>{e.exports=(qc(),Cb(Wb)).default})),fG=hn()});import mI from"node:module";import gI from"node:url";import fI from"node:os";import hI from"node:path";import yI from"node:fs";var Bc,xG,Vb=w(()=>{ue();Dc();Lc();Uc();Qs();jc();Bc=ce(((t,e)=>{let{create:i}=mn(),r=mI,n=gn(),{pathToFileURL:s}=gI,a=fn(),{emitDiagnostics:o}=Ii(),l=hn()("@apm-js-collab/tracing-hooks:module-patch");var c=class{constructor({instrumentations:d=[]}={}){this.packages=new Set(d.map(m=>m.module.name)),this.instrumentator=i(d),this.compile=r.prototype._compile}patch(){let d=this;r.prototype._compile=function(...g){let[f,h]=g,_=n(h);if(_&&d.packages.has(_.name)){l("found resolved module, checking if there is a transformer %s",h);let S=a(_.basedir,_.name),E=d.instrumentator.getTransformer(_.name,S,_.path);if(E){l("transforming file %s",h);try{g[0]=E.transform(f,"cjs")?.code,o({url:s(h).href,moduleName:E.moduleName}),(()=>{try{return process.env.TRACING_DUMP}catch{return}})()&&p(g[0],h)}catch(A){l("Error transforming module %s: %o",h,A),o({url:s(h).href,moduleName:E.moduleName,error:A})}finally{E.free()}}}return d.compile.apply(this,g)}}unpatch(){r.prototype._compile=this.compile}};function p(d,m){let g=fI,f=hI,h=yI,_=process.env.TRACING_DUMP_DIR??g.tmpdir(),S=f.dirname(m),E=f.basename(m),A=f.join(_,S.slice(f.parse(S).root.length)),D=f.join(A,E);l("Dumping patched code to: %s",D),h.mkdirSync(A,{recursive:!0}),h.writeFileSync(D,d)}e.exports=c})),xG=Bc()});import{readFileSync as zb}from"node:fs";import{dirname as Kb,join as bI}from"node:path";import{fileURLToPath as Yb}from"node:url";import{MessageChannel as _I}from"node:worker_threads";function Xb(){let{port1:t,port2:e}=new _I;return t.on("message",Wc.emitDiagnostics),t.unref(),e}function Zb(t={}){let e=t?.instrumentations||[];Jb=(0,wI.create)(e),Qb=new Set(e.map(i=>i.module.name)),yn=new Map,Gc=t?.diagnosticsPort?EI(t.diagnosticsPort):Wc.emitDiagnostics}function EI(t){return e=>{try{let i=e.error===void 0||e.error instanceof Error?e.error:new Error(String(e.error));t.postMessage({...e,error:i})}catch(i){Hc("failed to post diagnostics for %s: %o",e.url,i)}}}function TI(t){if(!t.url.startsWith("file:"))return t;let e=(0,SI.default)(Yb(t.url));if(e&&Qb.has(e.name)){let i=e.basedir,r=(0,kI.default)(i),n=Jb.getTransformer(e.name,r,e.path);n&&yn.set(t.url,n)}return t}function e_(t,e,i){return TI(i(t,e))}function $c(t,e,i){let r=i(t,e);if(yn.has(t)===!1)return r;if(r.format==="commonjs"){let n=new URL(r.responseURL??t);r.source??(r.source=zb(n))}return II(t,r)}function II(t,e){let i=e.source;if(i){let r=yn.get(t);if(xI(t,e.format))return Hc("skipping json module %s",t),r.free(),yn.delete(t),e;try{let n=typeof i=="string"?i:Buffer.from(i).toString("utf8"),s=e.format==="module"?"esm":e.format==="commonjs"?"cjs":RI(t,n);e.source=r.transform(n,s)?.code,e.shortCircuit=!0,Gc({url:t,moduleName:r.moduleName})}catch(n){Hc("Error transforming module %s: %o",t,n),Gc({url:t,moduleName:r.moduleName,error:n})}finally{r.free()}}return e}function xI(t,e){return e==="json"||AI.test(t)}function RI(t,e){return NI(t)??(OI.test(e)?"esm":"cjs")}function NI(t){let e;try{e=Yb(t)}catch{return}if(e.endsWith(".mjs")||e.endsWith(".mts"))return"esm";if(e.endsWith(".cjs")||e.endsWith(".cts"))return"cjs";let i=t_(Kb(e));return i==="module"?"esm":i==="commonjs"?"cjs":void 0}function t_(t){if(Fc.has(t))return Fc.get(t);let e;try{e=JSON.parse(zb(bI(t,"package.json"),"utf8")).type}catch{let i=Kb(t);i!==t&&(e=t_(i))}return Fc.set(t,e),e}var vI,wI,SI,kI,Wc,Hc,yn,Qb,Jb,Gc,AI,OI,Fc,i_=w(()=>{ue();jc();Dc();Lc();Uc();Qs();vI=ar(hn(),1),wI=mn(),SI=ar(gn(),1),kI=ar(fn(),1),Wc=Ii(),Hc=(0,vI.default)("@apm-js-collab/tracing-hooks:esm-hook"),yn=null,Qb=null,Jb=null,Gc=Wc.emitDiagnostics;AI=/\.json([?#]|$)/;OI=/(^|[\n;])\s*(import\s+|import\s*[{*'"]|export\b)/;Fc=new Map});import{createHash as r_}from"node:crypto";import{existsSync as o_,readFileSync as PI}from"node:fs";import*as CI from"node:module";import{dirname as Js,join as l_}from"node:path";import{fileURLToPath as Kc,pathToFileURL as Vc}from"node:url";function LI(t){if(t)return!0;let{major:e=0,minor:i=0}=fo(process.versions.node??"0.0.0");return e>25||e===25&&i>=1||e===24&&i>=13}function c_(t){if(zc.has(t))return zc.get(t);let e,i=l_(t,"package.json");if(o_(i))try{e=JSON.parse(PI(i,"utf8")).type}catch{e=void 0}else Js(t)!==t&&(e=c_(Js(t)));return zc.set(t,e),e}function UI(t){if(t.endsWith(".json"))return"json";if(t.endsWith(".mjs")||t.startsWith("file:")&&t.endsWith(".js")&&c_(Js(Kc(t)))==="module")return"module"}function qI(t){return(e,i,r)=>t(e,i,(n,s)=>{let a=r(n,s);if(a&&a.format==null){let o=UI(n);o&&(a.format=o)}return a})}function p_(t){st(()=>{console.warn(`[Sentry] ${t}`)})}function d_(t){p_(`${t} See ${DI}`)}function jI(t,e){let i=e instanceof Error?e.message:String(e),r=/^[\w$]+ is not a function$/.test(i),n=i==="transform is not a function",s=(Q.__SENTRY_ORCHESTRION__?.runtime?.length??0)===0;if(!(r&&!n&&s)){if(a_.has(t))return;a_.add(t),p_(`Could not instrument \`${t}\` (${i}). Other instrumented dependencies are unaffected, so this is not a bundling problem. If \`${t}\` should be traced, please report it.`);return}s_||(s_=!0,d_(`\`@sentry/server-runtime-injection\` was bundled into your application, so \`${t}\` and any other instrumented dependency load uninstrumented (${i}). Keep \`@sentry/server-runtime-injection\` external in your server bundle, or use the Sentry bundler plugin for build-time instrumentation.`))}function BI(){(0,MI.setDiagnosticsHook)(({url:t,moduleName:e,error:i})=>{if(i)i instanceof TypeError&&jI(e,i),U.warn(`[instrumentation] failed to inject diagnostics-channel into ${e}:`,i);else{var r;Q.__SENTRY_ORCHESTRION__=Q.__SENTRY_ORCHESTRION__||{},Q.__SENTRY_ORCHESTRION__.runtime=Q.__SENTRY_ORCHESTRION__.runtime||[],Q.__SENTRY_ORCHESTRION__.runtime.push(e),((r=Q.__SENTRY_ORCHESTRION__).runtimeFiles??(r.runtimeFiles={}))[e]=t,bt()?.emit("orchestrion.module-injected",e)}})}function u_(){let t=Q.__SENTRY_ORCHESTRION__??(Q.__SENTRY_ORCHESTRION__={});if(t.runtime||t.runtimeUnavailable)return;let e=globalThis,i=LI(!!e.Deno),r=CI;BI();try{if(typeof r.registerHooks=="function"&&i){Zb({instrumentations:ln});let n=new Map,s=e.Deno?qI($c):$c;r.registerHooks({resolve:e_,load:(c,p,d)=>{let m=s(c,p,d),g=m?.format??p.format;if((g==null||g==="commonjs")&&m?.shortCircuit===!0&&m?.source!=null&&c.startsWith("file:")){let f=r_("sha256").update(m.source).digest("hex");n.set(Vc(Kc(c)).href,f)}return m}});let a=r.Module.prototype,o=a._compile;new n_.default({instrumentations:ln}).patch();let l=a._compile;a._compile=function(c,p,...d){let m=Vc(p).href,g=n.get(m);return n.delete(m),(g!==void 0&&g===r_("sha256").update(c).digest("hex")?o:l).call(this,c,p,...d)},U.log("Registered diagnostics-channel injection via Module.registerHooks()")}else if(typeof r.register=="function"&&!e.Bun&&!e.Deno){let n=Xb(),s;s=import.meta.url;let a;a=l_(Js(Kc(import.meta.url)),"hook.js");let o=o_(a);o||U.warn(`No orchestrion loader hook at ${a}; falling back to the package specifier.`);let l=o?Vc(a).href:"@sentry/server-runtime-injection/hook";r.register(l,{parentURL:s,data:{instrumentations:ln,diagnosticsPort:n},transferList:[n]}),new n_.default({instrumentations:ln}).patch(),U.log("Registered diagnostics-channel injection via Module.register()")}else{t.runtimeUnavailable=!0,U.warn("No available Node API to register diagnostics-channel injection hooks; skipping.");return}}catch(n){t.runtimeUnavailable=!0;let s=n instanceof Error?n.message:String(n);d_(n?.code==="ERR_MODULE_NOT_FOUND"?`Channel-based integrations will not record spans: your deployment is missing a file from \`@sentry/server-runtime-injection\` (${s}). Your build's file tracing left it out. Deploy the whole \`@sentry/server-runtime-injection\` package directory with your server.`:`Failed to register diagnostics-channel injection hooks (${s}), so channel-based integrations will not record spans.`),U.warn("Diagnostics-channel injection registration error:",n);return}t.runtime=t.runtime||[]}var n_,MI,DI,zc,s_,a_,m_=w(()=>{ue();Vb();i_();Qs();vt();_b();n_=ar(Bc()),MI=Ii(),DI="https://docs.sentry.io/platforms/javascript/guides/node/troubleshooting/";zc=new Map;s_=!1,a_=new Set});import*as g_ from"node:os";import{isMainThread as FI,threadId as HI}from"worker_threads";var GI,Yc,f_=w(()=>{Gu();_t();vt();dl();Fs();vb();Rb();m_();GI=6e4,Yc=class extends cl{constructor(t){let e=t.includeServerName===!1?void 0:t.serverName||global.process.env.SENTRY_NAME||g_.hostname(),i={...t,platform:"node",runtime:t.runtime||{name:"node",version:global.process.version},serverName:e};tl(i,"node"),U.log(`Initializing Sentry: process: ${process.pid}, thread: ${FI?"main":`worker-${HI}`}.`),super(i),this._onExitFlushListener=()=>{this.emit("flush")},e&&this.on("beforeCaptureLog",r=>{r.attributes={...r.attributes,[ps]:e}}),process.on("beforeExit",this._onExitFlushListener),Go(this),Ob(this),(typeof __SENTRY_CHANNEL_INJECTION__>"u"||__SENTRY_CHANNEL_INJECTION__)&&t.enableRuntimeChannelInjection!==!1&&u_()}init(){this.getOptions().enableOpenTelemetrySetup?this.asyncLocalStorageLookup=xb():this.asyncLocalStorageLookup={asyncLocalStorage:kl()},super.init()}get tracer(){if(this._tracer)return this._tracer;let t="@sentry/node",e=At,i=Kt.getTracer(t,e);return this._tracer=i,i}async flush(t){return await this.traceProvider?.forceFlush(),this.getOptions().sendClientReports&&this._flushOutcomes(),super.flush(t)}async close(t){this._clientReportInterval&&clearInterval(this._clientReportInterval),this._clientReportOnExitFlushListener&&process.off("beforeExit",this._clientReportOnExitFlushListener),this._onExitFlushListener&&process.off("beforeExit",this._onExitFlushListener);let e=await super.close(t);return this.traceProvider&&await this.traceProvider.shutdown(),e}startClientReportTracking(){let t=this.getOptions();t.sendClientReports&&(this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{Hu&&U.log("Flushing client reports based on interval."),this._flushOutcomes()},t.clientReportFlushInterval??GI).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener))}_setupIntegrations(){Jo(),super._setupIntegrations()}}});var h_=w(()=>{Eb();f_()});var y_={};Jw(y_,{NodeClient:()=>Yc,Scope:()=>We,createTransport:()=>Ko,defaultStackParser:()=>mc,linkedErrorsIntegration:()=>ol});var b_=w(()=>{"use strict";h_();vt()});(function(){try{var t=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new t.Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="af6f58c9-c0b2-4b3c-9fdd-42ec795ae10e",t._sentryDebugIdIdentifier="sentry-dbid-af6f58c9-c0b2-4b3c-9fdd-42ec795ae10e")}catch{}})();import{delimiter as PN,dirname as CN,join as wr,resolve as kr}from"node:path";import{readFileSync as MN,realpathSync as ed,watch as DN}from"node:fs";import{fileURLToPath as LN}from"node:url";import{DefaultPackageManager as Vw,getAgentDir as Pe,ModelRuntime as UN,SessionManager as Ln,SettingsManager as qN,VERSION as td}from"@earendil-works/pi-coding-agent";import{getSupportedThinkingLevels as jN}from"@earendil-works/pi-ai";import{randomBytes as N_,randomUUID as Xc,timingSafeEqual as tA}from"node:crypto";import{readFile as iA,readdir as rA}from"node:fs/promises";import{createServer as nA}from"node:http";import{join as Zc}from"node:path";import{getAgentDir as sA}from"@earendil-works/pi-coding-agent";import{isAbsolute as A0,relative as x0}from"node:path";var Be={diagrams:"@pi-webapp/diagrams",git:"@pi-webapp/git",files:"@pi-webapp/files",terminal:"@pi-webapp/terminal"};var ld={id:Be.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 Xw}from"node:child_process";import{realpath as Zw}from"node:fs/promises";import{isAbsolute as cd,relative as e0,sep as t0,win32 as i0}from"node:path";var H=class extends Error{status;reason;constructor(e,i=400,r="git_failed"){super(e),this.name="WorkspaceGitError",this.status=i,this.reason=r}};function ee(t,e,i=2*1024*1024,r={}){let n=Object.fromEntries(Object.entries(process.env).filter(([s])=>!s.startsWith("GIT_")));return new Promise((s,a)=>{let o,l=Xw("git",["--no-pager","--literal-pathspecs","-c","core.fsmonitor=false",...e],{cwd:t,env:{...n,LC_ALL:"C",GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1"},encoding:"utf8",timeout:r.write?3e4:1e4,maxBuffer:i,windowsHide:!0},(c,p,d)=>{if(!c){if(o){a(new H("Git \u8F93\u5165\u4F20\u8F93\u5931\u8D25\uFF0C\u64CD\u4F5C\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\uFF1B\u4E0D\u8981\u81EA\u52A8\u91CD\u8BD5",503,r.write?"outcome_unknown":"git_failed"));return}s(p);return}if(r.write){let g=c.killed||c.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?"outcome_unknown":/index\.lock|cannot lock ref|could not lock/i.test(d)?"index_locked":/already exists/i.test(d)?"branch_exists":/already checked out|used by worktree/i.test(d)?"branch_in_use":/would be overwritten|local changes/i.test(d)?"dirty_worktree":/identity unknown|unable to auto-detect email|empty ident/i.test(d)?"identity_missing":"git_failed";a(new H("Git \u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u5237\u65B0\u68C0\u67E5\u4ED3\u5E93\u72B6\u6001\u3001\u8EAB\u4EFD\u6216 hooks \u914D\u7F6E",g==="outcome_unknown"?503:409,g));return}let m=c.code;m==="ENOENT"?a(new H("Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528",503)):m==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER"?a(new H("Git \u8F93\u51FA\u8FC7\u5927\uFF0C\u8BF7\u7F29\u5C0F\u8BFB\u53D6\u8303\u56F4",413)):/not a git repository/.test(d)?a(new H("\u5F53\u524D\u76EE\u5F55\u4E0D\u662F Git \u4ED3\u5E93",404)):a(new H(c.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))});l.stdin?.on("error",c=>{o=c}),r.input!==void 0&&l.stdin?.end(r.input)})}async function Fe(t){let e=await Zw(t),i;try{i=(await ee(e,["rev-parse","--show-toplevel"])).replace(/\n$/,"")}catch(n){if(n instanceof H&&n.status===404)return{kind:"not-repository"};if(n instanceof H&&n.message==="Git \u672A\u5B89\u88C5\u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528")return{kind:"unavailable"};throw n}let r=e0(i,e).split(t0).join("/");if(r===".."||r.startsWith("../")||cd(r))throw new H("\u4ED3\u5E93\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return{kind:"repository",cwd:e,root:i,scope:r?`${r}/`:""}}function pi(t){if(typeof t!="string"||!t||t.length>4096||t.includes("\0")||t.includes("\\")||cd(t)||i0.isAbsolute(t)||t.split("/").some(e=>!e||e==="."||e===".."))throw new H("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548",403)}import{createHash as f0}from"node:crypto";import{lstat as Wa,realpath as kd}from"node:fs/promises";import{dirname as Sd,isAbsolute as h0,relative as y0,resolve as Ar}from"node:path";import{lstat as u0}from"node:fs/promises";import{resolve as m0}from"node:path";import{createHash as r0}from"node:crypto";import{constants as Et}from"node:fs";import{open as Fa,opendir as n0,realpath as pd,stat as Un}from"node:fs/promises";import{isAbsolute as ud,relative as s0,resolve as a0,sep as o0,win32 as l0}from"node:path";var c0=1e3,p0={bytes:512*1024,lines:1e4},Ha={bytes:5*1024*1024,lines:2e5},md=8*1024*1024,d0=new Intl.Collator("en",{numeric:!0,sensitivity:"base"}),Ba=t=>r0("sha256").update(t).digest("hex"),X=class extends Error{status;reason;constructor(e,i=400,r){super(e),this.name="WorkspaceFileError",this.status=i,this.reason=r}};function dd(t,e){let i=s0(t,e);return i!==".."&&!i.startsWith(`..${o0}`)&&!ud(i)}async function Tr(t,e){if(typeof e!="string"||e.length>4096||e.includes("\0")||e.includes("\\")||ud(e)||l0.isAbsolute(e))throw new X("\u5DE5\u4F5C\u533A\u6587\u4EF6\u8DEF\u5F84\u65E0\u6548");let i=await pd(t),r=a0(i,e);if(!dd(i,r))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);let n=await pd(r);if(!dd(i,n))throw new X("\u6587\u4EF6\u4F4D\u4E8E\u5DE5\u4F5C\u533A\u4E4B\u5916",403);return n}async function qn(t){try{return await t()}catch(e){if(e instanceof X)throw e;let i=e.code;throw i==="ENOENT"||i==="ENOTDIR"?new X("\u6587\u4EF6\u6216\u76EE\u5F55\u5DF2\u4E0D\u5B58\u5728",404):i==="EACCES"||i==="EPERM"?new X("\u6CA1\u6709\u6743\u9650\u8BFB\u53D6\u6587\u4EF6\u6216\u76EE\u5F55",403):e}}async function gd(t,e){return qn(async()=>{let i=await Tr(t,e),r=[],n=!1;for await(let s of await n0(i)){if(s.name===".git")continue;if(r.length===c0){n=!0;break}let a=e?`${e}/${s.name}`:s.name,o=s.isDirectory()?"directory":s.isFile()?"file":"other";if(s.isSymbolicLink())try{let l=await Un(await Tr(t,a));o=l.isDirectory()?"directory":l.isFile()?"file":"other"}catch{}r.push({name:s.name,path:a,kind:o})}return r.sort((s,a)=>+(a.kind==="directory")-+(s.kind==="directory")||d0.compare(s.name,a.name)||s.name.localeCompare(a.name)),{path:e,entries:r,truncated:n}})}function fd(t){if(t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(["GIF87a","GIF89a"].includes(t.subarray(0,6).toString("ascii")))return"image/gif";if(t.subarray(0,4).toString("ascii")==="RIFF"&&t.subarray(8,12).toString("ascii")==="WEBP")return"image/webp"}async function Ir(t,e,i=p0){return qn(async()=>{let r=await Tr(t,e);if(!(await Un(r)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let n=await Fa(r,Et.O_RDONLY|Et.O_NONBLOCK|(Et.O_NOFOLLOW??0));try{let s=await n.stat();if(!s.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let a={path:e,size:s.size},o=Buffer.alloc(16);await n.read(o,0,o.length,0);let l=fd(o),c=l?md:i.bytes;if(s.size>c)return{...a,kind:"too-large",limit:c,unit:"bytes"};let p=Buffer.alloc(Math.min(s.size+1,c+1)),d=0;for(;d<p.length;){let{bytesRead:f}=await n.read(p,d,p.length-d,d);if(!f)break;d+=f}if(d>s.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let m=p.subarray(0,d);if(l)return{...a,kind:"image",mimeType:l,data:m.toString("base64")};if(m.some(f=>f===0||f<32&&![9,10,12,13,27].includes(f)))return{...a,kind:"unsupported"};let g=1;for(let f=0;f<m.length-1;f++)if(m[f]===10&&++g>i.lines)return{...a,kind:"too-large",limit:i.lines,unit:"lines"};try{return{...a,kind:"text",text:new TextDecoder("utf-8",{fatal:!0}).decode(m),version:Ba(m)}}catch{return{...a,kind:"unsupported"}}}finally{await n.close()}})}async function hd(t,e){return qn(async()=>{let i=await Tr(t,e);if(!(await Un(i)).isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");let r=await Fa(i,Et.O_RDONLY|Et.O_NONBLOCK|(Et.O_NOFOLLOW??0));try{let n=await r.stat();if(!n.isFile())throw new X("\u8FD9\u4E0D\u662F\u53EF\u9884\u89C8\u7684\u666E\u901A\u6587\u4EF6");if(n.size>md)throw new X("\u56FE\u7247\u8FC7\u5927\uFF0C\u65E0\u6CD5\u9884\u89C8",413);let s=Buffer.alloc(n.size+1),a=0;for(;a<s.length;){let{bytesRead:c}=await r.read(s,a,s.length-a,a);if(!c)break;a+=c}if(a>n.size)throw new X("\u6587\u4EF6\u6B63\u5728\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6",409);let o=s.subarray(0,a),l=fd(o);if(!l)throw new X("\u4E0D\u652F\u6301\u7684\u56FE\u7247\u7C7B\u578B",415);return{mimeType:l,bytes:o}}finally{await r.close()}})}async function yd(t,e,i,r){if(typeof i!="string"||typeof r!="string"||!/^[0-9a-f]{64}$/u.test(r))throw new X("\u4FDD\u5B58\u5185\u5BB9\u65E0\u6548");let n=Buffer.from(i,"utf8"),{bytes:s,lines:a}=Ha;if(n.length>s)throw new X(`\u6587\u4EF6\u8FC7\u5927\uFF0C\u6700\u591A\u4FDD\u5B58 ${s/1024/1024} MB`,413);let o=1;for(let l of n)if(l===10&&++o>a+1)throw new X(`\u6587\u4EF6\u884C\u6570\u8FC7\u591A\uFF0C\u6700\u591A\u4FDD\u5B58 ${a} \u884C`,413);return qn(async()=>{let l=await Tr(t,e);if(!(await Un(l)).isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");let c=await Fa(l,Et.O_RDWR|Et.O_NONBLOCK|(Et.O_NOFOLLOW??0));try{let p=await c.stat();if(!p.isFile())throw new X("\u53EA\u80FD\u4FDD\u5B58\u5DF2\u5B58\u5728\u7684\u666E\u901A\u6587\u4EF6");if(p.size>s)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");let d=Buffer.alloc(p.size+1),m=0;for(;m<d.length;){let{bytesRead:f}=await c.read(d,m,d.length-m,m);if(!f)break;m+=f}if(m>p.size||Ba(d.subarray(0,m))!==r)throw new X("\u6587\u4EF6\u5DF2\u5728\u78C1\u76D8\u4E0A\u66F4\u6539\uFF0C\u8BF7\u91CD\u65B0\u8BFB\u53D6\u540E\u518D\u4FDD\u5B58",409,"conflict");await c.truncate(0);let g=0;for(;g<n.length;)g+=(await c.write(n,g,n.length-g,g)).bytesWritten;return await c.sync(),{path:e,size:n.length,version:Ba(n)}}finally{await c.close()}})}var g0=1e3,bd=512*1024,_d=1e4;function vd(t,e){return e.startsWith(t)&&e.slice(t.length)||void 0}async function Bi(t){let e=await Fe(t);if(e.kind!=="repository")return e;let{root:i,scope:r}=e,n=await ee(e.cwd,["status","--porcelain=v2","--branch","-z","--untracked-files=all","--","."]),s={kind:"repository",root:i,scope:r,branch:null,head:null,upstream:null,ahead:null,behind:null,entries:[],truncated:!1},a=n.split("\0");for(let o=0;o<a.length;o++){let l=a[o];if(l.startsWith("# branch.oid ")){let S=l.slice(13);s.head=S==="(initial)"?null:S;continue}if(l.startsWith("# branch.head ")){let S=l.slice(14);s.branch=S==="(detached)"?null:S;continue}if(l.startsWith("# branch.upstream ")){s.upstream=l.slice(18);continue}if(l.startsWith("# branch.ab ")){let S=l.match(/\+(\d+) -(\d+)/);S&&(s.ahead=Number(S[1]),s.behind=Number(S[2]));continue}let c=l[0];if(!["1","2","u","?"].includes(c??""))continue;let p=c==="?"?1:c==="1"?8:c==="2"?9:10,d=0;for(let S=0;S<p;S++)d=l.indexOf(" ",d)+1;let m=vd(r,l.slice(d)),g=c==="2"?a[++o]:void 0;if(!m)continue;if(s.entries.length===g0){s.truncated=!0;continue}let f=l.slice(0,d).split(" "),h={path:m,index:c==="?"?"?":f[1][0],worktree:c==="?"?"?":f[1][1],conflict:c==="u",untracked:c==="?",submodule:c!=="?"&&f[2]!=="N..."},_=g===void 0?void 0:vd(r,g);_&&(h.originalPath=_),s.entries.push(h)}return s}async function wd(t,e,i){if(pi(e),!["staged","unstaged","untracked"].includes(i))throw new H("Git \u5DEE\u5F02\u8303\u56F4\u65E0\u6548");let r=await Bi(t);if(r.kind!=="repository")throw new H("\u5F53\u524D\u5DE5\u4F5C\u533A\u6CA1\u6709\u53EF\u8BFB\u53D6\u7684 Git \u4ED3\u5E93",404);let n={path:e,area:i},s=r.entries.find(o=>o.path===e);if(!s)return{...n,kind:"empty"};if(s.conflict)return{...n,kind:"conflict"};if(s.submodule)return{...n,kind:"submodule"};if(i==="untracked"){if(!s.untracked)return{...n,kind:"empty"};if(!(await u0(m0(t,e))).isFile())return{...n,kind:"unsupported"};let o=await Ir(t,e);if(o.kind==="too-large")return{...n,kind:"too-large"};if(o.kind!=="text")return{...n,kind:"binary"};if(!o.text)return{...n,kind:"empty"};let l=o.text.split(`
|
|
190
190
|
`),c=l.at(-1)==="";c&&l.pop();let p=`--- /dev/null
|
|
191
191
|
+++ b/${e.replace(/[\r\n]/g," ")}
|
|
192
192
|
@@ -0,0 +1,${l.length} @@
|
|
@@ -218,7 +218,7 @@ ${c.stack.split(`
|
|
|
218
218
|
`).slice(1).join(`
|
|
219
219
|
`)}`);let d=this.reportError(p,{...s,stage:"provider_login"});l.view={id:o,providerId:e,method:i,status:"error",error:"\u767B\u5F55\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u63D0\u4F9B\u65B9\u63D0\u793A\u5E76\u91CD\u8BD5\u3002",errorId:d}}}),{...l.view}}get(e){let i=this.flows.get(e)?.view;return i?{...i}:void 0}getActive(){let e=[...this.flows.values()].find(({view:i})=>i.status==="running"||i.status==="waiting")?.view;return e?{...e}:void 0}respond(e,i){let r=this.flows.get(e);if(!r?.answer||r.view.status!=="waiting"||r.view.prompt?.type==="select"&&!r.view.prompt.options.some(s=>s.id===i))return!1;let n=r.answer;return r.answer=void 0,r.reject=void 0,r.view={...r.view,status:"running",prompt:void 0},n(i),!0}cancel(e){let i=this.flows.get(e);return!i||i.view.status==="done"||i.view.status==="error"?!1:(i.view={...i.view,status:"cancelled",prompt:void 0},i.controller.abort(),i.reject?.(new Error("\u767B\u5F55\u5DF2\u53D6\u6D88")),i.answer=void 0,i.reject=void 0,!0)}close(){for(let e of this.flows.keys())this.cancel(e);this.flows.clear()}};import{randomBytes as jS}from"node:crypto";import{readFile as BS,rename as FS,rm as HS,stat as GS,writeFile as WS,mkdir as $S}from"node:fs/promises";import{dirname as VS}from"node:path";var zS=["openai-completions","openai-responses","anthropic-messages"];function Za(t){if(!t||typeof t!="object")return!1;let e=t;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||!zS.includes(e.api)||typeof e.baseUrl!="string"||e.baseUrl.length>2048)return!1;try{let i=new URL(e.baseUrl);return(i.protocol==="https:"||i.protocol==="http:")&&!!i.hostname&&!i.username&&!i.password&&!i.hash}catch{return!1}}async function Mu(t,e){if(!Za(e))throw new Error("\u81EA\u5B9A\u4E49\u63D0\u4F9B\u65B9\u540D\u79F0\u3001\u5730\u5740\u6216\u6A21\u578B\u65E0\u6548");let i;try{i=await BS(t,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}let r;if(i===void 0)r={providers:{}};else{try{r=JSON.parse(i)}catch{throw new Error("models.json \u542B\u6CE8\u91CA\u6216\u683C\u5F0F\u9519\u8BEF\uFF0C\u8BF7\u5728\u914D\u7F6E\u6587\u4EF6\u4E2D\u624B\u52A8\u6DFB\u52A0\u63D0\u4F9B\u65B9")}if(!r||typeof r!="object"||!r.providers||typeof r.providers!="object"||Array.isArray(r.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548")}if(Object.hasOwn(r.providers,e.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");let n={...r,providers:{...r.providers,[e.id]:{name:e.name.trim(),baseUrl:e.baseUrl,api:e.api,models:[{id:e.modelId.trim()}]}}};await $S(VS(t),{recursive:!0});let s=i===void 0?384:(await GS(t)).mode&511,a=`${t}.pi-web-${jS(6).toString("hex")}.tmp`;try{await WS(a,`${JSON.stringify(n,null,2)}
|
|
220
220
|
`,{mode:s,flag:"wx"}),await FS(a,t)}finally{await HS(a,{force:!0})}}import{randomBytes as KS}from"node:crypto";import{mkdir as YS,readFile as QS,rename as JS,rm as XS,stat as ZS,writeFile as ek}from"node:fs/promises";import{dirname as tk}from"node:path";function Du(t){if(!t||t.length>2048)return!1;try{let e=new URL(t);return(e.protocol==="https:"||e.protocol==="http:")&&!!e.hostname&&!e.username&&!e.password&&!e.search&&!e.hash}catch{return!1}}function Lu(t){if(!t||typeof t!="object")return!1;let e=t;return e.action==="save"?(e.originalId===void 0||typeof e.originalId=="string")&&Uu(e.model):e.action==="base_url"?e.baseUrl===null||typeof e.baseUrl=="string"&&Du(e.baseUrl):e.action==="remove"&&typeof e.id=="string"&&e.id.length>0&&e.id.length<=200}function Uu(t){if(!t||typeof t!="object")return!1;let e=t;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 i of[e.contextWindow,e.maxTokens])if(i!==void 0&&(!Number.isSafeInteger(i)||i<=0))return!1;return e.input===void 0||Array.isArray(e.input)&&e.input.length>0&&e.input.every(i=>i==="text"||i==="image")&&new Set(e.input).size===e.input.length}async function qu(t){let e;try{e=await QS(t,"utf8")}catch(r){if(r.code!=="ENOENT")throw r}if(e===void 0)return{config:{providers:{}}};let i;try{i=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(!i||typeof i!="object"||!i.providers||typeof i.providers!="object"||Array.isArray(i.providers))throw new Error("models.json \u7ED3\u6784\u65E0\u6548");return{config:i,existing:e}}async function ik(t,e,i){await YS(tk(t),{recursive:!0});let r=i===void 0?384:(await ZS(t)).mode&511,n=`${t}.pi-web-${KS(6).toString("hex")}.tmp`;try{await ek(n,`${JSON.stringify(e,null,2)}
|
|
221
|
-
`,{mode:r,flag:"wx"}),await JS(n,t)}finally{await XS(n,{force:!0})}}async function ju(t,e,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await qu(t),n=r.providers[e],s=new Set(n?.models?.map(a=>a.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:i.getModels(e).map(a=>({id:a.id,name:a.name,contextWindow:a.contextWindow,maxTokens:a.maxTokens,input:[...a.input],source:s.has(a.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[a.id]}))}}async function Bu(t,e,i,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await qu(t),a={...n.providers[e]??{}},o=[...a.models??[]],l={...a.modelOverrides??{}};if(i.action==="base_url"){if(i.baseUrl!==null&&!Du(i.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");i.baseUrl===null?delete a.baseUrl:a.baseUrl=i.baseUrl}else if(i.action==="save"){if(!Uu(i.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let c={id:i.model.id.trim(),...i.model.name===void 0?{}:{name:i.model.name},...i.model.contextWindow===void 0?{}:{contextWindow:i.model.contextWindow},...i.model.maxTokens===void 0?{}:{maxTokens:i.model.maxTokens},...i.model.input===void 0?{}:{input:i.model.input}},p=i.originalId,d=p===void 0?-1:o.findIndex(m=>m.id===p);if(p===void 0&&(o.some(m=>m.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(d>=0){if(c.id!==p&&(o.some(g=>g.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let m={...o[d],...c};for(let g of["name","contextWindow","maxTokens","input"])c[g]===void 0&&delete m[g];o[d]=m}else if(p!==void 0&&r.getModel(e,p)){if(c.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:m,...g}=c;l[p]={...l[p],...g};for(let f of["name","contextWindow","maxTokens","input"])c[f]===void 0&&delete l[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");o.push(c)}}else{let c=o.findIndex(p=>p.id===i.id);if(c>=0)o.splice(c,1);else if(Object.hasOwn(l,i.id))delete l[i.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")}o.length?a.models=o:delete a.models,Object.keys(l).length?a.modelOverrides=l:delete a.modelOverrides,Object.keys(a).length?n.providers[e]=a:delete n.providers[e],await ik(t,n,s)}function Fu(t){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(t.trim())}import{randomBytes as __,createHash as WI}from"node:crypto";import{fileURLToPath as $I}from"node:url";var Rr="pi-webapp@0.1.58-alpha.
|
|
221
|
+
`,{mode:r,flag:"wx"}),await JS(n,t)}finally{await XS(n,{force:!0})}}async function ju(t,e,i){if(!i.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:r}=await qu(t),n=r.providers[e],s=new Set(n?.models?.map(a=>a.id)??[]);return{providerId:e,baseUrl:n?.baseUrl,models:i.getModels(e).map(a=>({id:a.id,name:a.name,contextWindow:a.contextWindow,maxTokens:a.maxTokens,input:[...a.input],source:s.has(a.id)?"custom":"builtin",overridden:!!n?.modelOverrides?.[a.id]}))}}async function Bu(t,e,i,r){if(!r.getProvider(e))throw new Error("\u63D0\u4F9B\u65B9\u4E0D\u5B58\u5728");let{config:n,existing:s}=await qu(t),a={...n.providers[e]??{}},o=[...a.models??[]],l={...a.modelOverrides??{}};if(i.action==="base_url"){if(i.baseUrl!==null&&!Du(i.baseUrl))throw new Error("API \u5730\u5740\u65E0\u6548");i.baseUrl===null?delete a.baseUrl:a.baseUrl=i.baseUrl}else if(i.action==="save"){if(!Uu(i.model))throw new Error("\u6A21\u578B\u53C2\u6570\u65E0\u6548");let c={id:i.model.id.trim(),...i.model.name===void 0?{}:{name:i.model.name},...i.model.contextWindow===void 0?{}:{contextWindow:i.model.contextWindow},...i.model.maxTokens===void 0?{}:{maxTokens:i.model.maxTokens},...i.model.input===void 0?{}:{input:i.model.input}},p=i.originalId,d=p===void 0?-1:o.findIndex(m=>m.id===p);if(p===void 0&&(o.some(m=>m.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");if(d>=0){if(c.id!==p&&(o.some(g=>g.id===c.id)||r.getModel(e,c.id)))throw new Error("\u6A21\u578B ID \u5DF2\u5B58\u5728");let m={...o[d],...c};for(let g of["name","contextWindow","maxTokens","input"])c[g]===void 0&&delete m[g];o[d]=m}else if(p!==void 0&&r.getModel(e,p)){if(c.id!==p)throw new Error("\u5185\u7F6E\u6A21\u578B ID \u4E0D\u53EF\u4FEE\u6539");let{id:m,...g}=c;l[p]={...l[p],...g};for(let f of["name","contextWindow","maxTokens","input"])c[f]===void 0&&delete l[p][f]}else{if(p!==void 0)throw new Error("\u6A21\u578B\u4E0D\u5B58\u5728");o.push(c)}}else{let c=o.findIndex(p=>p.id===i.id);if(c>=0)o.splice(c,1);else if(Object.hasOwn(l,i.id))delete l[i.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")}o.length?a.models=o:delete a.models,Object.keys(l).length?a.modelOverrides=l:delete a.modelOverrides,Object.keys(a).length?n.providers[e]=a:delete n.providers[e],await ik(t,n,s)}function Fu(t){return/^(?:npm:|git:|https?:\/\/|ssh:\/\/|git@)/i.test(t.trim())}import{randomBytes as __,createHash as WI}from"node:crypto";import{fileURLToPath as $I}from"node:url";var Rr="pi-webapp@0.1.58-alpha.2+475e7448e57f36765c21",it="475e7448e57f36765c21";var VI="https://070c0b7c5ac18d940c294e63ecfa0793@o4506663318716416.ingest.us.sentry.io/4512191040716800";function Xs(t=process.env,e=console.warn){let i=r=>{let n={enabled:!1,environment:t.PI_WEB_SENTRY_ENVIRONMENT||"production",release:Rr,buildId:it},s=t[`PI_WEB_SENTRY_${r}_DSN`]??t.PI_WEB_SENTRY_DSN??VI;if(t.PI_WEB_SENTRY_ENABLED!=="true"||!s)return n;try{let a=new URL(s);if(a.protocol!=="https:"||!/^[\w-]+$/.test(a.username)||a.password||a.search||a.hash||!/\/(?:[\w-]+\/)*\d+$/.test(a.pathname))throw new Error;return{...n,enabled:!0,dsn:s}}catch{return e(`pi-webapp: invalid ${r.toLowerCase()} Sentry DSN; error reporting disabled for this side.`),n}};return{browser:i("BROWSER"),node:i("NODE")}}var wt=class{config;ready;reporter;client;salt=__(16);breadcrumbs=new Or;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=Xs(e.env),!this.config.node.enabled){this.ready=Promise.resolve();return}if(e.monitor!==!1){let i=$I(import.meta.url).replace(/\\/g,"/"),r=i.lastIndexOf("/src/"),n=r>=0?i.slice(0,r+5):i.slice(0,i.lastIndexOf("/")+1);this.fatal=s=>{s.stack?.replace(/\\/g,"/").includes(i.endsWith("extension.js")?i:n)&&this.capture(s,{stage:"fatal"})},process.on("uncaughtExceptionMonitor",this.fatal)}this.ready=Promise.resolve().then(()=>(b_(),y_)).then(i=>{if(!this.closed){this.client=new i.NodeClient({...this.config.node,dist:it,integrations:[],transport:e.transport??(r=>Fd(i.createTransport,r)),stackParser:i.defaultStackParser,beforeSend:Bd,sendClientReports:!1,dataCollection:{...Ud,httpBodies:[]},includeServerName:!1,enableRuntimeChannelInjection:!1,beforeSendLog:()=>null,beforeSendMetric:()=>null,enableOpenTelemetrySetup:!1,maxBreadcrumbs:100}),this.reporter=new Bn(this.client,"node",it,i,this.breadcrumbs),this.reporter.setState(this.state);for(let r of this.early)this.reporter.capture(r.error,r.context,r.eventId)}}).catch(()=>{this.failed=!0,console.warn("pi-webapp: Sentry initialization failed; error reporting disabled.")}).finally(()=>{this.early=[]})}capture(e,i={}){try{if(!this.enabled||di(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,i);if(this.early.length>=20)return;let r=__(16).toString("hex");return this.early.push({error:Fi(e),context:tt(i),eventId:r}),r}catch{return}}setState(e){this.state=tt({...this.state,...e}),this.reporter?.setState(this.state)}breadcrumb(e,i={}){this.enabled&&this.breadcrumbs.add(e,i)}session(e){return WI("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(),i;try{await Promise.race([this.ready,new Promise(r=>{i=setTimeout(r,500)})])}finally{clearTimeout(i),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 aA}from"@earendil-works/pi-coding-agent";function Jt(t,e,i){if(i!==void 0&&i!=="steer"&&i!=="followUp")throw new Error("\u8FFD\u52A0\u65B9\u5F0F\u65E0\u6548");if(t.interactions?.length)throw new Error("\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u4EA4\u4E92\u6216\u5BA1\u6279");if(!t.idle&&!i)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u9009\u62E9\u5F15\u5BFC\u6216\u6392\u961F");if(i&&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 YI}from"node:crypto";var v_="[pi-web workspace tab in view] ",w_=' \u2014 The user wrote this while looking at that workspace tab. Read "this", "here" or "current" as its content, and when a tool can act on that content (for example read and patch the open drawing or file), act on it in place instead of creating something new.';function zI(t){return{title:t.title,kind:t.kind,contentId:t.contentId,...t.plugin?{plugin:t.plugin}:{},...t.detail?{detail:t.detail}:{},...t.reference?{reference:t.reference}:{}}}function KI(t){let e=t.endsWith(w_)?t.slice(0,-w_.length):t;try{let i=JSON.parse(e);if(typeof i.title!="string"||typeof i.kind!="string"||typeof i.contentId!="string")return null;for(let r of["plugin","detail","reference"])if(i[r]!==void 0&&typeof i[r]!="string")return null;return zI(i)}catch{return null}}function bn(t){let e=[],i=t;for(;;){let n=/(^|\n\n)附件 ("(?:\\.|[^"\\])*"):([^\n]+)$/u.exec(i);if(!n||!/[\\/]pi-web[\\/]attachments[\\/][a-f0-9]{64}[\\/]/u.test(n[3]))break;let s;try{s=JSON.parse(n[2])}catch{break}e.unshift({name:s,image:/\.(?:png|jpe?g|webp|gif)$/iu.test(s)}),i=i.slice(0,n.index)}let r=i.lastIndexOf(v_);if(r!==-1&&(r===0||i.slice(r-2,r)===`
|
|
222
222
|
|
|
223
223
|
`)&&!i.slice(r).includes(`
|
|
224
224
|
`)){let n=KI(i.slice(r+v_.length));if(n)return{text:i.slice(0,Math.max(0,r-2)),attachments:e,context:n}}return{text:i,attachments:e}}var _n=t=>Buffer.byteLength(t.text)+t.images.reduce((e,i)=>e+i.data.length,0),Me=class extends Error{status=409},Xt=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,...bn(e.text),status:e.status,...e.error?{error:e.error}:{}}))}enqueue(e,i=[],r){if(this.validateText(e),this.entries.length>=50||this.entries.reduce((n,s)=>n+_n(s),_n({text:e,images:i}))>64*1024*1024)throw new Me("\u5F85\u5904\u7406\u63D0\u793A\u8BCD\u8FC7\u591A\uFF0C\u8BF7\u5148\u5904\u7406\u73B0\u6709\u961F\u5217");this.entries.push({id:YI(),revision:1,text:e,images:i.map(n=>({...n})),correlation:r,status:"queued"}),this.changed()}validateText(e){if(!e.trim()||e.length>32e3||e.trimStart().startsWith("/"))throw new Me("\u8FFD\u52A0\u63D0\u793A\u8BCD\u65E0\u6548\u3001\u8FC7\u957F\u6216\u5305\u542B\u659C\u6760\u6307\u4EE4")}find(e,i){let r=this.entries.find(n=>n.id===e);if(!r||r.revision!==i)throw new Me("\u961F\u5217\u9879\u5DF2\u53D8\u5316\u6216\u5DF2\u53D1\u9001\uFF0C\u8BF7\u4F7F\u7528\u6700\u65B0\u72B6\u6001\u91CD\u8BD5");if(r.status!=="queued")throw new Me("\u63D0\u793A\u8BCD\u6B63\u5728\u53D1\u9001\uFF0C\u65E0\u6CD5\u4FEE\u6539");return r}async update(e,i,r,n){let s=this.find(e,i);if(r.kind==="remove"){this.entries=this.entries.filter(a=>a!==s),this.changed();return}if(r.kind==="edit"){let a=bn(s.text),o=s.text.slice(a.text.length).replace(/^\n\n/u,""),l=[r.text.trim(),o].filter(Boolean).join(`
|
|
@@ -240,6 +240,6 @@ ${m.text.slice(-8192)}`:m.text]:[]}).join(`
|
|
|
240
240
|
${t.stack.split(`
|
|
241
241
|
`).slice(1).join(`
|
|
242
242
|
`)}`:void 0,i<3&&t.cause instanceof Error&&(n.cause=dv(t.cause,e,i+1)),Fi(n)}import{randomUUID as gv}from"node:crypto";import{randomUUID as ux}from"node:crypto";import{EnvHttpProxyAgent as mx,getGlobalDispatcher as o$,setGlobalDispatcher as l$}from"undici";var uv=t=>({httpProxy:t.http_proxy??t.HTTP_PROXY??t.all_proxy??t.ALL_PROXY??"",httpsProxy:t.https_proxy??t.HTTPS_PROXY??t.all_proxy??t.ALL_PROXY??"",noProxy:t.no_proxy??t.NO_PROXY??""});function gx(t,e){let i=uv(t),r;try{r=new URL(typeof e=="string"||e instanceof URL?e:e.url)}catch{return!1}if(!(r.protocol==="https:"&&i.httpsProxy||i.httpProxy))return!1;let n=i.noProxy.toLowerCase();if(n==="*")return!1;let s=Number(r.port)||(r.protocol==="https:"?443:80),a=r.hostname.toLowerCase();return!n.split(/[,\s]/).filter(Boolean).some(o=>{let l=o.match(/^(.+):(\d+)$/),c=(l?.[1]??o).replace(/^\*?\./,"");return(!l||Number(l[2])===s)&&(a===c||a.endsWith("."+c))})}function fx(t){let e=uv(t);for(let i of[e.httpProxy,e.httpsProxy].filter(Boolean))try{if(!["http:","https:"].includes(new URL(i).protocol))throw new Error}catch{throw Object.assign(new Error("HTTP proxy configuration is invalid or unsupported"),{code:"PROXY_CONFIGURATION_INVALID"})}return new mx(e)}function dp({env:t=process.env,onFailure:e=()=>{},fetchRequest:i=globalThis.fetch,autoClose:r=!1}={}){let n,s=new Set,a=i===globalThis.fetch,o=(p,d)=>{try{e(p,d)}catch{}},l=p=>p?p.close().finally(()=>s.delete(p)):Promise.resolve();return{fetch:async(p,d)=>{let m={requestId:ux(),phase:"headers",proxied:a&&gx(t,p)},g=r?void 0:n,f=!1,h=d?.signal??(p instanceof Request?p.signal:void 0),_=()=>S(),S=()=>{h?.removeEventListener("abort",_),!f&&r&&(f=!0,l(g).catch(()=>{}))},E;try{a?(g??=fx(t),s.add(g),r||(n=g),E=await i(p,{...d,dispatcher:g})):E=await i(p,d)}catch(N){throw o(N,m),S(),N}if(E.ok||o(void 0,{...m,status:E.status}),!E.body)return S(),E;let A=E.body.getReader();h?.addEventListener("abort",_,{once:!0}),h?.aborted&&S();let D=new ReadableStream({async pull(N){try{let G=await A.read();G.done?(N.close(),A.releaseLock(),S()):N.enqueue(G.value)}catch(G){o(G,{...m,phase:"body"}),N.error(G),A.releaseLock(),S()}},async cancel(N){try{await A.cancel(N)}finally{A.releaseLock(),S()}}}),C=new Response(D,{status:E.status,statusText:E.statusText,headers:E.headers});return Object.defineProperties(C,{url:{value:E.url},redirected:{value:E.redirected},type:{value:E.type}}),C},close:async()=>{await Promise.all([...s].map(l))}}}var mv=(t,e)=>dp({autoClose:!0}).fetch(t,e);var hx=new Set(["Error","TypeError","RangeError","SyntaxError","AbortError","TimeoutError","AggregateError","ConnectTimeoutError","HeadersTimeoutError","BodyTimeoutError","SocketError","RequestAbortedError","InvalidArgumentError","ResponseStatusCodeError","DOMException"]),yx=t=>typeof t=="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(t)?t:void 0;function up(t,e={}){let i=[],r=new Set,n=(l,c=0)=>{if(!l||c>4||r.has(l)||i.length>=8)return;r.add(l);let p=yx(l.code);if(i.push({name:hx.has(l.name)?l.name:"Error",...p?{code:p}:{}}),n(l.cause,c+1),l instanceof AggregateError)for(let d of l.errors.slice(0,4))n(d,c+1)};n(t);let s=i.flatMap(l=>l.code?[l.code]:[]),a=e.stage==="model_admission"||s.some(l=>["agent_settlement_timeout","sdk_capability_missing","hosted_admission_blocked"].includes(l))?"lifecycle":s.some(l=>/CERT|TLS|SSL/.test(l))?"tls":s.some(l=>/^PROXY_/.test(l))||e.proxied&&s.some(l=>/ECONNREFUSED|ENOTFOUND|EAI_AGAIN/.test(l))?"proxy":s.some(l=>/TIMEOUT|ETIMEDOUT/.test(l))||i.some(l=>/TimeoutError$/.test(l.name))?"timeout":i.some(l=>l.name==="AbortError"||l.code==="ABORT_ERR"||l.code==="UND_ERR_ABORTED")?"cancelled":s.some(l=>/ENOTFOUND|EAI_AGAIN/.test(l))?"dns":e.status>=500?"server":e.status>=400?"http":e.stage==="model_stream"?"interrupted":"network",o=l=>typeof l=="string"&&/^[\w-]{1,80}$/.test(l)?l:void 0;return{errorId:gv(),requestId:o(e.requestId)??gv(),...o(e.operationId)?{operationId:e.operationId}:{},stage:["model_headers","model_stream","model_admission","http_transport"].includes(e.stage)?e.stage:"model_headers",kind:a,...Number.isInteger(e.status)?{status:e.status}:{},proxied:e.proxied===!0,causes:i}}function fv({env:t=process.env,onDiagnostic:e=()=>{},fetchRequest:i=globalThis.fetch}={}){return dp({env:t,fetchRequest:i,onFailure:(r,n)=>e(up(r,{...n,stage:n.phase==="body"?"model_stream":"model_headers"}))})}function bx(t){let e={...process.env,...t};for(let i of["http_proxy","https_proxy","all_proxy","no_proxy"])t&&i.toUpperCase()in t&&!(i in t)&&delete e[i];return e}var _x=new Set(["openai-codex-responses","openai-responses","azure-openai-responses","openai-completions","anthropic-messages","mistral-conversations","pi-messages"]);function hv(t,e,i=()=>{}){let r=t.agent.streamFunction;t.agent.streamFunction=async(n,s,a)=>{if(!_x.has(n.api))return r(n,s,a);let o=i(),l=fv({env:bx(a?.env),...a?.fetch?{fetchRequest:a.fetch}:{},onDiagnostic:c=>{let p={...c,...o?{operationId:o}:{}};console.error(JSON.stringify({event:"model_transport_failure",...p})),e(p)}});try{let c=await r(n,s,{...a,fetch:l.fetch});return c.result().finally(()=>l.close()).catch(()=>{}),c}catch(c){throw await l.close(),c}}}function ur(t,e,i){try{t()}catch(r){let n=up(r,{...e,stage:"model_admission"});try{console.error(JSON.stringify({event:"model_admission_blocked",...n})),i?.(new Error("Model admission blocked before any HTTP request"),{...e,errorId:n.errorId,requestId:n.requestId,stage:n.stage,code:"hosted_admission_blocked",networkKind:n.kind,networkStage:n.stage,causeCodes:n.causes.flatMap(s=>s.code?[s.code]:[]).join(",")})}catch{}throw r}}var Ex=["read","grep","find","ls"];var bv=200,da=class{telemetryVersion=2;runtimeVersion=4;active=null;runtimes=new Map;selectedByWorkspace=new Map;queue=new Mi;generation=0;disposed=!1;publish;fallbackModel;isProjectTrusted;reportError;telemetry;onSessionsChanged;customTools;offHosted;hosted;constructor(e,i,r=()=>!1,n=()=>{},s={enabled:()=>!1,breadcrumb:()=>{},anonymize:()=>"unavailable"},a=()=>{},o=[],l){this.hosted=l,this.publish=e,this.fallbackModel=i,this.isProjectTrusted=r,this.reportError=n,this.onSessionsChanged=a,this.customTools=o,this.offHosted=l?.adapter.onThaw(()=>{for(let c of this.runtimes.values())this.scheduleQueued(c)}),this.telemetry={enabled:()=>{try{return s.enabled()}catch{return!1}},breadcrumb:(c,p)=>{try{s.enabled()&&s.breadcrumb(c,p)}catch{}},anonymize:c=>{try{return s.enabled()?s.anonymize(c):"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,i){return this.queue.run(async()=>{this.ensureAvailable();let r=await kt(e),n=i==="continue"?this.selectedByWorkspace.get(r):typeof i=="object"&&"sessionId"in i?this.runtimes.get(i.sessionId):void 0;if(n){if(n.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(n);return}if(typeof i=="object"&&"sessionId"in i)throw new Error("\u4F1A\u8BDD\u4E0D\u5B58\u5728");let s;if(i==="new")s=mr.create(r);else if(i==="continue"){let o=await mr.listAll(),l=await Ni(r,o),c=l[0]?.parentSessionPath?await pr(o,Ci(yv())):null,p=l.find(d=>!c?.has(d.id));s=p?mr.open(p.path):mr.create(r)}else s="sessionManager"in i?i.sessionManager:mr.open(i.sessionFile);if(await kx(s.getCwd())!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");let a=this.runtimes.get(s.getSessionId());if(a){if(a.cwd!==r)throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");this.activate(a);return}await this.replace(r,s,i==="new"?"new":"resume")})}reuseBlank(e){return this.queue.run(async()=>{this.ensureAvailable();let i=this.selectedByWorkspace.get(await kt(e));return!i||!this.blank(i)?!1:(this.activate(i),!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 i=this.runtimes.get(e);return!this.disposed&&i&&!i.closing?{cwd:i.cwd,sessionId:e}:null}hasSession(e,i){return this.runtimes.get(i)?.cwd===e}hasWorkspace(e){return this.selectedByWorkspace.has(e)}retainedSessions(){return[...this.runtimes.values()].map(e=>{let{session:i,cwd:r,prompts:n}=e,s=i.sessionManager.getBranch(),a=s.flatMap(o=>{let l=Ai(o);return l?[l]:[]});return{sessionId:i.sessionManager.getSessionId(),cwd:r,path:i.sessionManager.getSessionFile()??null,idle:i.isIdle&&!n.sending,name:na(i.sessionManager.getSessionName(),a),modified:s.at(-1)?.timestamp??new Date().toISOString(),blank:this.blank(e)}})}blank(e){return!e.detached&&!e.closing&&e.session.isIdle&&!e.prompts.sending&&e.prompts.length===0&&!e.session.sessionManager.getBranch().some(i=>Ai(i)?.role==="user")}rename(e,i){let r=this.runtimes.get(e);if(!r||r.closing)return!1;if(r.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");return r.session.setSessionName(i),!0}discard(e){return this.queue.run(async()=>{let i=this.runtimes.get(e);if(!i||i.closing)return null;if(i.detached)throw new Error("\u63D2\u4EF6\u4F1A\u8BDD\u4E0D\u80FD\u91CD\u547D\u540D\u6216\u5220\u9664");if(!i.session.isIdle||i.prompts.sending||i.prompts.length>0)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let r=this.active===i,n=i.session.sessionManager.getSessionFile()??null;return this.runtimes.delete(e),this.selectedByWorkspace.get(i.cwd)===i&&this.selectedByWorkspace.delete(i.cwd),r&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged(),{path:n,cwd:i.cwd,wasActive:r}})}activate(e){this.ensureAvailable(),this.active=e,this.selectedByWorkspace.set(e.cwd,e),this.publish({type:"snapshot",session:this.snapshotOf(e)}),this.onSessionsChanged()}publishFor(e,i){!this.disposed&&this.active===e&&!e.closing&&this.publish(i)}diagnostic(e,i,r,n){let s=`plugin=${i} session=${e.session.sessionManager.getSessionId()} generation=${e.generation} stage=${r}: ${n}`;console.error(s),this.publishFor(e,{type:"error",message:s})}async replace(e,i,r,n){let s=this.runtimes.get(i.getSessionId()),a=await Ri.discover(e,this.isProjectTrusted(e)),o=wx(),l=await lv(e,a.extensionRoots,this.isProjectTrusted(e)),c=new Sx({cwd:e,agentDir:yv(),noExtensions:!0,additionalExtensionPaths:l.paths,eventBus:o,extensionFactories:this.hosted?[this.hosted.adapter.extension(this.hosted.scope(e,i.getSessionId()))]:[]}),p=null;try{await c.reload();let d=c.getExtensions().errors;if(d.length)throw new Error(d.map(P=>`${P.path}: ${P.error}`).join("; "));let m=i.buildSessionProjection().model?void 0:this.active?.session.model??this.fallbackModel(),{session:g}=await vx({cwd:e,sessionManager:i,model:m,resourceLoader:c,customTools:this.customTools}),f=new dr({enabled:()=>this.telemetry.enabled(),capture:this.reportError,breadcrumb:(P,I)=>this.telemetry.breadcrumb(P,I),anonymize:P=>this.telemetry.anonymize(P)}),h={session:g,cwd:e,catalog:a,bus:o,generation:++this.generation,activityId:0,closing:!1,waitController:new AbortController,interactions:null,detach:()=>{},releasePaths:l.release,tools:f,streaming:null,prompts:null,detached:n?{owner:n,events:[],seq:0,lastText:"",restoreTools:null}:void 0};h.prompts=s?.prompts??new Xt(()=>{let P=this.runtimes.get(i.getSessionId())??h;this.publishFor(P,{type:"snapshot",session:this.snapshotOf(P)}),!this.disposed&&!P.closing&&this.onSessionsChanged()}),p=h,hv(g,P=>{h.networkDiagnostic=P},()=>h.operation?.operationId);let _=P=>this.publishFor(h,P),S=h.detached,E=(P,I)=>{S&&(S.events.push({seq:++S.seq,type:P,...I===void 0?{}:{text:I}}),S.events.length>bv&&S.events.splice(0,S.events.length-bv))};h.interactions=new cr(o,P=>!h.closing&&P.sessionId===g.sessionManager.getSessionId()&&Sn(a,P.pluginId),()=>_({type:"snapshot",session:this.snapshotOf(h)}));let A=0,D=o.on(oa,()=>_({type:"snapshot",session:this.snapshotOf(h)})),C=g.subscribe(P=>{if(S&&!h.closing&&(P.type==="message_end"&&P.message.role==="assistant"&&(P.message.stopReason==="error"?E("error",P.message.errorMessage??"Agent response failed"):S.lastText=P.message.content.flatMap(I=>I.type==="text"?[I.text]:[]).join(`
|
|
243
|
-
`)),P.type==="agent_settled"&&E("turn_end",S.lastText)),!this.disposed&&!h.closing){let I={...h.operation,session:this.telemetry.anonymize(g.sessionManager.getSessionId()),piVersion:pa,model:g.model?`${g.model.provider}/${g.model.id}`:null,thinkingLevel:g.thinkingLevel};if(P.type==="agent_start"&&(h.activityId++,this.telemetry.breadcrumb("agent_start",I)),P.type==="tool_execution_start"&&f.start(P,I),P.type==="tool_execution_end"&&f.end(P,I),P.type==="message_end"&&P.message.role==="assistant"&&P.message.stopReason==="error"){h.agentErrorReported=!0;let x=h.networkDiagnostic,L=this.reportError(new Error("Agent response failed"),{...h.operation,stage:"agent",code:"agent_failed",piVersion:pa,...x?{networkKind:x.kind,networkStage:x.stage,causeCodes:x.causes.flatMap(k=>k.code?[k.code]:[]).join(","),requestId:x.requestId}:{}})??x?.errorId;_({type:"error",message:P.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:L,inTranscript:!0,...h.operation})}P.type==="message_end"&&P.message.role==="toolResult"&&f.message(P.message,I),P.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",I),f.clear(),h.operation=void 0)}P.type==="message_update"&&P.message.role==="assistant"&&(h.streaming={id:"stream",role:"assistant",timestamp:new Date(P.message.timestamp).toISOString(),blocks:qt(P.message.content)},Date.now()-A>=60&&(A=Date.now(),_({type:"stream",message:h.streaming}))),P.type==="agent_settled"&&this.scheduleQueued(h),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(P.type)&&((P.type==="message_end"&&P.message.role==="assistant"||P.type==="agent_settled")&&(h.streaming=null,_({type:"stream",message:null})),_({type:"snapshot",session:this.snapshotOf(h)}),!this.disposed&&!h.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(P.type)&&this.onSessionsChanged())});h.detach=()=>{D(),C()},h.releaseHosted=this.hosted?.adapter.attach(g);let N=[],G=!0;if(await g.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:P=>{G&&N.push(P.error),this.diagnostic(h,a.plugins.find(I=>P.extensionPath.startsWith(I.root+"/"))?.id??P.extensionPath,P.event??"runtime",P.error)}}),G=!1,N.length)throw new Error(N.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");h.detached&&(h.detached.restoreTools=g.getActiveToolNames(),g.setActiveToolsByName(Ex)),this.runtimes.set(g.sessionManager.getSessionId(),h),p=null,h.detached?this.onSessionsChanged():this.activate(h)}catch(d){throw this.hosted?.adapter.releasePending(i.getSessionId()),p?await this.close(p,"quit"):(o.clear(),await l.release()),d}}async close(e,i){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await tv(e.session,i,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:i,cwd:r,catalog:n}=e,s=i.sessionManager.getBranch().flatMap(a=>{let o=Ai(a);return o?[o]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:r,name:na(i.sessionManager.getSessionName(),s),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel,thinkingLevels:i.getAvailableThinkingLevels(),idle:i.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:lr(i.sessionManager.getBranch()),promptQueue:{steering:[...i.getSteeringMessages()],followUp:[...i.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:i.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(i.sessionManager.getSessionId()),pluginEntries:tp(i.sessionManager.getBranch(),n.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 i=this.active;if(this.disposed||!i||i.closing||e.sessionId!==i.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=i.session.extensionRunner,n=await la(i.bus,e,15e3,i.waitController.signal);if(this.active!==i||i.closing||r!==i.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),n}requestInteraction(e,i){let r=this.runtimes.get(e.sessionId);return this.disposed||!r||r.closing?Promise.reject(new Error("\u4F1A\u8BDD\u4E0D\u53EF\u7528")):aa(r.bus,e,i)}resolveInteraction(e,i,r,n){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,i,r,n)}async send(e,i=[],r,n){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(Jt(this.snapshot(),e,n),n==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,i,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new Me("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,i,r,n)}async prompt(e,i,r,n,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");ur(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),Jt({...this.snapshotOf(e),idle:e.session.isIdle},i,s);let a=e.session,o=a.isIdle;o&&(e.operation=n,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...n,piVersion:pa});let l=!1,c,p,d=new Promise((m,g)=>{c=m,p=g});a.prompt(i,{images:r,streamingBehavior:s,preflightResult:m=>{m&&(l=!0,c())}}).then(()=>{l||c()}).catch(m=>{if(!l)p(m);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let g=this.reportError(Tt(m,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:pa});this.publishFor(e,{type:"error",message:m instanceof Error?m.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:g,...n})}});try{await d}catch(m){throw o&&(e.operation=void 0),m}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!lr(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(i,r,n)=>this.prompt(e,i,r,n))}async updateQueuedPrompt(e,i,r){let n=this.active;if(this.disposed||!n||n.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&n.session.isIdle)throw new Me("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await n.prompts.update(e,i,r,(s,a,o)=>this.prompt(n,s,a,o,"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(vn),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");ur(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=i.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!lr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!lr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=ca(this.snapshotOf(i).messages);i.operation=e,i.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(a=>{if(!this.disposed&&!i.closing&&!i.agentErrorReported){let o=this.reportError(Tt(a,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(i,{type:"error",message:a instanceof Error?a.message:"\u7EE7\u7EED\u5931\u8D25",errorId:o,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(i=>({provider:i.provider,id:i.id,name:i.name}))}async setModel(e,i){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let n=r.session.modelRuntime.getModel(e,i);if(!n)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(n),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}createDetached(e,i,r){return this.queue.run(async()=>{this.ensureAvailable();let n=await kt(e),s=mr.create(n);return await this.replace(n,s,"new",i),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let i=this.runtimes.get(e);return!this.disposed&&i?.detached&&!i.closing?i:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(i=>i.detached?.owner===e&&!i.closing).length}async sendDetached(e,i,r){let n=this.detachedRuntime(e);if(!n)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&n.detached.restoreTools&&(n.session.setActiveToolsByName(n.detached.restoreTools),n.detached.restoreTools=null),!n.session.isIdle||n.prompts.length>0){n.prompts.enqueue(i,[],void 0),this.scheduleQueued(n);return}await this.prompt(n,i,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let i=this.detachedRuntime(e);i&&(this.runtimes.delete(e),this.active===i&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged())})}detachedEvents(e,i){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(n=>n.seq>i),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(i=>this.close(i,"quit")))})}};import{basename as mp,dirname as Tx}from"node:path";function _v(t,e){let i=r=>e[r].map(n=>({name:r==="skills"&&mp(n.path).toLowerCase()==="skill.md"?mp(Tx(n.path)):mp(n.path),path:n.path,source:n.metadata.source,scope:n.metadata.scope,enabled:n.enabled}));return{packages:t.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:i("extensions"),skills:i("skills")}}import{execFile as Ix}from"node:child_process";var Ax=(t,e)=>new Promise((i,r)=>{Ix(t,[...e],{windowsHide:!0},n=>{n?r(n):i()})});async function gp(t,e=process.platform,i=process.env,r=Ax){if(i.PI_WEBAPP_AUTO_OPEN==="0"||i.PI_WEBAPP_RUNTIME==="desktop"||i.SSH_CONNECTION||i.SSH_TTY||i.SSH_CLIENT||e==="linux"&&!i.DISPLAY&&!i.WAYLAND_DISPLAY)return!1;let n=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return n===null?!1:(await r(n,[t]),!0)}import{execFile as EO}from"node:child_process";import{randomUUID as Pp}from"node:crypto";import{existsSync as Yv}from"node:fs";import{access as TO,mkdir as An,mkdtemp as IO,readFile as ni,realpath as AO,rename as Qv,rm as Jv,writeFile as Xv}from"node:fs/promises";import{join as pe}from"node:path";import{createHash as yp}from"node:crypto";import{readdir as Dx,realpath as Tv,rename as Lx,stat as Ux}from"node:fs/promises";import{join as ri}from"node:path";import{constants as fp}from"node:fs";import{DatabaseSync as xx}from"node:sqlite";import{lstat as Sv,mkdir as Ox,open as En,rename as Rx,unlink as kv}from"node:fs/promises";import{dirname as Nx,join as vv,resolve as Px}from"node:path";import{randomUUID as Cx}from"node:crypto";import{setTimeout as Mx}from"node:timers/promises";async function ve(t){await Ox(t,{recursive:!0,mode:448});let e=await Sv(t);if(!e.isDirectory()||e.isSymbolicLink())throw new y("invalid_storage","Plugin storage must be a real directory")}async function fe(t,e){let i;try{i=await En(t,fp.O_RDONLY|fp.O_NONBLOCK|(fp.O_NOFOLLOW??0))}catch(r){if(Zt(r))return null;throw r}try{let r=await i.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new y("invalid_storage","Invalid storage record size or type");let n=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<n.length;){let a=await i.read(n,s,n.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==r.size)throw new y("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await i.close()}}async function we(t,e=2*1024*1024){let i=await fe(t,e);if(!i)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new y("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function ze(t){let e=await fe(t,2097152);if(e===null)return null;let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new y("gc_recovery_required",`Invalid journal ${t}; stop all owners and inspect original bytes`)}if(!i||typeof i!="object"||Array.isArray(i))throw new y("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return i}async function Z(t,e){let i=`${t}.${Cx()}.tmp`,r=await En(i,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await Rx(i,t);let n;try{n=await En(Nx(t),"r"),await n.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await n?.close()}}finally{await kv(i).catch(()=>{})}}var Ev='{"version":2,"mechanism":"sqlite-exclusive"}',wv=t=>t.toString("utf8")===Ev,ua=new Set;async function hp(t,e,i=0){await ve(t);let r=vv(t,`${e}.lock`),n=vv(t,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new y(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),o;try{o=await En(n,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await o?.close()}let l=await Sv(n);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size>1024*1024)throw new y("invalid_storage","Ownership database must be a small, single-link regular file");let c=new xx(n,{allowExtension:!1}),p=Px(n),d=Date.now()+i,m=!1;try{for(;;){if(!ua.has(p))try{c.exec("BEGIN EXCLUSIVE"),ua.add(p),m=!0;break}catch(h){if(h.errcode!==5)throw h}if(Date.now()>=d)throw new y(s,"Another host owns this plugin storage; wait for it to stop before retrying");await Mx(10)}let f=await fe(r,4096);if(f===null){let h;try{h=await En(r,"wx",384),await h.writeFile(Ev),await h.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await h?.close()}f=await fe(r,4096)}if(f===null||!wv(f))throw a()}catch(f){throw c.close(),m&&ua.delete(p),f}let g=!1;return async()=>{if(g)return;let f=await fe(r,4096);if(f===null||!wv(f))throw new y("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await kv(r),c.close(),ua.delete(p),g=!0}}async function Se(t,e,i=2e3){let r=await hp(t,"transaction",i);try{return await e()}finally{await r()}}var ma=t=>ri(t,"host-pair"),qx=t=>yp("sha256").update(JSON.stringify(t)).digest("hex"),jx=10*6e4;async function Bx(t){let e=yp("sha256"),i=0,r=0;async function n(s){let a=(await Dx(ri(t,s),{withFileTypes:!0})).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0);for(let o of a){if(!s&&o.name==="node_modules")continue;let l=s?`${s}/${o.name}`:o.name;if(o.isSymbolicLink()||!o.isFile()&&!o.isDirectory())throw new y("host_pair_required","Candidate package contains non-regular resources");if(++i>1e4)throw new y("host_pair_required","Candidate package resource budget exceeded");if(o.isDirectory()){await n(l);continue}let c=await fe(ri(t,l),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new y("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([l,yp("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function bp(t,e){let i=await Tv(e),r=ri(e,"dist","hosted-worker.js");if(await Tv(r)!==ri(i,"dist","hosted-worker.js"))throw new y("host_pair_required","Candidate worker must remain inside the staged host");let n=await fe(ri(e,"package.json"),512*1024);if(!n)throw new y("host_pair_required","Candidate package metadata missing");let s=JSON.parse(n.toString("utf8")),a=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==t||a?.protocol!==2||a?.runtimeProtocol!==1||a?.pairJournal!==1||a?.ownershipProtocol!==2||!Array.isArray(a?.capabilities)||!["state","workspace","legacy","panels","messages"].every(l=>a.capabilities.includes(l)))throw new y("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 o=await fe(r,32*1024*1024);if(!o)throw new y("host_pair_required","Candidate worker missing");return qx([n.toString("base64"),o.toString("base64"),await Bx(e)])}async function ga(t){await Lx(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Fx=t=>t.schema===1&&/^[a-f0-9-]{36}$/.test(t.id)&&typeof t.version=="string"&&typeof t.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(t.hostDigest)&&/^[a-f0-9]{64}$/.test(t.fingerprint)&&Array.isArray(t.selections)&&!t.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(t.selection&&(typeof t.selection.path!="string"||!/^[a-f0-9]{64}$/.test(t.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(t.phase);async function _p(t){let e=ri(ma(t),"intent.json"),i,r=!0;try{i=await ze(e)}catch{i=null,r=!1}if(!r||i&&!Fx(i))return await ga(e),null;if(i){let{lifecyclePhase:n,...s}=i,a=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await Ux(e).then(o=>o.mtime.toISOString(),()=>new Date(0).toISOString());i={...s,updatedAt:a,phase:s.phase==="selected"&&n==="restart-requested"?"restart-requested":s.phase==="reconciled"&&n==="cancelled"?"cancelled":s.phase==="reconciled"&&n==="required-action"?"required-action":s.phase}}return i}async function fa(t,e){let{lifecyclePhase:i,...r}={...e,selections:[],updatedAt:new Date().toISOString()},n=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await Z(ri(ma(t),"intent.json"),n)}var vp=t=>t&&["selecting","selected","restart-requested"].includes(t.phase),Iv=(t,e=Date.now())=>!!t&&!!vp(t)&&e-Date.parse(t.updatedAt??"")<jx;import{promisify as xO}from"node:util";import{realpathSync as Ov,statSync as Hx}from"node:fs";import{basename as Gx,delimiter as Wx,dirname as Av,join as wp,resolve as $x}from"node:path";function xv(t){if(!t)return null;try{let e=Ov(t);return Gx(e)==="npm-cli.js"&&Hx(e).isFile()?e:null}catch{return null}}function Vx({execPath:t=process.execPath,env:e=process.env}={}){let i=xv(e.npm_execpath);if(i)return i;let r=new Set([Av(t)]);try{r.add(Av(Ov(t)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(Wx).filter(Boolean))r.add($x(s));for(let s of r)for(let a of[wp(s,"node_modules","npm","bin","npm-cli.js"),wp(s,"..","lib","node_modules","npm","bin","npm-cli.js"),wp(s,"npm")]){let o=xv(a);if(o)return o}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 Rv(t){return{file:process.execPath,args:[Vx(),...t]}}import{randomUUID as zx}from"node:crypto";import{mkdir as Cv,readFile as Kx,rename as kp,rm as Yx,unlink as pV,writeFile as Qx}from"node:fs/promises";import{isAbsolute as Nv,join as Tn}from"node:path";var Ep=1,Jx=1440*6e4,ha=t=>Tn(t,"pi-web","upgrade"),Tp=t=>Tn(ha(t),"candidate.json"),Xx=t=>Tn(ha(t),"transaction.json"),Pv=t=>Tn(ha(t),"history"),Mv=/^[a-f0-9-]{36}$/i;async function Zx(t,e){let i=`${t}.${zx()}.tmp`;try{await Qx(i,e,{mode:384}),await kp(i,t)}finally{await Yx(i,{force:!0})}}var eO=(t,e)=>Zx(t,JSON.stringify(e));async function Sp(t,e){await kp(t,`${t}.${e}-${Date.now()}`).catch(i=>{if(i?.code!=="ENOENT")throw i})}async function Dv(t,e,i=()=>!1){let r;try{r=JSON.parse(await Kx(t,"utf8"))}catch(n){return n?.code==="ENOENT"||await Sp(t,"invalid"),null}return e(r)?i(r)?(await Sp(t,"expired"),null):r:(await Sp(t,"invalid"),null)}function Lv(t){if(!t||typeof t!="object"||t.schema!==Ep||!Mv.test(t.id??""))return!1;try{St(t.version)}catch{return!1}return typeof t.launcher=="string"&&Nv(t.launcher)&&typeof t.packageRoot=="string"&&Nv(t.packageRoot)&&["stable","alpha"].includes(t.channel)&&typeof t.downgrade=="boolean"&&!Number.isNaN(Date.parse(t.createdAt??""))}async function ya(t,e=Date.now()){return Dv(Tp(t),Lv,i=>e-Date.parse(i.createdAt)>Jx)}async function Uv(t,e){let i={schema:Ep,createdAt:new Date().toISOString(),...e};if(!Lv(i))throw new Error("Invalid upgrade candidate");return await Cv(ha(t),{recursive:!0,mode:448}),await eO(Tp(t),i),i}async function Ip(t,e,i){let r=await ya(t);!r||e&&r.id!==e||(await Cv(Pv(t),{recursive:!0,mode:448}),await kp(Tp(t),Tn(Pv(t),`${r.id}-candidate-${i}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var tO=["selected","committed","rolled-back"];function iO(t){return!!t&&typeof t=="object"&&t.schema===Ep&&Mv.test(t.id??"")&&tO.includes(t.phase)&&typeof t.version=="string"&&typeof t.from=="string"&&!Number.isNaN(Date.parse(t.updatedAt??""))}async function qv(t){return Dv(Xx(t),iO)}import{readFile as rO,rename as nO,writeFile as sO,unlink as aO}from"node:fs/promises";import{join as oO}from"node:path";import{randomUUID as lO}from"node:crypto";var Ap=1,jv=t=>oO(t,"pi-web","launcher-handoff.json");function Bv(t){return t?.protocol===Ap&&typeof t.nonce=="string"&&t.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(t.requestId)&&Number.isSafeInteger(t.pid)&&t.pid>0&&["requested","draining","stopped","refused","failed"].includes(t.phase)}async function xp(t){try{let e=JSON.parse(await rO(jv(t),"utf8"));if(!Bv(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 cO(t,e){let i=`${t}.${lO()}.tmp`;try{await sO(i,JSON.stringify(e),{mode:384}),await nO(i,t)}finally{await aO(i).catch(()=>{})}}async function Fv(t,e){if(!Bv(e))throw new Error("Invalid launcher handoff receipt");await cO(jv(t),e)}import{execFile as pO}from"node:child_process";import{cp as dO,readFile as Op,realpath as uO,rm as mO}from"node:fs/promises";import{join as gr,sep as gO}from"node:path";import{promisify as fO}from"node:util";var Hv=fO(pO),Rp=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Np(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=t;return Rp.map(i=>{let r=e[i];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${i}@${r}`})}async function ba(t){return Promise.all(Rp.map(async e=>{let i=await or(t,e),r=JSON.parse(await Op(gr(i,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Gv(t,e){let i=JSON.parse(await Op(gr(e,"package.json"),"utf8"));if(i.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=i.peerDependencies===void 0?await ba(t):Np(i.peerDependencies);if(JSON.stringify(await ba(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let n=await or(t,"node-pty"),s=await or(e,"node-pty"),a=await uO(gr(e,"../.."));if(n===s||!s.startsWith(a+gO))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let o=async d=>JSON.parse(await Op(gr(d,"package.json"),"utf8")).version;if(await o(n)!==await o(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await mO(s,{recursive:!0,force:!0}),await dO(n,s,{recursive:!0});let l={...process.env};delete l.NODE_OPTIONS,delete l.NODE_PATH,delete l.ELECTRON_RUN_AS_NODE,await Hv(process.execPath,[gr(e,"desktop","check-pty.cjs")],{cwd:e,env:l,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await or(e,Rp[0]),{stdout:p}=await Hv(process.execPath,[gr(c,"dist","bundle","cli.js"),"--version"],{cwd:e,env:l,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}import{lstat as $v,readdir as Vv,readFile as hO,realpath as Wv,rm as yO}from"node:fs/promises";import{join as In,relative as bO,sep as zv}from"node:path";var _O=1440*6e4,vO=1024*1024,wO=4,SO=t=>t==="releases"||t==="history"||t.endsWith("-history");async function kO(t,e){let i=new Set,r=[...new Set(e.flatMap(a=>[a+zv,a+"/"]))],n=a=>{if(typeof a=="string")for(let o of r){let l=a.indexOf(o);l>=0&&i.add(a.slice(l+o.length).split(/[\\/]/)[0])}else Array.isArray(a)?a.forEach(n):a&&typeof a=="object"&&Object.values(a).forEach(n)},s=async(a,o)=>{let l=await Vv(a,{withFileTypes:!0}).catch(()=>[]);for(let c of l){let p=In(a,c.name);if(c.isDirectory()){o<wO&&!SO(c.name)&&await s(p,o+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await $v(p)).size>vO)continue;n(JSON.parse(await hO(p,"utf8")))}catch{}}};return await s(t,0),i}async function Kv(t){let e=In(t.agentDir,"pi-web"),i;try{i=await Wv(In(e,"releases"))}catch{return[]}let r=t.now??Date.now(),n=t.graceMs??_O,s=await kO(e,[In(e,"releases"),i]);try{let o=bO(i,await Wv(t.packageRoot));o&&!o.startsWith("..")&&s.add(o.split(zv)[0])}catch{}let a=[];for(let o of await Vv(i,{withFileTypes:!0}).catch(()=>[])){if(!o.isDirectory()||s.has(o.name))continue;let l=In(i,o.name);try{if(r-(await $v(l)).mtimeMs<n)continue;await yO(l,{recursive:!0,force:!0}),a.push(o.name)}catch{}}return a}var OO=xO(EO),fr=t=>["committed","cancelled","failed"].includes(t);function Zv(t){let e=t.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 RO(t,e){try{let i=Rv(t),{stdout:r}=await OO(i.file,i.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(i){let r=i;throw new Error(r.stderr?.trim()||r.message)}}var _a=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??RO,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 i=>{let r=(await this.runNpm(["view",`pi-webapp@${i}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return ba(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Np(s)},this.verifyPackage=e.verifyPackage??Gv,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?Ap:0}}async requestLauncherHandoff(e,i){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(i))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!fr(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let n=pe(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await ni(n,"utf8")),a=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!a(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let o=await xp(this.agentDir);if(o?.nonce===e&&["requested","draining"].includes(o.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let l,c=!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(l=await this.beforeRestart(),!a(JSON.parse(await ni(n,"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:i,pid:s.pid,phase:"requested"};try{await Fv(this.agentDir,p),c=!0}catch(d){let m=await xp(this.agentDir).catch(()=>null);if(c=m?.nonce===e&&m?.requestId===i&&["requested","draining","stopped"].includes(m.phase),!c)throw d}this.restartPending=!0}finally{!c&&l&&await l()}}async current(){let e=JSON.parse(await ni(pe(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return St(e.version),e.version}async pruneReleases(){if(this.preparing||this.preparedUpdate||this.restartPending||this.cancellation)return[];let e=await this.transaction();return e&&!fr(e.phase)?[]:Kv({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),i=await this.transaction();if(!i||fr(i.phase)||i.id===this.ownTransaction)return e;if(i.version===e&&["selecting","selected","restart-requested"].includes(i.phase))await this.record({...i,phase:"committed",message:"Selected version is running"});else if(i.phase==="restart-requested"){let r=await qv(this.agentDir);await this.record({...i,phase:"failed",message:r?.id===i.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Ip(this.agentDir,i.id,"superseded"),await this.record({...i,phase:"failed",message:`Interrupted while ${i.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return pe(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await ze(this.transactionPath)}catch{return await ga(this.transactionPath),null}return e?e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||typeof e.selectionPath!="string"?(await ga(this.transactionPath),null):e:null}async record(e){if(await An(pe(this.agentDir,"pi-web"),{recursive:!0}),await Z(this.transactionPath,e),fr(e.phase)){let i=pe(this.agentDir,"pi-web","update-history");await An(i,{recursive:!0}),await Z(pe(i,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),i=await ya(this.agentDir);i&&(!e||i.id===e.id)&&await Ip(this.agentDir,i.id,"cancelled"),e&&!fr(e.phase)&&await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0}get preferencePath(){return pe(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ni(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 i=`${this.preferencePath}.${Pp()}.tmp`;try{await An(pe(this.agentDir,"pi-web"),{recursive:!0}),await Xv(i,JSON.stringify({channel:e}),{mode:384}),await Qv(i,this.preferencePath)}finally{this.savingPreference=!1,await Jv(i,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),i=await this.channel(),r=Yv(pe(this.packageRoot,".git")),n={current:e,channel:i,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(n.launcher=this.launcherIdentity(),n.launcherHandoff={supported:n.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(n.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction();if(s&&!fr(s.phase)?n.recovery={version:s.version,phase:s.phase,canCancel:s.phase!=="restart-requested"}:s?.phase==="failed"&&s.message&&(n.lastFailure={version:s.version,message:s.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...n,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&&i==="alpha"&&!this.desktopReleaseChannels)return{...n,canRestart:!1,reason:n.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?n.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":n.canRestart||(n.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&&n.canRestart&&(n.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 a=JSON.parse((await this.runNpm(["view","pi-webapp",i==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),o=Array.isArray(a)&&a.length===1?a[0]:a,l=i==="alpha"?o:{latest:o};if(!l||!I_(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let c=l.latest;if(i==="alpha"&&l.alpha!==void 0){if(!ea(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");Ve(l.alpha,c)>0&&(c=l.alpha)}if(n.latest=c,n.downgrade=Ve(c,e)<0,n.available=i==="stable"?Ve(c,e)!==0:Ve(c,e)>0,n.available&&this.pluginWarnings){let p=await this.pluginWarnings(c).catch(()=>[]);p.length&&(n.pluginWarnings=p)}this.desktopManaged&&n.downgrade&&!this.desktopReleaseChannels&&Ve(c,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(n.canRestart=!1,n.requiresDesktopUpgrade=!0,n.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(a){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`)}return n}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let i=this.prepareUpdate(e);this.preparation=i;try{return await i}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(Yv(pe(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 i=await this.check();if(e.channel!==i.channel||e.version!==i.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 i=await this.check();if(e&&(e.channel!==i.channel||e.version!==i.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!i.canRestart)throw new Error(i.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!i.available||!i.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(i.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=pe(this.agentDir,"pi-web","releases");await An(r,{recursive:!0});let n=await IO(pe(await AO(r),`${i.latest}-`)),s=pe(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),a={schema:1,id:Pp(),phase:"downloading",version:i.latest,channel:i.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=a.id,await this.record(a);try{let o=this.desktopManaged?await this.targetPeerSpecs(i.latest):[];await this.runNpm(["install",`pi-webapp@${i.latest}`,...o,"--prefix",n,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=pe(n,"node_modules","pi-webapp");a={...a,phase:"validating",packageRoot:l},await this.record(a);let c=JSON.parse(await ni(pe(l,"package.json"),"utf8"));if(c.name!=="pi-webapp"||c.version!==i.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await ni(pe(this.packageRoot,"package.json"),"utf8"));if(i.downgrade&&Zv(c)!==Zv(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let d=pe(l,"bin","pi-webapp.mjs");return await Promise.all([d,pe(l,"dist","extension.js"),pe(l,"web","dist","index.html")].map(m=>TO(m))),this.desktopManaged&&(await Jc(this.agentDir,{version:i.latest,launcher:d,desktopProtocolVersion:ei}),await this.verifyPackage(this.packageRoot,l)),await this.prefetchPlugins?.(i.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await Uv(this.agentDir,{id:a.id,version:i.latest,launcher:d,packageRoot:l,channel:i.channel??"stable",downgrade:!!i.downgrade}),a={...a,phase:"prepared"},await this.record(a),this.preparedUpdate={id:a.id,update:{version:i.latest,launcher:d},channel:i.channel??"stable"},{version:i.latest,launcher:d}}catch(o){await Jv(n,{recursive:!0,force:!0});let l=(o instanceof Error?o.message:String(o)).slice(0,500);throw await this.record({...a,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${l}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),o}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:i=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let n,s=!1,a=pe(this.agentDir,"pi-web","launcher.restart");try{if(n=await this.beforeRestart?.(i),(await ya(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let o=await this.transaction();o?.id===r.id&&await this.record({...o,phase:"restart-requested"});try{if(JSON.parse(await ni(a,"utf8"))?.nonce!==this.launcherNonce){let c=pe(this.agentDir,"pi-web","restart-history");await An(c,{recursive:!0,mode:448}),await Qv(a,pe(c,`stale-${Pp()}.json`))}}catch{}try{await Xv(a,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(l){try{let c=JSON.parse(await ni(a,"utf8"));s=c.nonce===this.launcherNonce&&c.candidate===r.id}catch{}if(!s)throw l}this.restartPending=!0}catch(o){if(s){this.restartPending=!0;return}let l=await this.transaction();throw l?.id===r.id&&l.phase==="restart-requested"&&await this.record({...l,phase:"prepared"}),n&&await n(),o}}};import{createHash as Hw,randomUUID as BN}from"node:crypto";import{randomUUID as fN}from"node:crypto";import{join as Xp}from"node:path";import{randomUUID as iw}from"node:crypto";import{randomUUID as NO}from"node:crypto";function ew(t){let i=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(a=>typeof t[a]!="function").map(a=>String(a));if(i.length)return{supported:!1,missing:i};let r=`__pi_web_contract_${NO().replaceAll("-","")}`,n;try{if(n=t.getActiveTools(),!Array.isArray(n))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{t.registerTool(s),t.setActiveTools([...n,r]),(t.getAllTools().find(o=>o.name===r)?.exposure!=="hidden"||t.getActiveTools().includes(r))&&i.push("hidden-tool-exposure");let a={type:"object",properties:{contract:{type:"boolean"}}};t.registerTool({...s,parameters:a}),t.getAllTools().find(o=>o.name===r)?.parameters!==a&&i.push("dynamic-tool-registry")}catch{i.push("tool-registry-contract")}finally{try{t.setActiveTools(n)}catch{i.push("active-tool-registry")}}return{supported:!i.length,missing:i}}var PO;function tw(){return PO??=CO().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function CO(){let{createAgentSession:t,DefaultResourceLoader:e,SessionManager:i}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:n,rm:s}=await import("node:fs/promises"),{tmpdir:a}=await import("node:os"),{join:o}=await import("node:path"),l=await n(o(a(),"pi-sdk-contract-")),c,p=[],d=0,m=0,g=!1,f=!1;try{let h=(C,N,G)=>({name:C,label:C,description:"Inert host SDK contract check",exposure:N,parameters:{type:"object",properties:{}},execute:G}),_=()=>({content:[],details:void 0}),S=new e({cwd:l,agentDir:l,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[C=>{C.on("tool_call",N=>{if(N.toolName==="__contract_direct"&&(g=!!N.parentToolCallId),N.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let N of["hidden","model-only"])C.registerTool(h(`__contract_${N.replace("-","_")}`,N,async()=>(m++,_())));C.registerTool(h("__contract_protected","direct",async()=>(m++,_()))),C.registerTool(h("__contract_direct","direct",async()=>(d++,_()))),C.registerTool(h("__contract_driver","direct",async(N,G,P,I,x)=>{let L=await x.executeTool("__contract_hidden",{}),k=await x.executeTool("__contract_model_only",{}),b=await x.executeTool("__contract_direct",{}),j=await x.executeTool("__contract_protected",{});return(!L.isError||!k.isError)&&p.push("nested-tool-exposure"),(b.isError||d!==1)&&p.push("nested-tool-execution"),(!j.isError||m!==0)&&p.push("nested-tool-permission-guard"),g||p.push("nested-parent-identity"),f=!0,_()}))}]});await S.reload(),{session:c}=await t({cwd:l,agentDir:l,sessionManager:i.inMemory(l),resourceLoader:S}),await c.bindExtensions({mode:"print"});let E=c.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(E);let A=0;c.agent.streamFunction=async C=>{let N=A++===0,G={role:"assistant",api:C.api,provider:C.provider,model:C.id,timestamp:Date.now(),content:N?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:N?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},P=r();return P.push({type:"start",partial:G}),P.push({type:"done",reason:N?"toolUse":"stop",message:G}),P.end(G),P};let D;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((C,N)=>{D=setTimeout(()=>N(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(D)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(l,{recursive:!0,force:!0})}}var va=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??=tw().then(e=>{this.sdkContract=e;for(let i of this.bindings)if(i.ready&&!i.disposed)try{this.publish(i)}catch{i.compatible=!1,i.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(i=>this.waiters.add(i))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let i;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,n)=>{i=setTimeout(()=>n(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(i)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async i=>{await this.verifyCompatibility(),this.install(i,e)}}mountTui(e,i){let r=this.install(e,i);r.ready=!0;try{this.publish(r)}catch(n){throw this.release(r),n}return()=>this.release(r)}install(e,i){let r={pi:e,scope:{...i},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let n=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{n(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),n(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),n(e.on("tool_call",s=>{let a=r.owned.get(s.toolName);if(!a)return;let o=this.descriptors.get(a)?.find(l=>l.name===s.toolName);if(!o||!this.allowed(r,a,o,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),n(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),n(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let i=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!i)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");i.session=e,i.ready=!0,i.off=e.subscribe(r=>{r.type==="agent_settled"&&(i.busy=!1,this.notify())});try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}releasePending(e){for(let i of this.bindings)!i.session&&!i.ready&&i.scope.sessionId===e&&this.release(i)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let i of e.handlers)i();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,i,r,n=!1){let s=this.service.policy(i,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!n||s.allowNested===!0)}change(e,i){if(!this.frozen||[...this.bindings].some(n=>n.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(i);this.validateChange(e,r),this.descriptors.set(e,r);for(let n of this.bindings)n.ready&&this.publish(n)}validateChange(e,i){for(let n of this.bindings)if(n.compatible!==!1)for(let[s,a]of n.owned)this.assertOwner(n,a,s);let r=new Set;for(let n of i){if(!n.name||!n.action||!n.parameters||n.parameters.type!=="object"||r.has(n.name))throw new Error("Invalid hosted tool descriptor");r.add(n.name);for(let[s,a]of this.descriptors)if(s!==e&&a.some(o=>o.name===n.name))throw new Error(`Hosted tool ownership conflict: ${n.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,n.name)}}assertOwner(e,i,r){let n=e.owned.get(r);if(n&&n!==i)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(a=>a.name===r);if(s&&(!n||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=ew(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,n]of e.owned)this.assertOwner(e,n,r);for(let[r,n]of this.descriptors)for(let s of n)this.assertOwner(e,r,s.name);let i=new Set;for(let[r,n]of this.descriptors)for(let s of n){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;i.add(s.name);let a=this.service.policy(r,e.scope),o=a.exposure??"direct",l=!a.allowNested&&o==="direct"?"model-only":o,c={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:l,execute:async(p,d,m)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:iw(),scope:{...e.scope},kind:"tool",action:s.action,input:d},m)}};e.pi.registerTool(c),e.definitions.set(s.name,c)}for(let r of e.owned.keys())if(!i.has(r)){let n={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:MO};e.pi.registerTool(n),e.definitions.set(r,n)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let n=e.definitions.get(r);return!n||n.exposure==="direct"||n.exposure==="model-only"}))}async invokeAction(e,i,r,n,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(o=>o.scope.sessionId===i.sessionId&&o.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let a=this.service.policy(e,i);if(!a.enabled||a.planMode||a.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:iw(),scope:i,kind:"action",action:r,input:n},s)}};async function MO(){throw new Error("Hosted tool unavailable")}import{randomBytes as GR,randomUUID as WR,timingSafeEqual as $R}from"node:crypto";import{join as Ze}from"node:path";var DO=30,rw=/^[a-z][a-z0-9-]{0,63}$/,LO=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,xn=t=>{throw new y("invalid_package",t)},Cp=(t,e)=>t===void 0?[]:!Array.isArray(t)||t.length>32?xn(`Invalid ${e} declaration`):t;function hr(t){let e=t&&typeof t=="object"?t:{},i=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(o=>typeof o=="string"):[]),r=i.has("secrets")?Cp(e.secrets,"secrets").map(o=>{let l=o?.name;return typeof l=="string"&&rw.test(l)?l:xn("Invalid secret name")}):[],n=e.network,s=i.has("network")?Cp(n?.hosts,"network").map(o=>typeof o=="string"&&LO.test(o)?o:xn("Network hosts must be exact lowercase DNS names")):[],a=i.has("scheduler")?Cp(e.schedules,"schedules").map(o=>{let l=o;return!l||typeof l.id!="string"||!rw.test(l.id)||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!Number.isSafeInteger(l.intervalSec)||l.intervalSec<DO||l.intervalSec>86400?xn("Invalid schedule declaration"):{id:l.id,intervalSec:l.intervalSec,action:l.action}}):[];return new Set(a.map(o=>o.id)).size!==a.length&&xn("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:a,sessions:i.has("sessions")}}import{lookup as UO}from"node:dns/promises";import{isIP as qO}from"node:net";var jO=new Set(["GET","POST","PATCH","PUT","DELETE"]),BO=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),FO=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),wa=(t,e)=>{throw new y("network_denied",t,{status:403,reason:e})};function HO(t){let e=t.toLowerCase().replace(/^::ffff:/,"");if(qO(e)===4){let[i,r]=e.split(".").map(Number);return i===0||i===10||i===127||i===169&&r===254||i===172&&r>=16&&r<=31||i===192&&r===168||i===100&&r>=64&&r<=127||i>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function nw(t,e,i,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new y("invalid_input","Invalid network request");let a;try{a=new URL(s.url)}catch{throw new y("invalid_input","Invalid URL")}(a.protocol!=="https:"||a.username||a.password||a.port&&a.port!=="443")&&wa("Only plain https on port 443 is allowed","scheme"),e.includes(a.hostname)||wa("Host is not declared by the plugin","host");let o=(s.method??"GET").toUpperCase();if(!jO.has(o))throw new y("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new y("invalid_input","Invalid body");let l={};for(let[E,A]of Object.entries(s.headers??{})){if(typeof A!="string"||BO.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(A))throw new y("invalid_input",`Header not allowed: ${E.slice(0,64)}`);l[E]=A}let c=null;if(s.secret!==void 0){if(i.includes(s.secret)||wa("Secret is not declared by the plugin","secret"),c=await n.secrets.get(t,s.secret),!c)throw new y("secret_missing","Secret has not been configured",{status:412});l.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async E=>(await UO(E,{all:!0})).map(A=>A.address)))(a.hostname);(!p.length||p.some(HO))&&wa("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,m=n.maxResponseBytes??2*1024*1024,g=await(n.fetch??fetch)(a,{method:o,headers:l,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),f=[],h=0;if(g.body)for await(let E of g.body){if(h+=E.byteLength,h>m)throw new y("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let _=Buffer.concat(f).toString("utf8"),S={};return g.headers.forEach((E,A)=>{FO.has(A.toLowerCase())&&(S[A.toLowerCase()]=E)}),c&&(_=_.split(c).join("[redacted]")),{status:g.status,headers:S,body:_}}var Sa=(t,e,i)=>{if(typeof t!="string"||!t||t.length>e)throw new y("invalid_input",`Invalid ${i}`);return t};async function sw(t,e,i,r,n,s){let a=n&&typeof n=="object"&&!Array.isArray(n)?n:{};if(r==="sessions.create"){if(a.mode!=="plan")throw new y("invalid_input","Plugin sessions must start in plan mode");if(t.activeCount(e)>=s)throw new y("quota_exceeded","Too many active plugin sessions",{status:429});return t.create({pluginId:e,cwd:i,title:Sa(a.title,200,"title"),prompt:Sa(a.prompt,64*1024,"prompt"),mode:"plan"})}let o=Sa(a.sessionId,200,"sessionId");if(t.ownerOf(o)!==e)throw new y("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(a.mode!==void 0&&a.mode!=="execute")throw new y("invalid_input","Invalid mode");return await t.send(o,Sa(a.message,64*1024,"message"),a.mode),{ok:!0};case"sessions.release":return await t.release(o),{ok:!0};case"sessions.abort":return await t.abort(o),{ok:!0};case"sessions.events":return t.events(o,Number.isSafeInteger(a.after)&&a.after>=0?a.after:0);default:throw new y("method_denied","Unknown sessions method")}}var GO=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),ka=class{options;constructor(e){this.options=e}handles(e){return GO.has(e)}async call(e,i,r,n,s){let a=hr(i);if(n==="network.fetch"){if(!a.networkHosts.length)throw new y("capability_denied","Plugin did not declare network access",{status:403});return nw(e,a.networkHosts,a.secrets,s,this.options)}if(!a.sessions||!this.options.sessions)throw new y("capability_denied","Sessions capability is unavailable",{status:403});return sw(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var Ea=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,i){this.stop(e);let r=this.deps.setInterval??((n,s)=>{let a=setInterval(n,s);return a.unref(),a});this.timers.set(e,i.map(n=>r(()=>{this.tick(e,n)},n.intervalSec*1e3)))}stop(e){let i=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])i(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,i){let r=`${e}\0${i.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,i),!0}catch(n){return this.deps.onError?.(e,i,n),!1}finally{this.running.delete(r)}}};import{createHash as Vp,timingSafeEqual as vR}from"node:crypto";import{lstat as Sw,mkdtemp as $p,readdir as wR,readFile as SR,realpath as kR,rename as ER,rm as si,writeFile as TR}from"node:fs/promises";import{tmpdir as IR}from"node:os";import{join as ne}from"node:path";import{gunzipSync as QO}from"node:zlib";import{mkdir as JO,writeFile as XO}from"node:fs/promises";import{dirname as ZO,join as eR}from"node:path";import{constants as Mp}from"node:fs";import{lstat as lw,open as WO,readdir as aw,realpath as cw}from"node:fs/promises";import{createHash as $O}from"node:crypto";import{join as pw,relative as VO,resolve as zO,sep as KO}from"node:path";var de={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,wasm:16*1024*1024,other:2*1024*1024},YO={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],cjs:["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"],ttf:["font/ttf"],otf:["font/otf"],wasm:["application/wasm"]},re=t=>$O("sha256").update(t).digest("hex");function ie(t){throw new y("invalid_package",t)}async function Di(t,e,i){let r=e.split("/");(!r.length||r.some(o=>!o||o==="."||o===".."||!/^[\w.-]+$/.test(o)))&&ie("Invalid resource path");let n=t;for(let o=0;o<r.length;o++){n=pw(n,r[o]);let l=await lw(n);(l.isSymbolicLink()||(o<r.length-1?!l.isDirectory():!l.isFile()||l.nlink!==1))&&ie("Links and non-regular package files are forbidden")}let s=await cw(n);(s!==zO(t,e)||VO(t,s).startsWith(`..${KO}`))&&ie("Resource escapes package root");let a=await WO(n,Mp.O_RDONLY|Mp.O_NONBLOCK|(Mp.O_NOFOLLOW??0));try{let o=await a.stat();(!o.isFile()||o.nlink!==1||o.size>i)&&ie("Oversized or non-regular package file");let l=Buffer.alloc(Math.min(o.size+1,i+1)),c=0;for(;c<l.length;){let p=await a.read(l,c,l.length-c,c);if(!p.bytesRead)break;c+=p.bytesRead}return(c>i||c!==o.size)&&ie("Package resource changed during read"),l.subarray(0,c)}finally{await a.close()}}function ow(t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return ie("Invalid package JSON")}}async function Li(t,e){let i=await cw(t);(await lw(t)).isSymbolicLink()&&ie("Package root cannot be a symlink");let r=ow(await Di(i,"package.json",de.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&ie("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&ie("Invalid package version"),ti(r.piWebapp)||ie("Unsupported hosted manifest"),r.type!=="module"&&ie("Hosted package must declare ESM module type");for(let d of await aw(i,{withFileTypes:!0}))d.name==="dist"&&d.isDirectory()||(!d.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(d.name))&&ie("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(d=>/^(?:preinstall|install|postinstall|prepare)$/.test(d))&&ie("Hosted packages cannot run install lifecycle scripts");for(let d of["dependencies","optionalDependencies"]){let m=r[d];m&&(typeof m!="object"||Object.keys(m).length>0)&&ie("Hosted packages must contain all runtime dependencies")}let n=r.piWebapp,s=ow(await Di(i,n.resourcesManifest.slice(2),de.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>de.files)&&ie("Invalid resource manifest");let a=new Map,o=0;for(let d of s.files){(!d||typeof d!="object")&&ie("Invalid resource entry");let m=d,g={...m,path:typeof m.path=="string"&&m.path.startsWith("./")?m.path.slice(2):m.path};(!Oi(`./${g.path}`)||typeof g.sha256!="string"||!/^[a-f0-9]{64}$/.test(g.sha256)||!Number.isSafeInteger(g.bytes)||g.bytes<0||a.has(g.path))&&ie("Invalid or duplicate resource");let f=g.path.split(".").at(-1);YO[f]?.includes(g.mime)||ie("Unsupported resource MIME");let h=f==="js"||f==="mjs"||f==="cjs"?de.js:f==="css"?de.css:["woff","woff2","ttf","otf"].includes(f)?de.font:f==="wasm"?de.wasm:de.other;(g.bytes>h||(o+=g.bytes)>de.total)&&ie("Resource budget exceeded");let _=await Di(i,g.path,h);(_.length!==g.bytes||re(_)!==g.sha256)&&ie("Resource integrity mismatch"),a.set(g.path,Object.freeze({...g}))}for(let d of[n.backend.entry,n.frontend.document,n.frontend.controller])a.has(d.slice(2))||ie("Entrypoint is absent from resource manifest");let l=0;async function c(d,m=0){m>16&&ie("Package directory nesting limit exceeded");for(let g of await aw(pw(i,d),{withFileTypes:!0})){++l>de.files*2&&ie("Too many package entries");let f=`${d}/${g.name}`;(g.isSymbolicLink()||!g.isDirectory()&&!g.isFile())&&ie("Invalid archive member"),g.isDirectory()?await c(f,m+1):f!==n.resourcesManifest.slice(2)&&!a.has(f)&&ie("Undeclared distribution asset")}}await c("dist");let p=re(JSON.stringify({id:r.name,version:r.version,manifest:n,resources:[...a.values()].sort((d,m)=>d.path.localeCompare(m.path))}));return{id:r.name,version:r.version,root:i,manifest:n,resources:a,digest:p}}async function dw(t,e,i){if(i!==t.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Oi(`./${r}`))return null;let n=t.resources.get(r);if(!n||r===t.manifest.backend.entry.slice(2))return null;let s=await Di(t.root,r,n.bytes);if(s.length!==n.bytes||re(s)!==n.sha256)throw new y("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var Ta=64*1024*1024,tR=de.total+de.files*2048,te=t=>{throw new y("invalid_archive",t)};function yr(t){let e=t.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?t:t.subarray(0,e))}catch{return te("Archive has invalid UTF-8 paths")}}function uw(t){let e=yr(t).trim();if(!/^[0-7]+$/.test(e))return te("Unsupported archive number encoding");let i=parseInt(e,8);return Number.isSafeInteger(i)?i:te("Archive number exceeds limits")}function iR(t){let e=t.endsWith("/")?t.slice(0,-1):t;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return te("Archive must have one package root");let i=e.slice(8);return i.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?te("Archive path is not a safe relative package path"):i}function rR(t){let e={},i=0;for(;i<t.length;){let r=t.indexOf(32,i);if(r<0)return te("Invalid PAX header");let n=t.subarray(i,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return te("Invalid PAX record length");let s=Number(n),a=i+s;if(a>t.length||a<=r+2||t[a-1]!==10)return te("Truncated PAX record");let o=yr(t.subarray(r+1,a-1)),l=o.indexOf("=");if(l<1)return te("Invalid PAX record");let c=o.slice(0,l),p=o.slice(l+1);if(Object.hasOwn(e,c)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(c))return te("Unsupported PAX feature");e[c]=p,i=a}return e}function nR(t){if(!t.length||t.length>Ta)return te("Compressed archive exceeds budget");let e;try{e=QO(t,{maxOutputLength:tR})}catch{return te("Invalid or oversized gzip archive")}let i=[],r=new Set,n=0,s=0,a=0,o=0,l=null,c=!1;for(;n+512<=e.length;){let d=e.subarray(n,n+512);if(n+=512,d.every(D=>D===0)){if(l||e.subarray(n).some(D=>D!==0))return te("Unexpected archive data after end marker");c=!0;break}if(++o>de.files*2)return te("Too many archive headers");let m=0;for(let D=0;D<512;D++)m+=D>=148&&D<156?32:d[D];if(uw(d.subarray(148,156))!==m)return te("Invalid tar header checksum");let g=yr(d.subarray(257,263));if(g&&g!=="ustar"&&g!=="ustar ")return te("Unsupported tar format");let f=d[156],h=yr(d.subarray(345,500)),_=(h?h+"/":"")+yr(d.subarray(0,100)),S=uw(d.subarray(124,136));if(l&&(l.path!==void 0&&(_=l.path),l.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(l.size))return te("Invalid PAX size");S=Number(l.size)}if(!Number.isSafeInteger(S)||S<0||S>de.total||n+S>e.length)return te("Truncated or oversized tar member");let E=e.subarray(n,n+S);if(n+=Math.ceil(S/512)*512,f===120){if(l||S>8192)return te("Oversized or chained PAX header");l=rR(E);continue}if(l=null,f!==0&&f!==48&&f!==53)return te("Links and special archive members are forbidden");let A=f===53;if(A&&S!==0||yr(d.subarray(157,257)))return te("Invalid archive link or directory");if(_=iR(_),!_&&!A)return te("Invalid package root member");if(r.has(_))return te("Duplicate archive member");if(r.add(_),++s>de.files||(a+=S)>de.total)return te("Unpacked archive exceeds budget");i.push({path:_,data:E,directory:A})}if(!c||!r.has("package.json"))return te("Archive is incomplete or has no package.json");let p=new Set(i.filter(d=>!d.directory).map(d=>d.path));for(let d of i){let m=d.path.split("/");for(let g=1;g<m.length;g++)if(p.has(m.slice(0,g).join("/")))return te("Archive file/directory collision")}return i}async function Dp(t,e){let i=nR(t);for(let r of i){if(!r.path)continue;let n=eR(e,r.path);await JO(r.directory?n:ZO(n),{recursive:!0,mode:448}),r.directory||await XO(n,r.data,{flag:"wx",mode:384})}}import{lstat as sR,mkdir as aR,readdir as oR,realpath as lR,writeFile as cR}from"node:fs/promises";import{dirname as pR,join as Lp}from"node:path";async function mw(t,e){let i=await lR(t),r=await Di(i,"package.json",de.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("invalid_package","package.json must be an object");let s=[],a=0,o=0;async function l(m,g){if(g>16)throw new y("invalid_package","Package directory nesting limit exceeded");for(let f of await oR(Lp(i,m),{withFileTypes:!0})){let h=`${m}/${f.name}`;if(++a>de.files)throw new y("invalid_package","Too many package entries");if(f.isDirectory()){await l(h,g+1);continue}if(!f.isFile())throw new y("invalid_package",`Links and non-regular files are forbidden: ${h}`);let _=await Di(i,h,de.js);if((o+=_.length)>de.total)throw new y("invalid_package","Resource budget exceeded");let S=Lp(e,h);await aR(pR(S),{recursive:!0,mode:448}),await cR(S,_,{flag:"wx",mode:384}),s.push([h,re(_)])}}let c;try{c=await sR(Lp(i,"dist"))}catch(m){throw m.code==="ENOENT"?new y("dist_missing","dist/ does not exist yet; build the plugin first"):m}if(!c.isDirectory())throw new y("invalid_package","dist must be a real directory");await l("dist",0);let{version:p,...d}=n;return s.sort((m,g)=>m[0].localeCompare(g[0])),{contentHash:re(JSON.stringify({package:d,files:s})),packageJson:n}}function qe(t){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(t);return!e||e[0]!==t||e.slice(1).some(i=>!Number.isSafeInteger(Number(i)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function ft(t,e){let i=qe(t),r=qe(e);if(!i||!r)throw new y("invalid_version","Only exact stable semantic versions are supported");return i.major-r.major||i.minor-r.minor||i.patch-r.patch}function gw(t){let e=qe(t);if(e)return e;if(!ea(t))return null;let[i,r]=t.split("-alpha."),n=qe(i),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function Up(t){return!!gw(t)}function br(t,e){if(!Up(t)||typeof e!="string"||e.length>256)return!1;let i=e.split("||");if(!i.length||i.some(n=>!n.trim()))return!1;let r=[];for(let n of i){let s=n.trim().split(/\s+/),a=!0;for(let o of s){let l=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(o),c=l&&gw(l[2]);if(!l||!c)return!1;let p=l[2],d=Ve(t,p);switch(l[1]??"="){case"=":a&&=d===0;break;case">=":a&&=d>=0;break;case"<=":a&&=d<=0;break;case">":a&&=d>0;break;case"<":a&&=d<0;break;case"~":a&&=d>=0&&Ve(t,`${c.major}.${c.minor+1}.0-0`)<0;break;case"^":{let m=c.major?`${c.major+1}.0.0`:c.minor?`0.${c.minor+1}.0`:`0.0.${c.patch+1}`;a&&=d>=0&&Ve(t,`${m}-0`)<0;break}}}r.push(a)}return r.some(Boolean)}var qp=64*1024*1024,jp=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);function Bp(t,e){let i=t.get(e);if(!i)throw new y("unreviewed_plugin","No trusted tool policy for this package");return i}function fw(t,e){let i=t.get(e)?.workspace?.files??jp;for(let r of i)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>qp||r.createDirectory!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(r.createDirectory))throw new y("invalid_policy","Invalid workspace file rule");return i}function hw(t,e){let i=t.get(e)?.runtime?.invokeTimeoutMs;return i===void 0?void 0:Math.min(Math.max(i,1e3),18e4)}var yw=["drawing","design"],dR=/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,uR=/^[a-z][a-z0-9.-]{0,79}$/,Fp=/^[a-z][a-z0-9_]{0,63}$/,Ui=/^[a-z][a-z0-9_-]{0,63}$/,mR=/^[a-z][a-z0-9-]{0,63}$/,On=class{where;constructor(e){this.where=e}fail(e,i){throw new y("invalid_catalog",`${this.where}: ${e} ${i}`)}object(e,i,r,n=r){(!e||typeof e!="object"||Array.isArray(e))&&this.fail(i,"must be an object");let s=e;for(let a of Object.keys(s))r.includes(a)||this.fail(`${i}.${a}`,"is not a known field");for(let a of n)s[a]===void 0&&this.fail(`${i}.${a}`,"is required");return s}string(e,i,r=200,n){return(typeof e!="string"||!e.trim()||e.length>r)&&this.fail(i,`must be a non-empty string of at most ${r} characters`),n&&!n.test(e)&&this.fail(i,`has an invalid format (${JSON.stringify(e)})`),e}strings(e,i,r,n=64){(!Array.isArray(e)||e.length>n)&&this.fail(i,`must be an array of at most ${n} strings`);let s=e.map((a,o)=>this.string(a,`${i}[${o}]`,80,r));return new Set(s).size!==s.length&&this.fail(i,"contains duplicates"),s}text(e,i,r=500){let n=this.object(e,i,["zh","en"]);return{zh:this.string(n.zh,`${i}.zh`,r),en:this.string(n.en,`${i}.en`,r)}}integer(e,i,r,n){return(!Number.isSafeInteger(e)||e<r||e>n)&&this.fail(i,`must be an integer from ${r} to ${n}`),e}https(e,i,r){let n=this.string(e,i,2048),s;try{s=new URL(n)}catch{this.fail(i,"must be an absolute URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash||r!==void 0&&s.hostname!==r)&&this.fail(i,`must be an https URL${r?` on ${r}`:""} without credentials or fragment`),n}subset(e,i,r,n){for(let s of e)i.includes(s)||this.fail(r,`lists "${s}", which is not one of its ${n}`)}};function gR(t,e,i){let r=t.object(e,i,["entry","panels","artifactTools","toolViews","panelAlias"]),n=t.object(r.entry,`${i}.entry`,["label","description","kind"]),s=t.object(r.panelAlias,`${i}.panelAlias`,["prefix","kind","title"]);return{entry:{label:t.string(n.label,`${i}.entry.label`,64),description:t.text(n.description,`${i}.entry.description`,120),kind:t.string(n.kind,`${i}.entry.kind`,32,Ui)},panels:t.strings(r.panels,`${i}.panels`,Ui,16),artifactTools:t.strings(r.artifactTools,`${i}.artifactTools`,Fp,128),toolViews:t.strings(r.toolViews,`${i}.toolViews`,Fp,128),panelAlias:{prefix:t.string(s.prefix,`${i}.panelAlias.prefix`,32,/^[a-z][a-z0-9-]{0,30}:$/),kind:t.string(s.kind,`${i}.panelAlias.kind`,32,Ui),title:t.string(s.title,`${i}.panelAlias.title`,64)}}}function fR(t,e,i){return(!Array.isArray(e)||e.length<1||e.length>16)&&t.fail(i,"must be an array of 1 to 16 rules"),e.map((r,n)=>{let s=`${i}[${n}]`,a=t.object(r,s,["extension","binary","maxBytes","createDirectory"],["extension","binary","maxBytes"]);return typeof a.binary!="boolean"&&t.fail(`${s}.binary`,"must be a boolean"),{extension:t.string(a.extension,`${s}.extension`,17,/^\.[a-z0-9]{1,16}$/),binary:a.binary,maxBytes:t.integer(a.maxBytes,`${s}.maxBytes`,1,qp),...a.createDirectory!==void 0?{createDirectory:t.string(a.createDirectory,`${s}.createDirectory`,64,/^[A-Za-z0-9_-]{1,64}$/)}:{}}})}function hR(t,e,i){let r=t.object(e,i,Object.keys(e&&typeof e=="object"?e:{}),[]);return Object.keys(r).length>16&&t.fail(i,"declares more than 16 secrets"),Object.fromEntries(Object.entries(r).map(([n,s])=>{let a=`${i}.${n}`;t.string(n,`${i} key`,64,mR);let o=t.object(s,a,["provider","scope","createUrl","clientId"],["provider","scope","createUrl"]);return o.provider!=="github"&&t.fail(`${a}.provider`,'must be "github" (the only sign-in the host implements)'),[n,{provider:"github",scope:t.string(o.scope,`${a}.scope`,200,/^[\w:. -]+$/),createUrl:t.https(o.createUrl,`${a}.createUrl`,"github.com"),...o.clientId!==void 0?{clientId:t.string(o.clientId,`${a}.clientId`,64,/^[A-Za-z0-9._-]+$/)}:{}}]}))}function yR(t,e,i="policy"){let r=new On(e),n=r.object(t,i,["tools","readonlyActions","actions","checkpointActions","contribution","browser","workspace","runtime","secrets"],["tools","readonlyActions","actions","checkpointActions","contribution"]),s=r.object(n.tools,`${i}.tools`,Object.keys(n.tools&&typeof n.tools=="object"?n.tools:{}),[]);Object.keys(s).length>128&&r.fail(`${i}.tools`,"declares more than 128 tools");for(let[g,f]of Object.entries(s))r.string(g,`${i}.tools key`,64,Fp),r.string(f,`${i}.tools.${g}`,64,Ui);let a=Object.keys(s),o=Object.values(s),l=r.strings(n.readonlyActions,`${i}.readonlyActions`,Ui),c=r.strings(n.actions,`${i}.actions`,Ui),p=r.strings(n.checkpointActions,`${i}.checkpointActions`,Ui);r.subset(l,o,`${i}.readonlyActions`,"tool actions"),r.subset(p,c,`${i}.checkpointActions`,"actions");let d=gR(r,n.contribution,`${i}.contribution`);r.subset(d.artifactTools,a,`${i}.contribution.artifactTools`,"tools"),r.subset(d.toolViews,a,`${i}.contribution.toolViews`,"tools");let m={tools:s,readonlyActions:l,actions:c,checkpointActions:p,contribution:d};if(n.browser!==void 0){let g=r.object(n.browser,`${i}.browser`,["wasm"],[]);g.wasm!==void 0&&typeof g.wasm!="boolean"&&r.fail(`${i}.browser.wasm`,"must be a boolean"),m.browser=g.wasm===void 0?{}:{wasm:g.wasm}}if(n.workspace!==void 0&&(m.workspace={files:fR(r,r.object(n.workspace,`${i}.workspace`,["files"]).files,`${i}.workspace.files`)}),n.runtime!==void 0){let g=r.object(n.runtime,`${i}.runtime`,["invokeTimeoutMs"],[]);m.runtime=g.invokeTimeoutMs===void 0?{}:{invokeTimeoutMs:r.integer(g.invokeTimeoutMs,`${i}.runtime.invokeTimeoutMs`,1e3,18e4)}}return n.secrets!==void 0&&(m.secrets=hR(r,n.secrets,`${i}.secrets`)),m}var bR=["id","name","icon","description","registry","recommendedVersion","requiredCapabilities","reviewed","policy"];function Hp(t,e,i="plugin"){let r=new On(e),n=r.object(t,i,bR,["id","name","description","registry","recommendedVersion","requiredCapabilities","policy"]),s=r.string(n.id,`${i}.id`,214,dR);n.icon!==void 0&&!yw.includes(n.icon)&&r.fail(`${i}.icon`,`must be one of ${yw.join(", ")}`);let a=r.https(n.registry,`${i}.registry`);new URL(a).origin!==a&&r.fail(`${i}.registry`,"must be a bare origin such as https://registry.npmjs.org");let o=r.string(n.recommendedVersion,`${i}.recommendedVersion`,64);return qe(o)||r.fail(`${i}.recommendedVersion`,"must be a stable x.y.z version"),n.reviewed!==void 0&&r.string(n.reviewed,`${i}.reviewed`,1e3),{id:s,name:r.string(n.name,`${i}.name`,64),...n.icon!==void 0?{icon:n.icon}:{},description:r.text(n.description,`${i}.description`),registry:a,recommendedVersion:o,requiredCapabilities:r.strings(n.requiredCapabilities,`${i}.requiredCapabilities`,uR),policy:yR(n.policy,e,`${i}.policy`)}}function bw(t,e){let i=new On(e),r=i.object(t,"catalog",["schemaVersion","plugins"]);r.schemaVersion!==1&&i.fail("catalog.schemaVersion","must be 1"),(!Array.isArray(r.plugins)||r.plugins.length>64)&&i.fail("catalog.plugins","must be an array of at most 64 entries");let n=r.plugins.map((a,o)=>Hp(a,e,`catalog.plugins[${o}]`)),s=n.map(a=>a.id);for(let[a,o]of s.entries())s.indexOf(o)!==a&&i.fail(`catalog.plugins[${a}].id`,`duplicates ${o}`);return n}function Gp(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))Gp(e)}return t}var _w={schemaVersion:1,plugins:[{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"],reviewed:"Policy reviewed against package 6328c63.",policy:{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"}}}},{id:"@chengzhiyi/pi-pencil",name:"OpenPencil",icon:"design",description:{zh:"\u57FA\u4E8E OpenPencil \u7684 UI \u8BBE\u8BA1\uFF1A\u7F16\u8F91\u5DE5\u4F5C\u533A\u91CC\u7684 .fig \u8BBE\u8BA1\u7A3F\uFF0Cagent \u7684\u4FEE\u6539\u76F4\u63A5\u51FA\u73B0\u5728\u753B\u5E03\u4E0A\uFF0C\u53EF\u968F\u65F6\u64A4\u9500\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"UI design on OpenPencil: edit .fig designs in your workspace; the agent's changes appear on the canvas directly and you can undo them. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.0.2",requiredCapabilities:["state","workspace","panels","browser.wasm"],reviewed:"The tool set is deliberately small. Agent changes apply directly as new revisions; undoing one (revert), saving, syncing and locking stay human-only. accept/reject remain for proposals stored by older builds. import turns a file the person picked (.fig/.jam/.pen/.drawio) into a new design; upload carries an action input over the 2 MB request limit in chunks (bounded and owned by the uploading session in the plugin). A checkpoint freeze may flush a person's first edits in an empty workspace, which creates their design.",policy:{tools:{pencil_read_me:"reference",pencil_status:"status",pencil_inspect:"inspect",pencil_render:"render",pencil_apply_changes:"apply"},readonlyActions:["reference","status","inspect","render"],actions:["list","get","accept","reject","revert","save","open","import","upload","create","rename","selection","sync","lock"],checkpointActions:["get","list","sync","create"],contribution:{entry:{label:"OpenPencil",description:{zh:"UI \u8BBE\u8BA1",en:"UI design"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["pencil_apply_changes"],toolViews:[],panelAlias:{prefix:"pencil:",kind:"editor",title:"OpenPencil"}},browser:{wasm:!0},workspace:{files:[{extension:".fig",binary:!0,maxBytes:67108864,createDirectory:"designs"}]},runtime:{invokeTimeoutMs:12e4}}}]};var vw=Gp(bw(_w,"official-plugins.json")),Xe=Object.freeze(vw.map(({policy:t,...e})=>Object.freeze(e))),Ia=new Map(vw.map(t=>[t.id,t.policy]));function Ke(t,e=Xe){let i=e.find(r=>r.id===t);if(!i)throw new y("unknown_plugin","Plugin is not in the trusted official catalog");return i}function Wp(t,e,i){let r=t.piWebapp;return t.name===e.id&&!!qe(t.version)&&!t.deprecated&&ti(r)&&br(i,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function ww(t,e,i,r,n){if(!t||typeof t!="object"||!("versions"in t)||!t.versions||typeof t.versions!="object"||Array.isArray(t.versions))throw new y("registry_invalid","Invalid registry version catalog");let s=Object.entries(t.versions);if(s.length>1e4)throw new y("registry_invalid","Registry version catalog exceeds budget");let o=s.flatMap(([l,c])=>{if(!c||typeof c!="object")return[];let p=c;return p.version===l&&Wp(p,e,i)&&(!n||l===n)&&(!r||ft(l,r)>=0)?[p]:[]}).sort((l,c)=>ft(c.version,l.version))[0];if(!o)throw new y("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!o.dist||typeof o.dist.tarball!="string"||typeof o.dist.integrity!="string")throw new y("registry_invalid","Release is missing its immutable tarball integrity");return o}function AR(t,e){let i=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!i)throw new y("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(i[1],"base64"),n=Vp("sha512").update(t).digest();if(r.length!==n.length||!vR(r,n))throw new y("integrity_mismatch","Downloaded package failed integrity verification")}var _r=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Up(e.hostVersion))throw new y("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Xe,this.fetcher=e.fetch??mv}async index(){let e=await we(ne(this.root,"installed.json"));if(!e){if(await fe(ne(this.root,"installed.json"),2*1024*1024))throw new y("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 y("invalid_storage","Invalid plugin installation index");for(let[i,r]of Object.entries(e.versions))if(this.catalog.some(n=>n.id===i)){if(!Array.isArray(r)||r.length>16||new Set(r.map(n=>n.version)).size!==r.length)throw new y("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(i,n)}return e}validateRecord(e,i){if(!i||!qe(i.version)||!/^[a-f0-9]{64}$/.test(i.digest)||i.directory!==`${re(e)}/${i.version}-${i.digest}`||typeof i.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(i.integrity)||typeof i.installedAt!="string")throw new y("invalid_storage","Invalid installed plugin record")}path(e){return ne(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),i=await ze(ne(this.root,"install-journal.json"));if(i){if(i.schema!==1||Object.keys(i).some(s=>!["schema","pluginId","next"].includes(s)))throw new y("invalid_storage","Invalid install journal");Ke(i.pluginId,this.catalog),this.validateRecord(i.pluginId,i.next);let n=e.versions[i.pluginId]?.find(s=>s.version===i.next.version);if(n&&n.digest!==i.next.digest)throw new y("invalid_storage","Conflicting installation journal");await si(ne(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=ne(this.root,"staging");await ve(r);for(let n of await wR(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await Sw(ne(r,n))).isSymbolicLink())throw new y("invalid_storage","Invalid abandoned staging directory");await si(ne(r,n),{recursive:!0})}return e}async recoverCollection(e){let i=ne(this.root,"gc-journal.json"),r=await ze(i);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new y("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");Ke(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let n=r.records.filter(s=>e.versions[r.pluginId]?.some(a=>a.directory===s.directory));if(n.length&&n.length!==r.records.length)throw new y("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!n.length){await ve(ne(this.root,"versions")),await ve(ne(this.root,"versions",re(r.pluginId)));for(let s of r.records)await si(this.path(s),{recursive:!0,force:!0})}await si(i)}async collect(e,i){return Ke(e,this.catalog),Se(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]??[],s=new Set(await i()),a=n.at(-1);a&&s.add(a.version);let o=n.filter(l=>!s.has(l.version));return await this.removeLocked(e,r,o),o.map(l=>l.version)})}async removeLocked(e,i,r){r.length&&(await ve(ne(this.root,"versions")),await ve(ne(this.root,"versions",re(e))),await Z(ne(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),i.versions[e]=(i.versions[e]??[]).filter(n=>!r.some(s=>s.directory===n.directory)),i.revision++,await Z(ne(this.root,"installed.json"),i),await this.recoverCollection(i))}async inventory(){return Se(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,i){let r;try{r=new URL(e)}catch{throw new y("registry_denied","Invalid registry URL")}let n=new URL(i.registry);if(r.protocol!=="https:"||r.origin!==n.origin||r.username||r.password||r.hash||r.search)throw new y("registry_denied","Only the official registry origin is permitted");return r}async download(e,i,r,n="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),a;try{a=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(d){throw r?.aborted?r.reason:new y("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!a.ok||!a.body)throw await a.body?.cancel().catch(()=>{}),new y(a.status===404?`${n}_not_found`:"download_failed",`Registry ${n} request failed (${a.status})`);if(a.url&&new URL(a.url).origin!==e.origin)throw new y("registry_denied","Registry redirect is forbidden");let o=a.body.getReader(),l=[],c=0,p=()=>{o.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(a.headers.get("content-length"))>i)throw new y("download_too_large","Registry response exceeds budget");for(;;){let d=await o.read();if(d.done)break;if(c+=d.value.length,c>i)throw new y("download_too_large","Registry response exceeds budget");l.push(Buffer.from(d.value))}return s.throwIfAborted(),Buffer.concat(l)}catch(d){throw r?.aborted?r.reason:d instanceof y?d:new y("registry_unreachable",d instanceof Error?d.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await o.cancel().catch(()=>{}),o.releaseLock()}}async check(e,i,r,n){let s=Ke(e,this.catalog);if(r&&!qe(r))throw new y("invalid_version","Choose an exact stable version");let a=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),o,l=await this.download(a,8*1024*1024,n,"metadata");try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l))}catch{throw new y("registry_invalid","Invalid registry metadata JSON")}return ww(o,s,this.hostVersion,i,r)}async install(e,i,r){let n=Ke(e,this.catalog);if(!Wp(i,n,this.hostVersion))throw new y("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(i.dist.tarball,n),Ta,r);return this.installArchive(e,s,i.dist.integrity,i.version,r)}async installArchive(e,i,r,n,s){let a=Ke(e,this.catalog);if(!qe(n))throw new y("invalid_version","Choose an exact stable version");if(i.length>Ta)throw new y("download_too_large","Package archive exceeds budget");return AR(i,r),Se(this.root,async()=>{let o=await this.recoverLocked();s?.throwIfAborted();let l=await $p(ne(this.root,"staging","stage-"));try{await Dp(i,l),s?.throwIfAborted();let c=await Li(l,e);if(c.version!==n||!ti(c.manifest)||!br(this.hostVersion,c.manifest.hostRange)||!a.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new y("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,o,l,c,r,s)}finally{await si(l,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,i,r,n,s,a){let o=i.versions[e]?.find(d=>d.version===n.version);if(o&&o.digest!==n.digest)throw new y("version_replaced","An installed immutable version cannot be replaced with different content");let l={version:n.version,digest:n.digest,integrity:s,directory:`${re(e)}/${n.version}-${n.digest}`,installedAt:new Date().toISOString()};if(await ve(ne(this.root,"versions",re(e))),!o&&(i.versions[e]?.length??0)>=16)throw new y("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await Z(ne(this.root,"install-journal.json"),{schema:1,pluginId:e,next:l});let c=this.path(l),p=!1;try{await Sw(c),p=!0}catch(d){if(!Zt(d))throw d}if(p){if((await Li(c,e)).digest!==n.digest)throw new y("resource_changed","Installed package content was modified")}else await ER(r,c);return a?.throwIfAborted(),o||(i.versions[e]=[...i.versions[e]??[],l],i.revision++,await Z(ne(this.root,"installed.json"),i)),await si(ne(this.root,"install-journal.json")),{...n,root:await kR(c)}}async installDevArchive(e,i,r){Ke(e,this.catalog);let n=await SR(i),s="sha512-"+Vp("sha512").update(n).digest("base64"),a=await $p(ne(IR(),"pi-dev-archive-"));try{await Dp(n,a);let o=(await Li(a,e)).version;return await this.installArchive(e,n,s,o,r)}finally{await si(a,{recursive:!0,force:!0})}}async installDevDirectory(e,i,r){let n=Ke(e,this.catalog);return Se(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let a=await $p(ne(this.root,"staging","stage-"));try{let{contentHash:o,packageJson:l}=await mw(i,a);r?.throwIfAborted();let c=ne(this.root,"dev-sources.json"),p=await we(c)??{},d=p[e],m=s.versions[e]??[],g=d?.contentHash===o?m.find(N=>N.version===d.version):void 0;if(g){let N=await Li(this.path(g),e);if(N.digest!==g.digest)throw new y("resource_changed","Installed package integrity changed");return N}let f=typeof l.version=="string"?qe(l.version):null;if(!f)throw new y("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let h=Math.max(-1,...m.map(N=>qe(N.version)).filter(N=>N&&N.major===f.major&&N.minor===f.minor).map(N=>N.patch)),_=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),h+1),S=`${f.major}.${f.minor}.${_}`;await TR(ne(a,"package.json"),JSON.stringify({...l,version:S},null,2),{flag:"wx",mode:384});let E=await Li(a,e);if(!br(this.hostVersion,E.manifest.hostRange))throw new y("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let A=n.requiredCapabilities.filter(N=>!E.manifest.capabilities.includes(N));if(A.length)throw new y("incompatible_plugin",`Package lacks required capabilities: ${A.join(", ")}`);let D="sha512-"+Vp("sha512").update(o).digest("base64"),C=await this.commitStaged(e,s,a,E,D,r);return p[e]={contentHash:o,version:S},await Z(c,p),C}finally{await si(a,{recursive:!0,force:!0})}},1e4)}async load(e,i){let r=Ke(e,this.catalog);return Se(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(o=>o.version===i);if(!s)throw new y("not_installed","Plugin version is not installed");let a=await Li(this.path(s),e);if(a.digest!==s.digest)throw new y("resource_changed","Installed package integrity changed");if(!br(this.hostVersion,a.manifest.hostRange)||!r.requiredCapabilities.every(o=>a.manifest.capabilities.includes(o)))throw new y("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return a})}async removeVersions(e,i){Ke(e,this.catalog),await Se(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(a=>i.includes(a.version));await this.removeLocked(e,r,s)})}};import{lstat as Aa,mkdir as xR,open as kw,realpath as Ew,readdir as zp,link as OR,rename as RR,unlink as qi,copyFile as NR,rm as PR}from"node:fs/promises";import{dirname as CR,isAbsolute as Tw,join as J,relative as Iw,resolve as MR,sep as Kp,win32 as DR}from"node:path";import{randomUUID as Yp}from"node:crypto";var Rn=192*1024*1024,d7=512*1024,xw=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function LR(t){if(!t||typeof t!="object"||Array.isArray(t))throw new y("invalid_input","Expected object input");return t}function Aw(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new y("invalid_input","Invalid state key");return t}function Nn(t){if(t&&(!xw(t.stateRef)||typeof t.version!="string"||!Number.isSafeInteger(t.generation)||t.generation<1||!Number.isSafeInteger(t.schema)||t.schema<1||typeof t.enabled!="boolean"||typeof t.operationId!="string"))throw new y("invalid_storage","Invalid active plugin record");return t}var ji=class{root;pluginId;legacy;checkpoint;files;constructor(e,i,r,n,s=jp){this.root=J(e,re(i)),this.pluginId=i,this.legacy=r,this.checkpoint=n,this.files=s}rule(e){let i=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!i)throw new y("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return i}active(){return we(J(this.root,"active.json")).then(Nn)}async recover(){return Se(this.root,async()=>{let e=await this.active(),i=await ze(J(this.root,"transition.json"));if(!i)return{active:e,recovered:"none"};if(!i.next||!Object.hasOwn(i,"before")||Object.keys(i).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(i,"version")&&i.version!==1)throw new y("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Nn(i.next),Nn(i.before);let r=e?.operationId===i.next.operationId?"committed":"not_committed";if(!((a,o)=>a===null||o===null?a===o:["version","generation","stateRef","schema","enabled","operationId"].every(l=>a[l]===o[l]))(e,r==="committed"?i.next:i.before))throw new y("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=i.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await Z(J(this.root,"previous.json"),s),r==="committed"){let a=await ze(J(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(o=>["version","stateRef"].includes(o))&&await qi(J(this.root,"fork.json"))}return await qi(J(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,i){return Se(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new y("stale_generation","Plugin activation changed concurrently");let n=await ze(J(this.root,"fork.json"));if(n&&(n.version!==1||n.stateRef!==i.stateRef||Object.keys(n).some(a=>!["version","stateRef"].includes(a))))throw new y("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=Nn({...i,generation:e+1,operationId:Yp()});await ve(J(this.root,"states")),await ve(J(this.root,"states",s.stateRef)),await Z(J(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await Z(J(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await Z(J(this.root,"previous.json"),r),await qi(J(this.root,"transition.json")),await qi(J(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return Se(this.root,async()=>{let i=await this.assertGeneration(e,!1),r=Yp(),n=J(this.root,"states",r);if(await ze(J(this.root,"fork.json")))throw new y("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await Z(J(this.root,"fork.json"),{version:1,stateRef:r}),await ve(n);let s=J(this.root,"states",i.stateRef);for(let a of await zp(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new y("invalid_storage","Unexpected state file");if(!await fe(J(s,a),Rn))throw new y("invalid_storage","Missing state file");await NR(J(s,a),J(n,a))}return await this.checkpoint?.("forked"),r})}async collect(e){return Se(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await fe(J(this.root,c),2*1024*1024))throw new y("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let i=await this.active(),r=Nn(await ze(J(this.root,"previous.json")));if(!i&&await fe(J(this.root,"active.json"),2*1024*1024))throw new y("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let n=[i,r].filter(c=>!!c),s=J(this.root,"states");await ve(s);let a=await zp(s),o=new Set(n.map(c=>c.stateRef));for(let c of a){if(!xw(c))throw new y("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=J(s,c),d=await Aa(p);if(!d.isDirectory()||d.isSymbolicLink())throw new y("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await zp(p)){let g=await Aa(J(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!g.isFile()||g.isSymbolicLink()||g.nlink!==1)throw new y("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!o.has(c)){let f=await we(J(p,m),Rn);if(!f)throw new y("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(f,"committed")){let h=f;if(Object.keys(h).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||h.committed!==!0||!/^[a-f0-9]{64}$/.test(h.inputHash)||!/^[a-f0-9]{64}$/.test(h.nextHash)||typeof h.requestId!="string")throw new y("gc_recovery_required",`GC refused: unresolved file intent in states/${c}; reconcile the workspace save before cleanup`)}else{if(Object.keys(f).some(h=>!["revision","schema","value","requestId","inputHash"].includes(h)))throw new y("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(f)}}}}for(let c of o)if(!a.includes(c))throw new y("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let l=await e(n);for(let c of a)o.has(c)||await PR(J(s,c),{recursive:!0,force:!0});return l})}async assertGeneration(e,i=!0){let r=await this.active();if(!r||r.generation!==e||i&&!r.enabled)throw new y("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new y("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,i,r,n="session"){if(n!=="session"&&n!=="workspace")throw new y("invalid_input","Invalid state scope");let s=n==="workspace"?(this.scopeKey(i),JSON.stringify([i.scope.workspaceId,i.scope.cwd])):this.scopeKey(i);return J(this.root,"states",e.stateRef,`${re(s+":state:"+r)}.json`)}async call(e,i,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new y("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=LR(r);return Se(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(i){case"state.read":{let a=await we(this.statePath(s,e,Aw(n.key),n.scope),Rn);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,Aw(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new y("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new y("invalid_input","State value must be JSON serializable");let o=JSON.stringify(n);if(Buffer.byteLength(o)>Rn)throw new y("state_too_large","Plugin state exceeds limit");let l=await we(a,Rn);l&&this.validateState(l);let c=re(o);if(l?.requestId===e.requestId&&l.inputHash===c)return{revision:l.revision,schema:l.schema,value:l.value};if((l?.revision??0)!==n.expectedRevision)throw new y("revision_conflict","Plugin state changed concurrently");let p={revision:n.expectedRevision+1,schema:s.schema,value:n.value,requestId:e.requestId,inputHash:c};return await Z(a,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let a=this.rule(n.path),{target:o}=await this.fileTarget(e.scope.cwd,n.path),l=n.maxBytes===void 0?a.maxBytes:n.maxBytes;if(!Number.isSafeInteger(l)||l<=0||l>a.maxBytes)throw new y("invalid_input","Invalid workspace read limit");if(n.encoding!==void 0&&n.encoding!==(a.binary?"base64":"utf-8"))throw new y("invalid_input","Encoding does not match the reviewed file rule");let c=await fe(o,l);return c?a.binary?{base64:c.toString("base64"),bytes:c.length,hash:re(c)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:re(c)}:null}case"workspace.commit":return this.commitFile(s,e,n);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new y("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 y("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,i,r=!1){let n=this.rule(i);if(typeof i!="string"||i.length>4096||i.includes("\\")||i.includes("\0")||Tw(i)||DR.isAbsolute(i))throw new y("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await Ew(e),a=MR(s,i),o=Iw(s,a);if(!o||o===".."||o.startsWith(`..${Kp}`)||Tw(o))throw new y("invalid_path","Workspace path escapes root");let l=s,c=o.split(Kp);for(let d=0;d<c.length;d++){l=J(l,c[d]);let m;try{m=await Aa(l)}catch(g){if(!Zt(g))throw g;if(d<c.length-1){if(!r||!n.createDirectory||Iw(s,l)!==n.createDirectory)throw new y("invalid_path","Workspace directory does not exist");try{await xR(l,{mode:448})}catch(f){if(f.code!=="EEXIST")throw f}m=await Aa(l)}}if(m&&(m.isSymbolicLink()||(d<c.length-1?!m.isDirectory():!m.isFile()||m.nlink!==1)))throw new y("invalid_path","Workspace path contains a link or non-regular file")}let p=await Ew(CR(a));if(p!==s&&!p.startsWith(s+Kp))throw new y("invalid_path","Workspace directory changed");return{target:a,parent:p}}async commitFile(e,i,r){let n=this.rule(r.path),s=n.binary?typeof r.base64=="string"&&r.text===void 0&&/^[A-Za-z0-9+/]*={0,2}$/.test(r.base64)?Buffer.from(r.base64,"base64"):null:typeof r.text=="string"&&r.base64===void 0?Buffer.from(r.text):null;if(!s||s.length>n.maxBytes||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new y("invalid_input","Invalid file content or expected hash");let{target:a,parent:o}=await this.fileTarget(i.scope.cwd,r.path,!0),l=J(this.root,"states",e.stateRef,`${re(this.scopeKey(i)+":file:"+i.requestId+":"+String(r.path))}.json`),c=re(JSON.stringify(r)),p=re(s),d=await we(l);if(d&&(d.requestId!==i.requestId||d.inputHash!==c||d.nextHash!==p))throw new y("duplicate_request","Request ID was reused with different content");let m;try{m=await kw(`${a}.lock`,"wx",384)}catch(f){throw f.code==="EEXIST"?new y("file_busy","Workspace file is locked; original file preserved"):f}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:i.requestId}));let f=await fe(a,n.maxBytes),h=f?re(f):null;if(d&&h===p)return{hash:p};if(d?.committed||h!==r.expectedHash)throw new y("file_conflict","Workspace file already exists or changed externally");await Z(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!1}),g=J(o,`.plugin-${Yp()}.tmp`);let _=await kw(g,"wx",384);try{await _.writeFile(s),await _.sync()}finally{await _.close()}if((await this.fileTarget(i.scope.cwd,r.path)).parent!==o)throw new y("file_conflict","Workspace directory changed during save");let E=await fe(a,n.maxBytes);if((E?re(E):null)!==r.expectedHash)throw new y("file_conflict","Workspace file changed during save");if(await this.assertGeneration(i.generation),r.expectedHash===null){try{await OR(g,a)}catch(A){throw A.code==="EEXIST"?new y("file_conflict","Workspace file was created concurrently"):A}await qi(g),g=void 0}else await RR(g,a),g=void 0;return await Z(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{g&&await qi(g).catch(()=>{}),await m.close(),await qi(`${a}.lock`)}}};import{randomUUID as FR}from"node:crypto";import{fork as UR}from"node:child_process";import{randomUUID as qR}from"node:crypto";import{join as jR}from"node:path";import{EventEmitter as BR}from"node:events";var Ow=192*1024*1024,Pn=class t{child;pending=new Map;events=new BR;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,i,r,n){this.package=e,this.generation=i,this.broker=n;let s={};for(let a of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[a]&&(s[a]=process.env[a]);this.child=UR(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",a=>{this.receive(a)}),this.child.once("error",a=>this.fail(a)),this.child.once("exit",()=>this.fail(new y("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,i,r,n,s=1e4){let a=new t(e,i,r,n);try{await a.request("initialize",{entry:jR(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:i},s);let o=await a.request("describe",void 0,s);if(!o||!Array.isArray(o.tools)||o.tools.length>128)throw new y("invalid_tools","Invalid hosted tool catalog");let l=new Set;for(let c of o.tools){if(!c||typeof c.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(c.name)||l.has(c.name)||typeof c.label!="string"||typeof c.description!="string"||typeof c.action!="string"||!/^[\w.-]{1,80}$/.test(c.action)||!c.parameters||typeof c.parameters!="object"||Array.isArray(c.parameters)||c.parameters.type!=="object")throw new y("invalid_tools","Invalid or duplicate tool descriptor");l.add(c.name)}return a.tools=structuredClone(o.tools),await a.request("health",void 0,s),a}catch(o){throw await a.dispose(),o}}fail(e){this.stopped=!0;for(let i of this.pending.values())clearTimeout(i.timer),i.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let i;try{i=Buffer.byteLength(JSON.stringify(e))}catch{return}if(i>Ow){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let n=this.pending.get(r.id);if(!n)return;if(clearTimeout(n.timer),this.pending.delete(r.id),!n.expired){let s=r.error;r.ok===!0?n.resolve(r.value):n.reject(new y(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let n=this.pending.get(r.invocationId);try{if(!n?.invocation||n.expired)throw new y("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(n.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:me(s)})}}}request(e,i,r=3e4,n){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new y("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new y("worker_busy","Too many plugin requests"));let s=n?.requestId??qR();if(this.pending.has(s))return Promise.reject(new y("duplicate_request","An identical request is still running"));let a={type:"request",id:s,method:e,input:i};return Buffer.byteLength(JSON.stringify(a))>Ow?Promise.reject(new y("message_too_large","Plugin request exceeds limit")):new Promise((o,l)=>{let c=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),l(new y("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:o,reject:l,timer:c,invocation:n,expired:!1}),this.child.send(a,p=>{p&&(clearTimeout(c),this.pending.delete(s),l(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,i=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,i,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(i=>{let r=()=>{clearTimeout(n),this.events.off("idle",r),i(!0)},n=setTimeout(()=>{this.events.off("idle",r),i(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new y("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 i=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",i),this.child.kill("SIGTERM")})}}}};var HR={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},xa=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,i,r=HR,n){this.broker=e,this.workerEntry=i,this.hooks=r,this.capabilities=n}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 i=this.operations.then(e,e);return this.operations=i.catch(()=>{}),i}async ownRuntime(){if(this.releaseOwnership)return;let e=await hp(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,i,r)=>this.capabilities?.handles(i)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,i,r):this.broker.call(e,i,r);invoke(e,i){return this.phaseValue!=="active"||!this.worker?Promise.reject(new y("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},i)}flushAction(e,i){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new y("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},i)}replace(e,i=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new y("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new y("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(c){throw this.worker||await this.releaseOwnership?.(),c}let n=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let a=null,o=!1,l=!1;try{if(a=await Pn.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(i))throw new y("drain_pending","Plugin calls are still running; switch deferred without killing them");if(l=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(i))throw new y("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new y("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(a.tools)),this.phaseValue="switching";let c=r?await this.broker.forkState(n):FR(),p=await this.broker.activate(n,{version:e.version,stateRef:c,schema:e.manifest.dataSchemaVersion,enabled:!0});o=!0,this.worker=a,a=null,this.phaseValue="active",this.pendingPackage=null;let d=!1;try{await this.hooks.committed(p)}catch{d=!0}return await s?.dispose(),{pending:!1,active:p,...d?{reconnectRequired:!0}:{}}}catch(c){throw o||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",l&&await this.hooks.resume().catch(()=>{})),c}finally{await a?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,i=!1){return this.serialize(async()=>{let r=this.worker,n=this.phaseValue,s=await this.broker.active(),a=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))throw await this.releaseOwnership?.(),this.phaseValue="failed",new y("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Pn.start(r.package,r.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(l){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),l}}};this.phaseValue="draining";try{let l=async c=>{try{await c()}catch(p){if(!i)throw p}};await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Plugin work is still draining; current host retained")}),await l(()=>this.hooks.freeze()),await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(l){try{await a(),this.phaseValue=n,await this.hooks.resume()}catch(c){throw this.phaseValue="failed",c}throw l}let o=!1;return()=>this.serialize(async()=>{o||(await a(),this.phaseValue=n,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let i=this.worker,r;try{r=(await this.broker.recover()).active}catch(a){throw i||await this.releaseOwnership?.(),a}if(!r){if(i)throw this.phaseValue="failed",new y("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!i&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let n=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Checkpoint synchronization is still running");let a=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await i?.dispose(),await this.hooks.committed(a)}catch(a){throw this.worker===i&&(this.phaseValue=n,s&&await this.hooks.resume().catch(()=>{})),a}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let i=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Host checkpoint synchronization is still running");await i?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(n){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),n}})}};import{readFile as Rw}from"node:fs/promises";var Oa=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;constructor(e){this.options=e,this.installer=new _r({root:Ze(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let i=e.capabilities?new ka(e.capabilities):void 0;this.scheduler=new Ea({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:WR(),scope:s,kind:"action",action:n.action,input:{schedule:n.id}})},onError:(r,n,s)=>e.onScheduleError?.(r,n.id,s),...e.scheduleTimers});for(let r of this.installer.catalog){let n=new ji(Ze(e.root,"data"),r.id,e.legacy?.(r.id),void 0,e.workspaceRules?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new xa(n,e.workerEntry,{validateCandidate:a=>s.validateCandidate?.(a),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async a=>{if(a.enabled){let o=await this.installer.load(r.id,a.version);this.packages.set(r.id,o),this.assetTokens.set(r.id,GR(24).toString("base64url"));try{this.scheduler.start(r.id,hr(o.manifest).schedules)}catch(l){this.scheduler.stop(r.id),this.errors.set(r.id,me(l))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(a)}},i))}}devSource(e){let i=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return!i&&!r?null:async n=>(await this.collectSettled(e).catch(()=>{}),i?this.installer.installDevDirectory(e,i,n):this.installer.installDevArchive(e,r,n))}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){Ke(e,this.installer.catalog);let i=this.supervisors.get(e);if(!i)throw new y("unknown_plugin","Plugin runtime is not registered");return i}serialize(e,i){if(this.supervisor(e),this.closing)return Promise.reject(new y("manager_closed","Plugin manager is shutting down"));let 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,me(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,i,r=!1){return this.options.lifecycle?this.options.lifecycle(e,i,r):i()}async policies(){let e=await we(Ze(this.options.root,"policies","policies.json"));if(!e){if(await fe(Ze(this.options.root,"policies","policies.json"),2*1024*1024))throw new y("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[i,r]of Object.entries(e))if(this.installer.catalog.some(n=>n.id===i)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new y("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(i=>[i,{updatePolicy:"notify"}]))}async diagnostics(){return await we(Ze(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,i){await Se(Ze(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...i,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await Z(Ze(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,i){return this.recordCheck(e,{status:"up-to-date",version:i,message:"Developer source installed"})}async check(e,i,r,n){try{let s=await this.installer.check(e,i,r,n),a=!i||ft(s.version,i)>0;return a?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:a?"available":"up-to-date",version:s.version,message:a?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:me(s).code,message:me(s).message}),s}}async setPolicy(e,i){if(this.supervisor(e),!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion))throw new y("invalid_input","Invalid plugin update policy");await Se(Ze(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await Z(Ze(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return Se(ma(this.options.root),async()=>{let e=await _p(this.options.root);if(!e)return{intent:e,admitted:!1};if(!vp(e))return e.phase==="required-action"&&await fa(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await bp(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await bp(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Rw(this.options.workerEntry)).equals(await Rw(Ze(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(i){return await fa(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${me(i).message}; data retained`}),{intent:e,admitted:!1}}return await fa(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await Se(Ze(this.options.root,"policies"),async()=>{let i=await this.policies();await Z(Ze(this.options.root,"policies","policies.json"),i)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let i of this.installer.catalog){let r=this.supervisor(i.id),n=await r.broker.active();if(n?.enabled)try{let s=await this.compatiblePackage(i.id,n.version);await this.lifecycle(i.id,()=>r.replace(s)),this.packages.set(i.id,s),e||await this.collectSettled(i.id)}catch(s){let a=me(s),o=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(i.id,{...a,message:`Plugin unavailable: startup failed (${a.code}): ${a.message}; data retained. ${o}`})}}}async compatiblePackage(e,i){try{return await this.installer.load(e,i)}catch(r){if(me(r).code!=="incompatible_plugin")throw r;let n=((await this.installer.inventory()).versions[e]??[]).map(s=>s.version).filter(s=>s!==i).sort((s,a)=>ft(a,s));for(let s of n)try{return await this.installer.load(e,s)}catch{}throw r}}async inventory(){let e=await this.installer.inventory(),i=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let a=this.supervisor(s.id),o=await a.broker.active(),l=this.packages.get(s.id),c=(e.versions[s.id]??[]).map(p=>p.version).sort((p,d)=>ft(d,p));return{id:s.id,name:s.name,description:s.description,official:s.official!==!1,installed:!!c.length,installedVersions:c,version:c[0]??null,activeVersion:o?.version??null,enabled:o?.enabled??!1,phase:a.phase,generation:a.generation,pendingVersion:a.pendingVersion,updatePolicy:i[s.id]?.updatePolicy??"notify",pinnedVersion:i[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...l&&a.phase==="active"?{digest:l.digest,document:l.manifest.frontend.document.slice(2),controller:l.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${l.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,i])=>i.phase==="active"&&i.generation!==null?[{pluginId:e,generation:i.generation,descriptors:i.tools}]:[])}async manage(e,i,r,n){return this.serialize(e,async()=>{let s=this.supervisor(e),a=(await this.installer.inventory()).versions[e]??[],o=a.map(c=>c.version).sort((c,p)=>ft(p,c))[0],l=await(async()=>{switch(i){case"check":return this.isDevPlugin(e)?{version:o??null,dev:!0}:{version:(await this.check(e,o,void 0,n)).version};case"install":{let c=this.devSource(e);if(c){let m=await c(n);return await this.recordDevSync(e,m.version),{installed:!0,version:m.version}}let p=await this.check(e,o,r,n),d=await this.installer.install(e,p,n);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:d.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:d.version}}case"enable":{let c=r??o;if(!c)throw new y("not_installed","Install the plugin first");let p=await this.installer.load(e,c),d=await this.lifecycle(e,()=>s.replace(p));return d.pending||this.packages.set(e,p),d}case"retry":{let c=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return c&&!p.pending&&this.packages.set(e,await this.installer.load(e,c)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!o)throw new y("not_installed","Only installed plugins can be updated");let c=this.devSource(e);if(c){let f=await c(n),h=await s.broker.active();if(await this.recordDevSync(e,f.version),!h?.enabled)return{installed:!0,enabled:!1,version:f.version};if(h.version===f.version&&!s.pendingVersion)return{unchanged:!0,version:f.version};let _=await this.lifecycle(e,()=>s.replace(f));return _.pending||this.packages.set(e,f),_}let p=await this.check(e,o,r,n),d=await s.broker.active();if(p.version===o&&(!d?.enabled||d.version===o)&&!s.pendingVersion)return{unchanged:!0,version:o};let m=p.version===o?await this.installer.load(e,o):await this.installer.install(e,p,n);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:m.version,message:"Selected compatible release installed; activation may wait for editors"}),!d?.enabled)return{installed:!0,enabled:!1,version:m.version};let g=await this.lifecycle(e,()=>s.replace(m));return g.pending||this.packages.set(e,m),g}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,a.map(c=>c.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new y("invalid_operation","Unknown plugin management operation")}})().catch(async c=>{if(["install","update"].includes(i)){this.available.delete(e);let p=me(c);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw c});return["install","enable","retry","update"].includes(i)&&await this.collectSettled(e),l})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let i=this.supervisor(e);return i.broker.collect(async r=>this.installer.collect(e,async()=>{let n=(await this.policies())[e];return[...r.map(s=>s.version),...i.pendingVersion?[i.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...n?.pinnedVersion?[n.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Reconnect the plugin view before editing",{status:409})):n.invoke(r,this.options.invokeTimeoutMs?.(e))}flush(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Flush generation changed",{status:409})):n.flushAction(r)}async asset(e,i,r){let n=this.packages.get(e);if(!n)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(n.version,(s.get(n.version)??0)+1);try{return await dw(n,r,i)}finally{let a=s.get(n.version)-1;a?s.set(n.version,a):s.delete(n.version)}}async assetRequest(e){let i=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!i)return null;let r;try{r=decodeURIComponent(i[1])}catch{return null}let n=this.assetTokens.get(r),s=Buffer.from(i[2]);if(!n||s.length!==Buffer.byteLength(n)||!$R(s,Buffer.from(n)))return null;let a=await this.asset(r,i[3],i[4]);return a?{...a,pluginId:r}:null}servedManifest(e){return this.packages.get(e)?.manifest??null}async reconcileHostUpgrade(){if(Iv(await _p(this.options.root)))return!1;let e=await this.installer.inventory(),i=await this.policies(),r=!0;for(let n of this.installer.catalog){let s=e.versions[n.id];if(s?.length)try{let a=await this.supervisor(n.id).broker.active(),o=a?.enabled?a.version:s.map(c=>c.version).sort((c,p)=>ft(p,c))[0];try{await this.installer.load(n.id,o);continue}catch(c){if(me(c).code!=="incompatible_plugin")throw c}let l=await this.manage(n.id,"update");l&&typeof l=="object"&&"pending"in l&&l.pending&&(r=!1)}catch(a){r=!1;let o=me(a);this.errors.set(n.id,o),await this.recordCheck(n.id,{status:"failed",code:o.code,message:o.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,i){let r=new _r({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),n=await this.installer.inventory();for(let s of this.installer.catalog){let a=(n.versions[s.id]??[]).map(c=>c.version).sort((c,p)=>ft(p,c)),o=await this.supervisor(s.id).broker.active();if(!a.length||this.isDevPlugin(s.id))continue;let l=!1;for(let c of new Set([...o?.enabled?[o.version]:[],...a]))try{await r.load(s.id,c),l=!0;break}catch{}if(!l)try{let c=await r.check(s.id,a[0],void 0,i),p=await r.install(s.id,c,i);await this.recordCheck(s.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(c){i?.throwIfAborted();let p=me(c);await this.recordCheck(s.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let i=new _r({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),n=[];for(let s of this.installer.catalog){let a=r.versions[s.id],o=await this.supervisor(s.id).broker.active();if(!o?.enabled)continue;if(!a?.length){n.push({pluginId:s.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let l=[o.version,...a.map(d=>d.version).sort((d,m)=>ft(m,d))],c=!1,p="";for(let d of new Set(l))try{await i.load(s.id,d),c=!0;break}catch(m){p||=me(m).message}c||n.push({pluginId:s.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[];try{for(let[i,r]of this.supervisors)e.push(await this.lifecycle(i,()=>r.suspendForRestart(),!0));this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(i){throw await Promise.allSettled(e.reverse().map(r=>r())),this.closing=!1,i}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let i=[],r=async()=>{let n=await Promise.allSettled(i.map(a=>a()));this.closing=!1;let s=n.find(a=>a.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let n of this.supervisors.values())i.push(await n.suspendForRestart(void 0,e));return r}catch(n){throw await r(),n}}};import{randomUUID as VR}from"node:crypto";var K=t=>Object.assign(new Error(t),{status:409,code:"view_barrier"}),Cn=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,i,r=2e4,n=15e3,s=12e4){this.pluginId=e,this.generation=i,this.pollMs=r,this.freezeMs=n,this.staleMs=s}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));blockedOnlyByWork=()=>[...this.views.values()].every(e=>e.kind==="controller"||e.frozen||this.immediate||!["editor","workspace"].includes(e.kind));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(i=>i.scope.ownerId===e).map(i=>({...i.identity,viewToken:i.token,kind:i.kind,dirty:i.dirty,busy:i.busy}))}sameScope(e,i,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===i.sessionId&&e.identity.mountId===i.mountId&&e.identity.generation===i.generation}recovery(e,i){return{state:i,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,i){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&i.sessionId===e.sessionId&&r.scope.ownerId===i.ownerId&&r.scope.workspaceId===i.workspaceId)}admitAction(e,i){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||i.ownerId!==r.scope.ownerId||i.workspaceId!==r.scope.workspaceId||i.sessionId!==r.identity.sessionId)throw K("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw K("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,i,r=++this.sequence){return e.commands.push({id:r,type:i,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,i){if(!e||e.pluginId!==this.pluginId||e.sessionId!==i.sessionId||!i.ownerId||!i.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw K("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw K("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw K("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 K("Invalid registration capability");let a=e.viewToken??VR();if(this.cancelledRegistrations.has(a)||this.recoveries.has(a))throw K("View initialization was cancelled; register a new document identity");let o=this.views.get(a);if(o){if(!this.sameScope(o,e,i)||o.kind!==e.kind)throw K("Duplicate view capability");return{viewToken:a,commands:[]}}if([...this.views.values()].some(l=>l.scope.ownerId===i.ownerId&&l.identity.mountId===e.mountId))throw K("Duplicate mount");return this.views.set(a,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...i},token:a,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:a,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw K("Invalid view capability");let r=this.views.get(e.viewToken),n=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,i))throw K("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw K("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let a=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:a}}}if(r&&this.sameScope(r,e,i)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw K("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw K("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&n&&this.sameScope(n,e,i)){if(e.confirmation!=="discard-unconfirmed-edits")throw K("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!n){if(e.confirmation!=="discard-unconfirmed-edits")throw K("Explicit per-view discard confirmation required");if(this.switching)throw K("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,i))throw K("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw K("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw K("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw K("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(K("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw K("Invalid acknowledgement");let a=r.commands.find(o=>o.id===e.commandId);if(!a)throw K("Unknown command acknowledgement");r.commands=r.commands.filter(o=>o.id>e.commandId),a.type==="freeze"&&this.barrier?.id===a.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(K(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw K("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw K("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw K("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw K("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw K("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw K("Invalid poll cursor");if(r.waiter)throw K("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw K("Invalid poll mode");return!e.immediate&&!r.commands.some(a=>a.id>e.after)&&await new Promise(a=>{let o=setTimeout(l,Math.min(25e3,Math.max(50,this.pollMs)));function l(){clearTimeout(o),r.waiter=void 0,a()}r.waiter=l}),{viewToken:r.token,commands:r.commands.filter(a=>a.id>e.after)}}default:throw K("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw K("A view barrier is already active");if(!this.canSwitch()){let i=[...this.views.values()].filter(n=>n.activeActions||n.kind!=="controller"&&!n.frozen&&(n.busy||!this.immediate&&["editor","workspace"].includes(n.kind))),r=K(`Close editors before updating; old version retained. Pending views: ${i.map(n=>`${n.kind}:${n.identity.mountId}${n.activeActions?` (action in flight x${n.activeActions})`:n.busy?" (busy)":""}`).join(", ")}`);throw this.blockedOnlyByWork()?Object.assign(r,{reason:"view_busy"}):r}this.switching=!0;let e=++this.sequence;try{await new Promise((i,r)=>{let n=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):i())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>n(),reject:s=>n(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(a=>this.barrier?.pending.has(a.token));n(K(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(a=>`${a.kind}:${a.identity.mountId} (session ${a.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||n()})}catch(i){throw await this.resume(),i}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(i=>!i.frozen))throw K("Cannot commit before all views freeze");this.generation=e.generation;for(let i of this.views.values())this.enqueue(i,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(K("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(K("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var Nw={"image/png":t=>t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),"image/jpeg":t=>t[0]===255&&t[1]===216,"image/webp":t=>t.subarray(0,4).toString("latin1")==="RIFF"&&t.subarray(8,12).toString("latin1")==="WEBP"};function Pw(t){let e=t;if(!e||typeof e!="object"||e.$hosted!=="tool-result"||!Array.isArray(e.content))return{content:[{type:"text",text:JSON.stringify(t)??"null"}],details:t};let i=[],r=0;for(let n of e.content.slice(0,16)){let s=n;if(s?.type==="text"&&typeof s.text=="string")i.push({type:"text",text:s.text.slice(0,262144)});else if(s?.type==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&Nw[s.mimeType]&&r<4){let a=/^[A-Za-z0-9+/]*={0,2}$/.test(s.data)?Buffer.from(s.data,"base64"):null;a&&a.length<=2097152&&Nw[s.mimeType](a)?(i.push({type:"image",data:s.data,mimeType:s.mimeType}),r++):i.push({type:"text",text:"[image omitted by host: invalid or too large]"})}}return i.some(n=>n.type==="text")||i.unshift({type:"text",text:"(no text)"}),{content:i,details:e.details??null}}import{randomUUID as zR}from"node:crypto";var KR="Ov23limJmKiuu8cOP83E";function Qp(t,e,i=process.env){let r=t?.secrets&&Object.hasOwn(t.secrets,e)?t.secrets[e]:void 0;if(r?.provider==="github")return{clientId:i.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||r.clientId||KR,scope:r.scope,createUrl:r.createUrl}}var YR="https://github.com/login/device/code",QR="https://github.com/login/oauth/access_token",JR=8,Ra=class{flows=new Map;fetcher;now;constructor(e=(r,n)=>fetch(r,{...n,signal:n.signal??AbortSignal.timeout(15e3)}),i=Date.now){this.fetcher=e,this.now=i}async post(e,i){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(i).toString()})}catch{throw new y("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let n=await r.json().catch(()=>null);if(!n||typeof n!="object"||!r.ok&&!("error"in n))throw new y("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,i,r){if(!r.clientId)throw new y("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[d,m]of this.flows)m.expiresAt<=this.now()&&this.flows.delete(d);if(this.flows.size>=JR)throw new y("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(YR,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:a,verification_uri:o}=n,l=Number(n.expires_in),c=Math.max(Number(n.interval)||5,1);if(typeof s!="string"||typeof a!="string"||typeof o!="string"||!o.startsWith("https://github.com/")||!Number.isFinite(l))throw new y("oauth_failed",typeof n.error_description=="string"?n.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=zR();return this.flows.set(p,{pluginId:e,name:i,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+l*1e3,interval:c,nextPoll:this.now()+c*1e3}),{deviceId:p,userCode:a,verificationUri:o,interval:c,expiresIn:l}}async poll(e){let i=this.flows.get(e);if(!i||i.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<i.nextPoll)return{status:"pending"};i.nextPoll=this.now()+i.interval*1e3;let r=await this.post(QR,{client_id:i.clientId,device_code:i.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:i.pluginId,name:i.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return i.interval+=5,i.nextPoll=this.now()+i.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 Jp,readFileSync as Cw,readdirSync as XR,statSync as ZR}from"node:fs";import{lstat as eN,readdir as tN,writeFile as iN,mkdir as rN,rename as nN}from"node:fs/promises";import{delimiter as sN,dirname as aN,isAbsolute as oN,join as oi,resolve as Mn}from"node:path";var Na=t=>Xe.some(e=>e.id===t),Mw=()=>Xe.map(t=>t.id).join(", "),ai="piWebappCatalog",lN="https://registry.npmjs.org";function cN(t,e){let i=t[ai];if(i===void 0)throw new y("invalid_catalog",`${e}: ${t.name} is not an official plugin (official: ${Mw()}). Describe it in package.json "${ai}" with name, description and policy`);if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_catalog",`${e}: ${ai} must be an object`);if("id"in i||"registry"in i)throw new y("invalid_catalog",`${e}: ${ai} must not set id or registry; the package name is the id`);return{...Hp({registry:lN,recommendedVersion:"0.0.0",requiredCapabilities:[...t.piWebapp.capabilities],...i,id:t.name},e,ai),official:!1}}function pN(t=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(t??"").split(/[;\n]/).map(s=>s.trim()).filter(Boolean)){let s=n.lastIndexOf("="),a=n.slice(0,s),o=n.slice(s+1),l=s<1?`entry "${n}" is not <id>=<path.tgz>`:Na(a)?o.endsWith(".tgz")?Jp(Mn(o))?null:`archive not found: ${Mn(o)}`:`"${o}" is not a .tgz archive`:`"${a}" is not an official plugin (official: ${Mw()}); develop other packages from a directory in PI_WEBAPP_HOSTED_DEV_ROOTS`;if(l){i.push({level:"error",source:r,...Na(a)?{pluginId:a}:{},message:l});continue}e.set(a,Mn(o))}return{archives:e,notices:i}}var Dw=t=>oi(t,"pi-web","hosted-dev.json"),Lw=t=>oi(t,"pi-web","hosted-dev-status.json");function dN(t,e,i=process.cwd()){let r=[],n=[],s=(t.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(sN).map(o=>o.trim()).filter(Boolean);for(let o of s)r.push({path:Mn(i,o),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let a=s.length>0;if(e&&Jp(e)){a=!0;try{let o=JSON.parse(Cw(e,"utf8")),l=o&&typeof o=="object"?o.roots:void 0;if(!Array.isArray(l))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let c of l)typeof c!="string"||!oN(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:Mn(c),source:e})}catch(o){n.push({level:"error",source:e,message:`cannot read dev configuration: ${o instanceof Error?o.message:String(o)}`})}}return{specs:r,notices:n,configured:a}}function uN(t){let e=[];try{e=XR(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name!=="node_modules"&&Jp(oi(t,i.name,"package.json"))).map(i=>i.name)}catch{}return e.length?`package.json not found; this looks like a parent folder (packages inside: ${e.slice(0,3).join(", ")}). Point at the package directory itself`:"package.json not found; the folder is not a package (is the right branch checked out?)"}function mN(t){let e=(n,s)=>({notice:{level:"error",source:t.source,...s?{pluginId:s}:{},message:`${t.path}: ${n}`}}),i;try{i=ZR(t.path)}catch{return e("directory does not exist")}if(!i.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(Cw(oi(t.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?uN(t.path):"package.json is not valid JSON")}if(typeof r.name!="string")return e("package.json has no name");if(!ti(r.piWebapp))return e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name);if(Na(r.name))return{pluginId:r.name};try{return{pluginId:r.name,entry:cN({name:r.name,piWebapp:r.piWebapp,[ai]:r[ai]},"package.json")}}catch(n){return e(me(n).message,r.name)}}var Pa=class{catalog=[];policies=new Map;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 i=pN(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.archives=i.archives,this.archiveNotices=i.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let i=dN(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let a of i.specs){let o=mN(a);if(o.notice){r.push(o.notice);continue}let l=o.pluginId;if(n.has(l)){r.push({level:"error",pluginId:l,source:a.source,message:`${a.path}: plugin ${l} is already provided by ${n.get(l)}`});continue}if(this.archives.has(l)&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${l}; the dev directory wins`}),!Na(l)&&!this.catalog.some(c=>c.id===l)){if(!e){r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: ${l} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}let{policy:c,...p}=o.entry;this.catalog.push(p),this.policies.set(l,c)}else o.entry&&JSON.stringify(o.entry.policy)!==JSON.stringify(this.policies.get(l))&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: the ${ai} policy changed; restart pi-webapp once (npm run stop && npm run start) to apply it. Code still reloads live.`});n.set(l,a.path),s.set(l,a.source)}for(let a of[...this.roots.keys()])n.has(a)||this.roots.delete(a);for(let[a,o]of n)this.roots.set(a,o);this.rootSource.clear();for(let[a,o]of s)this.rootSource.set(a,o);return this.fileNotices=i.notices,this.rootNotices=r,{configured:i.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Ca=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 i of this.options.sources.notices())this.log(`${i.level}: ${i.message}`);let e=()=>{this.current=this.tick().catch(i=>{this.running&&this.log(`poll failed: ${me(i).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 i=this.roots.get(e);i&&(i.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,i])=>({pluginId:e,root:i.root,state:i.state,...i.version?{version:i.version}:{},...i.message?{message:i.message}:{}}))}}log(e){(this.options.log??(i=>console.error(`pi-webapp [hosted-dev] ${i}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let i of[...this.roots.keys()])e.has(i)||this.roots.delete(i);for(let[i,r]of e){let n=this.roots.get(i);(!n||n.root!==r)&&(n={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(i,n));let s=await gN(r);if(s===null){this.set(i,n,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),n.seen=void 0;continue}if(s!==n.seen){n.seen=s;continue}if(!this.stopped){if(s===n.applied){n.retry&&this.options.switcher.retry&&await this.apply(i,n,s,!0);continue}await this.apply(i,n,s)}}await this.publish()}set(e,i,r,n={}){let s=i.state!==r||i.message!==n.message||i.version!==n.version;i.state=r,i.message=n.message,i.code=n.code,i.version=n.version??i.version,s&&(i.at=new Date().toISOString(),this.log(`${e}: ${r}${n.version?` ${n.version}`:""}${n.message?` \u2014 ${n.message}`:""}`))}async apply(e,i,r,n=!1){n||this.set(e,i,"switching");try{let a=(await(n?this.options.switcher.retry(e):this.options.switcher.update(e))).plugins.find(o=>o.pluginId===e);i.applied=r,i.retry=!!a?.installed&&!!a.pendingVersion,a?.installed?a.pendingVersion?this.set(e,i,"pending",{version:a.version,message:`Waiting for editors to close before switching to ${a.pendingVersion}`}):this.set(e,i,"synced",{version:a.version}):this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(s){let a=me(s),o=a.reason==="view_busy",l=o||["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(a.code);n?(i.applied=r,i.retry=l):l||(i.applied=r);let c=a.code==="not_installed";o?this.set(e,i,"pending",{message:"An open editor is saving; switching once it finishes"}):c?this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,i,"error",{code:a.code,message:`${a.message} (${a.code}). Fix and save again.`})}i.at=new Date().toISOString()}async publish(){let e=this.info(),i=JSON.stringify(e);i!==this.lastNotices&&(this.lastNotices=i,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let n=Object.fromEntries([...this.roots].map(([o,l])=>[o,{root:l.root,state:l.state,version:l.version,message:l.message,code:l.code,at:l.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(o=>o.id),plugins:n,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let a=`${r}.${process.pid}.tmp`;try{await rN(aN(r),{recursive:!0}),await iN(a,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await nN(a,r)}catch{}}};async function gN(t){let e=[],i=async(r,n)=>{let s=await eN(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await i(oi(t,"package.json"),"package.json");let r=async(n,s,a)=>{if(!(a>16||e.length>8192))for(let o of(await tN(n,{withFileTypes:!0})).sort((l,c)=>l.name.localeCompare(c.name)))o.isDirectory()?await r(oi(n,o.name),`${s}/${o.name}`,a+1):await i(oi(n,o.name),`${s}/${o.name}`)};if(await r(oi(t,"dist"),"dist",0),!e.some(n=>n.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function hN(t){try{return[...hr(t).secrets]}catch{return[]}}var Ma=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ra;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Ia,e.dev?.enabled&&(this.devWatcher=new Ca({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async i=>{let r=await this.inventory();return r.plugins.find(n=>n.pluginId===i)?.installed?this.manage({pluginId:i,operation:"update",reopenEditors:!0}):r},retry:i=>this.manage({pluginId:i,operation:"retry",reopenEditors:!0})}})),this.adapter=new va({policy:(i,r)=>{let n=e.policy?.(i,r);return{...n,enabled:!this.recovery.has(i)&&this.manager.tools.some(s=>s.pluginId===i)&&n?.enabled!==!1}},invoke:async(i,r,n)=>{n?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(o=>o.pluginId===i);if(!s)throw new y("plugin_unavailable","Hosted tool unavailable");let a=await this.manager.invoke(i,s.generation,r);return Pw(a)}}),this.manager=new Oa({...e,workspaceRules:i=>fw(this.trusted,i),invokeTimeoutMs:i=>hw(this.trusted,i),lifecycle:(i,r,n)=>this.lifecycle(i,r,n),hooks:i=>({canSwitch:()=>this.coordinator(i).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(Bp(this.trusted,i).tools).length)throw new y("unreviewed_tool","Official tool set changed; review required");this.verifyTools(i,r),this.adapter.validateChange(i,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(i).freeze()},committed:async r=>{try{let n=r.enabled?this.manager.tools.find(s=>s.pluginId===i)?.descriptors:[];if(!n)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(i,n),r.enabled){let s=await this.manager.installer.load(i,r.version);this.documents.set(i,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:hN(s.manifest)})}else this.documents.delete(i);this.adapter.change(i,n),await this.coordinator(i).committed(r),e.changed?.(),this.recovery.delete(i)}catch(n){throw this.recovery.set(i,n),await this.coordinator(i).committed(r).catch(()=>{}),n}},resume:()=>this.coordinator(i).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:i=>this.manage(i),secret:async(i,r,n)=>{let s=this.options.capabilities?.secrets,a=this.documents.get(i)?.secrets;if(!s)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(!a?.includes(r))throw new y("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return n===null?await s.delete(i,r):await s.set(i,r,n),this.options.changed?.(),this.inventory()},secretAuth:async i=>{let r=this.options.capabilities?.secrets;if(!r)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(i.phase==="cancel")return this.deviceFlows.cancel(i.deviceId),{status:"cancelled"};if(i.phase==="start"){let s=this.documents.get(i.pluginId)?.secrets.includes(i.name)?Qp(this.trusted.get(i.pluginId),i.name):void 0;if(!s)throw new y("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(i.pluginId,i.name,s)}let n=await this.deviceFlows.poll(i.deviceId);return n.status!=="granted"?{status:n.status}:(await r.set(n.pluginId,n.name,n.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(i,r)=>{if(!this.options.approvals)throw new y("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(i,r),this.inventory()},action:(i,r)=>this.action(i,r?.checkpointOnly),views:async i=>{if(i.operation==="list-pending"){if(typeof i.pluginId!="string")throw new y("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(i.pluginId).pendingViews(this.options.ownerId)}}let r=i,n=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(n))},asset:async i=>{let r=await this.manager.assetRequest(i);if(!r)return null;let n=this.trusted.get(r.pluginId)?.browser?.wasm===!0&&R_(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:O_({wasm:n})}}}}verifyTools(e,i){let r=Bp(this.trusted,e);for(let n of i)if(!Object.hasOwn(r.tools,n.name)||r.tools[n.name]!==n.action||n.readonly!==r.readonlyActions.includes(n.action))throw new y("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let i=this.views.get(e);if(!i)throw new y("unknown_plugin","Hosted coordinator unavailable");return i}scope(e,i){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||i&&(r.cwd!==i.cwd||r.workspaceId!==i.workspaceId))throw new y("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,i){let r=this.manager.tools.find(n=>n.pluginId===e);if(!r||r.generation!==i)throw new y("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,i=!1){let r=this.queue.then(async()=>{if(this.closing&&!i)throw new y("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,i,r=!1){let n=this.switches.then(async()=>{if(this.closing&&!r)throw new y("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await i();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let a=await new ji(Xp(this.options.root,"data"),e).active();a&&await this.coordinator(e).committed(a).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new y("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=n.catch(()=>{}),n.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let i,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(n=>{i=setTimeout(()=>n(!1),e),i.unref?.()})])}finally{clearTimeout(i)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Xe)try{let i=await new ji(Xp(this.options.root,"data"),e.id).active();this.views.set(e.id,new Cn(e.id,i?.generation??0))}catch(i){this.recovery.set(e.id,i),this.views.set(e.id,new Cn(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Xp(this.options.root,"host-version.json");(await we(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await ve(this.options.root),await Z(e,{version:this.options.hostVersion}))}).catch(e=>{for(let i of this.options.catalog??Xe)this.recovery.set(i.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),i=this.options.capabilities?.secrets,r=new Map;for(let n of e.plugins){let s=n.enabled?this.documents.get(n.id)?.secrets??[]:[];i&&s.length&&r.set(n.id,await Promise.all(s.map(async a=>{let o=Qp(this.trusted.get(n.id),a);return{name:a,configured:await i.has(n.id,a),...o?{signIn:o.clientId?"browser":"token-page",...o.createUrl?{createUrl:o.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(n=>({pluginId:n.id,name:n.name,official:n.official,installed:n.installed,enabled:n.enabled,description:n.description,...r.has(n.id)?{secrets:r.get(n.id)}:{},icon:(this.options.catalog??Xe).find(s=>s.id===n.id)?.icon,hasRetainedData:n.activeVersion!==null,phase:this.recovery.has(n.id)?"reconnect-required":n.phase,updatePolicy:n.updatePolicy,pinnedVersion:n.pinnedVersion,updateDiagnostic:n.updateDiagnostic,...n.enabled&&n.activeVersion?{version:n.activeVersion}:n.version?{version:n.version}:{},...n.availableVersion?{availableVersion:n.availableVersion}:{},...n.pendingVersion?{pendingVersion:n.pendingVersion}:{},...n.generation!==null?{generation:n.generation}:{},...this.recovery.has(n.id)||n.error?{error:this.recovery.get(n.id)instanceof Error?this.recovery.get(n.id).message:n.error?.message??"Recovery required",errorCode:this.recovery.has(n.id)?"reconnect_required":n.error?.code}:{},...n.enabled&&n.assetBase&&this.documents.has(n.id)&&this.trusted.has(n.id)?{documentUrl:n.assetBase+this.documents.get(n.id).document,controllerUrl:n.assetBase+this.documents.get(n.id).controller,contribution:structuredClone(this.trusted.get(n.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new y("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new y("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let i=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(i){if(this.downloads.has(e.pluginId))throw new y("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,i)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new y("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let n=await this.manager.manage(e.pluginId,e.operation,e.version,i?.abort.signal);if(this.recovery.has(e.pluginId)||n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired)throw new y("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{i&&this.downloads.get(e.pluginId)===i&&this.downloads.delete(e.pluginId)}}async action(e,i=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new y("action_denied","Action is not reviewed by this host",{status:403});let n=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:fN(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||i){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new y("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new y("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{n()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let s of this.views.values())s.allowImmediateReopen(!0);let i=await this.manager.suspendForRestart(e),r=!1,n=async()=>{if(!r)try{await i(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=n,n}catch(i){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),i}finally{for(let i of this.views.values())i.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 i of this.views.values())i.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as yN,readdir as bN,unlink as _N}from"node:fs/promises";import{join as vr}from"node:path";import{randomUUID as vN}from"node:crypto";var Zp="hosted-migration.json";function Uw(t,e="@chengzhiyi/pi-excalidraw"){return async i=>{let{cwd:r,sessionId:n}=i.scope,s=vr(t,re(JSON.stringify([r,n])));await ve(t),await ve(s);let a=vr(s,"scope.lock"),o;try{o=await yN(a,"wx",384)}catch(l){throw l.code==="EEXIST"?new y("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):l}try{await o.writeFile(JSON.stringify({pid:process.pid,operationId:vN()}));let l=await we(vr(s,Zp));if(l&&(l.version!==1||l.pluginId!==e))throw new y("invalid_storage","Legacy scope belongs to another migration");let c=await bN(s),p=[];for(let m of c){if(m==="scope.lock"||m==="focus.json"||m===Zp||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(m))continue;if(!/^[\w-]{1,80}\.json$/.test(m))throw new y("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new y("invalid_storage","Too many legacy checkpoints");let g=await we(vr(s,m),3*512*1024);if(!g||g.version!==1||g.cwd!==r||g.sessionId!==n||!g.draft||m!==`${g.draft.id}.json`)throw new y("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(g.draft)}let d=await we(vr(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(m=>m.id===d)))throw new y("invalid_storage","Invalid legacy focused drawing");return l||await Z(vr(s,Zp),{version:1,pluginId:e,operationId:i.requestId}),{drafts:p,focused:d}}finally{await o.close(),await _N(a)}}}import{join as ON}from"node:path";import{randomUUID as wN}from"node:crypto";var SN=6e4,Da=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:i,sessionId:r,title:n})=>({id:e,pluginId:i,sessionId:r,title:n}))}async authorize(e,i){let r=this.entries.get(i);if(r&&r.pluginId!==e)throw new y("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new y("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<SN?new y("execute_denied","The user denied execution",{status:403}):(this.entries.set(i,{id:wN(),pluginId:e,sessionId:i,title:this.options.describe?.(i)??i,status:"pending"}),this.options.changed?.(),new y("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,i){let r=[...this.entries.values()].find(n=>n.id===e&&n.status==="pending");if(!r)throw new y("unknown_approval","No such pending approval",{status:404});r.status=i?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as kN,readFile as EN,rename as TN,writeFile as IN}from"node:fs/promises";import{randomUUID as AN,createHash as xN}from"node:crypto";import{join as qw}from"node:path";var La=class{dir;queue=Promise.resolve();constructor(e){this.dir=qw(e,"secrets")}file=e=>qw(this.dir,`${xN("sha256").update(e).digest("hex")}.json`);async read(e){try{let i=JSON.parse(await EN(this.file(e),"utf8"));if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch(i){if(!Zt(i))throw new y("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let i=this.queue.then(e,e);return this.queue=i.catch(()=>{}),i}async get(e,i){return(await this.read(e))[i]??null}has(e,i){return this.get(e,i).then(r=>r!==null)}set(e,i,r){return this.mutate(e,n=>{n[i]=r})}delete(e,i){return this.mutate(e,r=>{delete r[i]})}mutate(e,i){return this.serialize(async()=>{let r=await this.read(e);i(r),await kN(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${AN()}.tmp`;await IN(n,JSON.stringify(r),{mode:384}),await TN(n,this.file(e))})}};function jw(t,e){let i=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:n,title:s,prompt:a}){let o=await t.createDetached(n,r,s);try{await t.sendDetached(o,a,!1)}catch(l){throw await t.releaseDetached(o),l}return{sessionId:o}},ownerOf:r=>t.detachedOwner(r),activeCount:r=>t.detachedCount(r),async send(r,n,s){let a=t.detachedOwner(r);if(s==="execute"&&(!a||!await e(a,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await t.sendDetached(r,n,s==="execute")},abort:r=>t.abortDetached(r),release:r=>t.releaseDetached(r),async events(r,n){let s=t.detachedEvents(r,n);return{events:s.events.map(i),next:s.next}}}}var RN="scheduler";function Bw(t){let e=new Da({describe:t.sessionTitle,changed:t.changed}),i=()=>{let n=t.sessions();if(!n)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return n},r={createDetached:(...n)=>i().createDetached(...n),detachedOwner:n=>t.sessions()?.detachedOwner(n)??null,detachedCount:n=>t.sessions()?.detachedCount(n)??0,sendDetached:(...n)=>i().sendDetached(...n),abortDetached:n=>i().abortDetached(n),releaseDetached:async n=>{e.forget(n),await i().releaseDetached(n)},detachedEvents:(...n)=>i().detachedEvents(...n)};return{approvals:e,capabilities:{secrets:new La(ON(t.root,"capability-secrets")),sessions:jw(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=t.activeWorkspace();if(!n)return null;try{return t.trustedScope(n,RN)}catch{return null}}}}async function NN(){for(let t of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Xs(t),i=new wt({env:t,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await i.ready,e.node.enabled||e.browser.enabled||i.enabled||i.reporter||i.capture(new Error("Disabled release probe"))||await i.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await i.close()}}return{release:Rr,buildId:it,browser:Xs({}).browser}}async function Fw(){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 t=new wt({monitor:!1});try{if(await t.ready,!t.enabled)throw new Error("Sentry verification transport is disabled");let e=t.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await t.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Rr,buildId:it}}finally{await t.close()}}var Dn=kr(CN(LN(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),FN=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),u=globalThis[FN]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Xt(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:jt()}),Ee()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Mi,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};u.lifecycle??=new Mi;u.tuiGeneration??=0;u.stopChanged??=null;u.tuiWaitController??=new AbortController;u.tuiStreaming??=null;u.tuiPrompts??=new Xt(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:jt()}),Ee()});u.tuiPromptSessionId??=null;u.tuiAgentError??=!1;var Gw=!1;function HN(t){return Gw||(Gw=!0,setTimeout(()=>{t.pruneReleases().catch(()=>{})},6e4).unref()),t}function Ua(){return u.selected==="sdk"?u.workspaceSessions?.catalog??null:u.tuiCatalog}var GN=null;function WN(){return GN??=UN.create({refreshOnCreate:!1})}var qa=new Map;async function Sr(){let t=await WN(),e=u.selected==="tui"?u.current?.modelRegistry:void 0,i=new Set(e?.getRegisteredProviderIds()??[]);for(let r of qa.keys())i.has(r)||(t.unregisterProvider(r),qa.delete(r));for(let r of i){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),a=n??s;!a||qa.get(r)===a||(n?t.registerNativeProvider(n):s&&t.registerProvider(r,s),qa.set(r,a))}return await t.refresh({allowNetwork:!1}),t}function Te(){return u.selected==="sdk"?u.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():jt()}function jt(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...M_(u.current,u.current.sessionManager.getSessionName(),u.tuiCatalog?.ids()??[]),idle:u.current.isIdle()&&!u.tuiPrompts.sending,streaming:u.tuiStreaming,queuedPrompts:u.tuiPrompts.view(),hasPendingPrompts:u.current.hasPendingMessages?.()??!1,interactions:u.interactions?.pending(u.current.sessionManager.getSessionId())??[]}}async function nd(t,e,i,r,n){let s=je(t);Jt({...jt(),idle:s.isIdle()},e,n);let a=s.isIdle();a&&ur(()=>u.hosted?.adapter.assertAdmission(),r,(o,l)=>u.bridge?.reportError?.(o,l)),a&&(u.operation=r);try{let o=i.length?[{type:"text",text:e},...i]:e;if(u.replacementContext!==null&&u.replacementSessionId===t)await u.replacementContext.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n});else{if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n})}u.current?.sessionManager.getSessionId()===t&&u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:jt()})}catch(o){throw a&&(u.operation=void 0),o}}function id(){let t=u.current?.sessionManager.getSessionId(),e=u.tuiGeneration,i=()=>{if(!t||!u.current||u.tuiGeneration!==e||u.current.sessionManager.getSessionId()!==t||u.tuiAgentError)return!1;let r=jt();return!u.hosted?.adapter.isFrozen&&u.current.isIdle()&&!r.paused&&!r.interactions.length};u.tuiPrompts.schedule(i,(r,n,s)=>nd(t,r,n,s))}function Ne(t){if(Te().sessionId!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function zw(){let t=(u.workspaces?.list()??[]).map(d=>({...d})),e=u.activeWorkspaceId,i=Te(),n=u.current?jt():null,s=await xi(i.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)),a=n?await xi(n.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)):null,o=await Ln.listAll(),l=u.workspaceSessions?.retainedSessions()??[];n&&a&&l.push({sessionId:n.sessionId,cwd:a,path:null,name:n.name,modified:n.messages.at(-1)?.timestamp??new Date().toISOString(),idle:n.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&n.idle&&u.tuiPrompts.length===0&&!n.messages.some(d=>d.role==="user")});let c=await pr(o,Ci(Pe()),new Set(l.filter(d=>!d.idle).map(d=>d.sessionId))),p=(await Promise.all(t.map(async d=>{let g=(await Ni(d.path,o).catch(f=>(f instanceof wn?d.available=!1:u.bridge?.reportError?.(f,{stage:"workspace_sessions"}),[]))).map(f=>({id:f.id,workspaceId:d.id,path:f.path,name:f.name||f.firstMessage?.slice(0,50)||"",modified:f.modified.toISOString(),idle:!0}));for(let f of l.filter(h=>h.cwd===d.path)){if(f.blank&&f.sessionId!==i.sessionId)continue;let h=g.findIndex(S=>S.id===f.sessionId),_={id:f.sessionId,workspaceId:d.id,path:f.path??g[h]?.path??null,name:f.name,modified:f.modified,idle:f.idle};h<0?g.unshift(_):g[h]=_}return d.path===s&&!g.some(f=>f.id===i.sessionId)&&g.unshift({id:i.sessionId,workspaceId:d.id,path:null,name:i.name,modified:new Date().toISOString(),idle:i.idle}),g.map(f=>{let h=c.get(f.id)?.view;return h?{...f,subagent:h}:f})}))).flat();return{items:t,activeId:e,sessions:p}}var Ww=0;async function Ee(){if(!u.bridge)return;let t=++Ww;try{let e=await zw();t===Ww&&u.bridge?.publish({type:"workspaces",value:e})}catch(e){u.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function rd(t,e=!1){let i=u.workspaces?.get(t);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await kt(i.path),!e&&u.current&&i.path===await xi(u.current.cwd)&&!u.workspaceSessions?.hasWorkspace(i.path))u.selected="tui",u.activeWorkspaceId=t,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Te()});else{if(!u.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await u.workspaceSessions.reuseBlank(i.path))&&await u.workspaceSessions.open(i.path,e?"new":"continue"),u.selected="sdk",u.activeWorkspaceId=t,u.bridge?.publish({type:"snapshot",session:Te()})}await Ee()}async function $w(t,e,i){let r=u.workspaces?.get(t);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await kt(r.path);if(u.workspaceSessions?.hasSession(n,e)||u.current?.sessionManager.getSessionId()===e&&await xi(u.current.cwd)===n)return r;if(!(await Ni(n)).some(a=>a.id===e&&a.path===i))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function je(t){let e=u.current;if(e===null||e.sessionManager.getSessionId()!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function De(t){u.current=t,u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:Te()})}function Kw(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let t=u.selected==="sdk"?u.workspaceSessions?.path:u.current.cwd;if(!t)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=u.selected==="tui"?u.current.isProjectTrusted():u.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return qN.create(t,void 0,{projectTrusted:e})}async function Yw(){let t=Kw(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),i=new Vw({cwd:Te().cwd,agentDir:Pe(),settingsManager:t}),r=_v(i.listConfiguredPackages(),await i.resolve(async()=>"skip"));return{projectTrusted:t.isProjectTrusted(),global:e(t.getGlobalSettings()),project:e(t.getProjectSettings()),installed:r}}async function $N(t){Ne(t.sessionId);let e=u.selected==="tui"?je(t.sessionId):null;if(e?!e.isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=Kw();if(t.scope==="project"&&!i.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=t.value.trim(),n=t.scope==="project"?i.getProjectSettings():i.getGlobalSettings();if(t.kind==="packages"){let s=new Vw({cwd:Te().cwd,agentDir:Pe(),settingsManager:i});t.action==="add"?await s.installAndPersist(r,{local:t.scope==="project"}):await s.removeAndPersist(r,{local:t.scope==="project"})}else if(t.kind==="extensions"){let s=n.extensions??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectExtensionPaths(a):i.setExtensionPaths(a)}else{let s=n.skills??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectSkillPaths(a):i.setSkillPaths(a)}return await i.flush(),u.selected==="tui"?(u.commandContext&&await u.commandContext.reload(),u.current&&De(u.current)):(await u.workspaceSessions?.reload(),u.bridge?.publish({type:"plugins_changed"})),await Yw()}function ja(t,e=gp){if(u.hostedMode===!1||u.hostedMode===void 0&&u.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");u.hostedMode=!0;let i=(c,p)=>{let d=ed(c);return{cwd:d,sessionId:p,workspaceId:Hw("sha256").update(d).digest("hex")}},r=wr(Pe(),"pi-web","hosted"),n=new Pa({configPath:Dw(Pe())});u.hosted??=new Ma({root:r,...n.enabled?{dev:n,devStatusPath:Lw(Pe())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...Xe,...n.catalog],policies:new Map([...Ia,...n.policies])}:{},...Bw({root:r,sessions:()=>u.workspaceSessions,activeWorkspace:()=>u.workspaceSessions?.path??null,trustedScope:i,sessionTitle:c=>u.workspaceSessions?.retainedSessions().find(p=>p.sessionId===c)?.name,changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(MN(kr(Dn,"../../package.json"),"utf8")).version,packageRoot:kr(Dn,"../.."),workerEntry:kr(Dn,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${Hw("sha256").update(Pe()).digest("hex")}`,resolveSession:c=>{let p=u.current;if(p?.sessionManager.getSessionId()===c)return i(p.cwd,c);let d=u.workspaceSessions?.hostedScope(c);return d?i(d.cwd,c):null},legacy:()=>Uw(wr(Pe(),"pi-web","diagrams")),changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),u.offHostedThaw?.(),u.offHostedThaw=u.hosted?.adapter.onThaw(id),u.pi=t;let s=bu({async run(...c){if(!u.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return u.bridge.runPluginTool(...c)},async ask(c,p){if(u.pi&&c.sessionId===u.current?.sessionManager.getSessionId())return aa(u.pi.events,c,p);if(!u.workspaceSessions)throw new Error("The Web workbench is not open");return u.workspaceSessions.requestInteraction(c,p)}});for(let c of s)t.registerTool(c);u.tools?.clear(),u.tools=new dr({enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,capture:(c,p)=>u.bridge?.reportError?.(c,p),breadcrumb:(c,p)=>u.bridge?.breadcrumb?.(c,p),anonymize:c=>u.telemetry?.session(c)??"unavailable"});let a=c=>({...u.operation,session:u.telemetry?.session(c.sessionManager.getSessionId()),piVersion:td,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});u.interactions?.dispose(),u.interactions=new cr(t.events,c=>!!u.bridge&&c.sessionId===u.current?.sessionManager.getSessionId()&&Sn(u.tuiCatalog,c.pluginId),()=>{u.current&&u.selected==="tui"&&De(u.current)});let o=()=>{u.stopChanged?.(),u.stopChanged=t.events.on(oa,()=>{u.selected==="tui"&&u.current&&De(u.current)})};o(),t.on("session_start",async(c,p)=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiWaitController=new AbortController,u.tuiGeneration++,o(),u.current=p,u.releaseHostedTui?.(),u.releaseHostedTui=u.hosted?.adapter.mountTui(t,i(p.cwd,p.sessionManager.getSessionId())),u.hosted&&!await u.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),u.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(u.tuiPrompts=new Xt(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:jt()}),Ee()}),u.tuiPromptSessionId=p.sessionManager.getSessionId()),u.tuiAgentError=!1,u.bridge){let d=await Ri.discover(p.cwd,p.isProjectTrusted?.()??!1);if(u.current!==p)return;u.tuiCatalog=d}u.replacementSessionId!==p.sessionManager.getSessionId()&&(u.replacementContext=null,u.replacementSessionId=null),De(p),u.bridge&&u.selected==="tui"&&u.bridge.publish({type:"plugins_changed"}),u.selected==="tui"&&u.workspaces&&u.workspaces.add(p.cwd).then(async d=>{u.selected!=="tui"||u.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(u.activeWorkspaceId=d.id,await Ee())}).catch(d=>{u.bridge?.publish({type:"error",message:d instanceof Error?d.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:u.bridge.reportError?.(d,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!u.autoOpened&&(u.autoOpened=!0,l(p).catch(d=>{p.ui.notify(d instanceof Error?d.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),t.on("agent_start",(c,p)=>{u.tuiAgentError=!1,u.bridge?.breadcrumb?.("agent_start",a(p)),De(p),Ee()}),t.on("agent_end",(c,p)=>De(p)),t.on("agent_settled",(c,p)=>{u.bridge?.breadcrumb?.("agent_end",a(p)),u.tools?.clear(),u.operation=void 0,u.tuiStreaming=null,id(),De(p),Ee()}),t.on("tool_execution_start",(c,p)=>{u.tools?.start(c,a(p))}),t.on("tool_execution_end",(c,p)=>{u.tools?.end(c,a(p))}),t.on("model_select",(c,p)=>De(p)),t.on("thinking_level_select",(c,p)=>De(p)),t.on("message_end",(c,p)=>{if(c.message.role==="assistant"&&c.message.stopReason==="error"){u.tuiAgentError=!0;let d=u.bridge?.reportError?.(new Error("Agent response failed"),{...u.operation,stage:"agent",code:"agent_failed",piVersion:td});u.selected==="tui"&&u.bridge?.publish({type:"error",message:c.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:d,inTranscript:!0,...u.operation})}c.message.role==="toolResult"&&u.tools?.message(c.message,a(p)),c.message.role==="assistant"&&(u.tuiStreaming=null),u.selected==="tui"&&c.message.role==="assistant"&&u.bridge?.publish({type:"stream",message:null}),De(p),Ee()}),t.on("session_info_changed",(c,p)=>De(p)),t.on("message_update",(c,p)=>{if(u.current=p,c.message.role!=="assistant"||(u.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(c.message.timestamp).toISOString(),blocks:qt(c.message.content)},u.selected!=="tui"||u.bridge===null))return;let d=Date.now();d-u.lastStreamAt<60||(u.lastStreamAt=d,u.bridge.publish({type:"stream",message:u.tuiStreaming}))}),t.on("session_shutdown",async c=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiGeneration++,u.stopChanged?.(),u.stopChanged=null,u.interactions?.cancelAll(),u.releaseHostedTui?.(),u.releaseHostedTui=void 0,c.reason==="new"||c.reason==="resume"||c.reason==="fork"||c.reason==="reload"){u.current=null;return}await u.hosted?.shutdown(),u.hosted=void 0,u.offHostedThaw?.(),u.offHostedThaw=void 0,u.current=null;let p=u.bridge,d=u.telemetry;u.bridge=null,u.commandContext=null,u.replacementContext=null,u.replacementSessionId=null,u.pi=null;let m=u.workspaceSessions;u.workspaceSessions=null,await m?.dispose(),u.selected="tui",u.activeWorkspaceId=null,u.autoOpened=!1,u.tuiCatalog=null,u.stopPluginWatch?.(),u.stopPluginWatch=null,u.operation=void 0,u.telemetry=null,p?await p.close():await d?.close()});let l=async c=>{u.telemetry??=new wt;try{u.current=c,u.commandContext="newSession"in c?c:null,u.pi=t,u.tuiCatalog=await Ri.discover(c.cwd,c.isProjectTrusted?.()??!1),u.workspaces===null&&(u.workspaces=new sa(q_(Pe())),await u.workspaces.load());try{await u.workspaces.discover((await Ln.listAll()).map(m=>m.cwd))}catch(m){c.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${m instanceof Error?m.message:String(m)}`,"warning")}let p=await u.workspaces.add(c.cwd);if(u.selected==="tui"&&(u.activeWorkspaceId=p.id),u.bridge&&(u.bridge.protocolVersion!==7||u.bridge.buildId!==it||typeof u.bridge.reportError!="function"||typeof u.bridge.runPluginTool!="function")){let m=u.bridge;if(u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)&&u.workspaceSessions.session&&!u.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");u.bridge=null,await m.close(),await u.telemetry.close(),u.telemetry=new wt}if(u.bridge===null){let m=u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)?u.workspaceSessions:null,g=m?.session&&m.path?{path:m.path,sessionManager:m.session.sessionManager}:null;m&&(await m.dispose(),u.workspaceSessions=null),u.workspaceSessions??=new da(h=>{u.selected==="sdk"&&u.bridge?.publish(h)},()=>u.current?.model,h=>{try{return!!u.current&&ed(u.current.cwd)===h&&(u.current.isProjectTrusted?.()??!1)}catch{return!1}},(h,_)=>u.bridge?.reportError?.(h,_),{enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,breadcrumb:(h,_)=>u.bridge?.breadcrumb?.(h,_),anonymize:h=>u.telemetry?.session(h)??"unavailable"},()=>{Ee()},s,{adapter:u.hosted.adapter,scope:i}),g&&await u.workspaceSessions.open(g.path,{sessionManager:g.sessionManager});let f={hosted:u.hosted?.handlers,selfUpdate:HN(new _a({agentDir:Pe(),packageRoot:kr(Dn,"../.."),launcherNonce:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:h=>u.hosted.manager.hostUpdateWarnings(h),prefetchPlugins:(h,_)=>u.hosted.manager.prefetchForHost(h,_),beforeRestart:h=>u.hosted.prepareRestart(h)})),snapshot:Te,busyGitWorkspaces:()=>{let h=(u.workspaceSessions?.retainedSessions()??[]).filter(_=>!_.idle).map(_=>_.cwd);if(u.current&&(!u.current.isIdle()||u.tuiPrompts.sending))try{h.push(ed(u.current.cwd))}catch{h.push(u.current.cwd)}return h},plugins:async()=>{let h=Ua();return await h?.refreshAssets(),h?.view()??{plugins:[],errors:[]}},pluginAsset:async h=>Ua()?.asset(h)??null,async invokePluginAction(h,_,S,E){if(Ne(h),!Ua()?.has(_))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let A=u.selected,D=u.tuiGeneration,C=u.workspaceSessions?.session,N={requestId:BN(),sessionId:h,pluginId:_,action:S,input:E},G=u.selected==="sdk"?await u.workspaceSessions.invokePluginAction(N):await la(u.pi.events,N,15e3,u.tuiWaitController.signal);if(Ne(h),A!==u.selected||(A==="tui"?D!==u.tuiGeneration:C!==u.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return u.selected==="tui"&&u.current&&De(u.current),G},async resolvePluginInteraction(h,_,S,E){if(Ne(h),!Sn(Ua(),_))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");u.selected==="sdk"?u.workspaceSessions.resolveInteraction(h,_,S,E):u.interactions.resolve(h,_,S,E)},image(h,_,S){Ne(h);let A=(u.selected==="sdk"?u.workspaceSessions?.session?.sessionManager.getBranch():u.current?.sessionManager.getBranch())?.find(C=>C.id===_);if(A?.type!=="message"||A.message.role!=="user"||!Array.isArray(A.message.content))return null;let D=A.message.content[S];return D?.type!=="image"?null:{data:Buffer.from(D.data,"base64"),mimeType:D.mimeType}},async workspaces(){return zw()},async addWorkspace(h,_){let S=await u.workspaces.add(h,_);try{await rd(S.id,!0)}catch(E){throw await Ee(),E}},async selectWorkspace(h){await rd(h)},async newSessionInWorkspace(h){await rd(h,!0)},async removeWorkspace(h){if(h===u.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await u.workspaces.remove(h),await Ee()},async subagentHistory(h,_){let S=u.workspaces?.get(h);if(!S)return null;let E=await Ln.listAll(),A=(await Ni(S.path,E)).find(C=>C.id===_);if(!A)return null;let D=(await pr(E,Ci(Pe()))).get(_);return D?J_(A.path,_,D):null},async selectSession(h,_,S){let E=u.workspaces?.get(h);if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await kt(E.path),_===u.current?.sessionManager.getSessionId()&&E.path===await xi(u.current.cwd))u.selected="tui",u.activeWorkspaceId=h,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Te()});else{if(u.selected==="sdk"&&u.workspaceSessions?.session?.sessionManager.getSessionId()===_&&u.workspaceSessions.path===E.path)return;if(u.workspaceSessions?.hasSession(E.path,_))await u.workspaceSessions.open(E.path,{sessionId:_});else{let A=await Ln.listAll();if(!(await Ni(E.path,A)).some(N=>N.id===_&&N.path===S))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");if((await pr(A,Ci(Pe()))).has(_))throw new Error("\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E3A\u53EA\u8BFB");await u.workspaceSessions.open(E.path,{sessionFile:S})}u.selected="sdk",u.activeWorkspaceId=h,u.bridge?.publish({type:"snapshot",session:Te()})}await Ee()},async renameSession(h,_,S,E){let A=E.replace(/\s+/g," ").trim();if(A.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await $w(h,_,S),u.current?.sessionManager.getSessionId()===_&&u.pi?u.pi.setSessionName(A):u.workspaceSessions?.rename(_,A)||Ln.open(S).appendSessionInfo(A),u.selected==="tui"&&u.current?.sessionManager.getSessionId()===_&&u.bridge?.publish({type:"snapshot",session:Te()}),await Ee()},async deleteSession(h,_,S){let E=await $w(h,_,S);if(u.current?.sessionManager.getSessionId()===_)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 A=await u.workspaceSessions?.discard(_)??null,D=A?.path??(S||null);D&&await Z_(D,Pe()),A?.wasActive&&u.selected==="sdk"&&(await u.workspaceSessions.open(E.path,"new"),u.selected="sdk",u.activeWorkspaceId=h,u.bridge?.publish({type:"snapshot",session:Te()})),await Ee()},async models(){if(u.selected==="sdk")return u.workspaceSessions?.models()??[];let h=u.current;if(!h)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let _=h.scopedModels?.map(S=>`${S.model.provider}/${S.model.id}`)??[];return h.modelRegistry.getAvailable().filter(S=>_.length===0||_.includes(`${S.provider}/${S.id}`)).map(S=>({provider:S.provider,id:S.id,name:S.name}))},async providers(){let h=await Sr(),_=new Set((await h.listCredentials()).map(S=>S.providerId));return h.getProviders().map(S=>({id:S.id,name:S.name,configured:h.getProviderAuthStatus(S.id).configured,storedCredential:_.has(S.id),methods:[S.auth.apiKey?.login?"api_key":null,S.auth.oauth?"oauth":null].filter(E=>E!==null)}))},async providerModels(h){let _=await Sr();return ju(wr(Pe(),"models.json"),h,_)},async updateProviderModel(h,_,S){if(Ne(h),u.selected==="tui"?!je(h).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=Te().model;if(S.action==="remove"&&E===`${_}/${S.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(S.action==="save"&&S.originalId&&S.originalId!==S.model.id&&E===`${_}/${S.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let A=await Sr();await Bu(wr(Pe(),"models.json"),_,S,A),await A.refresh({providers:[_],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[_],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[_],allowNetwork:!1});let D=S.action==="save"?S.model.id:S.action==="base_url"&&E?.startsWith(`${_}/`)?E.slice(_.length+1):null;if(D&&E===`${_}/${D}`)if(u.selected==="sdk")try{await u.workspaceSessions.setModel(_,D)}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 C=je(h),N=C.modelRegistry.find(_,D);if(!N||!u.pi||!await u.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");De(C)}},async logoutProvider(h,_){if(Ne(h),u.selected==="tui"?!je(h).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Sr();if(!(await S.listCredentials()).some(E=>E.providerId===_))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await S.logout(_),await u.current?.modelRegistry.refresh({providers:[_],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[_],allowNetwork:!1})},async loginProvider(h,_,S){let E=await Sr();await E.login(h,_,Cu(h,_,S)),await E.refresh({providers:[h],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[h],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[h],allowNetwork:!1})},async addCustomProvider(h,_){if(Ne(h),u.selected==="tui"?!je(h).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Sr();if(S.getProvider(_.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await Mu(wr(Pe(),"models.json"),_),await S.refresh({allowNetwork:!1}),await u.current?.modelRegistry.refresh({allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return u.selected==="tui"?(u.pi?.getCommands()??[]).filter(h=>h.name!=="web"&&h.name!=="web-dev-reload").map(h=>({name:h.name,description:h.description})):[]},async compact(h){if(Ne(h),u.selected==="sdk"){let S=u.workspaceSessions?.session;if(!S||!S.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await S.compact(),u.bridge?.publish({type:"snapshot",session:Te()});return}let _=je(h);if(!_.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");_.compact()},async setModel(h,_,S){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.setModel(_,S);return}let E=je(h);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let A=E.modelRegistry.find(_,S);if(!A||!E.modelRegistry.getAvailable().some(D=>D.provider===_&&D.id===S))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!u.pi||!await u.pi.setModel(A))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");De(E)},async setThinkingLevel(h,_){if(Ne(h),!["off","minimal","low","medium","high","xhigh"].includes(_))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(u.selected==="sdk"){let A=u.workspaceSessions?.session;if(!A||!A.isIdle||!A.getAvailableThinkingLevels().includes(_))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");A.setThinkingLevel(_),u.bridge?.publish({type:"snapshot",session:Te()});return}let E=je(h);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!E.model||!jN(E.model).includes(_))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.setThinkingLevel(_),De(E)},config:Yw,updateConfig:$N,async send(h,_,S=[],E,A){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.send(_,S,E,A);return}let D=je(h);if(Jt(jt(),_,A),A==="followUp"&&(!D.isIdle()||u.tuiPrompts.length>0)){u.tuiPrompts.enqueue(_,S,E),id();return}if(D.isIdle()&&u.tuiPrompts.sending)throw new Me("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await nd(h,_,S,E,A)},async updateQueuedPrompt(h,_,S,E){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.updateQueuedPrompt(_,S,E);return}if(E.kind==="steer"&&je(h).isIdle())throw new Me("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await u.tuiPrompts.update(_,S,E,(A,D,C)=>nd(h,A,D,C,"steer"))},async abort(h){if(Ne(h),u.selected==="sdk")await u.workspaceSessions.stop();else{let _=je(h);if(_.isIdle()&&!u.tuiPrompts.sending)return;if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.tools?.cancel(),u.bridge?.breadcrumb?.("cancel",{...u.operation}),u.pi.appendEntry(vn),_.abort()}},async resume(h,_){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.resume(_);return}let S=je(h);if(ur(()=>u.hosted?.adapter.assertAdmission(),_,(E,A)=>u.bridge?.reportError?.(E,A)),!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!S.model||!u.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!S.modelRegistry.hasConfiguredAuth(S.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");u.operation=_;try{u.pi.sendMessage(ca(Te().messages),{triggerTurn:!0})}catch(E){throw u.operation=void 0,E}},async newSession(h){if(Ne(h),u.selected==="sdk"){let E=u.workspaces?.get(u.activeWorkspaceId??"");if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await u.workspaceSessions.reuseBlank(E.path)||await u.workspaceSessions.open(E.path,"new"),await Ee();return}let _=je(h);if(!_.isIdle()||u.tuiPrompts.length>0||u.commandContext===null){await u.workspaceSessions.open(_.cwd,"new"),u.selected="sdk",u.bridge?.publish({type:"snapshot",session:Te()}),await Ee();return}if((await u.commandContext.newSession({withSession:async E=>{u.commandContext=E,u.replacementContext=E,u.replacementSessionId=E.sessionManager.getSessionId(),u.current=E}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await Ee()}};f.addWorkspace=u.lifecycle.wrap(f.addWorkspace),f.selectWorkspace=u.lifecycle.wrap(f.selectWorkspace),f.newSessionInWorkspace=u.lifecycle.wrap(f.newSessionInWorkspace),f.removeWorkspace=u.lifecycle.wrap(f.removeWorkspace),f.selectSession=u.lifecycle.wrap(f.selectSession),f.renameSession=u.lifecycle.wrap(f.renameSession),f.deleteSession=u.lifecycle.wrap(f.deleteSession),f.newSession=u.lifecycle.wrap(f.newSession),f.updateConfig=u.lifecycle.wrap(f.updateConfig);try{u.bridge=await C_(f,Dn,u.telemetry)}catch(h){throw process.env.PI_WEBAPP_LAUNCHER_NONCE&&c.ui.notify(`pi-webapp-start-error: ${h instanceof Error?h.message:String(h)}`,"error"),h}}if(u.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let m=[],g=null;for(let f of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(PN).filter(Boolean))try{m.push(DN(wr(kr(f),"dist"),(h,_)=>{let S=String(_??"");["client.js","client.css"].includes(S)&&(g&&clearTimeout(g),g=setTimeout(()=>u.bridge?.publish({type:"plugins_changed"}),180))}))}catch(h){u.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${f}: ${String(h)}`})}u.stopPluginWatch=()=>{for(let f of m)f.close();g&&clearTimeout(g)}}let d=await e(u.bridge.url).catch(()=>!1);c.ui.notify(`pi-webapp: ${u.bridge.url}`,d?"info":"warning"),c.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw u.telemetry?.capture(p,{stage:"open_web",piVersion:td}),u.bridge||(await u.telemetry?.close(),u.telemetry=null),p}};t.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(c,p)=>l(p)}),t.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(c,p)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(c))throw new Error("Launcher stop receipt ID required");try{await u.hosted?.shutdown(),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!0})}`,"info")}catch(d){console.error("pi-webapp: plugin shutdown refused the stop request:",d),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!1})}`,"warning")}}}),t.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(c,p)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await p.waitForIdle(),await u.lifecycle.run(async()=>{let d=u.workspaceSessions?.session;d&&(await d.waitForIdle(),await u.workspaceSessions.reload()),await p.reload()}))}})}var A9=ja;export{A9 as default,NN as verifySentryDisabledRelease,Fw as verifySentryNodeRelease};
|
|
243
|
+
`)),P.type==="agent_settled"&&E("turn_end",S.lastText)),!this.disposed&&!h.closing){let I={...h.operation,session:this.telemetry.anonymize(g.sessionManager.getSessionId()),piVersion:pa,model:g.model?`${g.model.provider}/${g.model.id}`:null,thinkingLevel:g.thinkingLevel};if(P.type==="agent_start"&&(h.activityId++,this.telemetry.breadcrumb("agent_start",I)),P.type==="tool_execution_start"&&f.start(P,I),P.type==="tool_execution_end"&&f.end(P,I),P.type==="message_end"&&P.message.role==="assistant"&&P.message.stopReason==="error"){h.agentErrorReported=!0;let x=h.networkDiagnostic,L=this.reportError(new Error("Agent response failed"),{...h.operation,stage:"agent",code:"agent_failed",piVersion:pa,...x?{networkKind:x.kind,networkStage:x.stage,causeCodes:x.causes.flatMap(k=>k.code?[k.code]:[]).join(","),requestId:x.requestId}:{}})??x?.errorId;_({type:"error",message:P.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:L,inTranscript:!0,...h.operation})}P.type==="message_end"&&P.message.role==="toolResult"&&f.message(P.message,I),P.type==="agent_settled"&&(this.telemetry.breadcrumb("agent_end",I),f.clear(),h.operation=void 0)}P.type==="message_update"&&P.message.role==="assistant"&&(h.streaming={id:"stream",role:"assistant",timestamp:new Date(P.message.timestamp).toISOString(),blocks:qt(P.message.content)},Date.now()-A>=60&&(A=Date.now(),_({type:"stream",message:h.streaming}))),P.type==="agent_settled"&&this.scheduleQueued(h),["message_end","agent_start","agent_settled","session_info_changed","entry_appended","queue_update"].includes(P.type)&&((P.type==="message_end"&&P.message.role==="assistant"||P.type==="agent_settled")&&(h.streaming=null,_({type:"stream",message:null})),_({type:"snapshot",session:this.snapshotOf(h)}),!this.disposed&&!h.closing&&["message_end","agent_start","agent_settled","session_info_changed"].includes(P.type)&&this.onSessionsChanged())});h.detach=()=>{D(),C()},h.releaseHosted=this.hosted?.adapter.attach(g);let N=[],G=!0;if(await g.bindExtensions({mode:"print",shutdownHandler:()=>{},onError:P=>{G&&N.push(P.error),this.diagnostic(h,a.plugins.find(I=>P.extensionPath.startsWith(I.root+"/"))?.id??P.extensionPath,P.event??"runtime",P.error)}}),G=!1,N.length)throw new Error(N.join("; "));if(this.ensureAvailable(),s&&(!s.session.isIdle||s.prompts.sending))throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(s&&await this.close(s,r),this.disposed)throw new Error("\u5DE5\u4F5C\u533A\u670D\u52A1\u5DF2\u5173\u95ED");h.detached&&(h.detached.restoreTools=g.getActiveToolNames(),g.setActiveToolsByName(Ex)),this.runtimes.set(g.sessionManager.getSessionId(),h),p=null,h.detached?this.onSessionsChanged():this.activate(h)}catch(d){throw this.hosted?.adapter.releasePending(i.getSessionId()),p?await this.close(p,"quit"):(o.clear(),await l.release()),d}}async close(e,i){e.closing||(e.closing=!0,e.tools.clear(),e.waitController.abort(),e.interactions.dispose(),await tv(e.session,i,r=>this.diagnostic(e,"host","shutdown",r),5e3,()=>{e.detach(),e.bus.clear()}),e.releaseHosted?.(),await e.releasePaths())}snapshotOf(e){let{session:i,cwd:r,catalog:n}=e,s=i.sessionManager.getBranch().flatMap(a=>{let o=Ai(a);return o?[o]:[]});return{schemaVersion:1,sessionId:i.sessionManager.getSessionId(),cwd:r,name:na(i.sessionManager.getSessionName(),s),model:i.model?`${i.model.provider}/${i.model.id}`:null,thinkingLevel:i.thinkingLevel,thinkingLevels:i.getAvailableThinkingLevels(),idle:i.isIdle&&!e.prompts.sending,activityId:e.activityId,paused:lr(i.sessionManager.getBranch()),promptQueue:{steering:[...i.getSteeringMessages()],followUp:[...i.getFollowUpMessages()]},queuedPrompts:e.prompts.view(),contextUsage:i.getContextUsage()??null,messages:s,streaming:e.streaming,interactions:e.interactions.pending(i.sessionManager.getSessionId()),pluginEntries:tp(i.sessionManager.getBranch(),n.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 i=this.active;if(this.disposed||!i||i.closing||e.sessionId!==i.session.sessionManager.getSessionId())throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!i.catalog.has(e.pluginId))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let r=i.session.extensionRunner,n=await la(i.bus,e,15e3,i.waitController.signal);if(this.active!==i||i.closing||r!==i.session.extensionRunner)throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return this.publish({type:"snapshot",session:this.snapshot()}),n}requestInteraction(e,i){let r=this.runtimes.get(e.sessionId);return this.disposed||!r||r.closing?Promise.reject(new Error("\u4F1A\u8BDD\u4E0D\u53EF\u7528")):aa(r.bus,e,i)}resolveInteraction(e,i,r,n){if(this.disposed||!this.active||this.active.closing)throw new Error("Interaction host unavailable");this.active.interactions.resolve(e,i,r,n)}async send(e,i=[],r,n){if(this.disposed||!this.session||this.active?.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");let s=this.active;if(Jt(this.snapshot(),e,n),n==="followUp"&&(!s.session.isIdle||s.prompts.length>0)){s.prompts.enqueue(e,i,r),this.scheduleQueued(s);return}if(s.session.isIdle&&s.prompts.sending)throw new Me("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await this.prompt(s,e,i,r,n)}async prompt(e,i,r,n,s){if(this.disposed||e.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");ur(()=>this.hosted?.adapter.assertAdmission(),n,this.reportError),Jt({...this.snapshotOf(e),idle:e.session.isIdle},i,s);let a=e.session,o=a.isIdle;o&&(e.operation=n,e.agentErrorReported=!1,e.networkDiagnostic=void 0),this.telemetry.breadcrumb("send",{...n,piVersion:pa});let l=!1,c,p,d=new Promise((m,g)=>{c=m,p=g});a.prompt(i,{images:r,streamingBehavior:s,preflightResult:m=>{m&&(l=!0,c())}}).then(()=>{l||c()}).catch(m=>{if(!l)p(m);else if(!this.disposed&&!e.closing&&!e.agentErrorReported){let g=this.reportError(Tt(m,"Agent response failed"),{...n,stage:"agent",code:"agent_failed",piVersion:pa});this.publishFor(e,{type:"error",message:m instanceof Error?m.message:"Pi \u8BF7\u6C42\u5931\u8D25",errorCode:"unexpected_error",errorId:g,...n})}});try{await d}catch(m){throw o&&(e.operation=void 0),m}}queueReady(e){return!this.hosted?.adapter.isFrozen&&!this.disposed&&!e.closing&&e.session.isIdle&&!e.agentErrorReported&&!lr(e.session.sessionManager.getBranch())&&e.interactions.pending(e.session.sessionManager.getSessionId()).length===0}scheduleQueued(e){e.prompts.schedule(()=>this.queueReady(e),(i,r,n)=>this.prompt(e,i,r,n))}async updateQueuedPrompt(e,i,r){let n=this.active;if(this.disposed||!n||n.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(r.kind==="steer"&&n.session.isIdle)throw new Me("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await n.prompts.update(e,i,r,(s,a,o)=>this.prompt(n,s,a,o,"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(vn),await e.session.abort(),this.active===e&&!e.closing&&this.publish({type:"snapshot",session:this.snapshotOf(e)}))}async resume(e){let i=this.active;if(this.disposed||!i||i.closing)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");ur(()=>this.hosted?.adapter.assertAdmission(),e,this.reportError);let r=i.session;if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!lr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");if(!r.model)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!(r.modelRuntime.hasConfiguredAuth(r.model.provider)||await r.modelRuntime.checkAuth(r.model.provider)!==void 0))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");if(this.active!==i||i.closing)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");if(!r.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!lr(r.sessionManager.getBranch()))throw new Error("\u5F53\u524D\u4F1A\u8BDD\u6CA1\u6709\u6682\u505C\u7684\u4EFB\u52A1");let s=ca(this.snapshotOf(i).messages);i.operation=e,i.agentErrorReported=!1,this.telemetry.breadcrumb("resume",{...e}),r.sendCustomMessage(s,{triggerTurn:!0}).catch(a=>{if(!this.disposed&&!i.closing&&!i.agentErrorReported){let o=this.reportError(Tt(a,"Agent resume failed"),{...e,stage:"agent",code:"agent_failed"});this.publishFor(i,{type:"error",message:a instanceof Error?a.message:"\u7EE7\u7EED\u5931\u8D25",errorId:o,...e})}})}async models(){return(await this.session?.modelRuntime.getAvailable()??[]).map(i=>({provider:i.provider,id:i.id,name:i.name}))}async setModel(e,i){let r=this.active;if(this.disposed||!r||r.closing||!r.session.isIdle||r.prompts.sending)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let n=r.session.modelRuntime.getModel(e,i);if(!n)throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");await r.session.setModel(n),this.publishFor(r,{type:"snapshot",session:this.snapshotOf(r)})}createDetached(e,i,r){return this.queue.run(async()=>{this.ensureAvailable();let n=await kt(e),s=mr.create(n);return await this.replace(n,s,"new",i),this.runtimes.get(s.getSessionId()).session.setSessionName(r),s.getSessionId()})}detachedRuntime(e){let i=this.runtimes.get(e);return!this.disposed&&i?.detached&&!i.closing?i:null}detachedOwner(e){return this.detachedRuntime(e)?.detached.owner??null}detachedCount(e){return[...this.runtimes.values()].filter(i=>i.detached?.owner===e&&!i.closing).length}async sendDetached(e,i,r){let n=this.detachedRuntime(e);if(!n)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");if(r&&n.detached.restoreTools&&(n.session.setActiveToolsByName(n.detached.restoreTools),n.detached.restoreTools=null),!n.session.isIdle||n.prompts.length>0){n.prompts.enqueue(i,[],void 0),this.scheduleQueued(n);return}await this.prompt(n,i,[])}async abortDetached(e){await this.detachedRuntime(e)?.session.abort()}releaseDetached(e){return this.queue.run(async()=>{let i=this.detachedRuntime(e);i&&(this.runtimes.delete(e),this.active===i&&(this.active=null),await this.close(i,"quit"),this.onSessionsChanged())})}detachedEvents(e,i){let r=this.detachedRuntime(e)?.detached;if(!r)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");return{events:r.events.filter(n=>n.seq>i),next:r.seq}}dispose(){return this.disposed=!0,this.offHosted?.(),this.queue.run(async()=>{let e=[...this.runtimes.values()];this.active=null,this.runtimes.clear(),this.selectedByWorkspace.clear(),await Promise.all(e.map(i=>this.close(i,"quit")))})}};import{basename as mp,dirname as Tx}from"node:path";function _v(t,e){let i=r=>e[r].map(n=>({name:r==="skills"&&mp(n.path).toLowerCase()==="skill.md"?mp(Tx(n.path)):mp(n.path),path:n.path,source:n.metadata.source,scope:n.metadata.scope,enabled:n.enabled}));return{packages:t.map(r=>({name:r.source,path:r.installedPath??"",source:r.source,scope:r.scope,enabled:!!r.installedPath})),extensions:i("extensions"),skills:i("skills")}}import{execFile as Ix}from"node:child_process";var Ax=(t,e)=>new Promise((i,r)=>{Ix(t,[...e],{windowsHide:!0},n=>{n?r(n):i()})});async function gp(t,e=process.platform,i=process.env,r=Ax){if(i.PI_WEBAPP_AUTO_OPEN==="0"||i.PI_WEBAPP_RUNTIME==="desktop"||i.SSH_CONNECTION||i.SSH_TTY||i.SSH_CLIENT||e==="linux"&&!i.DISPLAY&&!i.WAYLAND_DISPLAY)return!1;let n=e==="darwin"?"open":e==="linux"?"xdg-open":e==="win32"?"explorer.exe":null;return n===null?!1:(await r(n,[t]),!0)}import{execFile as EO}from"node:child_process";import{randomUUID as Pp}from"node:crypto";import{existsSync as Yv}from"node:fs";import{access as TO,mkdir as An,mkdtemp as IO,readFile as ni,realpath as AO,rename as Qv,rm as Jv,writeFile as Xv}from"node:fs/promises";import{join as pe}from"node:path";import{createHash as yp}from"node:crypto";import{readdir as Dx,realpath as Tv,rename as Lx,stat as Ux}from"node:fs/promises";import{join as ri}from"node:path";import{constants as fp}from"node:fs";import{DatabaseSync as xx}from"node:sqlite";import{lstat as Sv,mkdir as Ox,open as En,rename as Rx,unlink as kv}from"node:fs/promises";import{dirname as Nx,join as vv,resolve as Px}from"node:path";import{randomUUID as Cx}from"node:crypto";import{setTimeout as Mx}from"node:timers/promises";async function ve(t){await Ox(t,{recursive:!0,mode:448});let e=await Sv(t);if(!e.isDirectory()||e.isSymbolicLink())throw new y("invalid_storage","Plugin storage must be a real directory")}async function fe(t,e){let i;try{i=await En(t,fp.O_RDONLY|fp.O_NONBLOCK|(fp.O_NOFOLLOW??0))}catch(r){if(Zt(r))return null;throw r}try{let r=await i.stat();if(!r.isFile()||r.nlink>1||r.size>e)throw new y("invalid_storage","Invalid storage record size or type");let n=Buffer.alloc(Math.min(r.size+1,e+1)),s=0;for(;s<n.length;){let a=await i.read(n,s,n.length-s,s);if(!a.bytesRead)break;s+=a.bytesRead}if(s>e||s!==r.size)throw new y("invalid_storage","Storage record changed during read");return n.subarray(0,s)}finally{await i.close()}}async function we(t,e=2*1024*1024){let i=await fe(t,e);if(!i)return null;try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i))}catch{throw new y("invalid_storage","Invalid JSON storage record; original bytes preserved")}}async function ze(t){let e=await fe(t,2097152);if(e===null)return null;let i;try{i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new y("gc_recovery_required",`Invalid journal ${t}; stop all owners and inspect original bytes`)}if(!i||typeof i!="object"||Array.isArray(i))throw new y("gc_recovery_required",`Invalid journal ${t}; original bytes preserved`);return i}async function Z(t,e){let i=`${t}.${Cx()}.tmp`,r=await En(i,"wx",384);try{try{await r.writeFile(JSON.stringify(e)),await r.sync()}finally{await r.close()}await Rx(i,t);let n;try{n=await En(Nx(t),"r"),await n.sync()}catch(s){if(!["EINVAL","EPERM","EACCES","EISDIR","ENOTSUP","EBADF"].includes(s.code??""))throw s}finally{await n?.close()}}finally{await kv(i).catch(()=>{})}}var Ev='{"version":2,"mechanism":"sqlite-exclusive"}',wv=t=>t.toString("utf8")===Ev,ua=new Set;async function hp(t,e,i=0){await ve(t);let r=vv(t,`${e}.lock`),n=vv(t,`${e}.ownership.sqlite`),s=e==="runtime"?"runtime_owned":"storage_busy",a=()=>new y(s,"Another host owns this plugin storage or a legacy ownership lock remains; stop all owners and verify a backup before offline recovery"),o;try{o=await En(n,"wx",384)}catch(f){if(f.code!=="EEXIST")throw f}finally{await o?.close()}let l=await Sv(n);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size>1024*1024)throw new y("invalid_storage","Ownership database must be a small, single-link regular file");let c=new xx(n,{allowExtension:!1}),p=Px(n),d=Date.now()+i,m=!1;try{for(;;){if(!ua.has(p))try{c.exec("BEGIN EXCLUSIVE"),ua.add(p),m=!0;break}catch(h){if(h.errcode!==5)throw h}if(Date.now()>=d)throw new y(s,"Another host owns this plugin storage; wait for it to stop before retrying");await Mx(10)}let f=await fe(r,4096);if(f===null){let h;try{h=await En(r,"wx",384),await h.writeFile(Ev),await h.sync()}catch(_){if(_.code!=="EEXIST")throw _}finally{await h?.close()}f=await fe(r,4096)}if(f===null||!wv(f))throw a()}catch(f){throw c.close(),m&&ua.delete(p),f}let g=!1;return async()=>{if(g)return;let f=await fe(r,4096);if(f===null||!wv(f))throw new y("invalid_storage","Ownership fence changed while held; preserve custody and inspect storage");await kv(r),c.close(),ua.delete(p),g=!0}}async function Se(t,e,i=2e3){let r=await hp(t,"transaction",i);try{return await e()}finally{await r()}}var ma=t=>ri(t,"host-pair"),qx=t=>yp("sha256").update(JSON.stringify(t)).digest("hex"),jx=10*6e4;async function Bx(t){let e=yp("sha256"),i=0,r=0;async function n(s){let a=(await Dx(ri(t,s),{withFileTypes:!0})).sort((o,l)=>o.name<l.name?-1:o.name>l.name?1:0);for(let o of a){if(!s&&o.name==="node_modules")continue;let l=s?`${s}/${o.name}`:o.name;if(o.isSymbolicLink()||!o.isFile()&&!o.isDirectory())throw new y("host_pair_required","Candidate package contains non-regular resources");if(++i>1e4)throw new y("host_pair_required","Candidate package resource budget exceeded");if(o.isDirectory()){await n(l);continue}let c=await fe(ri(t,l),64*1024*1024);if(!c||(r+=c.length)>256*1024*1024)throw new y("host_pair_required","Candidate package byte budget exceeded");e.update(JSON.stringify([l,yp("sha256").update(c).digest("hex")]))}}return await n(""),e.digest("hex")}async function bp(t,e){let i=await Tv(e),r=ri(e,"dist","hosted-worker.js");if(await Tv(r)!==ri(i,"dist","hosted-worker.js"))throw new y("host_pair_required","Candidate worker must remain inside the staged host");let n=await fe(ri(e,"package.json"),512*1024);if(!n)throw new y("host_pair_required","Candidate package metadata missing");let s=JSON.parse(n.toString("utf8")),a=s.piWebappHostedRuntime;if(s.name!=="pi-webapp"||s.version!==t||a?.protocol!==2||a?.runtimeProtocol!==1||a?.pairJournal!==1||a?.ownershipProtocol!==2||!Array.isArray(a?.capabilities)||!["state","workspace","legacy","panels","messages"].every(l=>a.capabilities.includes(l)))throw new y("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 o=await fe(r,32*1024*1024);if(!o)throw new y("host_pair_required","Candidate worker missing");return qx([n.toString("base64"),o.toString("base64"),await Bx(e)])}async function ga(t){await Lx(t,`${t}.corrupt-${Date.now()}`).catch(e=>{if(e.code!=="ENOENT")throw e})}var Fx=t=>t.schema===1&&/^[a-f0-9-]{36}$/.test(t.id)&&typeof t.version=="string"&&typeof t.packageRoot=="string"&&/^[a-f0-9]{64}$/.test(t.hostDigest)&&/^[a-f0-9]{64}$/.test(t.fingerprint)&&Array.isArray(t.selections)&&!t.selections.some(e=>!e||typeof e.id!="string"||typeof e.version!="string"||!/^[a-f0-9]{64}$/.test(e.digest)||!Object.hasOwn(e,"before"))&&!(t.selection&&(typeof t.selection.path!="string"||!/^[a-f0-9]{64}$/.test(t.selection.digest)))&&["prepared","selecting","selected","restart-requested","reconciled","cancelled","required-action"].includes(t.phase);async function _p(t){let e=ri(ma(t),"intent.json"),i,r=!0;try{i=await ze(e)}catch{i=null,r=!1}if(!r||i&&!Fx(i))return await ga(e),null;if(i){let{lifecyclePhase:n,...s}=i,a=typeof s.updatedAt=="string"&&!Number.isNaN(Date.parse(s.updatedAt))?s.updatedAt:await Ux(e).then(o=>o.mtime.toISOString(),()=>new Date(0).toISOString());i={...s,updatedAt:a,phase:s.phase==="selected"&&n==="restart-requested"?"restart-requested":s.phase==="reconciled"&&n==="cancelled"?"cancelled":s.phase==="reconciled"&&n==="required-action"?"required-action":s.phase}}return i}async function fa(t,e){let{lifecyclePhase:i,...r}={...e,selections:[],updatedAt:new Date().toISOString()},n=r.phase==="cancelled"?{...r,phase:"reconciled",lifecyclePhase:"cancelled"}:r.phase==="required-action"?{...r,phase:"reconciled",lifecyclePhase:"required-action"}:r.phase==="restart-requested"?{...r,phase:"selected",lifecyclePhase:"restart-requested"}:r;await Z(ri(ma(t),"intent.json"),n)}var vp=t=>t&&["selecting","selected","restart-requested"].includes(t.phase),Iv=(t,e=Date.now())=>!!t&&!!vp(t)&&e-Date.parse(t.updatedAt??"")<jx;import{promisify as xO}from"node:util";import{realpathSync as Ov,statSync as Hx}from"node:fs";import{basename as Gx,delimiter as Wx,dirname as Av,join as wp,resolve as $x}from"node:path";function xv(t){if(!t)return null;try{let e=Ov(t);return Gx(e)==="npm-cli.js"&&Hx(e).isFile()?e:null}catch{return null}}function Vx({execPath:t=process.execPath,env:e=process.env}={}){let i=xv(e.npm_execpath);if(i)return i;let r=new Set([Av(t)]);try{r.add(Av(Ov(t)))}catch{}let n=Object.entries(e).find(([s])=>s.toLowerCase()==="path")?.[1]??"";for(let s of n.split(Wx).filter(Boolean))r.add($x(s));for(let s of r)for(let a of[wp(s,"node_modules","npm","bin","npm-cli.js"),wp(s,"..","lib","node_modules","npm","bin","npm-cli.js"),wp(s,"npm")]){let o=xv(a);if(o)return o}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 Rv(t){return{file:process.execPath,args:[Vx(),...t]}}import{randomUUID as zx}from"node:crypto";import{mkdir as Cv,readFile as Kx,rename as kp,rm as Yx,unlink as pV,writeFile as Qx}from"node:fs/promises";import{isAbsolute as Nv,join as Tn}from"node:path";var Ep=1,Jx=1440*6e4,ha=t=>Tn(t,"pi-web","upgrade"),Tp=t=>Tn(ha(t),"candidate.json"),Xx=t=>Tn(ha(t),"transaction.json"),Pv=t=>Tn(ha(t),"history"),Mv=/^[a-f0-9-]{36}$/i;async function Zx(t,e){let i=`${t}.${zx()}.tmp`;try{await Qx(i,e,{mode:384}),await kp(i,t)}finally{await Yx(i,{force:!0})}}var eO=(t,e)=>Zx(t,JSON.stringify(e));async function Sp(t,e){await kp(t,`${t}.${e}-${Date.now()}`).catch(i=>{if(i?.code!=="ENOENT")throw i})}async function Dv(t,e,i=()=>!1){let r;try{r=JSON.parse(await Kx(t,"utf8"))}catch(n){return n?.code==="ENOENT"||await Sp(t,"invalid"),null}return e(r)?i(r)?(await Sp(t,"expired"),null):r:(await Sp(t,"invalid"),null)}function Lv(t){if(!t||typeof t!="object"||t.schema!==Ep||!Mv.test(t.id??""))return!1;try{St(t.version)}catch{return!1}return typeof t.launcher=="string"&&Nv(t.launcher)&&typeof t.packageRoot=="string"&&Nv(t.packageRoot)&&["stable","alpha"].includes(t.channel)&&typeof t.downgrade=="boolean"&&!Number.isNaN(Date.parse(t.createdAt??""))}async function ya(t,e=Date.now()){return Dv(Tp(t),Lv,i=>e-Date.parse(i.createdAt)>Jx)}async function Uv(t,e){let i={schema:Ep,createdAt:new Date().toISOString(),...e};if(!Lv(i))throw new Error("Invalid upgrade candidate");return await Cv(ha(t),{recursive:!0,mode:448}),await eO(Tp(t),i),i}async function Ip(t,e,i){let r=await ya(t);!r||e&&r.id!==e||(await Cv(Pv(t),{recursive:!0,mode:448}),await kp(Tp(t),Tn(Pv(t),`${r.id}-candidate-${i}.json`)).catch(n=>{if(n?.code!=="ENOENT")throw n}))}var tO=["selected","committed","rolled-back"];function iO(t){return!!t&&typeof t=="object"&&t.schema===Ep&&Mv.test(t.id??"")&&tO.includes(t.phase)&&typeof t.version=="string"&&typeof t.from=="string"&&!Number.isNaN(Date.parse(t.updatedAt??""))}async function qv(t){return Dv(Xx(t),iO)}import{readFile as rO,rename as nO,writeFile as sO,unlink as aO}from"node:fs/promises";import{join as oO}from"node:path";import{randomUUID as lO}from"node:crypto";var Ap=1,jv=t=>oO(t,"pi-web","launcher-handoff.json");function Bv(t){return t?.protocol===Ap&&typeof t.nonce=="string"&&t.nonce.length>0&&/^[a-f0-9-]{36}$/i.test(t.requestId)&&Number.isSafeInteger(t.pid)&&t.pid>0&&["requested","draining","stopped","refused","failed"].includes(t.phase)}async function xp(t){try{let e=JSON.parse(await rO(jv(t),"utf8"));if(!Bv(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 cO(t,e){let i=`${t}.${lO()}.tmp`;try{await sO(i,JSON.stringify(e),{mode:384}),await nO(i,t)}finally{await aO(i).catch(()=>{})}}async function Fv(t,e){if(!Bv(e))throw new Error("Invalid launcher handoff receipt");await cO(jv(t),e)}import{execFile as pO}from"node:child_process";import{cp as dO,readFile as Op,realpath as uO,rm as mO}from"node:fs/promises";import{join as gr,sep as gO}from"node:path";import{promisify as fO}from"node:util";var Hv=fO(pO),Rp=["@earendil-works/pi-coding-agent","@earendil-works/pi-ai"];function Np(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");let e=t;return Rp.map(i=>{let r=e[i];if(typeof r!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(r))throw new Error("\u65B0\u7248 Pi SDK \u5FC5\u987B\u58F0\u660E\u7ECF\u8FC7\u9A8C\u8BC1\u7684\u7CBE\u786E\u7248\u672C");return`${i}@${r}`})}async function ba(t){return Promise.all(Rp.map(async e=>{let i=await or(t,e),r=JSON.parse(await Op(gr(i,"package.json"),"utf8"));if(!/^\d+\.\d+\.\d+$/.test(r.version))throw new Error("\u968F\u5305 Pi \u7248\u672C\u65E0\u6548\uFF0C\u8BF7\u66F4\u65B0\u684C\u9762\u5916\u58F3");return`${e}@${r.version}`}))}async function Gv(t,e){let i=JSON.parse(await Op(gr(e,"package.json"),"utf8"));if(i.name!=="pi-webapp")throw new Error("\u65B0\u7248\u4E1A\u52A1\u5305\u5143\u6570\u636E\u65E0\u6548");let r=i.peerDependencies===void 0?await ba(t):Np(i.peerDependencies);if(JSON.stringify(await ba(e))!==JSON.stringify(r))throw new Error("\u65B0\u7248 Pi SDK \u5B89\u88C5\u7248\u672C\u4E0E\u4E1A\u52A1\u5305\u58F0\u660E\u4E0D\u7B26\uFF0C\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");let n=await or(t,"node-pty"),s=await or(e,"node-pty"),a=await uO(gr(e,"../.."));if(n===s||!s.startsWith(a+gO))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u4F9D\u8D56\u4E0D\u5728\u72EC\u7ACB\u66F4\u65B0\u76EE\u5F55\u5185");let o=async d=>JSON.parse(await Op(gr(d,"package.json"),"utf8")).version;if(await o(n)!==await o(s))throw new Error("\u65B0\u7248\u7EC8\u7AEF\u539F\u751F\u4F9D\u8D56\u9700\u8981\u66F4\u65B0\u684C\u9762\u5916\u58F3\uFF1B\u5F53\u524D\u5E94\u7528\u672A\u4FEE\u6539");await mO(s,{recursive:!0,force:!0}),await dO(n,s,{recursive:!0});let l={...process.env};delete l.NODE_OPTIONS,delete l.NODE_PATH,delete l.ELECTRON_RUN_AS_NODE,await Hv(process.execPath,[gr(e,"desktop","check-pty.cjs")],{cwd:e,env:l,timeout:2e4,maxBuffer:1024*1024,windowsHide:!0});let c=await or(e,Rp[0]),{stdout:p}=await Hv(process.execPath,[gr(c,"dist","bundle","cli.js"),"--version"],{cwd:e,env:l,timeout:3e4,maxBuffer:1024*1024,windowsHide:!0});if(p.trim()!==r[0].split("@").at(-1))throw new Error("\u65B0\u7248 Pi CLI \u7248\u672C\u6821\u9A8C\u5931\u8D25\uFF0C\u5F53\u524D\u8FD0\u884C\u7248\u672C\u672A\u4FEE\u6539")}import{lstat as $v,readdir as Vv,readFile as hO,realpath as Wv,rm as yO}from"node:fs/promises";import{join as In,relative as bO,sep as zv}from"node:path";var _O=1440*6e4,vO=1024*1024,wO=4,SO=t=>t==="releases"||t==="history"||t.endsWith("-history");async function kO(t,e){let i=new Set,r=[...new Set(e.flatMap(a=>[a+zv,a+"/"]))],n=a=>{if(typeof a=="string")for(let o of r){let l=a.indexOf(o);l>=0&&i.add(a.slice(l+o.length).split(/[\\/]/)[0])}else Array.isArray(a)?a.forEach(n):a&&typeof a=="object"&&Object.values(a).forEach(n)},s=async(a,o)=>{let l=await Vv(a,{withFileTypes:!0}).catch(()=>[]);for(let c of l){let p=In(a,c.name);if(c.isDirectory()){o<wO&&!SO(c.name)&&await s(p,o+1);continue}if(!(!c.isFile()||!c.name.endsWith(".json")))try{if((await $v(p)).size>vO)continue;n(JSON.parse(await hO(p,"utf8")))}catch{}}};return await s(t,0),i}async function Kv(t){let e=In(t.agentDir,"pi-web"),i;try{i=await Wv(In(e,"releases"))}catch{return[]}let r=t.now??Date.now(),n=t.graceMs??_O,s=await kO(e,[In(e,"releases"),i]);try{let o=bO(i,await Wv(t.packageRoot));o&&!o.startsWith("..")&&s.add(o.split(zv)[0])}catch{}let a=[];for(let o of await Vv(i,{withFileTypes:!0}).catch(()=>[])){if(!o.isDirectory()||s.has(o.name))continue;let l=In(i,o.name);try{if(r-(await $v(l)).mtimeMs<n)continue;await yO(l,{recursive:!0,force:!0}),a.push(o.name)}catch{}}return a}var OO=xO(EO),fr=t=>["committed","cancelled","failed"].includes(t);function Zv(t){let e=t.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 RO(t,e){try{let i=Rv(t),{stdout:r}=await OO(i.file,i.args,{timeout:18e4,maxBuffer:1024*1024,encoding:"utf8",windowsHide:!0,signal:e});return r}catch(i){let r=i;throw new Error(r.stderr?.trim()||r.message)}}var _a=class{agentDir;packageRoot;launcherNonce;runNpm;desktopManaged;desktopPackageUpdates;desktopReleaseChannels;targetPeerSpecs;verifyPackage;pluginWarnings;prefetchPlugins;preparing=!1;preparation;cancellation;downloadAbort;savingPreference=!1;restartPending=!1;preparedUpdate;ownTransaction;beforeRestart;constructor(e){this.agentDir=e.agentDir,this.packageRoot=e.packageRoot,this.launcherNonce=e.launcherNonce,this.runNpm=e.runNpm??RO,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 i=>{let r=(await this.runNpm(["view",`pi-webapp@${i}`,"peerDependencies","--json","--prefer-online"],this.downloadAbort?.signal)).trim();if(!r)return ba(this.packageRoot);let n=JSON.parse(r),s=Array.isArray(n)&&n.length===1?n[0]:n;return Np(s)},this.verifyPackage=e.verifyPackage??Gv,this.pluginWarnings=e.pluginWarnings,this.prefetchPlugins=e.prefetchPlugins,this.beforeRestart=e.beforeRestart}launcherIdentity(){return{version:process.env.PI_WEBAPP_LAUNCHER_VERSION??"unknown",desktopShell:{version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"},packageUpdates:this.desktopPackageUpdates,releaseChannels:this.desktopReleaseChannels,handoffProtocol:process.env.PI_WEBAPP_LAUNCHER_HANDOFF_PROTOCOL==="1"?Ap:0}}async requestLauncherHandoff(e,i){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(i))throw new Error("Invalid handoff request identity");if(this.preparing||this.restartPending||this.savingPreference||this.cancellation||this.preparedUpdate)throw new Error("\u5347\u7EA7\u6216\u542F\u52A8\u5668\u4EA4\u63A5\u6B63\u5728\u8FDB\u884C\u4E2D");await this.runningVersion();let r=await this.transaction();if(r&&!fr(r.phase))throw new Error("\u8BF7\u5148\u5B8C\u6210\u6216\u53D6\u6D88\u672A\u5B8C\u6210\u7684\u4E1A\u52A1\u5305\u66F4\u65B0\uFF0C\u518D\u4EA4\u63A5\u542F\u52A8\u5668");let n=pe(this.agentDir,"pi-web","launcher.json"),s=JSON.parse(await ni(n,"utf8")),a=p=>p.nonce===e&&p.pid===s.pid&&p.runtimeKind==="desktop"&&p.launcherHandoffProtocol===1;if(!a(s))throw new Error("\u540E\u53F0\u542F\u52A8\u5668\u8EAB\u4EFD\u5DF2\u53D8\u5316\uFF0C\u4EA4\u63A5\u672A\u6267\u884C");let o=await xp(this.agentDir);if(o?.nonce===e&&["requested","draining"].includes(o.phase))throw new Error("\u542F\u52A8\u5668\u4EA4\u63A5\u5C1A\u672A\u5B8C\u6210\uFF0C\u8BF7\u4FDD\u7559\u5F53\u524D\u7A97\u53E3");let l,c=!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(l=await this.beforeRestart(),!a(JSON.parse(await ni(n,"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:i,pid:s.pid,phase:"requested"};try{await Fv(this.agentDir,p),c=!0}catch(d){let m=await xp(this.agentDir).catch(()=>null);if(c=m?.nonce===e&&m?.requestId===i&&["requested","draining","stopped"].includes(m.phase),!c)throw d}this.restartPending=!0}finally{!c&&l&&await l()}}async current(){let e=JSON.parse(await ni(pe(this.packageRoot,"package.json"),"utf8"));if(e.name!=="pi-webapp")throw new Error("\u5F53\u524D pi-webapp \u7248\u672C\u65E0\u6548");return St(e.version),e.version}async pruneReleases(){if(this.preparing||this.preparedUpdate||this.restartPending||this.cancellation)return[];let e=await this.transaction();return e&&!fr(e.phase)?[]:Kv({agentDir:this.agentDir,packageRoot:this.packageRoot})}async runningVersion(){let e=await this.current(),i=await this.transaction();if(!i||fr(i.phase)||i.id===this.ownTransaction)return e;if(i.version===e&&["selecting","selected","restart-requested"].includes(i.phase))await this.record({...i,phase:"committed",message:"Selected version is running"});else if(i.phase==="restart-requested"){let r=await qv(this.agentDir);await this.record({...i,phase:"failed",message:r?.id===i.id&&r.phase==="rolled-back"&&r.message?r.message:"The launcher did not start the new version; current version kept"})}else await Ip(this.agentDir,i.id,"superseded"),await this.record({...i,phase:"failed",message:`Interrupted while ${i.phase} in an earlier run; superseded, current version kept`});return e}get transactionPath(){return pe(this.agentDir,"pi-web","update-transaction.json")}async transaction(){let e;try{e=await ze(this.transactionPath)}catch{return await ga(this.transactionPath),null}return e?e.schema!==1||!/^[a-f0-9-]{36}$/.test(e.id)||typeof e.version!="string"||!["stable","alpha"].includes(e.channel)||!["downloading","validating","prepared","selecting","selected","restart-requested","committed","cancelled","failed"].includes(e.phase)||typeof e.selectionPath!="string"?(await ga(this.transactionPath),null):e:null}async record(e){if(await An(pe(this.agentDir,"pi-web"),{recursive:!0}),await Z(this.transactionPath,e),fr(e.phase)){let i=pe(this.agentDir,"pi-web","update-history");await An(i,{recursive:!0}),await Z(pe(i,`${e.id}-${e.phase}.json`),e)}}async cancel(){if(this.cancellation)return this.cancellation;let e=this.cancelUpdate();this.cancellation=e;try{await e}finally{this.cancellation=void 0}}async cancelUpdate(){if(this.savingPreference)throw new Error("\u504F\u597D\u4FDD\u5B58\u4E2D\uFF0C\u8BF7\u7A0D\u540E\u53D6\u6D88");if(this.restartPending)throw new Error("\u91CD\u542F\u5DF2\u4EA4\u7ED9\u542F\u52A8\u5668\uFF1B\u65B0\u7248\u672C\u542F\u52A8\u5931\u8D25\u65F6\u4F1A\u81EA\u52A8\u6062\u590D\u5F53\u524D\u7248\u672C");this.preparing&&(this.downloadAbort?.abort(new Error("Update cancelled")),await this.preparation?.catch(()=>{}));let e=await this.transaction(),i=await ya(this.agentDir);i&&(!e||i.id===e.id)&&await Ip(this.agentDir,i.id,"cancelled"),e&&!fr(e.phase)&&await this.record({...e,phase:"cancelled",message:"\u66F4\u65B0\u5DF2\u53D6\u6D88\uFF1B\u539F\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559"}),this.preparedUpdate=void 0}get preferencePath(){return pe(this.agentDir,"pi-web","update-preferences.json")}async channel(){try{let e=JSON.parse(await ni(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 i=`${this.preferencePath}.${Pp()}.tmp`;try{await An(pe(this.agentDir,"pi-web"),{recursive:!0}),await Xv(i,JSON.stringify({channel:e}),{mode:384}),await Qv(i,this.preferencePath)}finally{this.savingPreference=!1,await Jv(i,{force:!0})}return{channel:e}}async check(){let e=await this.runningVersion(),i=await this.channel(),r=Yv(pe(this.packageRoot,".git")),n={current:e,channel:i,latest:null,available:!1,canRestart:!!this.launcherNonce&&!r};this.desktopManaged&&(n.launcher=this.launcherIdentity(),n.launcherHandoff={supported:n.launcher.handoffProtocol===1,required:!this.desktopReleaseChannels}),this.desktopManaged&&(n.desktopShell={version:process.env.PI_WEBAPP_DESKTOP_VERSION??"unknown",build:process.env.PI_WEBAPP_DESKTOP_BUILD??"unknown"});let s=await this.transaction();if(s&&!fr(s.phase)?n.recovery={version:s.version,phase:s.phase,canCancel:s.phase!=="restart-requested"}:s?.phase==="failed"&&s.message&&(n.lastFailure={version:s.version,message:s.message}),this.desktopManaged&&!this.desktopPackageUpdates)return{...n,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&&i==="alpha"&&!this.desktopReleaseChannels)return{...n,canRestart:!1,reason:n.launcherHandoff?.supported?"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u5DF2\u5B89\u88C5 build 14 \u6216\u66F4\u65B0\u684C\u9762\u65F6\uFF0C\u8BF7\u4F7F\u7528\u83DC\u5355\u300Cpi \u2192 \u5B89\u5168\u5207\u6362\u5230\u5F53\u524D\u684C\u9762\u542F\u52A8\u5668\u2026\u300D\u5B8C\u6210\u4EA4\u63A5\uFF0C\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002":"\u5F53\u524D\u540E\u53F0\u4ECD\u7531\u65E7\u684C\u9762\u542F\u52A8\u5668\u7BA1\u7406\uFF0C\u5C1A\u4E0D\u652F\u6301\u4F53\u9A8C\u7248\u6301\u4E45\u5316\u3002\u8BF7\u5148\u5207\u56DE\u7A33\u5B9A\u7248\u5E76\u5347\u7EA7\u4E1A\u52A1\u5305\uFF0C\u518D\u4F7F\u7528 build 14 \u6216\u66F4\u65B0\u684C\u9762\u83DC\u5355\u5B89\u5168\u5207\u6362\u542F\u52A8\u5668\uFF1B\u5DF2\u5B89\u88C5\u65B0\u7248\u684C\u9762\u65E0\u9700\u91CD\u590D\u5B89\u88C5\u3002"};r?n.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":n.canRestart||(n.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&&n.canRestart&&(n.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 a=JSON.parse((await this.runNpm(["view","pi-webapp",i==="alpha"?"dist-tags":"dist-tags.latest","--json","--prefer-online"])).trim()),o=Array.isArray(a)&&a.length===1?a[0]:a,l=i==="alpha"?o:{latest:o};if(!l||!I_(l.latest))throw new Error("npm \u8FD4\u56DE\u7684\u7248\u672C\u53F7\u65E0\u6548");let c=l.latest;if(i==="alpha"&&l.alpha!==void 0){if(!ea(l.alpha))throw new Error("npm \u8FD4\u56DE\u7684 alpha \u7248\u672C\u53F7\u65E0\u6548");Ve(l.alpha,c)>0&&(c=l.alpha)}if(n.latest=c,n.downgrade=Ve(c,e)<0,n.available=i==="stable"?Ve(c,e)!==0:Ve(c,e)>0,n.available&&this.pluginWarnings){let p=await this.pluginWarnings(c).catch(()=>[]);p.length&&(n.pluginWarnings=p)}this.desktopManaged&&n.downgrade&&!this.desktopReleaseChannels&&Ve(c,process.env.PI_WEBAPP_DESKTOP_VERSION??e)<0&&(n.canRestart=!1,n.requiresDesktopUpgrade=!0,n.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(a){throw new Error(`\u68C0\u67E5 npm \u66F4\u65B0\u5931\u8D25\uFF1A${a instanceof Error?a.message:String(a)}`)}return n}async prepare(e){if(this.preparation)throw new Error("\u5347\u7EA7\u51C6\u5907\u6B63\u5728\u8FDB\u884C\u4E2D");let i=this.prepareUpdate(e);this.preparation=i;try{return await i}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(Yv(pe(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 i=await this.check();if(e.channel!==i.channel||e.version!==i.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 i=await this.check();if(e&&(e.channel!==i.channel||e.version!==i.latest))throw new Error("\u66F4\u65B0\u76EE\u6807\u6216\u504F\u597D\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");if(!i.canRestart)throw new Error(i.reason??"\u5F53\u524D\u8FD0\u884C\u65B9\u5F0F\u4E0D\u652F\u6301\u66F4\u65B0");if(!i.available||!i.latest)throw new Error("\u5F53\u524D\u5DF2\u662F\u6700\u65B0\u7248\u672C");if(i.downgrade&&(e?.allowDowngrade!==!0||e.channel!=="stable"))throw new Error("\u5207\u56DE\u8F83\u4F4E\u7248\u672C\u9700\u660E\u786E\u786E\u8BA4\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u4E2D\u9009\u62E9\u7A33\u5B9A\u7248\u540E\u91CD\u8BD5");let r=pe(this.agentDir,"pi-web","releases");await An(r,{recursive:!0});let n=await IO(pe(await AO(r),`${i.latest}-`)),s=pe(this.agentDir,"pi-web",this.desktopManaged?"desktop-update.json":"update.json"),a={schema:1,id:Pp(),phase:"downloading",version:i.latest,channel:i.channel??"stable",selectionPath:s,ownerNonce:this.launcherNonce};this.ownTransaction=a.id,await this.record(a);try{let o=this.desktopManaged?await this.targetPeerSpecs(i.latest):[];await this.runNpm(["install",`pi-webapp@${i.latest}`,...o,"--prefix",n,"--ignore-scripts","--no-save","--no-audit","--no-fund",...this.desktopManaged?["--engine-strict"]:[]],this.downloadAbort.signal),this.downloadAbort.signal.throwIfAborted();let l=pe(n,"node_modules","pi-webapp");a={...a,phase:"validating",packageRoot:l},await this.record(a);let c=JSON.parse(await ni(pe(l,"package.json"),"utf8"));if(c.name!=="pi-webapp"||c.version!==i.latest)throw new Error("\u4E0B\u8F7D\u7684\u5305\u4E0E\u76EE\u6807\u7248\u672C\u4E0D\u7B26");let p=JSON.parse(await ni(pe(this.packageRoot,"package.json"),"utf8"));if(i.downgrade&&Zv(c)!==Zv(p))throw new Error("\u6570\u636E\u683C\u5F0F\u4E0D\u517C\u5BB9\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5207\u56DE\u65E7\u7248\u3002\u8BF7\u5148\u5907\u4EFD\u5E76\u6309\u6062\u590D\u6307\u5357\u64CD\u4F5C\u3002");let d=pe(l,"bin","pi-webapp.mjs");return await Promise.all([d,pe(l,"dist","extension.js"),pe(l,"web","dist","index.html")].map(m=>TO(m))),this.desktopManaged&&(await Jc(this.agentDir,{version:i.latest,launcher:d,desktopProtocolVersion:ei}),await this.verifyPackage(this.packageRoot,l)),await this.prefetchPlugins?.(i.latest,this.downloadAbort.signal).catch(()=>{}),this.downloadAbort.signal.throwIfAborted(),await Uv(this.agentDir,{id:a.id,version:i.latest,launcher:d,packageRoot:l,channel:i.channel??"stable",downgrade:!!i.downgrade}),a={...a,phase:"prepared"},await this.record(a),this.preparedUpdate={id:a.id,update:{version:i.latest,launcher:d},channel:i.channel??"stable"},{version:i.latest,launcher:d}}catch(o){await Jv(n,{recursive:!0,force:!0});let l=(o instanceof Error?o.message:String(o)).slice(0,500);throw await this.record({...a,phase:this.downloadAbort.signal.aborted?"cancelled":"failed",message:this.downloadAbort.signal.aborted?"\u4E0B\u8F7D\u5DF2\u53D6\u6D88\uFF1B\u5F53\u524D\u7248\u672C\u53CA\u63D2\u4EF6\u6570\u636E\u4FDD\u7559":`\u4E0B\u8F7D\u6216\u9A8C\u8BC1\u5931\u8D25\uFF1A${l}\uFF1B\u5F53\u524D\u7248\u672C\u548C\u63D2\u4EF6\u6570\u636E\u4FDD\u7559`}),o}}finally{this.preparing=!1,this.downloadAbort=void 0}}async requestRestart(e,{force:i=!1}={}){if(this.desktopManaged&&!this.desktopPackageUpdates)throw new Error("\u5F53\u524D\u684C\u9762\u5E94\u7528\u4E0D\u652F\u6301\u4E1A\u52A1\u5305\u5728\u7EBF\u66F4\u65B0");if(!this.launcherNonce)throw new Error("\u5F53\u524D\u9875\u9762\u65E0\u6CD5\u81EA\u52A8\u91CD\u542F Pi");let r=this.preparedUpdate;if(!r||r.update.version!==e.version||r.update.launcher!==e.launcher)throw new Error("\u6CA1\u6709\u5DF2\u51C6\u5907\u7684\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let n,s=!1,a=pe(this.agentDir,"pi-web","launcher.restart");try{if(n=await this.beforeRestart?.(i),(await ya(this.agentDir))?.id!==r.id)throw new Error("\u66F4\u65B0\u5019\u9009\u5DF2\u8FC7\u671F\u6216\u88AB\u66FF\u6362\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0");let o=await this.transaction();o?.id===r.id&&await this.record({...o,phase:"restart-requested"});try{if(JSON.parse(await ni(a,"utf8"))?.nonce!==this.launcherNonce){let c=pe(this.agentDir,"pi-web","restart-history");await An(c,{recursive:!0,mode:448}),await Qv(a,pe(c,`stale-${Pp()}.json`))}}catch{}try{await Xv(a,JSON.stringify({nonce:this.launcherNonce,candidate:r.id}),{mode:384,flag:"wx"}),s=!0}catch(l){try{let c=JSON.parse(await ni(a,"utf8"));s=c.nonce===this.launcherNonce&&c.candidate===r.id}catch{}if(!s)throw l}this.restartPending=!0}catch(o){if(s){this.restartPending=!0;return}let l=await this.transaction();throw l?.id===r.id&&l.phase==="restart-requested"&&await this.record({...l,phase:"prepared"}),n&&await n(),o}}};import{createHash as Hw,randomUUID as BN}from"node:crypto";import{randomUUID as fN}from"node:crypto";import{join as Xp}from"node:path";import{randomUUID as iw}from"node:crypto";import{randomUUID as NO}from"node:crypto";function ew(t){let i=["on","registerTool","getAllTools","getActiveTools","setActiveTools"].filter(a=>typeof t[a]!="function").map(a=>String(a));if(i.length)return{supported:!1,missing:i};let r=`__pi_web_contract_${NO().replaceAll("-","")}`,n;try{if(n=t.getActiveTools(),!Array.isArray(n))throw new Error}catch{return{supported:!1,missing:["initialized-tool-registry"]}}let s={name:r,label:"Hosted capability check",description:"Internal inert capability check",parameters:{type:"object",properties:{}},exposure:"hidden",execute:async()=>{throw new Error("Hosted capability check is never executable")}};try{t.registerTool(s),t.setActiveTools([...n,r]),(t.getAllTools().find(o=>o.name===r)?.exposure!=="hidden"||t.getActiveTools().includes(r))&&i.push("hidden-tool-exposure");let a={type:"object",properties:{contract:{type:"boolean"}}};t.registerTool({...s,parameters:a}),t.getAllTools().find(o=>o.name===r)?.parameters!==a&&i.push("dynamic-tool-registry")}catch{i.push("tool-registry-contract")}finally{try{t.setActiveTools(n)}catch{i.push("active-tool-registry")}}return{supported:!i.length,missing:i}}var PO;function tw(){return PO??=CO().catch(()=>({supported:!1,missing:["sdk-execution-contract"]}))}async function CO(){let{createAgentSession:t,DefaultResourceLoader:e,SessionManager:i}=await import("@earendil-works/pi-coding-agent"),{createAssistantMessageEventStream:r}=await import("@earendil-works/pi-ai"),{mkdtemp:n,rm:s}=await import("node:fs/promises"),{tmpdir:a}=await import("node:os"),{join:o}=await import("node:path"),l=await n(o(a(),"pi-sdk-contract-")),c,p=[],d=0,m=0,g=!1,f=!1;try{let h=(C,N,G)=>({name:C,label:C,description:"Inert host SDK contract check",exposure:N,parameters:{type:"object",properties:{}},execute:G}),_=()=>({content:[],details:void 0}),S=new e({cwd:l,agentDir:l,noExtensions:!0,noSkills:!0,noPromptTemplates:!0,extensionFactories:[C=>{C.on("tool_call",N=>{if(N.toolName==="__contract_direct"&&(g=!!N.parentToolCallId),N.toolName==="__contract_protected")return{block:!0,reason:"Inert host permission check"}});for(let N of["hidden","model-only"])C.registerTool(h(`__contract_${N.replace("-","_")}`,N,async()=>(m++,_())));C.registerTool(h("__contract_protected","direct",async()=>(m++,_()))),C.registerTool(h("__contract_direct","direct",async()=>(d++,_()))),C.registerTool(h("__contract_driver","direct",async(N,G,P,I,x)=>{let L=await x.executeTool("__contract_hidden",{}),k=await x.executeTool("__contract_model_only",{}),b=await x.executeTool("__contract_direct",{}),j=await x.executeTool("__contract_protected",{});return(!L.isError||!k.isError)&&p.push("nested-tool-exposure"),(b.isError||d!==1)&&p.push("nested-tool-execution"),(!j.isError||m!==0)&&p.push("nested-tool-permission-guard"),g||p.push("nested-parent-identity"),f=!0,_()}))}]});await S.reload(),{session:c}=await t({cwd:l,agentDir:l,sessionManager:i.inMemory(l),resourceLoader:S}),await c.bindExtensions({mode:"print"});let E=c.modelRuntime.getModels("openai")[0];if(!E)return{supported:!1,missing:["sdk-model-contract"]};await c.modelRuntime.setRuntimeApiKey("openai","inert-sdk-contract-check"),await c.setModel(E);let A=0;c.agent.streamFunction=async C=>{let N=A++===0,G={role:"assistant",api:C.api,provider:C.provider,model:C.id,timestamp:Date.now(),content:N?[{type:"toolCall",id:"contract-parent",name:"__contract_driver",arguments:{}}]:[{type:"text",text:"Inert contract complete"}],stopReason:N?"toolUse":"stop",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}},P=r();return P.push({type:"start",partial:G}),P.push({type:"done",reason:N?"toolUse":"stop",message:G}),P.end(G),P};let D;try{await Promise.race([c.prompt("Inert in-memory SDK permission contract check"),new Promise((C,N)=>{D=setTimeout(()=>N(new Error("SDK permission contract check timed out")),5e3)})])}finally{clearTimeout(D)}return f||p.push("sdk-tool-context"),{supported:!p.length,missing:p}}finally{c?.dispose(),await s(l,{recursive:!0,force:!0})}}var va=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??=tw().then(e=>{this.sdkContract=e;for(let i of this.bindings)if(i.ready&&!i.disposed)try{this.publish(i)}catch{i.compatible=!1,i.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(i=>this.waiters.add(i))}async freeze(e=3e4){if(this.frozen)throw new Error("Hosted adapter already frozen");this.frozen=!0;let i;try{await Promise.race([this.until(()=>!this.frozen||[...this.bindings].every(r=>r.compatible===!1||!r.busy)),new Promise((r,n)=>{i=setTimeout(()=>n(Object.assign(new Error("Hosted agent settlement timed out; current chat admission restored"),{code:"agent_settlement_timeout"})),e)})])}catch(r){throw this.thaw(),r}finally{clearTimeout(i)}}thaw(){this.frozen=!1,this.notify();for(let e of this.admissionListeners)e()}extension(e){return async i=>{await this.verifyCompatibility(),this.install(i,e)}}mountTui(e,i){let r=this.install(e,i);r.ready=!0;try{this.publish(r)}catch(n){throw this.release(r),n}return()=>this.release(r)}install(e,i){let r={pi:e,scope:{...i},busy:!1,disposed:!1,ready:!1,handlers:[],owned:new Map,definitions:new Map};if(this.bindings.add(r),typeof e.on!="function")return r.compatible=!1,r.missing=["on"],r;let n=s=>{if(typeof s!="function")throw new Error("SDK event subscription cannot be released");r.handlers.push(s)};try{n(e.on("before_agent_start",async()=>{for(;this.frozen&&r.compatible!==!1&&!r.busy&&!r.disposed;)await new Promise(s=>this.waiters.add(s));if(r.disposed)throw new Error("Hosted session disposed");r.busy=r.compatible!==!1})),n(e.on("agent_settled",()=>{r.busy=!1,this.notify()})),n(e.on("tool_call",s=>{let a=r.owned.get(s.toolName);if(!a)return;let o=this.descriptors.get(a)?.find(l=>l.name===s.toolName);if(!o||!this.allowed(r,a,o,!!s.parentToolCallId))return{block:!0,reason:"Hosted tool denied by host policy"}})),n(e.on("session_start",()=>{r.ready=!0,this.publish(r)})),n(e.on("session_shutdown",()=>this.release(r)))}catch{for(let s of r.handlers)try{s()}catch{}r.handlers=[],r.compatible=!1,r.missing=["hosted-lifecycle-events"]}return r}attach(e){let i=[...this.bindings].find(r=>r.scope.sessionId===e.sessionManager.getSessionId()&&!r.session);if(!i)throw new Error("Hosted inline extension missing for this session");if(!e.isIdle)throw new Error("Cannot attach hosted adapter to a running session");i.session=e,i.ready=!0,i.off=e.subscribe(r=>{r.type==="agent_settled"&&(i.busy=!1,this.notify())});try{this.publish(i)}catch(r){throw this.release(i),r}return()=>this.release(i)}releasePending(e){for(let i of this.bindings)!i.session&&!i.ready&&i.scope.sessionId===e&&this.release(i)}release(e){if(!e.disposed){e.disposed=!0,e.off?.();for(let i of e.handlers)i();e.handlers.length=0,e.definitions.clear(),this.bindings.delete(e),this.notify()}}allowed(e,i,r,n=!1){let s=this.service.policy(i,e.scope);return this.sdkContract?.supported===!0&&e.compatible===!0&&s.enabled&&(!s.allowlist||s.allowlist.includes(r.name))&&(!s.planMode||r.readonly===!0)&&(!n||s.allowNested===!0)}change(e,i){if(!this.frozen||[...this.bindings].some(n=>n.busy))throw new Error("Descriptor changes require frozen agent_settled boundary");let r=structuredClone(i);this.validateChange(e,r),this.descriptors.set(e,r);for(let n of this.bindings)n.ready&&this.publish(n)}validateChange(e,i){for(let n of this.bindings)if(n.compatible!==!1)for(let[s,a]of n.owned)this.assertOwner(n,a,s);let r=new Set;for(let n of i){if(!n.name||!n.action||!n.parameters||n.parameters.type!=="object"||r.has(n.name))throw new Error("Invalid hosted tool descriptor");r.add(n.name);for(let[s,a]of this.descriptors)if(s!==e&&a.some(o=>o.name===n.name))throw new Error(`Hosted tool ownership conflict: ${n.name}`);for(let s of this.bindings)s.compatible!==!1&&this.assertOwner(s,e,n.name)}}assertOwner(e,i,r){let n=e.owned.get(r);if(n&&n!==i)throw new Error(`Hosted tool ownership conflict: ${r}`);let s=e.pi.getAllTools().find(a=>a.name===r);if(s&&(!n||s.parameters!==e.definitions.get(r)?.parameters))throw new Error(`Tool already belongs to another extension or builtin: ${r}`)}publish(e){if(!this.sdkContract){this.verifyCompatibility();return}if(!this.sdkContract.supported){e.compatible=!1,e.missing=this.sdkContract.missing;return}if(e.compatible===void 0){let r=ew(e.pi);e.compatible=r.supported,e.missing=r.missing}if(!e.compatible)return;for(let[r,n]of e.owned)this.assertOwner(e,n,r);for(let[r,n]of this.descriptors)for(let s of n)this.assertOwner(e,r,s.name);let i=new Set;for(let[r,n]of this.descriptors)for(let s of n){if(e.owned.set(s.name,r),!this.allowed(e,r,s))continue;i.add(s.name);let a=this.service.policy(r,e.scope),o=a.exposure??"direct",l=!a.allowNested&&o==="direct"?"model-only":o,c={name:s.name,label:s.label,description:s.description,parameters:structuredClone(s.parameters),exposure:l,execute:async(p,d,m)=>{if(!this.allowed(e,r,s))throw new Error("Hosted tool denied by host policy");return this.service.invoke(r,{requestId:iw(),scope:{...e.scope},kind:"tool",action:s.action,input:d},m)}};e.pi.registerTool(c),e.definitions.set(s.name,c)}for(let r of e.owned.keys())if(!i.has(r)){let n={name:r,label:r,description:"Unavailable host tool",parameters:{type:"object",properties:{}},exposure:"hidden",execute:MO};e.pi.registerTool(n),e.definitions.set(r,n)}e.pi.setActiveTools(e.pi.getActiveTools().filter(r=>{let n=e.definitions.get(r);return!n||n.exposure==="direct"||n.exposure==="model-only"}))}async invokeAction(e,i,r,n,s){if(this.assertAdmission(),this.sdkContract?.supported!==!0)throw new Error("Hosted SDK capabilities are unavailable for this session");if([...this.bindings].some(o=>o.scope.sessionId===i.sessionId&&o.compatible===!1))throw new Error("Hosted SDK capabilities are unavailable for this session");let a=this.service.policy(e,i);if(!a.enabled||a.planMode||a.allowlist)throw new Error("Hosted action denied by host policy");return this.service.invoke(e,{requestId:iw(),scope:i,kind:"action",action:r,input:n},s)}};async function MO(){throw new Error("Hosted tool unavailable")}import{randomBytes as GR,randomUUID as WR,timingSafeEqual as $R}from"node:crypto";import{join as Ze}from"node:path";var DO=30,rw=/^[a-z][a-z0-9-]{0,63}$/,LO=/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,xn=t=>{throw new y("invalid_package",t)},Cp=(t,e)=>t===void 0?[]:!Array.isArray(t)||t.length>32?xn(`Invalid ${e} declaration`):t;function hr(t){let e=t&&typeof t=="object"?t:{},i=new Set(Array.isArray(e.capabilities)?e.capabilities.filter(o=>typeof o=="string"):[]),r=i.has("secrets")?Cp(e.secrets,"secrets").map(o=>{let l=o?.name;return typeof l=="string"&&rw.test(l)?l:xn("Invalid secret name")}):[],n=e.network,s=i.has("network")?Cp(n?.hosts,"network").map(o=>typeof o=="string"&&LO.test(o)?o:xn("Network hosts must be exact lowercase DNS names")):[],a=i.has("scheduler")?Cp(e.schedules,"schedules").map(o=>{let l=o;return!l||typeof l.id!="string"||!rw.test(l.id)||typeof l.action!="string"||!/^[\w.-]{1,80}$/.test(l.action)||!Number.isSafeInteger(l.intervalSec)||l.intervalSec<DO||l.intervalSec>86400?xn("Invalid schedule declaration"):{id:l.id,intervalSec:l.intervalSec,action:l.action}}):[];return new Set(a.map(o=>o.id)).size!==a.length&&xn("Duplicate schedule id"),{secrets:r,networkHosts:s,schedules:a,sessions:i.has("sessions")}}import{lookup as UO}from"node:dns/promises";import{isIP as qO}from"node:net";var jO=new Set(["GET","POST","PATCH","PUT","DELETE"]),BO=new Set(["authorization","cookie","host","proxy-authorization","connection","content-length","transfer-encoding"]),FO=new Set(["content-type","etag","link","location","retry-after","x-ratelimit-remaining","x-ratelimit-reset","x-github-request-id"]),wa=(t,e)=>{throw new y("network_denied",t,{status:403,reason:e})};function HO(t){let e=t.toLowerCase().replace(/^::ffff:/,"");if(qO(e)===4){let[i,r]=e.split(".").map(Number);return i===0||i===10||i===127||i===169&&r===254||i===172&&r>=16&&r<=31||i===192&&r===168||i===100&&r>=64&&r<=127||i>=224}return e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||/^fe[89ab]/.test(e)||e.startsWith("ff")}async function nw(t,e,i,r,n){let s=r;if(!s||typeof s!="object"||typeof s.url!="string")throw new y("invalid_input","Invalid network request");let a;try{a=new URL(s.url)}catch{throw new y("invalid_input","Invalid URL")}(a.protocol!=="https:"||a.username||a.password||a.port&&a.port!=="443")&&wa("Only plain https on port 443 is allowed","scheme"),e.includes(a.hostname)||wa("Host is not declared by the plugin","host");let o=(s.method??"GET").toUpperCase();if(!jO.has(o))throw new y("invalid_input","Unsupported method");if(s.body!==void 0&&(typeof s.body!="string"||s.body.length>1024*1024))throw new y("invalid_input","Invalid body");let l={};for(let[E,A]of Object.entries(s.headers??{})){if(typeof A!="string"||BO.has(E.toLowerCase())||!/^[\w-]{1,64}$/.test(E)||/[\r\n]/.test(A))throw new y("invalid_input",`Header not allowed: ${E.slice(0,64)}`);l[E]=A}let c=null;if(s.secret!==void 0){if(i.includes(s.secret)||wa("Secret is not declared by the plugin","secret"),c=await n.secrets.get(t,s.secret),!c)throw new y("secret_missing","Secret has not been configured",{status:412});l.Authorization=`Bearer ${c}`}let p=await(n.resolve??(async E=>(await UO(E,{all:!0})).map(A=>A.address)))(a.hostname);(!p.length||p.some(HO))&&wa("Host resolves to a non-public address","address");let d=n.timeoutMs??2e4,m=n.maxResponseBytes??2*1024*1024,g=await(n.fetch??fetch)(a,{method:o,headers:l,body:s.body,redirect:"manual",signal:AbortSignal.timeout(d)}),f=[],h=0;if(g.body)for await(let E of g.body){if(h+=E.byteLength,h>m)throw new y("response_too_large","Network response exceeds limit",{status:502});f.push(Buffer.from(E))}let _=Buffer.concat(f).toString("utf8"),S={};return g.headers.forEach((E,A)=>{FO.has(A.toLowerCase())&&(S[A.toLowerCase()]=E)}),c&&(_=_.split(c).join("[redacted]")),{status:g.status,headers:S,body:_}}var Sa=(t,e,i)=>{if(typeof t!="string"||!t||t.length>e)throw new y("invalid_input",`Invalid ${i}`);return t};async function sw(t,e,i,r,n,s){let a=n&&typeof n=="object"&&!Array.isArray(n)?n:{};if(r==="sessions.create"){if(a.mode!=="plan")throw new y("invalid_input","Plugin sessions must start in plan mode");if(t.activeCount(e)>=s)throw new y("quota_exceeded","Too many active plugin sessions",{status:429});return t.create({pluginId:e,cwd:i,title:Sa(a.title,200,"title"),prompt:Sa(a.prompt,64*1024,"prompt"),mode:"plan"})}let o=Sa(a.sessionId,200,"sessionId");if(t.ownerOf(o)!==e)throw new y("session_denied","Session was not created by this plugin",{status:403});switch(r){case"sessions.send":if(a.mode!==void 0&&a.mode!=="execute")throw new y("invalid_input","Invalid mode");return await t.send(o,Sa(a.message,64*1024,"message"),a.mode),{ok:!0};case"sessions.release":return await t.release(o),{ok:!0};case"sessions.abort":return await t.abort(o),{ok:!0};case"sessions.events":return t.events(o,Number.isSafeInteger(a.after)&&a.after>=0?a.after:0);default:throw new y("method_denied","Unknown sessions method")}}var GO=new Set(["network.fetch","sessions.create","sessions.send","sessions.abort","sessions.release","sessions.events"]),ka=class{options;constructor(e){this.options=e}handles(e){return GO.has(e)}async call(e,i,r,n,s){let a=hr(i);if(n==="network.fetch"){if(!a.networkHosts.length)throw new y("capability_denied","Plugin did not declare network access",{status:403});return nw(e,a.networkHosts,a.secrets,s,this.options)}if(!a.sessions||!this.options.sessions)throw new y("capability_denied","Sessions capability is unavailable",{status:403});return sw(this.options.sessions,e,r.scope.cwd,n,s,this.options.maxActiveSessions??3)}};var Ea=class{timers=new Map;running=new Set;deps;constructor(e){this.deps=e}start(e,i){this.stop(e);let r=this.deps.setInterval??((n,s)=>{let a=setInterval(n,s);return a.unref(),a});this.timers.set(e,i.map(n=>r(()=>{this.tick(e,n)},n.intervalSec*1e3)))}stop(e){let i=this.deps.clearInterval??(r=>clearInterval(r));for(let r of this.timers.get(e)??[])i(r);this.timers.delete(e)}stopAll(){for(let e of[...this.timers.keys()])this.stop(e)}async tick(e,i){let r=`${e}\0${i.id}`;if(this.running.has(r))return!1;this.running.add(r);try{return await this.deps.invoke(e,i),!0}catch(n){return this.deps.onError?.(e,i,n),!1}finally{this.running.delete(r)}}};import{createHash as Vp,timingSafeEqual as vR}from"node:crypto";import{lstat as Sw,mkdtemp as $p,readdir as wR,readFile as SR,realpath as kR,rename as ER,rm as si,writeFile as TR}from"node:fs/promises";import{tmpdir as IR}from"node:os";import{join as ne}from"node:path";import{gunzipSync as QO}from"node:zlib";import{mkdir as JO,writeFile as XO}from"node:fs/promises";import{dirname as ZO,join as eR}from"node:path";import{constants as Mp}from"node:fs";import{lstat as lw,open as WO,readdir as aw,realpath as cw}from"node:fs/promises";import{createHash as $O}from"node:crypto";import{join as pw,relative as VO,resolve as zO,sep as KO}from"node:path";var de={files:4096,total:128*1024*1024,js:16*1024*1024,css:4*1024*1024,font:8*1024*1024,wasm:16*1024*1024,other:2*1024*1024},YO={js:["text/javascript","application/javascript"],mjs:["text/javascript","application/javascript"],cjs:["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"],ttf:["font/ttf"],otf:["font/otf"],wasm:["application/wasm"]},re=t=>$O("sha256").update(t).digest("hex");function ie(t){throw new y("invalid_package",t)}async function Di(t,e,i){let r=e.split("/");(!r.length||r.some(o=>!o||o==="."||o===".."||!/^[\w.-]+$/.test(o)))&&ie("Invalid resource path");let n=t;for(let o=0;o<r.length;o++){n=pw(n,r[o]);let l=await lw(n);(l.isSymbolicLink()||(o<r.length-1?!l.isDirectory():!l.isFile()||l.nlink!==1))&&ie("Links and non-regular package files are forbidden")}let s=await cw(n);(s!==zO(t,e)||VO(t,s).startsWith(`..${KO}`))&&ie("Resource escapes package root");let a=await WO(n,Mp.O_RDONLY|Mp.O_NONBLOCK|(Mp.O_NOFOLLOW??0));try{let o=await a.stat();(!o.isFile()||o.nlink!==1||o.size>i)&&ie("Oversized or non-regular package file");let l=Buffer.alloc(Math.min(o.size+1,i+1)),c=0;for(;c<l.length;){let p=await a.read(l,c,l.length-c,c);if(!p.bytesRead)break;c+=p.bytesRead}return(c>i||c!==o.size)&&ie("Package resource changed during read"),l.subarray(0,c)}finally{await a.close()}}function ow(t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(t))}catch{return ie("Invalid package JSON")}}async function Li(t,e){let i=await cw(t);(await lw(t)).isSymbolicLink()&&ie("Package root cannot be a symlink");let r=ow(await Di(i,"package.json",de.other));(!r||typeof r.name!="string"||!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(r.name)||r.name.length>214||e&&r.name!==e)&&ie("Package identity mismatch"),(typeof r.version!="string"||!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(r.version))&&ie("Invalid package version"),ti(r.piWebapp)||ie("Unsupported hosted manifest"),r.type!=="module"&&ie("Hosted package must declare ESM module type");for(let d of await aw(i,{withFileTypes:!0}))d.name==="dist"&&d.isDirectory()||(!d.isFile()||!["package.json","README.md","LICENSE","NOTICE.txt"].includes(d.name))&&ie("Undeclared package-root asset or code");r.scripts&&Object.keys(r.scripts).some(d=>/^(?:preinstall|install|postinstall|prepare)$/.test(d))&&ie("Hosted packages cannot run install lifecycle scripts");for(let d of["dependencies","optionalDependencies"]){let m=r[d];m&&(typeof m!="object"||Object.keys(m).length>0)&&ie("Hosted packages must contain all runtime dependencies")}let n=r.piWebapp,s=ow(await Di(i,n.resourcesManifest.slice(2),de.other));(!s||s.version!==1||!Array.isArray(s.files)||!s.files.length||s.files.length>de.files)&&ie("Invalid resource manifest");let a=new Map,o=0;for(let d of s.files){(!d||typeof d!="object")&&ie("Invalid resource entry");let m=d,g={...m,path:typeof m.path=="string"&&m.path.startsWith("./")?m.path.slice(2):m.path};(!Oi(`./${g.path}`)||typeof g.sha256!="string"||!/^[a-f0-9]{64}$/.test(g.sha256)||!Number.isSafeInteger(g.bytes)||g.bytes<0||a.has(g.path))&&ie("Invalid or duplicate resource");let f=g.path.split(".").at(-1);YO[f]?.includes(g.mime)||ie("Unsupported resource MIME");let h=f==="js"||f==="mjs"||f==="cjs"?de.js:f==="css"?de.css:["woff","woff2","ttf","otf"].includes(f)?de.font:f==="wasm"?de.wasm:de.other;(g.bytes>h||(o+=g.bytes)>de.total)&&ie("Resource budget exceeded");let _=await Di(i,g.path,h);(_.length!==g.bytes||re(_)!==g.sha256)&&ie("Resource integrity mismatch"),a.set(g.path,Object.freeze({...g}))}for(let d of[n.backend.entry,n.frontend.document,n.frontend.controller])a.has(d.slice(2))||ie("Entrypoint is absent from resource manifest");let l=0;async function c(d,m=0){m>16&&ie("Package directory nesting limit exceeded");for(let g of await aw(pw(i,d),{withFileTypes:!0})){++l>de.files*2&&ie("Too many package entries");let f=`${d}/${g.name}`;(g.isSymbolicLink()||!g.isDirectory()&&!g.isFile())&&ie("Invalid archive member"),g.isDirectory()?await c(f,m+1):f!==n.resourcesManifest.slice(2)&&!a.has(f)&&ie("Undeclared distribution asset")}}await c("dist");let p=re(JSON.stringify({id:r.name,version:r.version,manifest:n,resources:[...a.values()].sort((d,m)=>d.path.localeCompare(m.path))}));return{id:r.name,version:r.version,root:i,manifest:n,resources:a,digest:p}}async function dw(t,e,i){if(i!==t.digest||e.length>1536)return null;let r;try{r=decodeURIComponent(e)}catch{return null}if(!Oi(`./${r}`))return null;let n=t.resources.get(r);if(!n||r===t.manifest.backend.entry.slice(2))return null;let s=await Di(t.root,r,n.bytes);if(s.length!==n.bytes||re(s)!==n.sha256)throw new y("resource_changed","Installed resource integrity mismatch");return{bytes:s,mime:n.mime}}var Ta=64*1024*1024,tR=de.total+de.files*2048,te=t=>{throw new y("invalid_archive",t)};function yr(t){let e=t.indexOf(0);try{return new TextDecoder("utf-8",{fatal:!0}).decode(e<0?t:t.subarray(0,e))}catch{return te("Archive has invalid UTF-8 paths")}}function uw(t){let e=yr(t).trim();if(!/^[0-7]+$/.test(e))return te("Unsupported archive number encoding");let i=parseInt(e,8);return Number.isSafeInteger(i)?i:te("Archive number exceeds limits")}function iR(t){let e=t.endsWith("/")?t.slice(0,-1):t;if(e==="package")return"";if(!e.startsWith("package/")||e.length>1024)return te("Archive must have one package root");let i=e.slice(8);return i.split("/").some(r=>!r||r==="."||r===".."||!/^[A-Za-z0-9_@.-]+$/.test(r))?te("Archive path is not a safe relative package path"):i}function rR(t){let e={},i=0;for(;i<t.length;){let r=t.indexOf(32,i);if(r<0)return te("Invalid PAX header");let n=t.subarray(i,r).toString("ascii");if(!/^[1-9]\d{0,5}$/.test(n))return te("Invalid PAX record length");let s=Number(n),a=i+s;if(a>t.length||a<=r+2||t[a-1]!==10)return te("Truncated PAX record");let o=yr(t.subarray(r+1,a-1)),l=o.indexOf("=");if(l<1)return te("Invalid PAX record");let c=o.slice(0,l),p=o.slice(l+1);if(Object.hasOwn(e,c)||!["path","size","mtime","atime","ctime","uid","gid","uname","gname","comment"].includes(c))return te("Unsupported PAX feature");e[c]=p,i=a}return e}function nR(t){if(!t.length||t.length>Ta)return te("Compressed archive exceeds budget");let e;try{e=QO(t,{maxOutputLength:tR})}catch{return te("Invalid or oversized gzip archive")}let i=[],r=new Set,n=0,s=0,a=0,o=0,l=null,c=!1;for(;n+512<=e.length;){let d=e.subarray(n,n+512);if(n+=512,d.every(D=>D===0)){if(l||e.subarray(n).some(D=>D!==0))return te("Unexpected archive data after end marker");c=!0;break}if(++o>de.files*2)return te("Too many archive headers");let m=0;for(let D=0;D<512;D++)m+=D>=148&&D<156?32:d[D];if(uw(d.subarray(148,156))!==m)return te("Invalid tar header checksum");let g=yr(d.subarray(257,263));if(g&&g!=="ustar"&&g!=="ustar ")return te("Unsupported tar format");let f=d[156],h=yr(d.subarray(345,500)),_=(h?h+"/":"")+yr(d.subarray(0,100)),S=uw(d.subarray(124,136));if(l&&(l.path!==void 0&&(_=l.path),l.size!==void 0)){if(!/^(0|[1-9]\d*)$/.test(l.size))return te("Invalid PAX size");S=Number(l.size)}if(!Number.isSafeInteger(S)||S<0||S>de.total||n+S>e.length)return te("Truncated or oversized tar member");let E=e.subarray(n,n+S);if(n+=Math.ceil(S/512)*512,f===120){if(l||S>8192)return te("Oversized or chained PAX header");l=rR(E);continue}if(l=null,f!==0&&f!==48&&f!==53)return te("Links and special archive members are forbidden");let A=f===53;if(A&&S!==0||yr(d.subarray(157,257)))return te("Invalid archive link or directory");if(_=iR(_),!_&&!A)return te("Invalid package root member");if(r.has(_))return te("Duplicate archive member");if(r.add(_),++s>de.files||(a+=S)>de.total)return te("Unpacked archive exceeds budget");i.push({path:_,data:E,directory:A})}if(!c||!r.has("package.json"))return te("Archive is incomplete or has no package.json");let p=new Set(i.filter(d=>!d.directory).map(d=>d.path));for(let d of i){let m=d.path.split("/");for(let g=1;g<m.length;g++)if(p.has(m.slice(0,g).join("/")))return te("Archive file/directory collision")}return i}async function Dp(t,e){let i=nR(t);for(let r of i){if(!r.path)continue;let n=eR(e,r.path);await JO(r.directory?n:ZO(n),{recursive:!0,mode:448}),r.directory||await XO(n,r.data,{flag:"wx",mode:384})}}import{lstat as sR,mkdir as aR,readdir as oR,realpath as lR,writeFile as cR}from"node:fs/promises";import{dirname as pR,join as Lp}from"node:path";async function mw(t,e){let i=await lR(t),r=await Di(i,"package.json",de.other),n;try{n=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r))}catch{throw new y("invalid_package","package.json is not valid JSON")}if(!n||typeof n!="object"||Array.isArray(n))throw new y("invalid_package","package.json must be an object");let s=[],a=0,o=0;async function l(m,g){if(g>16)throw new y("invalid_package","Package directory nesting limit exceeded");for(let f of await oR(Lp(i,m),{withFileTypes:!0})){let h=`${m}/${f.name}`;if(++a>de.files)throw new y("invalid_package","Too many package entries");if(f.isDirectory()){await l(h,g+1);continue}if(!f.isFile())throw new y("invalid_package",`Links and non-regular files are forbidden: ${h}`);let _=await Di(i,h,de.js);if((o+=_.length)>de.total)throw new y("invalid_package","Resource budget exceeded");let S=Lp(e,h);await aR(pR(S),{recursive:!0,mode:448}),await cR(S,_,{flag:"wx",mode:384}),s.push([h,re(_)])}}let c;try{c=await sR(Lp(i,"dist"))}catch(m){throw m.code==="ENOENT"?new y("dist_missing","dist/ does not exist yet; build the plugin first"):m}if(!c.isDirectory())throw new y("invalid_package","dist must be a real directory");await l("dist",0);let{version:p,...d}=n;return s.sort((m,g)=>m[0].localeCompare(g[0])),{contentHash:re(JSON.stringify({package:d,files:s})),packageJson:n}}function qe(t){let e=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(t);return!e||e[0]!==t||e.slice(1).some(i=>!Number.isSafeInteger(Number(i)))?null:{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}}function ft(t,e){let i=qe(t),r=qe(e);if(!i||!r)throw new y("invalid_version","Only exact stable semantic versions are supported");return i.major-r.major||i.minor-r.minor||i.patch-r.patch}function gw(t){let e=qe(t);if(e)return e;if(!ea(t))return null;let[i,r]=t.split("-alpha."),n=qe(i),s=Number(r);return n&&Number.isSafeInteger(s)?{...n,alpha:s}:null}function Up(t){return!!gw(t)}function br(t,e){if(!Up(t)||typeof e!="string"||e.length>256)return!1;let i=e.split("||");if(!i.length||i.some(n=>!n.trim()))return!1;let r=[];for(let n of i){let s=n.trim().split(/\s+/),a=!0;for(let o of s){let l=/^(>=|<=|>|<|=|\^|~)?(.+)$/.exec(o),c=l&&gw(l[2]);if(!l||!c)return!1;let p=l[2],d=Ve(t,p);switch(l[1]??"="){case"=":a&&=d===0;break;case">=":a&&=d>=0;break;case"<=":a&&=d<=0;break;case">":a&&=d>0;break;case"<":a&&=d<0;break;case"~":a&&=d>=0&&Ve(t,`${c.major}.${c.minor+1}.0-0`)<0;break;case"^":{let m=c.major?`${c.major+1}.0.0`:c.minor?`0.${c.minor+1}.0`:`0.0.${c.patch+1}`;a&&=d>=0&&Ve(t,`${m}-0`)<0;break}}}r.push(a)}return r.some(Boolean)}var qp=64*1024*1024,jp=Object.freeze([Object.freeze({extension:".excalidraw",binary:!1,maxBytes:512*1024,createDirectory:"diagrams"})]);function Bp(t,e){let i=t.get(e);if(!i)throw new y("unreviewed_plugin","No trusted tool policy for this package");return i}function fw(t,e){let i=t.get(e)?.workspace?.files??jp;for(let r of i)if(!/^\.[a-z0-9]{1,16}$/.test(r.extension)||!Number.isSafeInteger(r.maxBytes)||r.maxBytes<=0||r.maxBytes>qp||r.createDirectory!==void 0&&!/^[A-Za-z0-9_-]{1,64}$/.test(r.createDirectory))throw new y("invalid_policy","Invalid workspace file rule");return i}function hw(t,e){let i=t.get(e)?.runtime?.invokeTimeoutMs;return i===void 0?void 0:Math.min(Math.max(i,1e3),18e4)}var yw=["drawing","design"],dR=/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,uR=/^[a-z][a-z0-9.-]{0,79}$/,Fp=/^[a-z][a-z0-9_]{0,63}$/,Ui=/^[a-z][a-z0-9_-]{0,63}$/,mR=/^[a-z][a-z0-9-]{0,63}$/,On=class{where;constructor(e){this.where=e}fail(e,i){throw new y("invalid_catalog",`${this.where}: ${e} ${i}`)}object(e,i,r,n=r){(!e||typeof e!="object"||Array.isArray(e))&&this.fail(i,"must be an object");let s=e;for(let a of Object.keys(s))r.includes(a)||this.fail(`${i}.${a}`,"is not a known field");for(let a of n)s[a]===void 0&&this.fail(`${i}.${a}`,"is required");return s}string(e,i,r=200,n){return(typeof e!="string"||!e.trim()||e.length>r)&&this.fail(i,`must be a non-empty string of at most ${r} characters`),n&&!n.test(e)&&this.fail(i,`has an invalid format (${JSON.stringify(e)})`),e}strings(e,i,r,n=64){(!Array.isArray(e)||e.length>n)&&this.fail(i,`must be an array of at most ${n} strings`);let s=e.map((a,o)=>this.string(a,`${i}[${o}]`,80,r));return new Set(s).size!==s.length&&this.fail(i,"contains duplicates"),s}text(e,i,r=500){let n=this.object(e,i,["zh","en"]);return{zh:this.string(n.zh,`${i}.zh`,r),en:this.string(n.en,`${i}.en`,r)}}integer(e,i,r,n){return(!Number.isSafeInteger(e)||e<r||e>n)&&this.fail(i,`must be an integer from ${r} to ${n}`),e}https(e,i,r){let n=this.string(e,i,2048),s;try{s=new URL(n)}catch{this.fail(i,"must be an absolute URL")}return(s.protocol!=="https:"||s.username||s.password||s.hash||r!==void 0&&s.hostname!==r)&&this.fail(i,`must be an https URL${r?` on ${r}`:""} without credentials or fragment`),n}subset(e,i,r,n){for(let s of e)i.includes(s)||this.fail(r,`lists "${s}", which is not one of its ${n}`)}};function gR(t,e,i){let r=t.object(e,i,["entry","panels","artifactTools","toolViews","panelAlias"]),n=t.object(r.entry,`${i}.entry`,["label","description","kind"]),s=t.object(r.panelAlias,`${i}.panelAlias`,["prefix","kind","title"]);return{entry:{label:t.string(n.label,`${i}.entry.label`,64),description:t.text(n.description,`${i}.entry.description`,120),kind:t.string(n.kind,`${i}.entry.kind`,32,Ui)},panels:t.strings(r.panels,`${i}.panels`,Ui,16),artifactTools:t.strings(r.artifactTools,`${i}.artifactTools`,Fp,128),toolViews:t.strings(r.toolViews,`${i}.toolViews`,Fp,128),panelAlias:{prefix:t.string(s.prefix,`${i}.panelAlias.prefix`,32,/^[a-z][a-z0-9-]{0,30}:$/),kind:t.string(s.kind,`${i}.panelAlias.kind`,32,Ui),title:t.string(s.title,`${i}.panelAlias.title`,64)}}}function fR(t,e,i){return(!Array.isArray(e)||e.length<1||e.length>16)&&t.fail(i,"must be an array of 1 to 16 rules"),e.map((r,n)=>{let s=`${i}[${n}]`,a=t.object(r,s,["extension","binary","maxBytes","createDirectory"],["extension","binary","maxBytes"]);return typeof a.binary!="boolean"&&t.fail(`${s}.binary`,"must be a boolean"),{extension:t.string(a.extension,`${s}.extension`,17,/^\.[a-z0-9]{1,16}$/),binary:a.binary,maxBytes:t.integer(a.maxBytes,`${s}.maxBytes`,1,qp),...a.createDirectory!==void 0?{createDirectory:t.string(a.createDirectory,`${s}.createDirectory`,64,/^[A-Za-z0-9_-]{1,64}$/)}:{}}})}function hR(t,e,i){let r=t.object(e,i,Object.keys(e&&typeof e=="object"?e:{}),[]);return Object.keys(r).length>16&&t.fail(i,"declares more than 16 secrets"),Object.fromEntries(Object.entries(r).map(([n,s])=>{let a=`${i}.${n}`;t.string(n,`${i} key`,64,mR);let o=t.object(s,a,["provider","scope","createUrl","clientId"],["provider","scope","createUrl"]);return o.provider!=="github"&&t.fail(`${a}.provider`,'must be "github" (the only sign-in the host implements)'),[n,{provider:"github",scope:t.string(o.scope,`${a}.scope`,200,/^[\w:. -]+$/),createUrl:t.https(o.createUrl,`${a}.createUrl`,"github.com"),...o.clientId!==void 0?{clientId:t.string(o.clientId,`${a}.clientId`,64,/^[A-Za-z0-9._-]+$/)}:{}}]}))}function yR(t,e,i="policy"){let r=new On(e),n=r.object(t,i,["tools","readonlyActions","actions","checkpointActions","contribution","browser","workspace","runtime","secrets"],["tools","readonlyActions","actions","checkpointActions","contribution"]),s=r.object(n.tools,`${i}.tools`,Object.keys(n.tools&&typeof n.tools=="object"?n.tools:{}),[]);Object.keys(s).length>128&&r.fail(`${i}.tools`,"declares more than 128 tools");for(let[g,f]of Object.entries(s))r.string(g,`${i}.tools key`,64,Fp),r.string(f,`${i}.tools.${g}`,64,Ui);let a=Object.keys(s),o=Object.values(s),l=r.strings(n.readonlyActions,`${i}.readonlyActions`,Ui),c=r.strings(n.actions,`${i}.actions`,Ui),p=r.strings(n.checkpointActions,`${i}.checkpointActions`,Ui);r.subset(l,o,`${i}.readonlyActions`,"tool actions"),r.subset(p,c,`${i}.checkpointActions`,"actions");let d=gR(r,n.contribution,`${i}.contribution`);r.subset(d.artifactTools,a,`${i}.contribution.artifactTools`,"tools"),r.subset(d.toolViews,a,`${i}.contribution.toolViews`,"tools");let m={tools:s,readonlyActions:l,actions:c,checkpointActions:p,contribution:d};if(n.browser!==void 0){let g=r.object(n.browser,`${i}.browser`,["wasm"],[]);g.wasm!==void 0&&typeof g.wasm!="boolean"&&r.fail(`${i}.browser.wasm`,"must be a boolean"),m.browser=g.wasm===void 0?{}:{wasm:g.wasm}}if(n.workspace!==void 0&&(m.workspace={files:fR(r,r.object(n.workspace,`${i}.workspace`,["files"]).files,`${i}.workspace.files`)}),n.runtime!==void 0){let g=r.object(n.runtime,`${i}.runtime`,["invokeTimeoutMs"],[]);m.runtime=g.invokeTimeoutMs===void 0?{}:{invokeTimeoutMs:r.integer(g.invokeTimeoutMs,`${i}.runtime.invokeTimeoutMs`,1e3,18e4)}}return n.secrets!==void 0&&(m.secrets=hR(r,n.secrets,`${i}.secrets`)),m}var bR=["id","name","icon","description","registry","recommendedVersion","requiredCapabilities","reviewed","policy"];function Hp(t,e,i="plugin"){let r=new On(e),n=r.object(t,i,bR,["id","name","description","registry","recommendedVersion","requiredCapabilities","policy"]),s=r.string(n.id,`${i}.id`,214,dR);n.icon!==void 0&&!yw.includes(n.icon)&&r.fail(`${i}.icon`,`must be one of ${yw.join(", ")}`);let a=r.https(n.registry,`${i}.registry`);new URL(a).origin!==a&&r.fail(`${i}.registry`,"must be a bare origin such as https://registry.npmjs.org");let o=r.string(n.recommendedVersion,`${i}.recommendedVersion`,64);return qe(o)||r.fail(`${i}.recommendedVersion`,"must be a stable x.y.z version"),n.reviewed!==void 0&&r.string(n.reviewed,`${i}.reviewed`,1e3),{id:s,name:r.string(n.name,`${i}.name`,64),...n.icon!==void 0?{icon:n.icon}:{},description:r.text(n.description,`${i}.description`),registry:a,recommendedVersion:o,requiredCapabilities:r.strings(n.requiredCapabilities,`${i}.requiredCapabilities`,uR),policy:yR(n.policy,e,`${i}.policy`)}}function bw(t,e){let i=new On(e),r=i.object(t,"catalog",["schemaVersion","plugins"]);r.schemaVersion!==1&&i.fail("catalog.schemaVersion","must be 1"),(!Array.isArray(r.plugins)||r.plugins.length>64)&&i.fail("catalog.plugins","must be an array of at most 64 entries");let n=r.plugins.map((a,o)=>Hp(a,e,`catalog.plugins[${o}]`)),s=n.map(a=>a.id);for(let[a,o]of s.entries())s.indexOf(o)!==a&&i.fail(`catalog.plugins[${a}].id`,`duplicates ${o}`);return n}function Gp(t){if(t&&typeof t=="object"&&!Object.isFrozen(t)){Object.freeze(t);for(let e of Object.values(t))Gp(e)}return t}var _w={schemaVersion:1,plugins:[{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"],reviewed:"Policy reviewed against package 6328c63.",policy:{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"}}}},{id:"@chengzhiyi/pi-pencil",name:"OpenPencil",icon:"design",description:{zh:"\u57FA\u4E8E OpenPencil \u7684 UI \u8BBE\u8BA1\uFF1A\u7F16\u8F91\u5DE5\u4F5C\u533A\u91CC\u7684 .fig \u8BBE\u8BA1\u7A3F\uFF0Cagent \u7684\u4FEE\u6539\u76F4\u63A5\u51FA\u73B0\u5728\u753B\u5E03\u4E0A\uFF0C\u53EF\u968F\u65F6\u64A4\u9500\u3002\u6309\u9700\u5B89\u88C5\u3002",en:"UI design on OpenPencil: edit .fig designs in your workspace; the agent's changes appear on the canvas directly and you can undo them. Optional download."},registry:"https://registry.npmjs.org",recommendedVersion:"0.0.2",requiredCapabilities:["state","workspace","panels","browser.wasm"],reviewed:"The tool set is deliberately small. Agent changes apply directly as new revisions; undoing one (revert), saving, syncing and locking stay human-only. accept/reject remain for proposals stored by older builds. import turns a file the person picked (.fig/.jam/.pen/.drawio) into a new design; upload carries an action input over the 2 MB request limit in chunks (bounded and owned by the uploading session in the plugin). A checkpoint freeze may flush a person's first edits in an empty workspace, which creates their design.",policy:{tools:{pencil_read_me:"reference",pencil_status:"status",pencil_inspect:"inspect",pencil_render:"render",pencil_apply_changes:"apply"},readonlyActions:["reference","status","inspect","render"],actions:["list","get","accept","reject","revert","save","open","import","upload","create","rename","selection","sync","lock"],checkpointActions:["get","list","sync","create"],contribution:{entry:{label:"OpenPencil",description:{zh:"UI \u8BBE\u8BA1",en:"UI design"},kind:"workspace"},panels:["workspace","editor"],artifactTools:["pencil_apply_changes"],toolViews:[],panelAlias:{prefix:"pencil:",kind:"editor",title:"OpenPencil"}},browser:{wasm:!0},workspace:{files:[{extension:".fig",binary:!0,maxBytes:67108864,createDirectory:"designs"}]},runtime:{invokeTimeoutMs:12e4}}}]};var vw=Gp(bw(_w,"official-plugins.json")),Xe=Object.freeze(vw.map(({policy:t,...e})=>Object.freeze(e))),Ia=new Map(vw.map(t=>[t.id,t.policy]));function Ke(t,e=Xe){let i=e.find(r=>r.id===t);if(!i)throw new y("unknown_plugin","Plugin is not in the trusted official catalog");return i}function Wp(t,e,i){let r=t.piWebapp;return t.name===e.id&&!!qe(t.version)&&!t.deprecated&&ti(r)&&br(i,r.hostRange)&&e.requiredCapabilities.every(n=>r.capabilities.includes(n))}function ww(t,e,i,r,n){if(!t||typeof t!="object"||!("versions"in t)||!t.versions||typeof t.versions!="object"||Array.isArray(t.versions))throw new y("registry_invalid","Invalid registry version catalog");let s=Object.entries(t.versions);if(s.length>1e4)throw new y("registry_invalid","Registry version catalog exceeds budget");let o=s.flatMap(([l,c])=>{if(!c||typeof c!="object")return[];let p=c;return p.version===l&&Wp(p,e,i)&&(!n||l===n)&&(!r||ft(l,r)>=0)?[p]:[]}).sort((l,c)=>ft(c.version,l.version))[0];if(!o)throw new y("no_compatible_version","No compatible stable plugin release is available; installed code and data preserved");if(!o.dist||typeof o.dist.tarball!="string"||typeof o.dist.integrity!="string")throw new y("registry_invalid","Release is missing its immutable tarball integrity");return o}function AR(t,e){let i=/^sha512-([A-Za-z0-9+/]{86}==)$/.exec(e);if(!i)throw new y("invalid_integrity","A single SHA-512 tarball integrity is required");let r=Buffer.from(i[1],"base64"),n=Vp("sha512").update(t).digest();if(r.length!==n.length||!vR(r,n))throw new y("integrity_mismatch","Downloaded package failed integrity verification")}var _r=class{root;hostVersion;catalog;fetcher;constructor(e){if(!Up(e.hostVersion))throw new y("invalid_version","Host requires an exact stable or alpha.N version");this.root=e.root,this.hostVersion=e.hostVersion,this.catalog=e.catalog??Xe,this.fetcher=e.fetch??mv}async index(){let e=await we(ne(this.root,"installed.json"));if(!e){if(await fe(ne(this.root,"installed.json"),2*1024*1024))throw new y("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 y("invalid_storage","Invalid plugin installation index");for(let[i,r]of Object.entries(e.versions))if(this.catalog.some(n=>n.id===i)){if(!Array.isArray(r)||r.length>16||new Set(r.map(n=>n.version)).size!==r.length)throw new y("invalid_storage","Invalid installed version list");for(let n of r)this.validateRecord(i,n)}return e}validateRecord(e,i){if(!i||!qe(i.version)||!/^[a-f0-9]{64}$/.test(i.digest)||i.directory!==`${re(e)}/${i.version}-${i.digest}`||typeof i.integrity!="string"||!/^sha512-[A-Za-z0-9+/]{86}==$/.test(i.integrity)||typeof i.installedAt!="string")throw new y("invalid_storage","Invalid installed plugin record")}path(e){return ne(this.root,"versions",e.directory)}async recoverLocked(){let e=await this.index(),i=await ze(ne(this.root,"install-journal.json"));if(i){if(i.schema!==1||Object.keys(i).some(s=>!["schema","pluginId","next"].includes(s)))throw new y("invalid_storage","Invalid install journal");Ke(i.pluginId,this.catalog),this.validateRecord(i.pluginId,i.next);let n=e.versions[i.pluginId]?.find(s=>s.version===i.next.version);if(n&&n.digest!==i.next.digest)throw new y("invalid_storage","Conflicting installation journal");await si(ne(this.root,"install-journal.json"))}await this.recoverCollection(e);let r=ne(this.root,"staging");await ve(r);for(let n of await wR(r)){if(!/^stage-[A-Za-z0-9]+$/.test(n)||(await Sw(ne(r,n))).isSymbolicLink())throw new y("invalid_storage","Invalid abandoned staging directory");await si(ne(r,n),{recursive:!0})}return e}async recoverCollection(e){let i=ne(this.root,"gc-journal.json"),r=await ze(i);if(!r)return;if(r.schema!==1||Object.keys(r).some(s=>!["schema","pluginId","records"].includes(s))||!Array.isArray(r.records)||!r.records.length)throw new y("gc_recovery_required","Invalid gc-journal.json; stop all owners and inspect it before cleanup");Ke(r.pluginId,this.catalog);for(let s of r.records)this.validateRecord(r.pluginId,s);let n=r.records.filter(s=>e.versions[r.pluginId]?.some(a=>a.directory===s.directory));if(n.length&&n.length!==r.records.length)throw new y("gc_recovery_required","Conflicting GC journal/index; restore installation metadata before cleanup");if(!n.length){await ve(ne(this.root,"versions")),await ve(ne(this.root,"versions",re(r.pluginId)));for(let s of r.records)await si(this.path(s),{recursive:!0,force:!0})}await si(i)}async collect(e,i){return Ke(e,this.catalog),Se(this.root,async()=>{let r=await this.recoverLocked(),n=r.versions[e]??[],s=new Set(await i()),a=n.at(-1);a&&s.add(a.version);let o=n.filter(l=>!s.has(l.version));return await this.removeLocked(e,r,o),o.map(l=>l.version)})}async removeLocked(e,i,r){r.length&&(await ve(ne(this.root,"versions")),await ve(ne(this.root,"versions",re(e))),await Z(ne(this.root,"gc-journal.json"),{schema:1,pluginId:e,records:r}),i.versions[e]=(i.versions[e]??[]).filter(n=>!r.some(s=>s.directory===n.directory)),i.revision++,await Z(ne(this.root,"installed.json"),i),await this.recoverCollection(i))}async inventory(){return Se(this.root,async()=>{let e=await this.recoverLocked();return{revision:e.revision,versions:structuredClone(e.versions)}})}trustedUrl(e,i){let r;try{r=new URL(e)}catch{throw new y("registry_denied","Invalid registry URL")}let n=new URL(i.registry);if(r.protocol!=="https:"||r.origin!==n.origin||r.username||r.password||r.hash||r.search)throw new y("registry_denied","Only the official registry origin is permitted");return r}async download(e,i,r,n="tarball"){let s=AbortSignal.any([AbortSignal.timeout(6e4),...r?[r]:[]]),a;try{a=await this.fetcher(e,{redirect:"error",signal:s,headers:{Accept:"application/json, application/octet-stream"}})}catch(d){throw r?.aborted?r.reason:new y("registry_unreachable",d instanceof Error?d.message:"Registry network request failed")}if(!a.ok||!a.body)throw await a.body?.cancel().catch(()=>{}),new y(a.status===404?`${n}_not_found`:"download_failed",`Registry ${n} request failed (${a.status})`);if(a.url&&new URL(a.url).origin!==e.origin)throw new y("registry_denied","Registry redirect is forbidden");let o=a.body.getReader(),l=[],c=0,p=()=>{o.cancel(s.reason).catch(()=>{})};s.addEventListener("abort",p,{once:!0});try{if(s.throwIfAborted(),Number(a.headers.get("content-length"))>i)throw new y("download_too_large","Registry response exceeds budget");for(;;){let d=await o.read();if(d.done)break;if(c+=d.value.length,c>i)throw new y("download_too_large","Registry response exceeds budget");l.push(Buffer.from(d.value))}return s.throwIfAborted(),Buffer.concat(l)}catch(d){throw r?.aborted?r.reason:d instanceof y?d:new y("registry_unreachable",d instanceof Error?d.message:"Registry response interrupted")}finally{s.removeEventListener("abort",p),await o.cancel().catch(()=>{}),o.releaseLock()}}async check(e,i,r,n){let s=Ke(e,this.catalog);if(r&&!qe(r))throw new y("invalid_version","Choose an exact stable version");let a=this.trustedUrl(`${s.registry}/${encodeURIComponent(e)}`,s),o,l=await this.download(a,8*1024*1024,n,"metadata");try{o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l))}catch{throw new y("registry_invalid","Invalid registry metadata JSON")}return ww(o,s,this.hostVersion,i,r)}async install(e,i,r){let n=Ke(e,this.catalog);if(!Wp(i,n,this.hostVersion))throw new y("incompatible_plugin","Plugin release is incompatible with this host");let s=await this.download(this.trustedUrl(i.dist.tarball,n),Ta,r);return this.installArchive(e,s,i.dist.integrity,i.version,r)}async installArchive(e,i,r,n,s){let a=Ke(e,this.catalog);if(!qe(n))throw new y("invalid_version","Choose an exact stable version");if(i.length>Ta)throw new y("download_too_large","Package archive exceeds budget");return AR(i,r),Se(this.root,async()=>{let o=await this.recoverLocked();s?.throwIfAborted();let l=await $p(ne(this.root,"staging","stage-"));try{await Dp(i,l),s?.throwIfAborted();let c=await Li(l,e);if(c.version!==n||!ti(c.manifest)||!br(this.hostVersion,c.manifest.hostRange)||!a.requiredCapabilities.every(p=>c.manifest.capabilities.includes(p)))throw new y("incompatible_plugin","Archive version/capabilities differ from selected release");return await this.commitStaged(e,o,l,c,r,s)}finally{await si(l,{recursive:!0,force:!0})}},1e4)}async commitStaged(e,i,r,n,s,a){let o=i.versions[e]?.find(d=>d.version===n.version);if(o&&o.digest!==n.digest)throw new y("version_replaced","An installed immutable version cannot be replaced with different content");let l={version:n.version,digest:n.digest,integrity:s,directory:`${re(e)}/${n.version}-${n.digest}`,installedAt:new Date().toISOString()};if(await ve(ne(this.root,"versions",re(e))),!o&&(i.versions[e]?.length??0)>=16)throw new y("version_budget","Retained plugin version budget reached; collect unreferenced versions first");await Z(ne(this.root,"install-journal.json"),{schema:1,pluginId:e,next:l});let c=this.path(l),p=!1;try{await Sw(c),p=!0}catch(d){if(!Zt(d))throw d}if(p){if((await Li(c,e)).digest!==n.digest)throw new y("resource_changed","Installed package content was modified")}else await ER(r,c);return a?.throwIfAborted(),o||(i.versions[e]=[...i.versions[e]??[],l],i.revision++,await Z(ne(this.root,"installed.json"),i)),await si(ne(this.root,"install-journal.json")),{...n,root:await kR(c)}}async installDevArchive(e,i,r){Ke(e,this.catalog);let n=await SR(i),s="sha512-"+Vp("sha512").update(n).digest("base64"),a=await $p(ne(IR(),"pi-dev-archive-"));try{await Dp(n,a);let o=(await Li(a,e)).version;return await this.installArchive(e,n,s,o,r)}finally{await si(a,{recursive:!0,force:!0})}}async installDevDirectory(e,i,r){let n=Ke(e,this.catalog);return Se(this.root,async()=>{let s=await this.recoverLocked();r?.throwIfAborted();let a=await $p(ne(this.root,"staging","stage-"));try{let{contentHash:o,packageJson:l}=await mw(i,a);r?.throwIfAborted();let c=ne(this.root,"dev-sources.json"),p=await we(c)??{},d=p[e],m=s.versions[e]??[],g=d?.contentHash===o?m.find(N=>N.version===d.version):void 0;if(g){let N=await Li(this.path(g),e);if(N.digest!==g.digest)throw new y("resource_changed","Installed package integrity changed");return N}let f=typeof l.version=="string"?qe(l.version):null;if(!f)throw new y("invalid_version","A dev package needs an exact stable x.y.z version in package.json");let h=Math.max(-1,...m.map(N=>qe(N.version)).filter(N=>N&&N.major===f.major&&N.minor===f.minor).map(N=>N.patch)),_=Math.max(Math.floor((Date.now()-Date.UTC(2026,0,1))/1e3),h+1),S=`${f.major}.${f.minor}.${_}`;await TR(ne(a,"package.json"),JSON.stringify({...l,version:S},null,2),{flag:"wx",mode:384});let E=await Li(a,e);if(!br(this.hostVersion,E.manifest.hostRange))throw new y("incompatible_plugin",`Package hostRange ${E.manifest.hostRange} does not include host ${this.hostVersion}`);let A=n.requiredCapabilities.filter(N=>!E.manifest.capabilities.includes(N));if(A.length)throw new y("incompatible_plugin",`Package lacks required capabilities: ${A.join(", ")}`);let D="sha512-"+Vp("sha512").update(o).digest("base64"),C=await this.commitStaged(e,s,a,E,D,r);return p[e]={contentHash:o,version:S},await Z(c,p),C}finally{await si(a,{recursive:!0,force:!0})}},1e4)}async load(e,i){let r=Ke(e,this.catalog);return Se(this.root,async()=>{let n=await this.recoverLocked(),s=n.versions[e]?.find(o=>o.version===i);if(!s)throw new y("not_installed","Plugin version is not installed");let a=await Li(this.path(s),e);if(a.digest!==s.digest)throw new y("resource_changed","Installed package integrity changed");if(!br(this.hostVersion,a.manifest.hostRange)||!r.requiredCapabilities.every(o=>a.manifest.capabilities.includes(o)))throw new y("incompatible_plugin","Installed plugin range/capabilities are incompatible with this host");return a})}async removeVersions(e,i){Ke(e,this.catalog),await Se(this.root,async()=>{let r=await this.recoverLocked(),s=(r.versions[e]??[]).filter(a=>i.includes(a.version));await this.removeLocked(e,r,s)})}};import{lstat as Aa,mkdir as xR,open as kw,realpath as Ew,readdir as zp,link as OR,rename as RR,unlink as qi,copyFile as NR,rm as PR}from"node:fs/promises";import{dirname as CR,isAbsolute as Tw,join as J,relative as Iw,resolve as MR,sep as Kp,win32 as DR}from"node:path";import{randomUUID as Yp}from"node:crypto";var Rn=192*1024*1024,d7=512*1024,xw=t=>typeof t=="string"&&/^[a-f0-9-]{36}$/.test(t);function LR(t){if(!t||typeof t!="object"||Array.isArray(t))throw new y("invalid_input","Expected object input");return t}function Aw(t){if(typeof t!="string"||!/^[\w.-]{1,160}$/.test(t)||t==="."||t==="..")throw new y("invalid_input","Invalid state key");return t}function Nn(t){if(t&&(!xw(t.stateRef)||typeof t.version!="string"||!Number.isSafeInteger(t.generation)||t.generation<1||!Number.isSafeInteger(t.schema)||t.schema<1||typeof t.enabled!="boolean"||typeof t.operationId!="string"))throw new y("invalid_storage","Invalid active plugin record");return t}var ji=class{root;pluginId;legacy;checkpoint;files;constructor(e,i,r,n,s=jp){this.root=J(e,re(i)),this.pluginId=i,this.legacy=r,this.checkpoint=n,this.files=s}rule(e){let i=typeof e=="string"?this.files.find(r=>e.toLowerCase().endsWith(r.extension)):void 0;if(!i)throw new y("invalid_path",`Use a workspace-relative ${this.files.map(r=>r.extension).join("/")} path`);return i}active(){return we(J(this.root,"active.json")).then(Nn)}async recover(){return Se(this.root,async()=>{let e=await this.active(),i=await ze(J(this.root,"transition.json"));if(!i)return{active:e,recovered:"none"};if(!i.next||!Object.hasOwn(i,"before")||Object.keys(i).some(a=>!["version","before","next"].includes(a))||Object.hasOwn(i,"version")&&i.version!==1)throw new y("invalid_storage","Invalid activation journal; stop all owners and inspect transition.json");Nn(i.next),Nn(i.before);let r=e?.operationId===i.next.operationId?"committed":"not_committed";if(!((a,o)=>a===null||o===null?a===o:["version","generation","stateRef","schema","enabled","operationId"].every(l=>a[l]===o[l]))(e,r==="committed"?i.next:i.before))throw new y("gc_recovery_required","Activation journal does not match the active pointer; original bytes preserved");let s=i.before;if(r==="committed"&&s&&s.stateRef!==e.stateRef&&await Z(J(this.root,"previous.json"),s),r==="committed"){let a=await ze(J(this.root,"fork.json"));a?.version===1&&a.stateRef===e.stateRef&&Object.keys(a).every(o=>["version","stateRef"].includes(o))&&await qi(J(this.root,"fork.json"))}return await qi(J(this.root,"transition.json")),{active:e,recovered:r}})}async activate(e,i){return Se(this.root,async()=>{let r=await this.active();if((r?.generation??0)!==e)throw new y("stale_generation","Plugin activation changed concurrently");let n=await ze(J(this.root,"fork.json"));if(n&&(n.version!==1||n.stateRef!==i.stateRef||Object.keys(n).some(a=>!["version","stateRef"].includes(a))))throw new y("gc_recovery_required","Activation refused: unresolved fork.json belongs to another target; stop all owners and inspect it");let s=Nn({...i,generation:e+1,operationId:Yp()});await ve(J(this.root,"states")),await ve(J(this.root,"states",s.stateRef)),await Z(J(this.root,"transition.json"),{version:1,before:r,next:s}),await this.checkpoint?.("prepared");try{await Z(J(this.root,"active.json"),s)}catch(a){if((await this.active())?.operationId!==s.operationId)throw a}await this.checkpoint?.("committed");try{r&&r.stateRef!==s.stateRef&&await Z(J(this.root,"previous.json"),r),await qi(J(this.root,"transition.json")),await qi(J(this.root,"fork.json")).catch(()=>{})}catch{}return await this.checkpoint?.("cleaned"),s})}async forkState(e){return Se(this.root,async()=>{let i=await this.assertGeneration(e,!1),r=Yp(),n=J(this.root,"states",r);if(await ze(J(this.root,"fork.json")))throw new y("gc_recovery_required","Unresolved fork.json; stop all owners and inspect the reserved state before retrying");await Z(J(this.root,"fork.json"),{version:1,stateRef:r}),await ve(n);let s=J(this.root,"states",i.stateRef);for(let a of await zp(s)){if(!/^[a-f0-9]{64}\.json$/.test(a))throw new y("invalid_storage","Unexpected state file");if(!await fe(J(s,a),Rn))throw new y("invalid_storage","Missing state file");await NR(J(s,a),J(n,a))}return await this.checkpoint?.("forked"),r})}async collect(e){return Se(this.root,async()=>{for(let c of["transition.json","fork.json"])if(await fe(J(this.root,c),2*1024*1024))throw new y("gc_recovery_required",`GC refused: unresolved ${c}; stop all owners and inspect recovery references`);let i=await this.active(),r=Nn(await ze(J(this.root,"previous.json")));if(!i&&await fe(J(this.root,"active.json"),2*1024*1024))throw new y("gc_recovery_required","GC refused: null active pointer; restore activation metadata before cleanup");let n=[i,r].filter(c=>!!c),s=J(this.root,"states");await ve(s);let a=await zp(s),o=new Set(n.map(c=>c.stateRef));for(let c of a){if(!xw(c))throw new y("gc_recovery_required","GC refused: unexpected state directory; inspect states before cleanup");let p=J(s,c),d=await Aa(p);if(!d.isDirectory()||d.isSymbolicLink())throw new y("gc_recovery_required","GC refused: linked/non-directory state snapshot");for(let m of await zp(p)){let g=await Aa(J(p,m));if(!/^[a-f0-9]{64}\.json$/.test(m)||!g.isFile()||g.isSymbolicLink()||g.nlink!==1)throw new y("gc_recovery_required","GC refused: unexpected snapshot content; original bytes preserved");if(!o.has(c)){let f=await we(J(p,m),Rn);if(!f)throw new y("gc_recovery_required","GC refused: missing snapshot record");if(Object.hasOwn(f,"committed")){let h=f;if(Object.keys(h).some(_=>!["requestId","inputHash","nextHash","committed"].includes(_))||h.committed!==!0||!/^[a-f0-9]{64}$/.test(h.inputHash)||!/^[a-f0-9]{64}$/.test(h.nextHash)||typeof h.requestId!="string")throw new y("gc_recovery_required",`GC refused: unresolved file intent in states/${c}; reconcile the workspace save before cleanup`)}else{if(Object.keys(f).some(h=>!["revision","schema","value","requestId","inputHash"].includes(h)))throw new y("gc_recovery_required","GC refused: unknown snapshot envelope; original bytes preserved");this.validateState(f)}}}}for(let c of o)if(!a.includes(c))throw new y("gc_recovery_required","GC refused: referenced snapshot is missing; restore recovery data first");let l=await e(n);for(let c of a)o.has(c)||await PR(J(s,c),{recursive:!0,force:!0});return l})}async assertGeneration(e,i=!0){let r=await this.active();if(!r||r.generation!==e||i&&!r.enabled)throw new y("stale_generation","Plugin generation is no longer active");return r}scopeKey(e){if(!e.scope||typeof e.scope.cwd!="string"||!e.scope.cwd||typeof e.scope.sessionId!="string"||!e.scope.sessionId||typeof e.scope.workspaceId!="string"||!e.scope.workspaceId)throw new y("invalid_scope","Missing authenticated plugin scope");return JSON.stringify([e.scope.workspaceId,e.scope.cwd,e.scope.sessionId])}statePath(e,i,r,n="session"){if(n!=="session"&&n!=="workspace")throw new y("invalid_input","Invalid state scope");let s=n==="workspace"?(this.scopeKey(i),JSON.stringify([i.scope.workspaceId,i.scope.cwd])):this.scopeKey(i);return J(this.root,"states",e.stateRef,`${re(s+":state:"+r)}.json`)}async call(e,i,r){if(!Number.isSafeInteger(e.generation)||!/^[\w-]{1,160}$/.test(e.requestId))throw new y("invalid_lease","Invalid invocation lease");this.scopeKey(e);let n=LR(r);return Se(this.root,async()=>{let s=await this.assertGeneration(e.generation);switch(i){case"state.read":{let a=await we(this.statePath(s,e,Aw(n.key),n.scope),Rn);return a?(this.validateState(a),{revision:a.revision,schema:a.schema,value:a.value}):null}case"state.compareAndSwap":{let a=this.statePath(s,e,Aw(n.key),n.scope);if(!Number.isSafeInteger(n.expectedRevision)||n.expectedRevision<0||n.schema!==s.schema||!Object.hasOwn(n,"value"))throw new y("invalid_input","Invalid state revision or schema");if(JSON.stringify(n.value)===void 0)throw new y("invalid_input","State value must be JSON serializable");let o=JSON.stringify(n);if(Buffer.byteLength(o)>Rn)throw new y("state_too_large","Plugin state exceeds limit");let l=await we(a,Rn);l&&this.validateState(l);let c=re(o);if(l?.requestId===e.requestId&&l.inputHash===c)return{revision:l.revision,schema:l.schema,value:l.value};if((l?.revision??0)!==n.expectedRevision)throw new y("revision_conflict","Plugin state changed concurrently");let p={revision:n.expectedRevision+1,schema:s.schema,value:n.value,requestId:e.requestId,inputHash:c};return await Z(a,p),{revision:p.revision,schema:p.schema,value:p.value}}case"workspace.read":{let a=this.rule(n.path),{target:o}=await this.fileTarget(e.scope.cwd,n.path),l=n.maxBytes===void 0?a.maxBytes:n.maxBytes;if(!Number.isSafeInteger(l)||l<=0||l>a.maxBytes)throw new y("invalid_input","Invalid workspace read limit");if(n.encoding!==void 0&&n.encoding!==(a.binary?"base64":"utf-8"))throw new y("invalid_input","Encoding does not match the reviewed file rule");let c=await fe(o,l);return c?a.binary?{base64:c.toString("base64"),bytes:c.length,hash:re(c)}:{text:new TextDecoder("utf-8",{fatal:!0}).decode(c),hash:re(c)}:null}case"workspace.commit":return this.commitFile(s,e,n);case"legacy.read":return this.legacy?this.legacy(e):null;default:throw new y("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 y("invalid_storage","Invalid plugin state; original bytes preserved")}async fileTarget(e,i,r=!1){let n=this.rule(i);if(typeof i!="string"||i.length>4096||i.includes("\\")||i.includes("\0")||Tw(i)||DR.isAbsolute(i))throw new y("invalid_path",`Use a workspace-relative ${n.extension} path`);let s=await Ew(e),a=MR(s,i),o=Iw(s,a);if(!o||o===".."||o.startsWith(`..${Kp}`)||Tw(o))throw new y("invalid_path","Workspace path escapes root");let l=s,c=o.split(Kp);for(let d=0;d<c.length;d++){l=J(l,c[d]);let m;try{m=await Aa(l)}catch(g){if(!Zt(g))throw g;if(d<c.length-1){if(!r||!n.createDirectory||Iw(s,l)!==n.createDirectory)throw new y("invalid_path","Workspace directory does not exist");try{await xR(l,{mode:448})}catch(f){if(f.code!=="EEXIST")throw f}m=await Aa(l)}}if(m&&(m.isSymbolicLink()||(d<c.length-1?!m.isDirectory():!m.isFile()||m.nlink!==1)))throw new y("invalid_path","Workspace path contains a link or non-regular file")}let p=await Ew(CR(a));if(p!==s&&!p.startsWith(s+Kp))throw new y("invalid_path","Workspace directory changed");return{target:a,parent:p}}async commitFile(e,i,r){let n=this.rule(r.path),s=n.binary?typeof r.base64=="string"&&r.text===void 0&&/^[A-Za-z0-9+/]*={0,2}$/.test(r.base64)?Buffer.from(r.base64,"base64"):null:typeof r.text=="string"&&r.base64===void 0?Buffer.from(r.text):null;if(!s||s.length>n.maxBytes||!(r.expectedHash===null||typeof r.expectedHash=="string"&&/^[a-f0-9]{64}$/.test(r.expectedHash)))throw new y("invalid_input","Invalid file content or expected hash");let{target:a,parent:o}=await this.fileTarget(i.scope.cwd,r.path,!0),l=J(this.root,"states",e.stateRef,`${re(this.scopeKey(i)+":file:"+i.requestId+":"+String(r.path))}.json`),c=re(JSON.stringify(r)),p=re(s),d=await we(l);if(d&&(d.requestId!==i.requestId||d.inputHash!==c||d.nextHash!==p))throw new y("duplicate_request","Request ID was reused with different content");let m;try{m=await kw(`${a}.lock`,"wx",384)}catch(f){throw f.code==="EEXIST"?new y("file_busy","Workspace file is locked; original file preserved"):f}let g;try{await m.writeFile(JSON.stringify({pid:process.pid,requestId:i.requestId}));let f=await fe(a,n.maxBytes),h=f?re(f):null;if(d&&h===p)return{hash:p};if(d?.committed||h!==r.expectedHash)throw new y("file_conflict","Workspace file already exists or changed externally");await Z(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!1}),g=J(o,`.plugin-${Yp()}.tmp`);let _=await kw(g,"wx",384);try{await _.writeFile(s),await _.sync()}finally{await _.close()}if((await this.fileTarget(i.scope.cwd,r.path)).parent!==o)throw new y("file_conflict","Workspace directory changed during save");let E=await fe(a,n.maxBytes);if((E?re(E):null)!==r.expectedHash)throw new y("file_conflict","Workspace file changed during save");if(await this.assertGeneration(i.generation),r.expectedHash===null){try{await OR(g,a)}catch(A){throw A.code==="EEXIST"?new y("file_conflict","Workspace file was created concurrently"):A}await qi(g),g=void 0}else await RR(g,a),g=void 0;return await Z(l,{requestId:i.requestId,inputHash:c,nextHash:p,committed:!0}),{hash:p}}finally{g&&await qi(g).catch(()=>{}),await m.close(),await qi(`${a}.lock`)}}};import{randomUUID as FR}from"node:crypto";import{fork as UR}from"node:child_process";import{randomUUID as qR}from"node:crypto";import{join as jR}from"node:path";import{EventEmitter as BR}from"node:events";var Ow=192*1024*1024,Pn=class t{child;pending=new Map;events=new BR;stopped=!1;unhealthy=!1;closing=!1;generation;package;tools=[];broker;constructor(e,i,r,n){this.package=e,this.generation=i,this.broker=n;let s={};for(let a of["LANG","LC_ALL","TZ","TMPDIR","TMP","TEMP","SystemRoot","WINDIR"])process.env[a]&&(s[a]=process.env[a]);this.child=UR(r,[],{env:s,execArgv:[],cwd:e.root,stdio:["ignore","ignore","ignore","ipc"],serialization:"json"}),this.child.on("message",a=>{this.receive(a)}),this.child.once("error",a=>this.fail(a)),this.child.once("exit",()=>this.fail(new y("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,i,r,n,s=1e4){let a=new t(e,i,r,n);try{await a.request("initialize",{entry:jR(e.root,e.manifest.backend.entry.slice(2)),pluginId:e.id,version:e.version,generation:i},s);let o=await a.request("describe",void 0,s);if(!o||!Array.isArray(o.tools)||o.tools.length>128)throw new y("invalid_tools","Invalid hosted tool catalog");let l=new Set;for(let c of o.tools){if(!c||typeof c.name!="string"||!/^[A-Za-z_][\w-]{0,79}$/.test(c.name)||l.has(c.name)||typeof c.label!="string"||typeof c.description!="string"||typeof c.action!="string"||!/^[\w.-]{1,80}$/.test(c.action)||!c.parameters||typeof c.parameters!="object"||Array.isArray(c.parameters)||c.parameters.type!=="object")throw new y("invalid_tools","Invalid or duplicate tool descriptor");l.add(c.name)}return a.tools=structuredClone(o.tools),await a.request("health",void 0,s),a}catch(o){throw await a.dispose(),o}}fail(e){this.stopped=!0;for(let i of this.pending.values())clearTimeout(i.timer),i.reject(e);this.pending.clear(),this.events.emit("idle")}async receive(e){if(!e||typeof e!="object"||this.stopped)return;let i;try{i=Buffer.byteLength(JSON.stringify(e))}catch{return}if(i>Ow){this.unhealthy=!0;return}let r=e;if(r.type==="response"&&typeof r.id=="string"){let n=this.pending.get(r.id);if(!n)return;if(clearTimeout(n.timer),this.pending.delete(r.id),!n.expired){let s=r.error;r.ok===!0?n.resolve(r.value):n.reject(new y(s?.code??"plugin_failed",s?.message??"Plugin request failed",s))}this.inFlight||this.events.emit("idle")}else if(r.type==="broker-request"&&typeof r.id=="string"&&typeof r.invocationId=="string"&&typeof r.method=="string"){let n=this.pending.get(r.invocationId);try{if(!n?.invocation||n.expired)throw new y("invalid_lease","Plugin invocation lease is no longer writable");let s=await this.broker(n.invocation,r.method,r.input);this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!0,value:s})}catch(s){this.child.connected&&this.child.send({type:"broker-response",id:r.id,ok:!1,error:me(s)})}}}request(e,i,r=3e4,n){if(this.stopped||this.closing&&e!=="dispose")return Promise.reject(new y("worker_closed","Plugin process is not available"));if(this.pending.size>=64)return Promise.reject(new y("worker_busy","Too many plugin requests"));let s=n?.requestId??qR();if(this.pending.has(s))return Promise.reject(new y("duplicate_request","An identical request is still running"));let a={type:"request",id:s,method:e,input:i};return Buffer.byteLength(JSON.stringify(a))>Ow?Promise.reject(new y("message_too_large","Plugin request exceeds limit")):new Promise((o,l)=>{let c=setTimeout(()=>{let p=this.pending.get(s);p&&(p.expired=!0,this.unhealthy=!0,p.invocation||this.pending.delete(s),l(new y("worker_timeout","Plugin request timed out; execution outcome may be unknown")))},r);this.pending.set(s,{resolve:o,reject:l,timer:c,invocation:n,expired:!1}),this.child.send(a,p=>{p&&(clearTimeout(c),this.pending.delete(s),l(p),this.inFlight||this.events.emit("idle"))})})}invoke(e,i=3e4){return!this.healthy||e.generation!==this.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.request("invoke",e,i,e)}waitForIdle(e=3e4){return this.inFlight?new Promise(i=>{let r=()=>{clearTimeout(n),this.events.off("idle",r),i(!0)},n=setTimeout(()=>{this.events.off("idle",r),i(!1)},e);this.events.once("idle",r)}):Promise.resolve(!0)}async dispose(){if(!this.stopped){if(this.inFlight)throw new y("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 i=()=>{clearTimeout(r),e()},r=setTimeout(()=>{this.child.kill("SIGKILL")},1e3);this.child.once("exit",i),this.child.kill("SIGTERM")})}}}};var HR={canSwitch:()=>!0,freeze:async()=>{},committed:async()=>{},resume:async()=>{}},xa=class{worker=null;operations=Promise.resolve();phaseValue="disabled";pendingPackage=null;releaseOwnership=null;broker;workerEntry;hooks;capabilities;constructor(e,i,r=HR,n){this.broker=e,this.workerEntry=i,this.hooks=r,this.capabilities=n}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 i=this.operations.then(e,e);return this.operations=i.catch(()=>{}),i}async ownRuntime(){if(this.releaseOwnership)return;let e=await hp(this.broker.root,"runtime");this.releaseOwnership=async()=>{await e(),this.releaseOwnership=null}}callBroker=(e,i,r)=>this.capabilities?.handles(i)?!this.worker||e.generation!==this.worker.generation?Promise.reject(new y("stale_generation","Plugin runtime is not active at this generation")):this.capabilities.call(this.broker.pluginId,this.worker.package.manifest,e,i,r):this.broker.call(e,i,r);invoke(e,i){return this.phaseValue!=="active"||!this.worker?Promise.reject(new y("plugin_unavailable","Plugin is disabled or waiting at a safe switch boundary")):this.worker.invoke({...e,generation:this.worker.generation},i)}flushAction(e,i){return!this.worker||!["active","draining"].includes(this.phaseValue)?Promise.reject(new y("plugin_unavailable","No plugin is available for checkpoint synchronization")):this.worker.invoke({...e,kind:"action",generation:this.worker.generation},i)}replace(e,i=3e4){return this.serialize(async()=>{if(e.id!==this.broker.pluginId)throw new y("identity_mismatch","Plugin package identity mismatch");if(!await this.hooks.canSwitch())return this.pendingPackage=e,{pending:!0};await this.ownRuntime();let r;try{if(r=(await this.broker.recover()).active,r&&r.schema!==e.manifest.dataSchemaVersion)throw new y("migration_required","Cross-schema activation requires a verified state migration; old state preserved")}catch(c){throw this.worker||await this.releaseOwnership?.(),c}let n=r?.generation??0,s=this.worker;s||(this.phaseValue="starting");let a=null,o=!1,l=!1;try{if(a=await Pn.start(e,n+1,this.workerEntry,this.callBroker),this.phaseValue="draining",s&&!await s.waitForIdle(i))throw new y("drain_pending","Plugin calls are still running; switch deferred without killing them");if(l=!0,await this.hooks.freeze(),s&&!await s.waitForIdle(i))throw new y("drain_pending","Checkpoint synchronization is still running");if(!await this.hooks.canSwitch())throw new y("editor_busy","Editor became active during preparation; switch deferred");await this.hooks.validateCandidate?.(structuredClone(a.tools)),this.phaseValue="switching";let c=r?await this.broker.forkState(n):FR(),p=await this.broker.activate(n,{version:e.version,stateRef:c,schema:e.manifest.dataSchemaVersion,enabled:!0});o=!0,this.worker=a,a=null,this.phaseValue="active",this.pendingPackage=null;let d=!1;try{await this.hooks.committed(p)}catch{d=!0}return await s?.dispose(),{pending:!1,active:p,...d?{reconnectRequired:!0}:{}}}catch(c){throw o||(this.phaseValue=s?.healthy?"active":s?"failed":"disabled",l&&await this.hooks.resume().catch(()=>{})),c}finally{await a?.dispose(),this.worker||await this.releaseOwnership?.()}})}retryPending(e){return this.pendingPackage?this.replace(this.pendingPackage,e):Promise.resolve({pending:!1})}suspendForRestart(e=3e4,i=!1){return this.serialize(async()=>{let r=this.worker,n=this.phaseValue,s=await this.broker.active(),a=async()=>{if(!(!r||this.worker)){if(await this.ownRuntime(),JSON.stringify(await this.broker.active())!==JSON.stringify(s))throw await this.releaseOwnership?.(),this.phaseValue="failed",new y("restart_recovery_changed","Plugin state changed during host handoff; retain data and reconnect to its current owner");try{this.worker=await Pn.start(r.package,r.generation,this.workerEntry,this.callBroker),await this.hooks.validateCandidate?.(this.worker.tools)}catch(l){throw await this.worker?.dispose(),this.worker=null,this.phaseValue="failed",await this.releaseOwnership?.(),l}}};this.phaseValue="draining";try{let l=async c=>{try{await c()}catch(p){if(!i)throw p}};await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Plugin work is still draining; current host retained")}),await l(()=>this.hooks.freeze()),await l(async()=>{if(r&&!await r.waitForIdle(e))throw new y("drain_pending","Checkpoint work is still draining; current host retained")}),await r?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(l){try{await a(),this.phaseValue=n,await this.hooks.resume()}catch(c){throw this.phaseValue="failed",c}throw l}let o=!1;return()=>this.serialize(async()=>{o||(await a(),this.phaseValue=n,await this.hooks.resume(),o=!0)})})}disable(e=3e4){return this.serialize(async()=>{await this.ownRuntime();let i=this.worker,r;try{r=(await this.broker.recover()).active}catch(a){throw i||await this.releaseOwnership?.(),a}if(!r){if(i)throw this.phaseValue="failed",new y("storage_missing","Active plugin storage is missing; refusing to report a successful disable");this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}if(!i&&!r.enabled){this.phaseValue="disabled",this.pendingPackage=null,await this.releaseOwnership?.();return}let n=this.phaseValue;this.phaseValue="draining";let s=!1;try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Plugin still has in-flight work; not killed");if(s=!0,await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Checkpoint synchronization is still running");let a=await this.broker.activate(r.generation,{version:r.version,stateRef:r.stateRef,schema:r.schema,enabled:!1});this.worker=null,this.phaseValue="disabled",this.pendingPackage=null,await i?.dispose(),await this.hooks.committed(a)}catch(a){throw this.worker===i&&(this.phaseValue=n,s&&await this.hooks.resume().catch(()=>{})),a}finally{this.worker||await this.releaseOwnership?.()}})}shutdown(e=3e4){return this.serialize(async()=>{let i=this.worker,r=this.phaseValue;this.phaseValue="draining";try{if(i&&!await i.waitForIdle(e))throw new y("drain_pending","Host shutdown still has plugin work to drain");if(await this.hooks.freeze(),i&&!await i.waitForIdle(e))throw new y("drain_pending","Host checkpoint synchronization is still running");await i?.dispose(),this.worker=null,this.phaseValue="disabled",await this.releaseOwnership?.()}catch(n){throw this.phaseValue=r,await this.hooks.resume().catch(()=>{}),n}})}};import{readFile as Rw}from"node:fs/promises";var Oa=class{installer;options;supervisors=new Map;packages=new Map;assetTokens=new Map;operations=new Map;errors=new Map;available=new Map;assetLeases=new Map;closing=!1;scheduler;constructor(e){this.options=e,this.installer=new _r({root:Ze(e.root,"packages"),hostVersion:e.hostVersion,catalog:e.catalog,fetch:e.fetch});let i=e.capabilities?new ka(e.capabilities):void 0;this.scheduler=new Ea({invoke:async(r,n)=>{let s=this.closing?null:e.scheduledScope?.(r)??null;s&&await this.supervisor(r).invoke({requestId:WR(),scope:s,kind:"action",action:n.action,input:{schedule:n.id}})},onError:(r,n,s)=>e.onScheduleError?.(r,n.id,s),...e.scheduleTimers});for(let r of this.installer.catalog){let n=new ji(Ze(e.root,"data"),r.id,e.legacy?.(r.id),void 0,e.workspaceRules?.(r.id)),s=e.hooks(r.id);this.supervisors.set(r.id,new xa(n,e.workerEntry,{validateCandidate:a=>s.validateCandidate?.(a),canSwitch:()=>s.canSwitch(),freeze:()=>s.freeze(),resume:()=>s.resume(),committed:async a=>{if(a.enabled){let o=await this.installer.load(r.id,a.version);this.packages.set(r.id,o),this.assetTokens.set(r.id,GR(24).toString("base64url"));try{this.scheduler.start(r.id,hr(o.manifest).schedules)}catch(l){this.scheduler.stop(r.id),this.errors.set(r.id,me(l))}}else this.scheduler.stop(r.id),this.packages.delete(r.id),this.assetTokens.delete(r.id);await s.committed(a)}},i))}}devSource(e){let i=this.options.devRoots?.get(e),r=this.options.devArchives?.get(e);return!i&&!r?null:async n=>(await this.collectSettled(e).catch(()=>{}),i?this.installer.installDevDirectory(e,i,n):this.installer.installDevArchive(e,r,n))}isDevPlugin(e){return!!(this.options.devRoots?.has(e)||this.options.devArchives?.has(e))}supervisor(e){Ke(e,this.installer.catalog);let i=this.supervisors.get(e);if(!i)throw new y("unknown_plugin","Plugin runtime is not registered");return i}serialize(e,i){if(this.supervisor(e),this.closing)return Promise.reject(new y("manager_closed","Plugin manager is shutting down"));let 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,me(n))}).finally(()=>{this.operations.get(e)===r&&this.operations.delete(e)}),r}lifecycle(e,i,r=!1){return this.options.lifecycle?this.options.lifecycle(e,i,r):i()}async policies(){let e=await we(Ze(this.options.root,"policies","policies.json"));if(!e){if(await fe(Ze(this.options.root,"policies","policies.json"),2*1024*1024))throw new y("invalid_storage","Null plugin policies; restore pin/disable choices before cleanup");return{}}for(let[i,r]of Object.entries(e))if(this.installer.catalog.some(n=>n.id===i)&&(!r||!["notify","automatic","pinned"].includes(r.updatePolicy)||r.updatePolicy==="pinned"&&!r.pinnedVersion||r.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(r.pinnedVersion)))throw new y("invalid_storage","Invalid plugin update policy");return Object.fromEntries(Object.keys(e).map(i=>[i,{updatePolicy:"notify"}]))}async diagnostics(){return await we(Ze(this.options.root,"policies","update-checks.json"))??{}}async recordCheck(e,i){await Se(Ze(this.options.root,"policies"),async()=>{let r=await this.diagnostics();r[e]={...i,hostVersion:this.options.hostVersion,checkedAt:new Date().toISOString()},await Z(Ze(this.options.root,"policies","update-checks.json"),r)})}recordDevSync(e,i){return this.recordCheck(e,{status:"up-to-date",version:i,message:"Developer source installed"})}async check(e,i,r,n){try{let s=await this.installer.check(e,i,r,n),a=!i||ft(s.version,i)>0;return a?this.available.set(e,s):this.available.delete(e),await this.recordCheck(e,{status:a?"available":"up-to-date",version:s.version,message:a?"Compatible stable release available":"No newer compatible stable release; installed code preserved"}),s}catch(s){throw this.available.delete(e),await this.recordCheck(e,{status:"failed",code:me(s).code,message:me(s).message}),s}}async setPolicy(e,i){if(this.supervisor(e),!["notify","automatic","pinned"].includes(i.updatePolicy)||i.updatePolicy==="pinned"&&!i.pinnedVersion||i.pinnedVersion&&!/^\d+\.\d+\.\d+$/.test(i.pinnedVersion))throw new y("invalid_input","Invalid plugin update policy");await Se(Ze(this.options.root,"policies"),async()=>{let r=await this.policies();r[e]={updatePolicy:"notify"},await Z(Ze(this.options.root,"policies","policies.json"),r)})}settleHostPair(){return Se(ma(this.options.root),async()=>{let e=await _p(this.options.root);if(!e)return{intent:e,admitted:!1};if(!vp(e))return e.phase==="required-action"&&await fa(this.options.root,e),{intent:e,admitted:!1};try{if(e.version!==this.options.hostVersion||e.hostDigest!==await bp(e.version,e.packageRoot)||this.options.packageRoot&&e.hostDigest!==await bp(this.options.hostVersion,this.options.packageRoot)||!Buffer.from(await Rw(this.options.workerEntry)).equals(await Rw(Ze(e.packageRoot,"dist","hosted-worker.js"))))throw new Error("Running host differs from selected pair")}catch(i){return await fa(this.options.root,{...e,phase:"cancelled",message:`Selected host not running; current host and plugins retained. ${me(i).message}; data retained`}),{intent:e,admitted:!1}}return await fa(this.options.root,{...e,phase:"reconciled",message:"Selected host running; plugins load independently and report their own errors"}),{intent:e,admitted:!0}})}async start(){await Se(Ze(this.options.root,"policies"),async()=>{let i=await this.policies();await Z(Ze(this.options.root,"policies","policies.json"),i)});let{admitted:e}=await this.settleHostPair();await this.installer.inventory();for(let i of this.installer.catalog){let r=this.supervisor(i.id),n=await r.broker.active();if(n?.enabled)try{let s=await this.compatiblePackage(i.id,n.version);await this.lifecycle(i.id,()=>r.replace(s)),this.packages.set(i.id,s),e||await this.collectSettled(i.id)}catch(s){let a=me(s),o=["runtime_owned","storage_busy"].includes(a.code)?"Stop all owners, verify a backup and use the offline hosted-recovery tool.":"Update, reinstall or disable this plugin; the rest of the app is unaffected.";this.errors.set(i.id,{...a,message:`Plugin unavailable: startup failed (${a.code}): ${a.message}; data retained. ${o}`})}}}async compatiblePackage(e,i){try{return await this.installer.load(e,i)}catch(r){if(me(r).code!=="incompatible_plugin")throw r;let n=((await this.installer.inventory()).versions[e]??[]).map(s=>s.version).filter(s=>s!==i).sort((s,a)=>ft(a,s));for(let s of n)try{return await this.installer.load(e,s)}catch{}throw r}}async inventory(){let e=await this.installer.inventory(),i=await this.policies(),r=await this.diagnostics();return{plugins:await Promise.all(this.installer.catalog.map(async s=>{let a=this.supervisor(s.id),o=await a.broker.active(),l=this.packages.get(s.id),c=(e.versions[s.id]??[]).map(p=>p.version).sort((p,d)=>ft(d,p));return{id:s.id,name:s.name,description:s.description,official:s.official!==!1,installed:!!c.length,installedVersions:c,version:c[0]??null,activeVersion:o?.version??null,enabled:o?.enabled??!1,phase:a.phase,generation:a.generation,pendingVersion:a.pendingVersion,updatePolicy:i[s.id]?.updatePolicy??"notify",pinnedVersion:i[s.id]?.pinnedVersion,updateDiagnostic:r[s.id],availableVersion:this.available.get(s.id)?.version??(r[s.id]?.status==="available"?r[s.id].version??null:null),...this.errors.has(s.id)?{error:this.errors.get(s.id)}:{},...l&&a.phase==="active"?{digest:l.digest,document:l.manifest.frontend.document.slice(2),controller:l.manifest.frontend.controller.slice(2),assetBase:`/hosted-plugins/${encodeURIComponent(s.id)}/${this.assetTokens.get(s.id)}/${l.digest}/`}:{}}})),errors:[]}}get tools(){return[...this.supervisors].flatMap(([e,i])=>i.phase==="active"&&i.generation!==null?[{pluginId:e,generation:i.generation,descriptors:i.tools}]:[])}async manage(e,i,r,n){return this.serialize(e,async()=>{let s=this.supervisor(e),a=(await this.installer.inventory()).versions[e]??[],o=a.map(c=>c.version).sort((c,p)=>ft(p,c))[0],l=await(async()=>{switch(i){case"check":return this.isDevPlugin(e)?{version:o??null,dev:!0}:{version:(await this.check(e,o,void 0,n)).version};case"install":{let c=this.devSource(e);if(c){let m=await c(n);return await this.recordDevSync(e,m.version),{installed:!0,version:m.version}}let p=await this.check(e,o,r,n),d=await this.installer.install(e,p,n);return this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:d.version,message:"Selected compatible release installed; enablement unchanged"}),{installed:!0,version:d.version}}case"enable":{let c=r??o;if(!c)throw new y("not_installed","Install the plugin first");let p=await this.installer.load(e,c),d=await this.lifecycle(e,()=>s.replace(p));return d.pending||this.packages.set(e,p),d}case"retry":{let c=s.pendingVersion,p=await this.lifecycle(e,()=>s.retryPending());return c&&!p.pending&&this.packages.set(e,await this.installer.load(e,c)),p}case"disable":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),{enabled:!1};case"update":{if(!o)throw new y("not_installed","Only installed plugins can be updated");let c=this.devSource(e);if(c){let f=await c(n),h=await s.broker.active();if(await this.recordDevSync(e,f.version),!h?.enabled)return{installed:!0,enabled:!1,version:f.version};if(h.version===f.version&&!s.pendingVersion)return{unchanged:!0,version:f.version};let _=await this.lifecycle(e,()=>s.replace(f));return _.pending||this.packages.set(e,f),_}let p=await this.check(e,o,r,n),d=await s.broker.active();if(p.version===o&&(!d?.enabled||d.version===o)&&!s.pendingVersion)return{unchanged:!0,version:o};let m=p.version===o?await this.installer.load(e,o):await this.installer.install(e,p,n);if(this.available.delete(e),await this.recordCheck(e,{status:"up-to-date",version:m.version,message:"Selected compatible release installed; activation may wait for editors"}),!d?.enabled)return{installed:!0,enabled:!1,version:m.version};let g=await this.lifecycle(e,()=>s.replace(m));return g.pending||this.packages.set(e,m),g}case"uninstall":return await this.lifecycle(e,()=>s.disable()),this.packages.delete(e),await this.installer.removeVersions(e,a.map(c=>c.version)),this.available.delete(e),{installed:!1,dataPreserved:!0};default:throw new y("invalid_operation","Unknown plugin management operation")}})().catch(async c=>{if(["install","update"].includes(i)){this.available.delete(e);let p=me(c);await this.recordCheck(e,{status:"failed",code:p.code,message:p.message})}throw c});return["install","enable","retry","update"].includes(i)&&await this.collectSettled(e),l})}collect(e){return this.serialize(e,()=>this.collectSettled(e))}async collectSettled(e){let i=this.supervisor(e);return i.broker.collect(async r=>this.installer.collect(e,async()=>{let n=(await this.policies())[e];return[...r.map(s=>s.version),...i.pendingVersion?[i.pendingVersion]:[],...this.packages.has(e)?[this.packages.get(e).version]:[],...n?.pinnedVersion?[n.pinnedVersion]:[],...this.assetLeases.get(e)?.keys()??[]]}))}invoke(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Reconnect the plugin view before editing",{status:409})):n.invoke(r,this.options.invokeTimeoutMs?.(e))}flush(e,i,r){let n=this.supervisor(e);return i!==n.generation?Promise.reject(new y("stale_generation","Flush generation changed",{status:409})):n.flushAction(r)}async asset(e,i,r){let n=this.packages.get(e);if(!n)return null;let s=this.assetLeases.get(e);s||(s=new Map,this.assetLeases.set(e,s)),s.set(n.version,(s.get(n.version)??0)+1);try{return await dw(n,r,i)}finally{let a=s.get(n.version)-1;a?s.set(n.version,a):s.delete(n.version)}}async assetRequest(e){let i=/^\/hosted-plugins\/([^/]+)\/([A-Za-z0-9_-]{32})\/([a-f0-9]{64})\/(.+)$/.exec(e);if(!i)return null;let r;try{r=decodeURIComponent(i[1])}catch{return null}let n=this.assetTokens.get(r),s=Buffer.from(i[2]);if(!n||s.length!==Buffer.byteLength(n)||!$R(s,Buffer.from(n)))return null;let a=await this.asset(r,i[3],i[4]);return a?{...a,pluginId:r}:null}servedManifest(e){return this.packages.get(e)?.manifest??null}async reconcileHostUpgrade(){if(Iv(await _p(this.options.root)))return!1;let e=await this.installer.inventory(),i=await this.policies(),r=!0;for(let n of this.installer.catalog){let s=e.versions[n.id];if(s?.length)try{let a=await this.supervisor(n.id).broker.active(),o=a?.enabled?a.version:s.map(c=>c.version).sort((c,p)=>ft(p,c))[0];try{await this.installer.load(n.id,o);continue}catch(c){if(me(c).code!=="incompatible_plugin")throw c}let l=await this.manage(n.id,"update");l&&typeof l=="object"&&"pending"in l&&l.pending&&(r=!1)}catch(a){r=!1;let o=me(a);this.errors.set(n.id,o),await this.recordCheck(n.id,{status:"failed",code:o.code,message:o.message})}}return r}async pairSnapshot(){return{policies:await this.policies(),active:await Promise.all(this.installer.catalog.map(async e=>[e.id,await this.supervisor(e.id).broker.active()]))}}async prefetchForHost(e,i){let r=new _r({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog,fetch:this.options.fetch}),n=await this.installer.inventory();for(let s of this.installer.catalog){let a=(n.versions[s.id]??[]).map(c=>c.version).sort((c,p)=>ft(p,c)),o=await this.supervisor(s.id).broker.active();if(!a.length||this.isDevPlugin(s.id))continue;let l=!1;for(let c of new Set([...o?.enabled?[o.version]:[],...a]))try{await r.load(s.id,c),l=!0;break}catch{}if(!l)try{let c=await r.check(s.id,a[0],void 0,i),p=await r.install(s.id,c,i);await this.recordCheck(s.id,{status:"up-to-date",version:p.version,message:"Release compatible with the next software version downloaded; activation happens on that version"})}catch(c){i?.throwIfAborted();let p=me(c);await this.recordCheck(s.id,{status:"failed",code:p.code,message:`${p.message}; plugin will be unavailable after the software update until a compatible release is installed`}).catch(()=>{})}}}async hostUpdateWarnings(e){let i=new _r({root:this.installer.root,hostVersion:e,catalog:this.installer.catalog}),r=await this.installer.inventory(),n=[];for(let s of this.installer.catalog){let a=r.versions[s.id],o=await this.supervisor(s.id).broker.active();if(!o?.enabled)continue;if(!a?.length){n.push({pluginId:s.id,message:"Plugin is not installed; it stays unavailable after the update until it is reinstalled"});continue}let l=[o.version,...a.map(d=>d.version).sort((d,m)=>ft(m,d))],c=!1,p="";for(let d of new Set(l))try{await i.load(s.id,d),c=!0;break}catch(m){p||=me(m).message}c||n.push({pluginId:s.id,message:`No installed version supports ${e} (${p}); it is unavailable after the update until a compatible release is installed`})}return n}async shutdown(){this.closing=!0,await Promise.allSettled(this.operations.values());let e=[];try{for(let[i,r]of this.supervisors)e.push(await this.lifecycle(i,()=>r.suspendForRestart(),!0));this.scheduler.stopAll(),this.packages.clear(),this.assetTokens.clear()}catch(i){throw await Promise.allSettled(e.reverse().map(r=>r())),this.closing=!1,i}}async suspendForRestart(e=!1){this.closing=!0,await Promise.allSettled(this.operations.values());let i=[],r=async()=>{let n=await Promise.allSettled(i.map(a=>a()));this.closing=!1;let s=n.find(a=>a.status==="rejected");if(s?.status==="rejected")throw s.reason};try{for(let n of this.supervisors.values())i.push(await n.suspendForRestart(void 0,e));return r}catch(n){throw await r(),n}}};import{randomUUID as VR}from"node:crypto";var K=t=>Object.assign(new Error(t),{status:409,code:"view_barrier"}),Cn=class{views=new Map;recoveries=new Map;cancelledRegistrations=new Set;retired=new Map;sequence=0;barrier=null;switching=!1;immediate=!1;pluginId;generation;pollMs;freezeMs;staleMs;constructor(e,i,r=2e4,n=15e3,s=12e4){this.pluginId=e,this.generation=i,this.pollMs=r,this.freezeMs=n,this.staleMs=s}allowImmediateReopen(e){this.immediate=e}canSwitch=()=>[...this.views.values()].every(e=>e.kind==="controller"?!e.activeActions:this.switching?e.frozen&&!e.dirty&&!e.busy:e.frozen||!e.busy&&(this.immediate||!["editor","workspace"].includes(e.kind)));blockedOnlyByWork=()=>[...this.views.values()].every(e=>e.kind==="controller"||e.frozen||this.immediate||!["editor","workspace"].includes(e.kind));authoringViews(){return[...this.views.values()].filter(e=>e.kind!=="controller")}pendingViews(e){return this.authoringViews().filter(i=>i.scope.ownerId===e).map(i=>({...i.identity,viewToken:i.token,kind:i.kind,dirty:i.dirty,busy:i.busy}))}sameScope(e,i,r){return e.scope.ownerId===r.ownerId&&e.scope.workspaceId===r.workspaceId&&e.identity.sessionId===i.sessionId&&e.identity.mountId===i.mountId&&e.identity.generation===i.generation}recovery(e,i){return{state:i,kind:e.kind,dirty:e.dirty,busy:e.busy||!!e.activeActions}}authorizesFlush(e,i){let r=e.viewToken?this.views.get(e.viewToken):void 0;return!!(this.barrier&&r&&this.barrier.pending.has(r.token)&&e.pluginId===this.pluginId&&e.generation===this.generation&&r.identity.generation===e.generation&&r.identity.mountId===e.mountId&&r.identity.sessionId===e.sessionId&&i.sessionId===e.sessionId&&r.scope.ownerId===i.ownerId&&r.scope.workspaceId===i.workspaceId)}admitAction(e,i){if(e.viewToken===void 0&&e.mountId===void 0)return()=>{};let r=e.viewToken?this.views.get(e.viewToken):void 0;if(!r||r.identity.generation!==this.generation||e.generation!==r.identity.generation||e.mountId!==r.identity.mountId||e.sessionId!==r.identity.sessionId||i.ownerId!==r.scope.ownerId||i.workspaceId!==r.scope.workspaceId||i.sessionId!==r.identity.sessionId)throw K("Unknown or stale view action capability");if(this.switching&&r.kind==="controller")throw K("Controller admission paused during plugin switching");return r.initialized=!0,r.activeActions=(r.activeActions??0)+1,()=>{r.activeActions--}}enqueue(e,i,r=++this.sequence){return e.commands.push({id:r,type:i,generation:this.generation}),e.waiter?.(),r}retire(e){e.waiter?.(),this.views.delete(e.token),this.cancelledRegistrations.add(e.token),this.retired.set(e.token,{identity:e.identity,scope:e.scope}),this.retired.size>1024&&this.retired.delete(this.retired.keys().next().value)}async handle(e,i){if(!e||e.pluginId!==this.pluginId||e.sessionId!==i.sessionId||!i.ownerId||!i.workspaceId||typeof e.mountId!="string"||e.mountId.length>200||!e.mountId)throw K("Invalid authenticated view scope");if(e.operation==="register"){if(this.switching||e.generation!==this.generation)throw K("Generation is switching; reconnect");if(!["controller","workspace","editor","tool"].includes(e.kind))throw K("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 K("Invalid registration capability");let a=e.viewToken??VR();if(this.cancelledRegistrations.has(a)||this.recoveries.has(a))throw K("View initialization was cancelled; register a new document identity");let o=this.views.get(a);if(o){if(!this.sameScope(o,e,i)||o.kind!==e.kind)throw K("Duplicate view capability");return{viewToken:a,commands:[]}}if([...this.views.values()].some(l=>l.scope.ownerId===i.ownerId&&l.identity.mountId===e.mountId))throw K("Duplicate mount");return this.views.set(a,{identity:{pluginId:e.pluginId,sessionId:e.sessionId,generation:e.generation,mountId:e.mountId},scope:{...i},token:a,kind:e.kind,initialized:!1,dirty:e.kind!=="controller",busy:e.kind!=="controller",frozen:!1,commands:[],seenAt:Date.now()}),{viewToken:a,commands:[]}}if(typeof e.viewToken!="string"||!e.viewToken||e.viewToken.length>200)throw K("Invalid view capability");let r=this.views.get(e.viewToken),n=this.recoveries.get(e.viewToken),s=this.retired.get(e.viewToken);if(s&&!this.sameScope(s,e,i))throw K("Unknown or stale view capability");if(e.operation==="status"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw K("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};let a=!r.waiter&&Date.now()-r.seenAt>this.staleMs;return{viewToken:r.token,commands:[],recovery:{...this.recovery(r,this.switching||r.activeActions?"active":"unconfirmed"),stale:a}}}if(r&&this.sameScope(r,e,i)&&e.operation!=="reconcile"&&e.operation!=="recover"&&(r.seenAt=Date.now()),e.operation==="reconcile"||e.operation==="recover"){if(r&&!this.sameScope(r,e,i)||n&&!this.sameScope(n,e,i))throw K("Unknown or stale view capability");if(n)return{viewToken:e.viewToken,commands:[],recovery:this.recovery(n,"retained")};if(s)return{viewToken:e.viewToken,commands:[],recovery:{state:"retired"}};if(!r)return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[],recovery:{state:"absent"}};if(this.switching||r.activeActions)return{viewToken:r.token,commands:[],recovery:this.recovery(r,"active")};if(r.kind==="controller")return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retired")};if(e.operation==="recover"){if(e.confirmation!=="retain-unconfirmed-edits")throw K("Explicit recovery confirmation required");return r.waiter?.(),this.views.delete(r.token),this.cancelledRegistrations.add(r.token),this.recoveries.set(r.token,r),{viewToken:r.token,commands:[],recovery:this.recovery(r,"retained")}}return{viewToken:r.token,commands:[],recovery:this.recovery(r,"unconfirmed")}}if(e.operation==="discard"&&n&&this.sameScope(n,e,i)){if(e.confirmation!=="discard-unconfirmed-edits")throw K("Explicit per-view discard confirmation required");return this.recoveries.delete(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(e.operation==="discard"&&!r&&!n){if(e.confirmation!=="discard-unconfirmed-edits")throw K("Explicit per-view discard confirmation required");if(this.switching)throw K("View has an active barrier or action; discard refused");return this.cancelledRegistrations.add(e.viewToken),{viewToken:e.viewToken,commands:[]}}if(!r||!this.sameScope(r,e,i))throw K("Unknown or stale view capability");switch(e.operation){case"cancel-initialization":if(r.initialized||r.activeActions||this.switching)throw K("View already initialized; preserve its recovery record");this.retire(r);break;case"change":if(e.generation!==this.generation)throw K("Generation changed; reconnect before publishing view status");if(typeof e.dirty!="boolean"||typeof e.busy!="boolean")throw K("Invalid view status");r.initialized=!0,r.dirty=e.dirty,r.busy=e.busy,(r.dirty||r.busy)&&r.frozen&&(r.frozen=!1,this.barrier?.reject(K("A frozen view changed")));break;case"ack":{if(typeof e.ok!="boolean")throw K("Invalid acknowledgement");let a=r.commands.find(o=>o.id===e.commandId);if(!a)throw K("Unknown command acknowledgement");r.commands=r.commands.filter(o=>o.id>e.commandId),a.type==="freeze"&&this.barrier?.id===a.id&&(e.ok?(r.frozen=!0,r.dirty=!1,r.busy=!1,this.barrier.pending.delete(r.token),this.barrier.pending.size||this.barrier.resolve()):this.barrier.reject(K(e.error??"A view could not flush/freeze")));break}case"discard":if(e.confirmation!=="discard-unconfirmed-edits")throw K("Explicit per-view discard confirmation required");if(this.switching||r.activeActions)throw K("View has an active barrier or action; discard refused");this.retire(r);break;case"close":if(r.activeActions)throw K("View action still in flight");if(r.kind!=="controller"&&(r.dirty||r.busy)&&!r.frozen)throw K("Dirty view cannot close without a successful flush");if(this.barrier?.pending.has(r.token))throw K("View must acknowledge freeze before closing");this.retire(r);break;case"poll":{if(!Number.isSafeInteger(e.after)||e.after<0||e.after>this.sequence)throw K("Invalid poll cursor");if(r.waiter)throw K("Only one poll per view is allowed");if(e.immediate!==void 0&&typeof e.immediate!="boolean")throw K("Invalid poll mode");return!e.immediate&&!r.commands.some(a=>a.id>e.after)&&await new Promise(a=>{let o=setTimeout(l,Math.min(25e3,Math.max(50,this.pollMs)));function l(){clearTimeout(o),r.waiter=void 0,a()}r.waiter=l}),{viewToken:r.token,commands:r.commands.filter(a=>a.id>e.after)}}default:throw K("Unknown view operation")}return{viewToken:r.token,commands:[]}}freeze=async()=>{if(this.switching)throw K("A view barrier is already active");if(!this.canSwitch()){let i=[...this.views.values()].filter(n=>n.activeActions||n.kind!=="controller"&&!n.frozen&&(n.busy||!this.immediate&&["editor","workspace"].includes(n.kind))),r=K(`Close editors before updating; old version retained. Pending views: ${i.map(n=>`${n.kind}:${n.identity.mountId}${n.activeActions?` (action in flight x${n.activeActions})`:n.busy?" (busy)":""}`).join(", ")}`);throw this.blockedOnlyByWork()?Object.assign(r,{reason:"view_busy"}):r}this.switching=!0;let e=++this.sequence;try{await new Promise((i,r)=>{let n=s=>{this.barrier?.id===e&&(clearTimeout(this.barrier.timer),this.barrier=null,s?r(s):i())};this.barrier={id:e,pending:new Set(this.authoringViews().map(s=>s.token)),resolve:()=>n(),reject:s=>n(s),timer:setTimeout(()=>{let s=this.authoringViews().filter(a=>this.barrier?.pending.has(a.token));n(K(`Missing view flush acknowledgement; old version retained. Plugin: ${this.pluginId}. Pending views: ${s.map(a=>`${a.kind}:${a.identity.mountId} (session ${a.identity.sessionId})`).join(", ")}. Save and close these views, or review their recovery records before retrying.`))},this.freezeMs)};for(let s of this.authoringViews())this.enqueue(s,"freeze",e);this.authoringViews().length||n()})}catch(i){throw await this.resume(),i}};committed=async e=>{if(!this.switching||this.barrier||this.authoringViews().some(i=>!i.frozen))throw K("Cannot commit before all views freeze");this.generation=e.generation;for(let i of this.views.values())this.enqueue(i,"committed");this.switching=!1,this.immediate=!1};resume=async()=>{this.barrier?.reject(K("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(K("Coordinator stopped"));for(let e of this.views.values())e.waiter?.()}};var Nw={"image/png":t=>t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),"image/jpeg":t=>t[0]===255&&t[1]===216,"image/webp":t=>t.subarray(0,4).toString("latin1")==="RIFF"&&t.subarray(8,12).toString("latin1")==="WEBP"};function Pw(t){let e=t;if(!e||typeof e!="object"||e.$hosted!=="tool-result"||!Array.isArray(e.content))return{content:[{type:"text",text:JSON.stringify(t)??"null"}],details:t};let i=[],r=0;for(let n of e.content.slice(0,16)){let s=n;if(s?.type==="text"&&typeof s.text=="string")i.push({type:"text",text:s.text.slice(0,262144)});else if(s?.type==="image"&&typeof s.data=="string"&&typeof s.mimeType=="string"&&Nw[s.mimeType]&&r<4){let a=/^[A-Za-z0-9+/]*={0,2}$/.test(s.data)?Buffer.from(s.data,"base64"):null;a&&a.length<=2097152&&Nw[s.mimeType](a)?(i.push({type:"image",data:s.data,mimeType:s.mimeType}),r++):i.push({type:"text",text:"[image omitted by host: invalid or too large]"})}}return i.some(n=>n.type==="text")||i.unshift({type:"text",text:"(no text)"}),{content:i,details:e.details??null}}import{randomUUID as zR}from"node:crypto";var KR="Ov23limJmKiuu8cOP83E";function Qp(t,e,i=process.env){let r=t?.secrets&&Object.hasOwn(t.secrets,e)?t.secrets[e]:void 0;if(r?.provider==="github")return{clientId:i.PI_WEBAPP_GITHUB_CLIENT_ID?.trim()||r.clientId||KR,scope:r.scope,createUrl:r.createUrl}}var YR="https://github.com/login/device/code",QR="https://github.com/login/oauth/access_token",JR=8,Ra=class{flows=new Map;fetcher;now;constructor(e=(r,n)=>fetch(r,{...n,signal:n.signal??AbortSignal.timeout(15e3)}),i=Date.now){this.fetcher=e,this.now=i}async post(e,i){let r;try{r=await this.fetcher(e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded","User-Agent":"pi-webapp"},body:new URLSearchParams(i).toString()})}catch{throw new y("oauth_unreachable","Cannot reach github.com. Check your network and retry.",{status:502})}let n=await r.json().catch(()=>null);if(!n||typeof n!="object"||!r.ok&&!("error"in n))throw new y("oauth_failed",`GitHub sign-in failed (${r.status})`,{status:502});return n}async start(e,i,r){if(!r.clientId)throw new y("oauth_unavailable","Browser sign-in is not configured",{status:503});for(let[d,m]of this.flows)m.expiresAt<=this.now()&&this.flows.delete(d);if(this.flows.size>=JR)throw new y("oauth_busy","Too many sign-ins in progress",{status:429});let n=await this.post(YR,{client_id:r.clientId,scope:r.scope}),{device_code:s,user_code:a,verification_uri:o}=n,l=Number(n.expires_in),c=Math.max(Number(n.interval)||5,1);if(typeof s!="string"||typeof a!="string"||typeof o!="string"||!o.startsWith("https://github.com/")||!Number.isFinite(l))throw new y("oauth_failed",typeof n.error_description=="string"?n.error_description:"GitHub sign-in could not start. Check that Device Flow is enabled for the OAuth App.",{status:502});let p=zR();return this.flows.set(p,{pluginId:e,name:i,clientId:r.clientId,deviceCode:s,expiresAt:this.now()+l*1e3,interval:c,nextPoll:this.now()+c*1e3}),{deviceId:p,userCode:a,verificationUri:o,interval:c,expiresIn:l}}async poll(e){let i=this.flows.get(e);if(!i||i.expiresAt<=this.now())return this.flows.delete(e),{status:"expired"};if(this.now()<i.nextPoll)return{status:"pending"};i.nextPoll=this.now()+i.interval*1e3;let r=await this.post(QR,{client_id:i.clientId,device_code:i.deviceCode,grant_type:"urn:ietf:params:oauth:grant-type:device_code"});if(typeof r.access_token=="string"&&r.access_token)return this.flows.delete(e),{status:"granted",token:r.access_token,pluginId:i.pluginId,name:i.name};switch(r.error){case"authorization_pending":return{status:"pending"};case"slow_down":return i.interval+=5,i.nextPoll=this.now()+i.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 Jp,readFileSync as Cw,readdirSync as XR,statSync as ZR}from"node:fs";import{lstat as eN,readdir as tN,writeFile as iN,mkdir as rN,rename as nN}from"node:fs/promises";import{delimiter as sN,dirname as aN,isAbsolute as oN,join as oi,resolve as Mn}from"node:path";var Na=t=>Xe.some(e=>e.id===t),Mw=()=>Xe.map(t=>t.id).join(", "),ai="piWebappCatalog",lN="https://registry.npmjs.org";function cN(t,e){let i=t[ai];if(i===void 0)throw new y("invalid_catalog",`${e}: ${t.name} is not an official plugin (official: ${Mw()}). Describe it in package.json "${ai}" with name, description and policy`);if(!i||typeof i!="object"||Array.isArray(i))throw new y("invalid_catalog",`${e}: ${ai} must be an object`);if("id"in i||"registry"in i)throw new y("invalid_catalog",`${e}: ${ai} must not set id or registry; the package name is the id`);return{...Hp({registry:lN,recommendedVersion:"0.0.0",requiredCapabilities:[...t.piWebapp.capabilities],...i,id:t.name},e,ai),official:!1}}function pN(t=process.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES){let e=new Map,i=[],r="PI_WEBAPP_HOSTED_DEV_ARCHIVES";for(let n of(t??"").split(/[;\n]/).map(s=>s.trim()).filter(Boolean)){let s=n.lastIndexOf("="),a=n.slice(0,s),o=n.slice(s+1),l=s<1?`entry "${n}" is not <id>=<path.tgz>`:Na(a)?o.endsWith(".tgz")?Jp(Mn(o))?null:`archive not found: ${Mn(o)}`:`"${o}" is not a .tgz archive`:`"${a}" is not an official plugin (official: ${Mw()}); develop other packages from a directory in PI_WEBAPP_HOSTED_DEV_ROOTS`;if(l){i.push({level:"error",source:r,...Na(a)?{pluginId:a}:{},message:l});continue}e.set(a,Mn(o))}return{archives:e,notices:i}}var Dw=t=>oi(t,"pi-web","hosted-dev.json"),Lw=t=>oi(t,"pi-web","hosted-dev-status.json");function dN(t,e,i=process.cwd()){let r=[],n=[],s=(t.PI_WEBAPP_HOSTED_DEV_ROOTS??"").split(sN).map(o=>o.trim()).filter(Boolean);for(let o of s)r.push({path:Mn(i,o),source:"PI_WEBAPP_HOSTED_DEV_ROOTS"});let a=s.length>0;if(e&&Jp(e)){a=!0;try{let o=JSON.parse(Cw(e,"utf8")),l=o&&typeof o=="object"?o.roots:void 0;if(!Array.isArray(l))throw new Error('expected {"roots": ["/absolute/package/dir", ...]}');for(let c of l)typeof c!="string"||!oN(c)?n.push({level:"error",source:e,message:`root ${JSON.stringify(c)} must be an absolute path string`}):r.push({path:Mn(c),source:e})}catch(o){n.push({level:"error",source:e,message:`cannot read dev configuration: ${o instanceof Error?o.message:String(o)}`})}}return{specs:r,notices:n,configured:a}}function uN(t){let e=[];try{e=XR(t,{withFileTypes:!0}).filter(i=>i.isDirectory()&&i.name!=="node_modules"&&Jp(oi(t,i.name,"package.json"))).map(i=>i.name)}catch{}return e.length?`package.json not found; this looks like a parent folder (packages inside: ${e.slice(0,3).join(", ")}). Point at the package directory itself`:"package.json not found; the folder is not a package (is the right branch checked out?)"}function mN(t){let e=(n,s)=>({notice:{level:"error",source:t.source,...s?{pluginId:s}:{},message:`${t.path}: ${n}`}}),i;try{i=ZR(t.path)}catch{return e("directory does not exist")}if(!i.isDirectory())return e("not a directory (expected the package directory containing package.json)");let r;try{r=JSON.parse(Cw(oi(t.path,"package.json"),"utf8"))}catch(n){return e(n.code==="ENOENT"?uN(t.path):"package.json is not valid JSON")}if(typeof r.name!="string")return e("package.json has no name");if(!ti(r.piWebapp))return e('package.json "piWebapp" is not a valid hosted v2 manifest (apiVersion, hostRange, backend, frontend, resourcesManifest, capabilities)',r.name);if(Na(r.name))return{pluginId:r.name};try{return{pluginId:r.name,entry:cN({name:r.name,piWebapp:r.piWebapp,[ai]:r[ai]},"package.json")}}catch(n){return e(me(n).message,r.name)}}var Pa=class{catalog=[];policies=new Map;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 i=pN(this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES);this.archives=i.archives,this.archiveNotices=i.notices,this.fileNotices=[],this.enabled=!!this.env.PI_WEBAPP_HOSTED_DEV_ARCHIVES;let r=this.refresh(!0);this.enabled||=r.configured}refresh(e=!1){let i=dN(this.env,this.configPath,this.cwd),r=[],n=new Map,s=new Map;for(let a of i.specs){let o=mN(a);if(o.notice){r.push(o.notice);continue}let l=o.pluginId;if(n.has(l)){r.push({level:"error",pluginId:l,source:a.source,message:`${a.path}: plugin ${l} is already provided by ${n.get(l)}`});continue}if(this.archives.has(l)&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: PI_WEBAPP_HOSTED_DEV_ARCHIVES also provides ${l}; the dev directory wins`}),!Na(l)&&!this.catalog.some(c=>c.id===l)){if(!e){r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: ${l} was not part of this host's startup configuration. Restart pi-webapp once (npm run stop && npm run start) to list it.`});continue}let{policy:c,...p}=o.entry;this.catalog.push(p),this.policies.set(l,c)}else o.entry&&JSON.stringify(o.entry.policy)!==JSON.stringify(this.policies.get(l))&&r.push({level:"warning",pluginId:l,source:a.source,message:`${a.path}: the ${ai} policy changed; restart pi-webapp once (npm run stop && npm run start) to apply it. Code still reloads live.`});n.set(l,a.path),s.set(l,a.source)}for(let a of[...this.roots.keys()])n.has(a)||this.roots.delete(a);for(let[a,o]of n)this.roots.set(a,o);this.rootSource.clear();for(let[a,o]of s)this.rootSource.set(a,o);return this.fileNotices=i.notices,this.rootNotices=r,{configured:i.configured}}notices(){return[...this.archiveNotices,...this.fileNotices,...this.rootNotices]}},Ca=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 i of this.options.sources.notices())this.log(`${i.level}: ${i.message}`);let e=()=>{this.current=this.tick().catch(i=>{this.running&&this.log(`poll failed: ${me(i).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 i=this.roots.get(e);i&&(i.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,i])=>({pluginId:e,root:i.root,state:i.state,...i.version?{version:i.version}:{},...i.message?{message:i.message}:{}}))}}log(e){(this.options.log??(i=>console.error(`pi-webapp [hosted-dev] ${i}`)))(e)}async tick(){this.options.sources.refresh();let e=this.options.sources.roots;for(let i of[...this.roots.keys()])e.has(i)||this.roots.delete(i);for(let[i,r]of e){let n=this.roots.get(i);(!n||n.root!==r)&&(n={root:r,state:"waiting-build",at:new Date().toISOString()},this.roots.set(i,n));let s=await gN(r);if(s===null){this.set(i,n,"waiting-build",{message:"dist/ or package.json is missing; waiting for a build"}),n.seen=void 0;continue}if(s!==n.seen){n.seen=s;continue}if(!this.stopped){if(s===n.applied){n.retry&&this.options.switcher.retry&&await this.apply(i,n,s,!0);continue}await this.apply(i,n,s)}}await this.publish()}set(e,i,r,n={}){let s=i.state!==r||i.message!==n.message||i.version!==n.version;i.state=r,i.message=n.message,i.code=n.code,i.version=n.version??i.version,s&&(i.at=new Date().toISOString(),this.log(`${e}: ${r}${n.version?` ${n.version}`:""}${n.message?` \u2014 ${n.message}`:""}`))}async apply(e,i,r,n=!1){n||this.set(e,i,"switching");try{let a=(await(n?this.options.switcher.retry(e):this.options.switcher.update(e))).plugins.find(o=>o.pluginId===e);i.applied=r,i.retry=!!a?.installed&&!!a.pendingVersion,a?.installed?a.pendingVersion?this.set(e,i,"pending",{version:a.version,message:`Waiting for editors to close before switching to ${a.pendingVersion}`}):this.set(e,i,"synced",{version:a.version}):this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"})}catch(s){let a=me(s),o=a.reason==="view_busy",l=o||["storage_busy","manager_closed","download_pending","plugin_unavailable"].includes(a.code);n?(i.applied=r,i.retry=l):l||(i.applied=r);let c=a.code==="not_installed";o?this.set(e,i,"pending",{message:"An open editor is saving; switching once it finishes"}):c?this.set(e,i,"not-installed",{message:"Not installed; install it from the plugin page to start using this source"}):this.set(e,i,"error",{code:a.code,message:`${a.message} (${a.code}). Fix and save again.`})}i.at=new Date().toISOString()}async publish(){let e=this.info(),i=JSON.stringify(e);i!==this.lastNotices&&(this.lastNotices=i,this.options.changed?.());let r=this.options.statusPath;if(!r)return;let n=Object.fromEntries([...this.roots].map(([o,l])=>[o,{root:l.root,state:l.state,version:l.version,message:l.message,code:l.code,at:l.at}])),s=JSON.stringify({pid:process.pid,catalog:this.options.sources.catalog.map(o=>o.id),plugins:n,notices:e.notices});if(s===this.lastStatus)return;this.lastStatus=s;let a=`${r}.${process.pid}.tmp`;try{await rN(aN(r),{recursive:!0}),await iN(a,JSON.stringify({...JSON.parse(s),updatedAt:new Date().toISOString()})),await nN(a,r)}catch{}}};async function gN(t){let e=[],i=async(r,n)=>{let s=await eN(r);e.push(`${n}:${s.size}:${s.mtimeMs}:${s.ino}`)};try{await i(oi(t,"package.json"),"package.json");let r=async(n,s,a)=>{if(!(a>16||e.length>8192))for(let o of(await tN(n,{withFileTypes:!0})).sort((l,c)=>l.name.localeCompare(c.name)))o.isDirectory()?await r(oi(n,o.name),`${s}/${o.name}`,a+1):await i(oi(n,o.name),`${s}/${o.name}`)};if(await r(oi(t,"dist"),"dist",0),!e.some(n=>n.startsWith("dist/resources.json:")))return null}catch(r){if(r.code==="ENOENT")return null;throw r}return e.join("|")}function hN(t){try{return[...hr(t).secrets]}catch{return[]}}var Ma=class{manager;adapter;handlers;views=new Map;documents=new Map;queue=Promise.resolve();switches=Promise.resolve();recovery=new Map;deviceFlows=new Ra;restartPreparation;restartResume;closing=!1;started=!1;starting;stopping;options;trusted;devWatcher;constructor(e){this.options=e,this.trusted=e.policies??Ia,e.dev?.enabled&&(this.devWatcher=new Ca({sources:e.dev,statusPath:e.devStatusPath,pollMs:e.devPollMs,changed:()=>e.changed?.(),switcher:{update:async i=>{let r=await this.inventory();return r.plugins.find(n=>n.pluginId===i)?.installed?this.manage({pluginId:i,operation:"update",reopenEditors:!0}):r},retry:i=>this.manage({pluginId:i,operation:"retry",reopenEditors:!0})}})),this.adapter=new va({policy:(i,r)=>{let n=e.policy?.(i,r);return{...n,enabled:!this.recovery.has(i)&&this.manager.tools.some(s=>s.pluginId===i)&&n?.enabled!==!1}},invoke:async(i,r,n)=>{n?.throwIfAborted(),this.scope(r.scope.sessionId,r.scope);let s=this.manager.tools.find(o=>o.pluginId===i);if(!s)throw new y("plugin_unavailable","Hosted tool unavailable");let a=await this.manager.invoke(i,s.generation,r);return Pw(a)}}),this.manager=new Oa({...e,workspaceRules:i=>fw(this.trusted,i),invokeTimeoutMs:i=>hw(this.trusted,i),lifecycle:(i,r,n)=>this.lifecycle(i,r,n),hooks:i=>({canSwitch:()=>this.coordinator(i).canSwitch(),validateCandidate:r=>{if(r.length!==Object.keys(Bp(this.trusted,i).tools).length)throw new y("unreviewed_tool","Official tool set changed; review required");this.verifyTools(i,r),this.adapter.validateChange(i,r)},freeze:async()=>{if(!this.adapter.isFrozen)throw new Error("Missing outer Agent settlement barrier");await this.coordinator(i).freeze()},committed:async r=>{try{let n=r.enabled?this.manager.tools.find(s=>s.pluginId===i)?.descriptors:[];if(!n)throw new Error("Committed runtime descriptors missing");if(this.verifyTools(i,n),r.enabled){let s=await this.manager.installer.load(i,r.version);this.documents.set(i,{document:s.manifest.frontend.document.replace(/^\.\//,""),controller:s.manifest.frontend.controller.replace(/^\.\//,""),secrets:hN(s.manifest)})}else this.documents.delete(i);this.adapter.change(i,n),await this.coordinator(i).committed(r),e.changed?.(),this.recovery.delete(i)}catch(n){throw this.recovery.set(i,n),await this.coordinator(i).committed(r).catch(()=>{}),n}},resume:()=>this.coordinator(i).resume()})}),this.handlers={inventory:()=>this.inventory(),manage:i=>this.manage(i),secret:async(i,r,n)=>{let s=this.options.capabilities?.secrets,a=this.documents.get(i)?.secrets;if(!s)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(!a?.includes(r))throw new y("secret_undeclared","The enabled plugin does not declare this secret",{status:404});return n===null?await s.delete(i,r):await s.set(i,r,n),this.options.changed?.(),this.inventory()},secretAuth:async i=>{let r=this.options.capabilities?.secrets;if(!r)throw new y("hosted_unavailable","Secrets are not available",{status:503});if(i.phase==="cancel")return this.deviceFlows.cancel(i.deviceId),{status:"cancelled"};if(i.phase==="start"){let s=this.documents.get(i.pluginId)?.secrets.includes(i.name)?Qp(this.trusted.get(i.pluginId),i.name):void 0;if(!s)throw new y("secret_undeclared","The enabled plugin does not declare browser sign-in for this secret",{status:404});return this.deviceFlows.start(i.pluginId,i.name,s)}let n=await this.deviceFlows.poll(i.deviceId);return n.status!=="granted"?{status:n.status}:(await r.set(n.pluginId,n.name,n.token),this.options.changed?.(),{status:"granted",catalog:await this.inventory()})},decide:(i,r)=>{if(!this.options.approvals)throw new y("hosted_unavailable","Approvals are not available",{status:503});return this.options.approvals.decide(i,r),this.inventory()},action:(i,r)=>this.action(i,r?.checkpointOnly),views:async i=>{if(i.operation==="list-pending"){if(typeof i.pluginId!="string")throw new y("invalid_input","Invalid plugin identity",{status:400});return{views:this.coordinator(i.pluginId).pendingViews(this.options.ownerId)}}let r=i,n=this.scope(r.sessionId);return r.operation==="register"&&this.generation(r.pluginId,r.generation),this.coordinator(r.pluginId).handle(r,this.viewScope(n))},asset:async i=>{let r=await this.manager.assetRequest(i);if(!r)return null;let n=this.trusted.get(r.pluginId)?.browser?.wasm===!0&&R_(this.manager.servedManifest(r.pluginId));return{bytes:r.bytes,mime:r.mime,csp:O_({wasm:n})}}}}verifyTools(e,i){let r=Bp(this.trusted,e);for(let n of i)if(!Object.hasOwn(r.tools,n.name)||r.tools[n.name]!==n.action||n.readonly!==r.readonlyActions.includes(n.action))throw new y("unreviewed_tool","Official tool ownership/readonly policy changed; review required")}coordinator(e){let i=this.views.get(e);if(!i)throw new y("unknown_plugin","Hosted coordinator unavailable");return i}scope(e,i){let r=typeof e=="string"?this.options.resolveSession(e):null;if(!r||r.sessionId!==e||!r.cwd||!r.workspaceId||i&&(r.cwd!==i.cwd||r.workspaceId!==i.workspaceId))throw new y("invalid_scope","Session is not retained by this authenticated host",{status:403});return{...r}}viewScope(e){return{ownerId:this.options.ownerId,workspaceId:e.workspaceId,sessionId:e.sessionId}}generation(e,i){let r=this.manager.tools.find(n=>n.pluginId===e);if(!r||r.generation!==i)throw new y("stale_generation","Reconnect and re-handshake hosted views",{status:409});return r}enqueue(e,i=!1){let r=this.queue.then(async()=>{if(this.closing&&!i)throw new y("manager_closed","Host is shutting down");return e()});return this.queue=r.catch(()=>{}),r}lifecycle(e,i,r=!1){let n=this.switches.then(async()=>{if(this.closing&&!r)throw new y("manager_closed","Host is shutting down");try{this.adapter.isFrozen||await this.adapter.freeze();let s=await i();if(s&&typeof s=="object"&&"reconnectRequired"in s&&s.reconnectRequired){this.recovery.has(e)||this.recovery.set(e,new Error("Committed plugin publication requires recovery"));let a=await new ji(Xp(this.options.root,"data"),e).active();a&&await this.coordinator(e).committed(a).catch(()=>{})}if(this.recovery.has(e)&&!r)throw new y("reconnect_required","Plugin publication failed; recover this plugin without restarting chat",{status:503});return s}finally{if(!r)for(let s of this.views.values())s.allowImmediateReopen(!1);r||this.adapter.thaw()}});return this.switches=n.catch(()=>{}),n.catch(s=>{throw r&&this.adapter.thaw(),s})}async admit(e){let i,r=this.start().then(()=>!0);r.catch(()=>{});try{return await Promise.race([r,new Promise(n=>{i=setTimeout(()=>n(!1),e),i.unref?.()})])}finally{clearTimeout(i)}}start(){return this.starting??=this.startOnce().catch(e=>{throw this.starting=void 0,e}),this.starting}async startOnce(){if(!this.started){await this.adapter.verifyCompatibility();for(let e of this.options.catalog??Xe)try{let i=await new ji(Xp(this.options.root,"data"),e.id).active();this.views.set(e.id,new Cn(e.id,i?.generation??0))}catch(i){this.recovery.set(e.id,i),this.views.set(e.id,new Cn(e.id,0))}await this.enqueue(async()=>{if(await this.manager.start(),this.recovery.size)return;let e=Xp(this.options.root,"host-version.json");(await we(e))?.version!==this.options.hostVersion&&await this.manager.reconcileHostUpgrade()&&(await ve(this.options.root),await Z(e,{version:this.options.hostVersion}))}).catch(e=>{for(let i of this.options.catalog??Xe)this.recovery.set(i.id,e);this.adapter.thaw()}),this.started=!0,this.devWatcher?.start()}}hostUpdateWarnings(e){return this.manager.hostUpdateWarnings(e)}async inventory(){let e=await this.manager.inventory(),i=this.options.capabilities?.secrets,r=new Map;for(let n of e.plugins){let s=n.enabled?this.documents.get(n.id)?.secrets??[]:[];i&&s.length&&r.set(n.id,await Promise.all(s.map(async a=>{let o=Qp(this.trusted.get(n.id),a);return{name:a,configured:await i.has(n.id,a),...o?{signIn:o.clientId?"browser":"token-page",...o.createUrl?{createUrl:o.createUrl}:{}}:{}}})))}return{...this.devWatcher?{dev:this.devWatcher.info()}:{},plugins:e.plugins.map(n=>({pluginId:n.id,name:n.name,official:n.official,installed:n.installed,enabled:n.enabled,description:n.description,...r.has(n.id)?{secrets:r.get(n.id)}:{},icon:(this.options.catalog??Xe).find(s=>s.id===n.id)?.icon,hasRetainedData:n.activeVersion!==null,phase:this.recovery.has(n.id)?"reconnect-required":n.phase,updatePolicy:n.updatePolicy,pinnedVersion:n.pinnedVersion,updateDiagnostic:n.updateDiagnostic,...n.enabled&&n.activeVersion?{version:n.activeVersion}:n.version?{version:n.version}:{},...n.availableVersion?{availableVersion:n.availableVersion}:{},...n.pendingVersion?{pendingVersion:n.pendingVersion}:{},...n.generation!==null?{generation:n.generation}:{},...this.recovery.has(n.id)||n.error?{error:this.recovery.get(n.id)instanceof Error?this.recovery.get(n.id).message:n.error?.message??"Recovery required",errorCode:this.recovery.has(n.id)?"reconnect_required":n.error?.code}:{},...n.enabled&&n.assetBase&&this.documents.has(n.id)&&this.trusted.has(n.id)?{documentUrl:n.assetBase+this.documents.get(n.id).document,controllerUrl:n.assetBase+this.documents.get(n.id).controller,contribution:structuredClone(this.trusted.get(n.id).contribution)}:{}})),...this.options.approvals?.pending().length?{approvals:this.options.approvals.pending()}:{}}}downloads=new Map;async manage(e){if(e.operation==="cancel-download"){let r=this.downloads.get(e.pluginId);if(!r||r.id!==e.downloadId)throw new y("download_not_pending","This download is no longer pending; refresh to verify its outcome",{status:409});return r.abort.abort(new y("download_cancelled","Download cancellation requested; already committed installations are retained",{status:409})),this.inventory()}let i=e.downloadId&&["install","update","check"].includes(e.operation)?{id:e.downloadId,abort:new AbortController}:void 0;if(i){if(this.downloads.has(e.pluginId))throw new y("download_pending","Another download is pending",{status:409});this.downloads.set(e.pluginId,i)}try{return await this.enqueue(async()=>{let r=this.coordinator(e.pluginId);r.allowImmediateReopen(e.reopenEditors===!0||e.operation==="disable"||e.operation==="uninstall");try{if(e.operation==="policy"){if(!e.updatePolicy)throw new y("invalid_input","Update policy is required");await this.manager.setPolicy(e.pluginId,{updatePolicy:e.updatePolicy,...e.updatePolicy==="pinned"?{pinnedVersion:e.version}:{}});return}let n=await this.manager.manage(e.pluginId,e.operation,e.version,i?.abort.signal);if(this.recovery.has(e.pluginId)||n&&typeof n=="object"&&"reconnectRequired"in n&&n.reconnectRequired)throw new y("reconnect_required","Runtime committed but publication failed; explicit recovery required",{status:503})}finally{r.allowImmediateReopen(!1)}}),this.options.changed?.(),this.devWatcher?.invalidate(e.pluginId),this.inventory()}finally{i&&this.downloads.get(e.pluginId)===i&&this.downloads.delete(e.pluginId)}}async action(e,i=!1){let r=this.scope(e.sessionId);if(!this.trusted.get(e.pluginId)?.actions.includes(e.action))throw new y("action_denied","Action is not reviewed by this host",{status:403});let n=this.coordinator(e.pluginId).admitAction(e,this.viewScope(r));try{let s={requestId:fN(),scope:r,action:e.action,input:e.input??{}};if(this.adapter.isFrozen||i){if(this.adapter.isFrozen&&this.trusted.get(e.pluginId).checkpointActions.includes(e.action)&&this.coordinator(e.pluginId).authorizesFlush(e,this.viewScope(r)))return await this.manager.flush(e.pluginId,e.generation,s);throw new y("plugin_unavailable","Only authenticated barrier checkpoint actions are admitted during switching",{status:409})}if(this.recovery.has(e.pluginId))throw new y("plugin_unavailable","Plugin publication recovery required",{status:503});return this.generation(e.pluginId,e.generation),await this.manager.invoke(e.pluginId,e.generation,{...s,kind:"action"})}finally{n()}}prepareRestart(e=!1){return this.restartPreparation?this.restartPreparation:(this.restartPreparation=this.enqueue(async()=>{this.closing=!0,this.devWatcher?.stop();try{await this.adapter.freeze();for(let s of this.views.values())s.allowImmediateReopen(!0);let i=await this.manager.suspendForRestart(e),r=!1,n=async()=>{if(!r)try{await i(),r=!0}finally{this.closing=!1,this.restartResume=void 0,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start()}};return this.restartResume=n,n}catch(i){throw this.closing=!1,this.restartPreparation=void 0,this.adapter.thaw(),this.devWatcher?.start(),i}finally{for(let i of this.views.values())i.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 i of this.views.values())i.allowImmediateReopen(!1);throw this.closing=!1,this.stopping=void 0,this.adapter.thaw(),this.devWatcher?.start(),e}),this.stopping}};import{open as yN,readdir as bN,unlink as _N}from"node:fs/promises";import{join as vr}from"node:path";import{randomUUID as vN}from"node:crypto";var Zp="hosted-migration.json";function Uw(t,e="@chengzhiyi/pi-excalidraw"){return async i=>{let{cwd:r,sessionId:n}=i.scope,s=vr(t,re(JSON.stringify([r,n])));await ve(t),await ve(s);let a=vr(s,"scope.lock"),o;try{o=await yN(a,"wx",384)}catch(l){throw l.code==="EEXIST"?new y("legacy_busy","Legacy drawing writer is active or needs explicit lock recovery",{status:409}):l}try{await o.writeFile(JSON.stringify({pid:process.pid,operationId:vN()}));let l=await we(vr(s,Zp));if(l&&(l.version!==1||l.pluginId!==e))throw new y("invalid_storage","Legacy scope belongs to another migration");let c=await bN(s),p=[];for(let m of c){if(m==="scope.lock"||m==="focus.json"||m===Zp||/^[\w-]{1,80}\.json\.[a-f0-9-]{36}\.tmp$/.test(m))continue;if(!/^[\w-]{1,80}\.json$/.test(m))throw new y("invalid_storage","Unexpected legacy checkpoint member; original bytes preserved");if(p.length>=100)throw new y("invalid_storage","Too many legacy checkpoints");let g=await we(vr(s,m),3*512*1024);if(!g||g.version!==1||g.cwd!==r||g.sessionId!==n||!g.draft||m!==`${g.draft.id}.json`)throw new y("invalid_storage","Legacy checkpoint scope or identity mismatch");p.push(g.draft)}let d=await we(vr(s,"focus.json"),1024);if(d!==null&&(typeof d!="string"||!p.some(m=>m.id===d)))throw new y("invalid_storage","Invalid legacy focused drawing");return l||await Z(vr(s,Zp),{version:1,pluginId:e,operationId:i.requestId}),{drafts:p,focused:d}}finally{await o.close(),await _N(a)}}}import{join as ON}from"node:path";import{randomUUID as wN}from"node:crypto";var SN=6e4,Da=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:i,sessionId:r,title:n})=>({id:e,pluginId:i,sessionId:r,title:n}))}async authorize(e,i){let r=this.entries.get(i);if(r&&r.pluginId!==e)throw new y("execute_denied","Session belongs to another plugin",{status:403});if(r?.status==="allowed")return!0;throw r?.status==="pending"?new y("approval_required","Waiting for the user to approve execution",{status:409}):r?.status==="denied"&&this.now()-r.decidedAt<SN?new y("execute_denied","The user denied execution",{status:403}):(this.entries.set(i,{id:wN(),pluginId:e,sessionId:i,title:this.options.describe?.(i)??i,status:"pending"}),this.options.changed?.(),new y("approval_required","Waiting for the user to approve execution",{status:409}))}decide(e,i){let r=[...this.entries.values()].find(n=>n.id===e&&n.status==="pending");if(!r)throw new y("unknown_approval","No such pending approval",{status:404});r.status=i?"allowed":"denied",r.decidedAt=this.now(),this.options.changed?.()}forget(e){this.entries.delete(e)&&this.options.changed?.()}};import{mkdir as kN,readFile as EN,rename as TN,writeFile as IN}from"node:fs/promises";import{randomUUID as AN,createHash as xN}from"node:crypto";import{join as qw}from"node:path";var La=class{dir;queue=Promise.resolve();constructor(e){this.dir=qw(e,"secrets")}file=e=>qw(this.dir,`${xN("sha256").update(e).digest("hex")}.json`);async read(e){try{let i=JSON.parse(await EN(this.file(e),"utf8"));if(i&&typeof i=="object"&&!Array.isArray(i))return i}catch(i){if(!Zt(i))throw new y("invalid_storage","Secret store is unreadable")}return{}}serialize(e){let i=this.queue.then(e,e);return this.queue=i.catch(()=>{}),i}async get(e,i){return(await this.read(e))[i]??null}has(e,i){return this.get(e,i).then(r=>r!==null)}set(e,i,r){return this.mutate(e,n=>{n[i]=r})}delete(e,i){return this.mutate(e,r=>{delete r[i]})}mutate(e,i){return this.serialize(async()=>{let r=await this.read(e);i(r),await kN(this.dir,{recursive:!0,mode:448});let n=`${this.file(e)}.${AN()}.tmp`;await IN(n,JSON.stringify(r),{mode:384}),await TN(n,this.file(e))})}};function jw(t,e){let i=r=>({seq:r.seq,type:r.type,...r.text===void 0?{}:{text:r.text}});return{async create({pluginId:r,cwd:n,title:s,prompt:a}){let o=await t.createDetached(n,r,s);try{await t.sendDetached(o,a,!1)}catch(l){throw await t.releaseDetached(o),l}return{sessionId:o}},ownerOf:r=>t.detachedOwner(r),activeCount:r=>t.detachedCount(r),async send(r,n,s){let a=t.detachedOwner(r);if(s==="execute"&&(!a||!await e(a,r)))throw Object.assign(new Error("Execution was not authorized by the host"),{code:"execute_denied",status:403});await t.sendDetached(r,n,s==="execute")},abort:r=>t.abortDetached(r),release:r=>t.releaseDetached(r),async events(r,n){let s=t.detachedEvents(r,n);return{events:s.events.map(i),next:s.next}}}}var RN="scheduler";function Bw(t){let e=new Da({describe:t.sessionTitle,changed:t.changed}),i=()=>{let n=t.sessions();if(!n)throw Object.assign(new Error("Workspace sessions are not available yet"),{code:"sessions_unavailable",status:503});return n},r={createDetached:(...n)=>i().createDetached(...n),detachedOwner:n=>t.sessions()?.detachedOwner(n)??null,detachedCount:n=>t.sessions()?.detachedCount(n)??0,sendDetached:(...n)=>i().sendDetached(...n),abortDetached:n=>i().abortDetached(n),releaseDetached:async n=>{e.forget(n),await i().releaseDetached(n)},detachedEvents:(...n)=>i().detachedEvents(...n)};return{approvals:e,capabilities:{secrets:new La(ON(t.root,"capability-secrets")),sessions:jw(r,(n,s)=>e.authorize(n,s))},scheduledScope:()=>{let n=t.activeWorkspace();if(!n)return null;try{return t.trustedScope(n,RN)}catch{return null}}}}async function NN(){for(let t of[{},{PI_WEB_SENTRY_DSN:"https://public@example.com/1"},{PI_WEB_SENTRY_ENABLED:"false"}]){let e=Xs(t),i=new wt({env:t,monitor:!1,transport:()=>{throw new Error("Disabled telemetry loaded a transport")}});try{if(await i.ready,e.node.enabled||e.browser.enabled||i.enabled||i.reporter||i.capture(new Error("Disabled release probe"))||await i.flush())throw new Error("Packaged Sentry is not disabled by default")}finally{await i.close()}}return{release:Rr,buildId:it,browser:Xs({}).browser}}async function Fw(){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 t=new wt({monitor:!1});try{if(await t.ready,!t.enabled)throw new Error("Sentry verification transport is disabled");let e=t.capture(new Error("Sentry Node release verification"),{stage:"release_verification",code:"sentry_release_probe"});if(!e||!await t.flush(3e3))throw new Error("Sentry verification event was not delivered");return{eventId:e,release:Rr,buildId:it}}finally{await t.close()}}var Dn=kr(CN(LN(import.meta.url)),import.meta.url.endsWith("/pi-host.ts")?"../../../../web/dist":"../web/dist"),FN=Symbol.for(`pi-web.bridge-state:${import.meta.url}`),u=globalThis[FN]??={bridge:null,current:null,commandContext:null,pi:null,replacementContext:null,replacementSessionId:null,lastStreamAt:0,tuiStreaming:null,tuiPrompts:new Xt(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:jt()}),Ee()}),tuiPromptSessionId:null,tuiAgentError:!1,workspaces:null,workspaceSessions:null,selected:"tui",activeWorkspaceId:null,autoOpened:!1,tuiCatalog:null,stopPluginWatch:null,interactions:null,lifecycle:new Mi,tuiGeneration:0,stopChanged:null,tuiWaitController:new AbortController};u.lifecycle??=new Mi;u.tuiGeneration??=0;u.stopChanged??=null;u.tuiWaitController??=new AbortController;u.tuiStreaming??=null;u.tuiPrompts??=new Xt(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:jt()}),Ee()});u.tuiPromptSessionId??=null;u.tuiAgentError??=!1;var Gw=!1;function HN(t){return Gw||(Gw=!0,setTimeout(()=>{t.pruneReleases().catch(()=>{})},6e4).unref()),t}function Ua(){return u.selected==="sdk"?u.workspaceSessions?.catalog??null:u.tuiCatalog}var GN=null;function WN(){return GN??=UN.create({refreshOnCreate:!1})}var qa=new Map;async function Sr(){let t=await WN(),e=u.selected==="tui"?u.current?.modelRegistry:void 0,i=new Set(e?.getRegisteredProviderIds()??[]);for(let r of qa.keys())i.has(r)||(t.unregisterProvider(r),qa.delete(r));for(let r of i){let n=e?.getRegisteredNativeProvider(r),s=e?.getRegisteredProviderConfig(r),a=n??s;!a||qa.get(r)===a||(n?t.registerNativeProvider(n):s&&t.registerProvider(r,s),qa.set(r,a))}return await t.refresh({allowNetwork:!1}),t}function Te(){return u.selected==="sdk"?u.workspaceSessions?.snapshot()??(()=>{throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD")})():jt()}function jt(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");return{...M_(u.current,u.current.sessionManager.getSessionName(),u.tuiCatalog?.ids()??[]),idle:u.current.isIdle()&&!u.tuiPrompts.sending,streaming:u.tuiStreaming,queuedPrompts:u.tuiPrompts.view(),hasPendingPrompts:u.current.hasPendingMessages?.()??!1,interactions:u.interactions?.pending(u.current.sessionManager.getSessionId())??[]}}async function nd(t,e,i,r,n){let s=je(t);Jt({...jt(),idle:s.isIdle()},e,n);let a=s.isIdle();a&&ur(()=>u.hosted?.adapter.assertAdmission(),r,(o,l)=>u.bridge?.reportError?.(o,l)),a&&(u.operation=r);try{let o=i.length?[{type:"text",text:e},...i]:e;if(u.replacementContext!==null&&u.replacementSessionId===t)await u.replacementContext.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n});else{if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.sendUserMessage(o,{expandPromptTemplates:!0,deliverAs:n})}u.current?.sessionManager.getSessionId()===t&&u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:jt()})}catch(o){throw a&&(u.operation=void 0),o}}function id(){let t=u.current?.sessionManager.getSessionId(),e=u.tuiGeneration,i=()=>{if(!t||!u.current||u.tuiGeneration!==e||u.current.sessionManager.getSessionId()!==t||u.tuiAgentError)return!1;let r=jt();return!u.hosted?.adapter.isFrozen&&u.current.isIdle()&&!r.paused&&!r.interactions.length};u.tuiPrompts.schedule(i,(r,n,s)=>nd(t,r,n,s))}function Ne(t){if(Te().sessionId!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362")}async function zw(){let t=(u.workspaces?.list()??[]).map(d=>({...d})),e=u.activeWorkspaceId,i=Te(),n=u.current?jt():null,s=await xi(i.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)),a=n?await xi(n.cwd).catch(d=>(u.bridge?.reportError?.(d,{stage:"workspace_path"}),null)):null,o=await Ln.listAll(),l=u.workspaceSessions?.retainedSessions()??[];n&&a&&l.push({sessionId:n.sessionId,cwd:a,path:null,name:n.name,modified:n.messages.at(-1)?.timestamp??new Date().toISOString(),idle:n.idle,blank:!!process.env.PI_WEBAPP_LAUNCHER_NONCE&&n.idle&&u.tuiPrompts.length===0&&!n.messages.some(d=>d.role==="user")});let c=await pr(o,Ci(Pe()),new Set(l.filter(d=>!d.idle).map(d=>d.sessionId))),p=(await Promise.all(t.map(async d=>{let g=(await Ni(d.path,o).catch(f=>(f instanceof wn?d.available=!1:u.bridge?.reportError?.(f,{stage:"workspace_sessions"}),[]))).map(f=>({id:f.id,workspaceId:d.id,path:f.path,name:f.name||f.firstMessage?.slice(0,50)||"",modified:f.modified.toISOString(),idle:!0}));for(let f of l.filter(h=>h.cwd===d.path)){if(f.blank&&f.sessionId!==i.sessionId)continue;let h=g.findIndex(S=>S.id===f.sessionId),_={id:f.sessionId,workspaceId:d.id,path:f.path??g[h]?.path??null,name:f.name,modified:f.modified,idle:f.idle};h<0?g.unshift(_):g[h]=_}return d.path===s&&!g.some(f=>f.id===i.sessionId)&&g.unshift({id:i.sessionId,workspaceId:d.id,path:null,name:i.name,modified:new Date().toISOString(),idle:i.idle}),g.map(f=>{let h=c.get(f.id)?.view;return h?{...f,subagent:h}:f})}))).flat();return{items:t,activeId:e,sessions:p}}var Ww=0;async function Ee(){if(!u.bridge)return;let t=++Ww;try{let e=await zw();t===Ww&&u.bridge?.publish({type:"workspaces",value:e})}catch(e){u.bridge?.reportError?.(e,{stage:"workspace_list"})}}async function rd(t,e=!1){let i=u.workspaces?.get(t);if(!i)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await kt(i.path),!e&&u.current&&i.path===await xi(u.current.cwd)&&!u.workspaceSessions?.hasWorkspace(i.path))u.selected="tui",u.activeWorkspaceId=t,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Te()});else{if(!u.workspaceSessions)throw new Error("Pi \u5DE5\u4F5C\u533A\u670D\u52A1\u4E0D\u53EF\u7528");(!e||!await u.workspaceSessions.reuseBlank(i.path))&&await u.workspaceSessions.open(i.path,e?"new":"continue"),u.selected="sdk",u.activeWorkspaceId=t,u.bridge?.publish({type:"snapshot",session:Te()})}await Ee()}async function $w(t,e,i){let r=u.workspaces?.get(t);if(!r)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");let n=await kt(r.path);if(u.workspaceSessions?.hasSession(n,e)||u.current?.sessionManager.getSessionId()===e&&await xi(u.current.cwd)===n)return r;if(!(await Ni(n)).some(a=>a.id===e&&a.path===i))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");return r}function je(t){let e=u.current;if(e===null||e.sessionManager.getSessionId()!==t)throw new Error("\u4F1A\u8BDD\u5DF2\u5207\u6362");return e}function De(t){u.current=t,u.selected==="tui"&&u.bridge?.publish({type:"snapshot",session:Te()})}function Kw(){if(u.current===null)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let t=u.selected==="sdk"?u.workspaceSessions?.path:u.current.cwd;if(!t)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u5DE5\u4F5C\u533A");let e=u.selected==="tui"?u.current.isProjectTrusted():u.workspaceSessions?.session?.settingsManager.isProjectTrusted()??!1;return qN.create(t,void 0,{projectTrusted:e})}async function Yw(){let t=Kw(),e=n=>({packages:(n.packages??[]).map(s=>typeof s=="string"?s:s.source),extensions:n.extensions??[],skills:n.skills??[]}),i=new Vw({cwd:Te().cwd,agentDir:Pe(),settingsManager:t}),r=_v(i.listConfiguredPackages(),await i.resolve(async()=>"skip"));return{projectTrusted:t.isProjectTrusted(),global:e(t.getGlobalSettings()),project:e(t.getProjectSettings()),installed:r}}async function $N(t){Ne(t.sessionId);let e=u.selected==="tui"?je(t.sessionId):null;if(e?!e.isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let i=Kw();if(t.scope==="project"&&!i.isProjectTrusted())throw new Error("\u5F53\u524D\u9879\u76EE\u5C1A\u672A\u53D7\u4FE1\u4EFB\uFF0C\u65E0\u6CD5\u4FEE\u6539\u9879\u76EE\u8BBE\u7F6E");let r=t.value.trim(),n=t.scope==="project"?i.getProjectSettings():i.getGlobalSettings();if(t.kind==="packages"){let s=new Vw({cwd:Te().cwd,agentDir:Pe(),settingsManager:i});t.action==="add"?await s.installAndPersist(r,{local:t.scope==="project"}):await s.removeAndPersist(r,{local:t.scope==="project"})}else if(t.kind==="extensions"){let s=n.extensions??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectExtensionPaths(a):i.setExtensionPaths(a)}else{let s=n.skills??[],a=t.action==="add"?[...new Set([...s,r])]:s.filter(o=>o!==r);t.scope==="project"?i.setProjectSkillPaths(a):i.setSkillPaths(a)}return await i.flush(),u.selected==="tui"?(u.commandContext&&await u.commandContext.reload(),u.current&&De(u.current)):(await u.workspaceSessions?.reload(),u.bridge?.publish({type:"plugins_changed"})),await Yw()}function ja(t,e=gp){if(u.hostedMode===!1||u.hostedMode===void 0&&u.workspaceSessions)throw new Error("Stop the older builtin host before migrating drawing ownership; reload cannot replace retained sessions");u.hostedMode=!0;let i=(c,p)=>{let d=ed(c);return{cwd:d,sessionId:p,workspaceId:Hw("sha256").update(d).digest("hex")}},r=wr(Pe(),"pi-web","hosted"),n=new Pa({configPath:Dw(Pe())});u.hosted??=new Ma({root:r,...n.enabled?{dev:n,devStatusPath:Lw(Pe())}:{},...n.enabled?{devArchives:n.archives,devRoots:n.roots}:{},...n.catalog.length?{catalog:[...Xe,...n.catalog],policies:new Map([...Ia,...n.policies])}:{},...Bw({root:r,sessions:()=>u.workspaceSessions,activeWorkspace:()=>u.workspaceSessions?.path??null,trustedScope:i,sessionTitle:c=>u.workspaceSessions?.retainedSessions().find(p=>p.sessionId===c)?.name,changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),hostVersion:JSON.parse(MN(kr(Dn,"../../package.json"),"utf8")).version,packageRoot:kr(Dn,"../.."),workerEntry:kr(Dn,"../../dist/hosted-worker.js"),ownerId:`local:${process.getuid?.()??"host"}:${Hw("sha256").update(Pe()).digest("hex")}`,resolveSession:c=>{let p=u.current;if(p?.sessionManager.getSessionId()===c)return i(p.cwd,c);let d=u.workspaceSessions?.hostedScope(c);return d?i(d.cwd,c):null},legacy:()=>Uw(wr(Pe(),"pi-web","diagrams")),changed:()=>u.bridge?.publish({type:"hosted_plugins_changed"})}),u.offHostedThaw?.(),u.offHostedThaw=u.hosted?.adapter.onThaw(id),u.pi=t;let s=bu({async run(...c){if(!u.bridge)throw new Error("Open the pi-web workbench first; workspace terminals live there.");return u.bridge.runPluginTool(...c)},async ask(c,p){if(u.pi&&c.sessionId===u.current?.sessionManager.getSessionId())return aa(u.pi.events,c,p);if(!u.workspaceSessions)throw new Error("The Web workbench is not open");return u.workspaceSessions.requestInteraction(c,p)}});for(let c of s)t.registerTool(c);u.tools?.clear(),u.tools=new dr({enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,capture:(c,p)=>u.bridge?.reportError?.(c,p),breadcrumb:(c,p)=>u.bridge?.breadcrumb?.(c,p),anonymize:c=>u.telemetry?.session(c)??"unavailable"});let a=c=>({...u.operation,session:u.telemetry?.session(c.sessionManager.getSessionId()),piVersion:td,model:c.model?`${c.model.provider}/${c.model.id}`:null,thinkingLevel:c.thinkingLevel});u.interactions?.dispose(),u.interactions=new cr(t.events,c=>!!u.bridge&&c.sessionId===u.current?.sessionManager.getSessionId()&&Sn(u.tuiCatalog,c.pluginId),()=>{u.current&&u.selected==="tui"&&De(u.current)});let o=()=>{u.stopChanged?.(),u.stopChanged=t.events.on(oa,()=>{u.selected==="tui"&&u.current&&De(u.current)})};o(),t.on("session_start",async(c,p)=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiWaitController=new AbortController,u.tuiGeneration++,o(),u.current=p,u.releaseHostedTui?.(),u.releaseHostedTui=u.hosted?.adapter.mountTui(t,i(p.cwd,p.sessionManager.getSessionId())),u.hosted&&!await u.hosted.admit(1e4)&&console.error("pi-webapp: plugin startup is still running; the host continues and plugins report on their own cards"),u.tuiPromptSessionId!==p.sessionManager.getSessionId()&&(u.tuiPrompts=new Xt(()=>{u.selected==="tui"&&u.current&&u.bridge?.publish({type:"snapshot",session:jt()}),Ee()}),u.tuiPromptSessionId=p.sessionManager.getSessionId()),u.tuiAgentError=!1,u.bridge){let d=await Ri.discover(p.cwd,p.isProjectTrusted?.()??!1);if(u.current!==p)return;u.tuiCatalog=d}u.replacementSessionId!==p.sessionManager.getSessionId()&&(u.replacementContext=null,u.replacementSessionId=null),De(p),u.bridge&&u.selected==="tui"&&u.bridge.publish({type:"plugins_changed"}),u.selected==="tui"&&u.workspaces&&u.workspaces.add(p.cwd).then(async d=>{u.selected!=="tui"||u.current?.sessionManager.getSessionId()!==p.sessionManager.getSessionId()||(u.activeWorkspaceId=d.id,await Ee())}).catch(d=>{u.bridge?.publish({type:"error",message:d instanceof Error?d.message:"\u65E0\u6CD5\u6CE8\u518C\u5F53\u524D\u5DE5\u4F5C\u533A",errorCode:"unexpected_error",errorId:u.bridge.reportError?.(d,{stage:"workspace_register"})})}),process.env.PI_WEBAPP_AUTO_OPEN==="1"&&p.mode==="tui"&&!u.autoOpened&&(u.autoOpened=!0,l(p).catch(d=>{p.ui.notify(d instanceof Error?d.message:"Web \u542F\u52A8\u5931\u8D25","error")}))}),t.on("agent_start",(c,p)=>{u.tuiAgentError=!1,u.bridge?.breadcrumb?.("agent_start",a(p)),De(p),Ee()}),t.on("agent_end",(c,p)=>De(p)),t.on("agent_settled",(c,p)=>{u.bridge?.breadcrumb?.("agent_end",a(p)),u.tools?.clear(),u.operation=void 0,u.tuiStreaming=null,id(),De(p),Ee()}),t.on("tool_execution_start",(c,p)=>{u.tools?.start(c,a(p))}),t.on("tool_execution_end",(c,p)=>{u.tools?.end(c,a(p))}),t.on("model_select",(c,p)=>De(p)),t.on("thinking_level_select",(c,p)=>De(p)),t.on("message_end",(c,p)=>{if(c.message.role==="assistant"&&c.message.stopReason==="error"){u.tuiAgentError=!0;let d=u.bridge?.reportError?.(new Error("Agent response failed"),{...u.operation,stage:"agent",code:"agent_failed",piVersion:td});u.selected==="tui"&&u.bridge?.publish({type:"error",message:c.message.errorMessage??"Agent response failed",errorCode:"unexpected_error",errorId:d,inTranscript:!0,...u.operation})}c.message.role==="toolResult"&&u.tools?.message(c.message,a(p)),c.message.role==="assistant"&&(u.tuiStreaming=null),u.selected==="tui"&&c.message.role==="assistant"&&u.bridge?.publish({type:"stream",message:null}),De(p),Ee()}),t.on("session_info_changed",(c,p)=>De(p)),t.on("message_update",(c,p)=>{if(u.current=p,c.message.role!=="assistant"||(u.tuiStreaming={id:"stream",role:"assistant",timestamp:new Date(c.message.timestamp).toISOString(),blocks:qt(c.message.content)},u.selected!=="tui"||u.bridge===null))return;let d=Date.now();d-u.lastStreamAt<60||(u.lastStreamAt=d,u.bridge.publish({type:"stream",message:u.tuiStreaming}))}),t.on("session_shutdown",async c=>{if(u.tuiStreaming=null,u.tools?.clear(),u.operation=void 0,u.tuiWaitController.abort(),u.tuiGeneration++,u.stopChanged?.(),u.stopChanged=null,u.interactions?.cancelAll(),u.releaseHostedTui?.(),u.releaseHostedTui=void 0,c.reason==="new"||c.reason==="resume"||c.reason==="fork"||c.reason==="reload"){u.current=null;return}await u.hosted?.shutdown(),u.hosted=void 0,u.offHostedThaw?.(),u.offHostedThaw=void 0,u.current=null;let p=u.bridge,d=u.telemetry;u.bridge=null,u.commandContext=null,u.replacementContext=null,u.replacementSessionId=null,u.pi=null;let m=u.workspaceSessions;u.workspaceSessions=null,await m?.dispose(),u.selected="tui",u.activeWorkspaceId=null,u.autoOpened=!1,u.tuiCatalog=null,u.stopPluginWatch?.(),u.stopPluginWatch=null,u.operation=void 0,u.telemetry=null,p?await p.close():await d?.close()});let l=async c=>{u.telemetry??=new wt;try{u.current=c,u.commandContext="newSession"in c?c:null,u.pi=t,u.tuiCatalog=await Ri.discover(c.cwd,c.isProjectTrusted?.()??!1),u.workspaces===null&&(u.workspaces=new sa(q_(Pe())),await u.workspaces.load());try{await u.workspaces.discover((await Ln.listAll()).map(m=>m.cwd))}catch(m){c.ui.notify(`\u65E0\u6CD5\u8BFB\u53D6\u90E8\u5206 Pi \u5386\u53F2\u5DE5\u4F5C\u533A\uFF1A${m instanceof Error?m.message:String(m)}`,"warning")}let p=await u.workspaces.add(c.cwd);if(u.selected==="tui"&&(u.activeWorkspaceId=p.id),u.bridge&&(u.bridge.protocolVersion!==7||u.bridge.buildId!==it||typeof u.bridge.reportError!="function"||typeof u.bridge.runPluginTool!="function")){let m=u.bridge;if(u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)&&u.workspaceSessions.session&&!u.workspaceSessions.session.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F\u518D\u5207\u6362\u5DE5\u4F5C\u533A");u.bridge=null,await m.close(),await u.telemetry.close(),u.telemetry=new wt}if(u.bridge===null){let m=u.workspaceSessions&&(u.workspaceSessions.telemetryVersion!==2||u.workspaceSessions.runtimeVersion!==4)?u.workspaceSessions:null,g=m?.session&&m.path?{path:m.path,sessionManager:m.session.sessionManager}:null;m&&(await m.dispose(),u.workspaceSessions=null),u.workspaceSessions??=new da(h=>{u.selected==="sdk"&&u.bridge?.publish(h)},()=>u.current?.model,h=>{try{return!!u.current&&ed(u.current.cwd)===h&&(u.current.isProjectTrusted?.()??!1)}catch{return!1}},(h,_)=>u.bridge?.reportError?.(h,_),{enabled:()=>!!u.telemetry?.enabled&&!!u.bridge,breadcrumb:(h,_)=>u.bridge?.breadcrumb?.(h,_),anonymize:h=>u.telemetry?.session(h)??"unavailable"},()=>{Ee()},s,{adapter:u.hosted.adapter,scope:i}),g&&await u.workspaceSessions.open(g.path,{sessionManager:g.sessionManager});let f={hosted:u.hosted?.handlers,selfUpdate:HN(new _a({agentDir:Pe(),packageRoot:kr(Dn,"../.."),launcherNonce:process.env.PI_WEBAPP_FOREGROUND==="1"?void 0:process.env.PI_WEBAPP_LAUNCHER_NONCE,pluginWarnings:h=>u.hosted.manager.hostUpdateWarnings(h),prefetchPlugins:(h,_)=>u.hosted.manager.prefetchForHost(h,_),beforeRestart:h=>u.hosted.prepareRestart(h)})),snapshot:Te,busyGitWorkspaces:()=>{let h=(u.workspaceSessions?.retainedSessions()??[]).filter(_=>!_.idle).map(_=>_.cwd);if(u.current&&(!u.current.isIdle()||u.tuiPrompts.sending))try{h.push(ed(u.current.cwd))}catch{h.push(u.current.cwd)}return h},plugins:async()=>{let h=Ua();return await h?.refreshAssets(),h?.view()??{plugins:[],errors:[]}},pluginAsset:async h=>Ua()?.asset(h)??null,async invokePluginAction(h,_,S,E){if(Ne(h),!Ua()?.has(_))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");let A=u.selected,D=u.tuiGeneration,C=u.workspaceSessions?.session,N={requestId:BN(),sessionId:h,pluginId:_,action:S,input:E},G=u.selected==="sdk"?await u.workspaceSessions.invokePluginAction(N):await la(u.pi.events,N,15e3,u.tuiWaitController.signal);if(Ne(h),A!==u.selected||(A==="tui"?D!==u.tuiGeneration:C!==u.workspaceSessions?.session))throw new Error("\u4F1A\u8BDD\u8FD0\u884C\u5B9E\u4F8B\u5DF2\u5207\u6362");return u.selected==="tui"&&u.current&&De(u.current),G},async resolvePluginInteraction(h,_,S,E){if(Ne(h),!Sn(Ua(),_))throw new Error("\u63D2\u4EF6\u672A\u542F\u7528");u.selected==="sdk"?u.workspaceSessions.resolveInteraction(h,_,S,E):u.interactions.resolve(h,_,S,E)},image(h,_,S){Ne(h);let A=(u.selected==="sdk"?u.workspaceSessions?.session?.sessionManager.getBranch():u.current?.sessionManager.getBranch())?.find(C=>C.id===_);if(A?.type!=="message"||A.message.role!=="user"||!Array.isArray(A.message.content))return null;let D=A.message.content[S];return D?.type!=="image"?null:{data:Buffer.from(D.data,"base64"),mimeType:D.mimeType}},async workspaces(){return zw()},async addWorkspace(h,_){let S=await u.workspaces.add(h,_);try{await rd(S.id,!0)}catch(E){throw await Ee(),E}},async selectWorkspace(h){await rd(h)},async newSessionInWorkspace(h){await rd(h,!0)},async removeWorkspace(h){if(h===u.activeWorkspaceId)throw new Error("\u8BF7\u5148\u5207\u6362\u5230\u5176\u4ED6\u5DE5\u4F5C\u533A");await u.workspaces.remove(h),await Ee()},async subagentHistory(h,_){let S=u.workspaces?.get(h);if(!S)return null;let E=await Ln.listAll(),A=(await Ni(S.path,E)).find(C=>C.id===_);if(!A)return null;let D=(await pr(E,Ci(Pe()))).get(_);return D?J_(A.path,_,D):null},async selectSession(h,_,S){let E=u.workspaces?.get(h);if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");if(await kt(E.path),_===u.current?.sessionManager.getSessionId()&&E.path===await xi(u.current.cwd))u.selected="tui",u.activeWorkspaceId=h,u.bridge?.publish({type:"stream",message:null}),u.bridge?.publish({type:"snapshot",session:Te()});else{if(u.selected==="sdk"&&u.workspaceSessions?.session?.sessionManager.getSessionId()===_&&u.workspaceSessions.path===E.path)return;if(u.workspaceSessions?.hasSession(E.path,_))await u.workspaceSessions.open(E.path,{sessionId:_});else{let A=await Ln.listAll();if(!(await Ni(E.path,A)).some(N=>N.id===_&&N.path===S))throw new Error("\u4F1A\u8BDD\u4E0D\u5C5E\u4E8E\u8BE5\u5DE5\u4F5C\u533A");if((await pr(A,Ci(Pe()))).has(_))throw new Error("\u5B50\u4EFB\u52A1\u8BB0\u5F55\u4E3A\u53EA\u8BFB");await u.workspaceSessions.open(E.path,{sessionFile:S})}u.selected="sdk",u.activeWorkspaceId=h,u.bridge?.publish({type:"snapshot",session:Te()})}await Ee()},async renameSession(h,_,S,E){let A=E.replace(/\s+/g," ").trim();if(A.length>120)throw new Error("\u4F1A\u8BDD\u540D\u79F0\u8FC7\u957F");await $w(h,_,S),u.current?.sessionManager.getSessionId()===_&&u.pi?u.pi.setSessionName(A):u.workspaceSessions?.rename(_,A)||Ln.open(S).appendSessionInfo(A),u.selected==="tui"&&u.current?.sessionManager.getSessionId()===_&&u.bridge?.publish({type:"snapshot",session:Te()}),await Ee()},async deleteSession(h,_,S){let E=await $w(h,_,S);if(u.current?.sessionManager.getSessionId()===_)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 A=await u.workspaceSessions?.discard(_)??null,D=A?.path??(S||null);D&&await Z_(D,Pe()),A?.wasActive&&u.selected==="sdk"&&(await u.workspaceSessions.open(E.path,"new"),u.selected="sdk",u.activeWorkspaceId=h,u.bridge?.publish({type:"snapshot",session:Te()})),await Ee()},async models(){if(u.selected==="sdk")return u.workspaceSessions?.models()??[];let h=u.current;if(!h)throw new Error("\u6CA1\u6709\u6D3B\u52A8\u4F1A\u8BDD");let _=h.scopedModels?.map(S=>`${S.model.provider}/${S.model.id}`)??[];return h.modelRegistry.getAvailable().filter(S=>_.length===0||_.includes(`${S.provider}/${S.id}`)).map(S=>({provider:S.provider,id:S.id,name:S.name}))},async providers(){let h=await Sr(),_=new Set((await h.listCredentials()).map(S=>S.providerId));return h.getProviders().map(S=>({id:S.id,name:S.name,configured:h.getProviderAuthStatus(S.id).configured,storedCredential:_.has(S.id),methods:[S.auth.apiKey?.login?"api_key":null,S.auth.oauth?"oauth":null].filter(E=>E!==null)}))},async providerModels(h){let _=await Sr();return ju(wr(Pe(),"models.json"),h,_)},async updateProviderModel(h,_,S){if(Ne(h),u.selected==="tui"?!je(h).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let E=Te().model;if(S.action==="remove"&&E===`${_}/${S.id}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");if(S.action==="save"&&S.originalId&&S.originalId!==S.model.id&&E===`${_}/${S.originalId}`)throw new Error("\u8BF7\u5148\u5207\u6362\u5F53\u524D\u4F7F\u7528\u7684\u6A21\u578B");let A=await Sr();await Bu(wr(Pe(),"models.json"),_,S,A),await A.refresh({providers:[_],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[_],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[_],allowNetwork:!1});let D=S.action==="save"?S.model.id:S.action==="base_url"&&E?.startsWith(`${_}/`)?E.slice(_.length+1):null;if(D&&E===`${_}/${D}`)if(u.selected==="sdk")try{await u.workspaceSessions.setModel(_,D)}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 C=je(h),N=C.modelRegistry.find(_,D);if(!N||!u.pi||!await u.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");De(C)}},async logoutProvider(h,_){if(Ne(h),u.selected==="tui"?!je(h).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Sr();if(!(await S.listCredentials()).some(E=>E.providerId===_))throw new Error("\u8BE5\u63D0\u4F9B\u65B9\u6CA1\u6709\u5DF2\u4FDD\u5B58\u7684\u8BA4\u8BC1");await S.logout(_),await u.current?.modelRegistry.refresh({providers:[_],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[_],allowNetwork:!1})},async loginProvider(h,_,S){let E=await Sr();await E.login(h,_,Cu(h,_,S)),await E.refresh({providers:[h],allowNetwork:!1}),await u.current?.modelRegistry.refresh({providers:[h],allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({providers:[h],allowNetwork:!1})},async addCustomProvider(h,_){if(Ne(h),u.selected==="tui"?!je(h).isIdle():!u.workspaceSessions?.session?.isIdle)throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let S=await Sr();if(S.getProvider(_.id))throw new Error("\u63D0\u4F9B\u65B9\u5DF2\u5B58\u5728");await Mu(wr(Pe(),"models.json"),_),await S.refresh({allowNetwork:!1}),await u.current?.modelRegistry.refresh({allowNetwork:!1}),await u.workspaceSessions?.session?.modelRuntime.refresh({allowNetwork:!1})},commands(){return u.selected==="tui"?(u.pi?.getCommands()??[]).filter(h=>h.name!=="web"&&h.name!=="web-dev-reload").map(h=>({name:h.name,description:h.description})):[]},async compact(h){if(Ne(h),u.selected==="sdk"){let S=u.workspaceSessions?.session;if(!S||!S.isIdle)throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");await S.compact(),u.bridge?.publish({type:"snapshot",session:Te()});return}let _=je(h);if(!_.isIdle())throw new Error("\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");_.compact()},async setModel(h,_,S){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.setModel(_,S);return}let E=je(h);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");let A=E.modelRegistry.find(_,S);if(!A||!E.modelRegistry.getAvailable().some(D=>D.provider===_&&D.id===S))throw new Error("\u6A21\u578B\u4E0D\u53EF\u7528");if(!u.pi||!await u.pi.setModel(A))throw new Error("\u6A21\u578B\u63D0\u4F9B\u65B9\u672A\u914D\u7F6E\u8BA4\u8BC1");De(E)},async setThinkingLevel(h,_){if(Ne(h),!["off","minimal","low","medium","high","xhigh"].includes(_))throw new Error("\u63A8\u7406\u5F3A\u5EA6\u65E0\u6548");if(u.selected==="sdk"){let A=u.workspaceSessions?.session;if(!A||!A.isIdle||!A.getAvailableThinkingLevels().includes(_))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");A.setThinkingLevel(_),u.bridge?.publish({type:"snapshot",session:Te()});return}let E=je(h);if(!E.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!E.model||!jN(E.model).includes(_))throw new Error("\u5F53\u524D\u6A21\u578B\u4E0D\u652F\u6301\u6B64\u63A8\u7406\u5F3A\u5EA6");if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.pi.setThinkingLevel(_),De(E)},config:Yw,updateConfig:$N,async send(h,_,S=[],E,A){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.send(_,S,E,A);return}let D=je(h);if(Jt(jt(),_,A),A==="followUp"&&(!D.isIdle()||u.tuiPrompts.length>0)){u.tuiPrompts.enqueue(_,S,E),id();return}if(D.isIdle()&&u.tuiPrompts.sending)throw new Me("\u961F\u5217\u6B63\u5728\u53D1\u9001\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");await nd(h,_,S,E,A)},async updateQueuedPrompt(h,_,S,E){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.updateQueuedPrompt(_,S,E);return}if(E.kind==="steer"&&je(h).isIdle())throw new Me("\u5F53\u524D\u6CA1\u6709\u53EF\u5F15\u5BFC\u7684\u6267\u884C\uFF0C\u8BF7\u5148\u7EE7\u7EED\u6216\u53D1\u9001\u4EFB\u52A1");await u.tuiPrompts.update(_,S,E,(A,D,C)=>nd(h,A,D,C,"steer"))},async abort(h){if(Ne(h),u.selected==="sdk")await u.workspaceSessions.stop();else{let _=je(h);if(_.isIdle()&&!u.tuiPrompts.sending)return;if(!u.pi)throw new Error("Pi \u4F1A\u8BDD\u4E0D\u53EF\u7528");u.tools?.cancel(),u.bridge?.breadcrumb?.("cancel",{...u.operation}),u.pi.appendEntry(vn),_.abort()}},async resume(h,_){if(Ne(h),u.selected==="sdk"){await u.workspaceSessions.resume(_);return}let S=je(h);if(ur(()=>u.hosted?.adapter.assertAdmission(),_,(E,A)=>u.bridge?.reportError?.(E,A)),!S.isIdle())throw new Error("Pi \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u56DE\u590D\u7ED3\u675F");if(!S.model||!u.pi)throw new Error("\u8BF7\u5148\u9009\u62E9\u6A21\u578B");if(!S.modelRegistry.hasConfiguredAuth(S.model))throw new Error("\u8BF7\u5148\u8FDE\u63A5\u5F53\u524D\u6A21\u578B");u.operation=_;try{u.pi.sendMessage(ca(Te().messages),{triggerTurn:!0})}catch(E){throw u.operation=void 0,E}},async newSession(h){if(Ne(h),u.selected==="sdk"){let E=u.workspaces?.get(u.activeWorkspaceId??"");if(!E)throw new Error("\u5DE5\u4F5C\u533A\u4E0D\u5B58\u5728");await u.workspaceSessions.reuseBlank(E.path)||await u.workspaceSessions.open(E.path,"new"),await Ee();return}let _=je(h);if(!_.isIdle()||u.tuiPrompts.length>0||u.commandContext===null){await u.workspaceSessions.open(_.cwd,"new"),u.selected="sdk",u.bridge?.publish({type:"snapshot",session:Te()}),await Ee();return}if((await u.commandContext.newSession({withSession:async E=>{u.commandContext=E,u.replacementContext=E,u.replacementSessionId=E.sessionManager.getSessionId(),u.current=E}})).cancelled)throw new Error("\u65B0\u4F1A\u8BDD\u5DF2\u53D6\u6D88");await Ee()}};f.addWorkspace=u.lifecycle.wrap(f.addWorkspace),f.selectWorkspace=u.lifecycle.wrap(f.selectWorkspace),f.newSessionInWorkspace=u.lifecycle.wrap(f.newSessionInWorkspace),f.removeWorkspace=u.lifecycle.wrap(f.removeWorkspace),f.selectSession=u.lifecycle.wrap(f.selectSession),f.renameSession=u.lifecycle.wrap(f.renameSession),f.deleteSession=u.lifecycle.wrap(f.deleteSession),f.newSession=u.lifecycle.wrap(f.newSession),f.updateConfig=u.lifecycle.wrap(f.updateConfig);try{u.bridge=await C_(f,Dn,u.telemetry)}catch(h){throw process.env.PI_WEBAPP_LAUNCHER_NONCE&&c.ui.notify(`pi-webapp-start-error: ${h instanceof Error?h.message:String(h)}`,"error"),h}}if(u.stopPluginWatch===null&&process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS){let m=[],g=null;for(let f of(process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS??"").split(PN).filter(Boolean))try{m.push(DN(wr(kr(f),"dist"),(h,_)=>{let S=String(_??"");["client.js","client.css"].includes(S)&&(g&&clearTimeout(g),g=setTimeout(()=>u.bridge?.publish({type:"plugins_changed"}),180))}))}catch(h){u.bridge?.publish({type:"error",message:`\u63D2\u4EF6\u76D1\u542C\u5931\u8D25\uFF1A${f}: ${String(h)}`})}u.stopPluginWatch=()=>{for(let f of m)f.close();g&&clearTimeout(g)}}let d=await e(u.bridge.url).catch(()=>!1);c.ui.notify(`pi-webapp: ${u.bridge.url}`,d?"info":"warning"),c.ui.setStatus("pi-webapp","Web \u5DF2\u542F\u52A8 \xB7 /web \u91CD\u65B0\u6253\u5F00")}catch(p){throw u.telemetry?.capture(p,{stage:"open_web",piVersion:td}),u.bridge||(await u.telemetry?.close(),u.telemetry=null),p}};t.registerCommand("web",{description:"Open the current Pi session in a local web interface",handler:async(c,p)=>l(p)}),t.registerCommand("web-prepare-stop",{description:"Save hosted plugin views and release runtime ownership before stopping",handler:async(c,p)=>{if(!/^prepare-stop-[a-f0-9-]{36}$/.test(c))throw new Error("Launcher stop receipt ID required");try{await u.hosted?.shutdown(),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!0})}`,"info")}catch(d){console.error("pi-webapp: plugin shutdown refused the stop request:",d),p.ui.notify(`pi-webapp-stop: ${JSON.stringify({id:c,ok:!1})}`,"warning")}}}),t.registerCommand("web-dev-reload",{description:"Reload local pi-webapp plugins during development",handler:async(c,p)=>{process.env.PI_WEBAPP_PLUGIN_DEV_ROOTS&&(await p.waitForIdle(),await u.lifecycle.run(async()=>{let d=u.workspaceSessions?.session;d&&(await d.waitForIdle(),await u.workspaceSessions.reload()),await p.reload()}))}})}var A9=ja;export{A9 as default,NN as verifySentryDisabledRelease,Fw as verifySentryNodeRelease};
|
|
244
244
|
|
|
245
|
-
//# debugId=
|
|
245
|
+
//# debugId=af6f58c9-c0b2-4b3c-9fdd-42ec795ae10e
|